Database System Design: Requirements to Worked Sketches
"By contrast, you shouldn't start designing your schema for DynamoDB until you know the questions it will need to answer." — Amazon DynamoDB Developer Guide, NoSQL design for DynamoDB
Summary: Database design is a method, not a favourite product: requirements become access patterns, access patterns become numbers, and the numbers pick the model, the scale rung and the consistency level. Focus: The eight-step method (requirements, access patterns, sizing, model, scale ladder, consistency menu, HA/backup/tenancy, operations) and three worked sketches with full numbers: a URL shortener, an order/inventory system and a chat/feed. Learning goal: Given a one-paragraph product brief, produce in an hour a sizing sheet, a schema with indexes, the key queries, a scaling path with triggers and a failure analysis you can defend in a design review or an interview.
This page is the capstone of the database section: it does not teach any one mechanism, it teaches how to combine them. Each step links to the page that owns the detail: the scale ladder to Storage & Data Scaling, the consistency menu to Eventual Consistency in Database Systems, lost updates and write skew to Isolation Levels, replicas and failover to Replication & Failover, PITR to Backup, PITR & DR, tenancy to Multi-Tenancy, migrations to Zero-Downtime Schema Migrations, dashboards to Database Observability, keys to ID Generation, and data models to NoSQL Families and Wide-Column & Key-Value. The normal forms and column types themselves are in Schema Design.
Page map
| If you are looking for | Go to |
|---|---|
| The method and the numbers on one screen | Everything in one minute |
| Why design from access patterns, not from a favourite database | Why a method |
| Dean's latency numbers, DDIA, Well-Architected, DynamoDB, Google Cloud | Where the method comes from |
| Read/write ratio, SLOs, retention, compliance | Requirements that matter |
| Listing every query before the schema | Access-pattern-first modelling |
| QPS, GB/year, bandwidth, working set | Back-of-envelope sizing |
| Relational vs document vs KV vs wide-column vs graph vs time-series vs search | Choosing a data model |
| Index, vertical, pool, replicas, cache, partition, shard | The scale ladder |
| Strong, read-your-writes, bounded staleness, eventual | The consistency menu |
| RPO/RTO, replicas, PITR, pool vs silo | HA, backup and multi-tenancy |
| Headroom, cost, schema evolution, observability | Headroom, Cost, Schema evolution, Observability |
| What each product gives you | Per-product behaviour |
| Formulas, Little's Law, hot-row limits, knobs, error codes | Mechanics |
| URL shortener, order/inventory, chat/feed with numbers, schema, code | The three worked sketches |
| The checklist before a design review | Choosing: the decision checklist |
| Monolith to multi-region | In architecture |
| Measure your own numbers | Lab |
| Interview-style questions | Self-check |
| Wrong beliefs, cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The method. Each step produces an artefact; the next step consumes it.
| Step | Question it answers | Artefact | Typical mistake |
|---|---|---|---|
| 1. Requirements | What must be true, how fast, for how long, under which law? | Read/write ratio, p99 SLO, consistency per operation, retention, compliance list | "It must scale" with no number |
| 2. Access patterns | Which exact queries run, how often, with which keys? | Access-pattern table | Designing tables first, queries later |
| 3. Sizing | How many requests, bytes and hot rows? | QPS avg/peak, GB/year, bandwidth, working set | Average instead of peak; forgetting indexes and replicas |
| 4. Data model | Which model serves the patterns with the fewest moving parts? | Model + engine + schema + indexes | Picking NoSQL for "scale" at 50 writes/s |
| 5. Scale ladder | What do we do at 10× and 100×, and what triggers it? | Trigger list per rung | Sharding on day one |
| 6. Consistency menu | Which operation needs which guarantee? | Consistency per operation | One global level for everything |
| 7. HA / backup / tenancy | What can we lose, how long can we be down, who shares what? | RPO/RTO, replica plan, PITR, tenancy model | Replicas mistaken for backups |
| 8. Operate | What does it cost, how does it change, how do we see it? | Cost line, migration plan, dashboards and alerts | No plan for the first ALTER TABLE |
Numbers to memorise. Latencies from Norvig's table (Jeff Dean's numbers) and the Berkeley interactive model; the conversions are arithmetic.
| Thing | Value | Use it to |
|---|---|---|
| Main memory reference | 100 ns | Cached lookups are effectively free |
| Round trip inside one data centre | 500 µs (0.5 ms) | Each DB round trip costs ~0.5 ms before any work: count round trips |
| Disk seek (spinning) | 8 ms | Why random I/O on HDD killed OLTP; SSD random read is tens of µs |
| Read 1 MB sequentially from disk | 20 ms (HDD) | Scans are bandwidth-bound |
| US ↔ Europe round trip | 150 ms | Cross-region synchronous writes cost this per commit |
| 1 day | 86,400 s (≈ 10^5) | 1M/day ≈ 12/s |
| 1 month | ≈ 2.6M s | 100M/month ≈ 39/s |
| 1 year | ≈ 31.5M s (≈ π × 10^7) | 1 KB/s for a year ≈ 31.5 GB |
| Peak factor | 2–5× normal, 10–50× for flash events | Size for peak, not average |
The sketches in one table.
| Sketch | Shape | Peak load | Storage/year | Model | Hard part |
|---|---|---|---|---|---|
| URL shortener | 100:1 read-heavy point lookups | ~20k reads/s, ~200 writes/s | ~600 GB | KV access on PostgreSQL + Redis (or DynamoDB) | Cache stampede on a viral link; analytics writes |
| Order / inventory | Write-critical transactions | ~230 checkouts/s (flash sale) | ~730 GB | Relational (PostgreSQL/MySQL) | Oversell (lost update), purchase limits (write skew), hot SKU row |
| Chat / feed | Write-heavy append + fan-out | ~14k messages/s; ~35k timeline inserts/s | ~73 TB raw | Wide-column (Cassandra/ScyllaDB) + Redis timelines | Hot partitions, celebrity fan-out |
Why a method, not a favourite database
Every database is fast at something and slow at something else. A design that starts from "we use MongoDB" or "we use PostgreSQL" tends to discover its access patterns in production. A design that starts from requirements discovers them on a whiteboard, where changing your mind is free. The AWS Well-Architected Framework says the same thing in one sentence:
"The optimal data management solution for a particular system varies based on the kind of data type (block, file, or object), access patterns (random or sequential), required throughput, frequency of access (online, offline, archival), frequency of update (WORM, dynamic), and availability and durability constraints." — AWS Well-Architected Framework, Performance Efficiency Pillar: Data management
| Designing from the product ("we use X") | Designing from the requirements |
|---|---|
| Fast start, familiar tools | One extra hour of tables and arithmetic |
| Access patterns discovered by incidents | Access patterns listed before the schema |
| Scaling decisions taken under pressure | Scaling triggers written down in advance |
| One consistency level for every operation | A consistency choice per operation |
| Cost discovered on the first invoice | Cost estimated with the sizing sheet |
The analogy we reuse on this page: designing a restaurant kitchen. You do not buy ovens first. You start from the menu (the access patterns), the covers per night and the Saturday rush (QPS average and peak), what must never go wrong (allergens: the invariants), how long ingredients are kept and what the health inspector requires (retention and compliance). Only then do you choose stations (data models), how many cooks (replicas), the walk-in fridge (cache), and when you would open a second kitchen (sharding).
Three common misunderstandings, up front
- "NoSQL scales, SQL doesn't." A single PostgreSQL or MySQL primary on current hardware handles thousands of writes per second and tens of thousands of indexed reads; the order sketch below needs ~3k row changes/s at a flash-sale peak. Notion ran on one PostgreSQL instance until 2021 and then sharded it, and Figma ran on "a single Postgres database hosted on AWS's largest physical instance" in 2020. The question is never "SQL or NoSQL" but which access patterns and which numbers.
- "Design the schema, then write the queries." In relational systems that works for flexibility; in DynamoDB, Cassandra and any sharded system it fails, because the partition key decides which queries are cheap. Even in PostgreSQL, the index set comes from the queries.
- "Capacity planning means average load." Systems fail at peak. A daily average of 12 orders/s hides a flash sale at 230/s and a hot product that receives most of them.
Where the method comes from
Latency numbers. Jeff Dean's "Numbers Everyone Should Know" circulated from his talks; the most cited written copy is in Peter Norvig's Teach Yourself Programming in Ten Years, under the heading "Approximate timing for various operations on a typical PC", which lists for example "fetch from main memory 100 nanosec", "fetch from new disk location (seek) 8,000,000 nanosec" and "send packet US to Europe and back 150 milliseconds". Colin Scott's Berkeley interactive page extrapolates the numbers per year; its source code fixes the in-data-centre round trip at return 500000; // ns (0.5 ms) and the WAN round trip at 150 ms. Use them for orders of magnitude, never as benchmarks.
Load parameters and data models (secondary source). Kleppmann's Designing Data-Intensive Applications, chapters 1–3, frames the same steps: describe load with load parameters (requests per second, read/write ratio, fan-out), describe performance with percentiles rather than averages, then pick a data model (relational, document, graph) and a storage engine (B-tree vs LSM). Its chapter 1 uses the home-timeline fan-out problem that the chat/feed sketch below works through. We cite the book as a secondary source; the numbers on this page are our own arithmetic.
Access-pattern-first modelling. The DynamoDB Developer Guide makes it a rule: "The first step in designing your DynamoDB application is to identify the specific query patterns that the system must satisfy", and it names three properties to know before you begin: data size, data shape and data velocity. Its single-table advice ("You should maintain as few tables as possible in a DynamoDB application") follows from the same idea: put items that are read together under one partition key.
Choosing a database. Google Cloud's guidance divides the space into relational and non-relational families (document, key-value, in-memory, wide-column, graph) and gives the coarse rule: "Broadly, if your data structure is not going to change much, select a relational database." The AWS pillar's first best practice is "PERF03-BP01 Use a purpose-built data store that best supports your data access and storage requirements".
Production evidence. The scale-ladder rungs on this page are documented by the companies that climbed them: Instagram's logical shards inside PostgreSQL (2012), Shopify's pods (2016) and its Vitess migration for the Shop app, Notion's 480 logical shards on 32 databases (2021), Figma's vertical then horizontal partitioning (2020–2024), and Discord's move of messages from MongoDB to Cassandra and then ScyllaDB. Each is quoted where it is used.
The order of the method follows the system-design chapter of the reference course the site benchmarks against: requirements, access patterns, scale ladder, consistency menu, HA/backup/multi-tenant, worked sketch.
The method, step by step
The picture is the whole page in one loop: requirements feed access patterns, access patterns feed the sizing sheet, the sizing sheet picks the model and the scale rung, the consistency menu and HA plan are chosen per operation, and operations (cost, schema evolution, observability) close the loop. If the numbers do not fit any rung at an acceptable cost, you go back and renegotiate a requirement (retention, latency, consistency), which is often the cheapest fix of all.
Requirements that matter Must-know
In plain words: before drawing a single table, write down how much is read versus written, how fast it must answer, what must never be wrong, how long data is kept, and which law applies.
Common misunderstanding: "Requirements are the product manager's job; we just need the features." Functional features ("users can shorten a link") do not pick a database. Non-functional requirements do: a 100:1 read ratio, a p99 of 50 ms and a five-year retention pick the design.
Definition: the requirements that change a database design are:
| Requirement | Ask | Why it changes the design | Example answer |
|---|---|---|---|
| Read/write ratio | Reads per write, per entity | Read-heavy → replicas and caches; write-heavy → LSM engines, batching, partitioning | URL shortener 100:1; chat ≈ 1:1 on storage |
| Latency SLO | p50/p99 per operation, from where | Number of round trips and which tier may serve the read | Redirect p99 ≤ 50 ms server-side |
| Throughput | Average and peak per operation | Instance size, pool size, partition count | Checkout peak 230/s |
| Consistency | Per operation: may it be stale, by how much? | Primary vs replica vs cache; isolation; quorum | Stock decrement strong; product page 5 s stale OK |
| Durability / RPO | How many committed writes may be lost? | Sync vs async replication, fsync policy | Orders: 0; click counts: 1 minute |
| Availability / RTO | How long may writes be down? | Failover automation, multi-AZ, multi-region | 99.95% ≈ 22 min/month |
| Retention | How long is each data class kept, then what? | Partitioning by time, TTL, archive tiers | Orders 7–10 years (confirm with finance); chat forever; clicks 13 months raw |
| Compliance | Which regimes apply? | Encryption, residency, erasure, audit | GDPR right to erasure, PCI DSS for card data, data residency for EU users |
| Growth | Rows/day now and in 2 years | When each rung of the scale ladder triggers | 100M links/month, +50%/year |
Sequence (how a requirements interview goes):
1 Brief: "Users shorten links and we redirect them."
2 Ask: how many links/month? -> 100M, +50%/year
3 Ask: redirects per link? -> ~100 over its life (100:1)
4 Ask: redirect latency target? -> p99 50 ms server-side
5 Ask: can a redirect be stale? -> yes, seconds; deletes within 1 min
6 Ask: how long are links kept? -> 5 years default, custom expiry
7 Ask: analytics? -> clicks per link per day, 13 months
8 Ask: law? -> GDPR: owner can delete account and links
9 Output: requirement table -> next step: access patternsReal scenarios: a payments team discovers after launch that the regulator requires 10 years of history, and the single 4 TB table cannot be vacuumed or re-indexed in a maintenance window; a chat product promises "messages forever" and finds that 70% of its storage bill is attachments nobody opens; an analytics feature writes one row per click to the OLTP primary and halves its write headroom.
What each product gives you for the requirement:
| Requirement | PostgreSQL | MySQL InnoDB | DynamoDB | Cassandra / ScyllaDB |
|---|---|---|---|---|
| Retention by time | Declarative partitioning + DETACH PARTITION | Range partitioning + DROP PARTITION | Item TTL attribute | Table default_time_to_live, TWCS compaction |
| RPO 0 | synchronous_commit = on + synchronous_standby_names | Semi-sync replication (AFTER_SYNC) | Multi-AZ by design | Write consistency QUORUM/LOCAL_QUORUM |
| Erasure | DELETE + VACUUM; crypto-shredding for backups | DELETE + purge | DeleteItem | Tombstones until gc_grace_seconds |
How to use it: fill the table above for every entity before any schema. If a cell is "don't know", write the assumption and the person who will confirm it.
Access-pattern-first modelling Must-know
In plain words: list every query the product will run (who asks, with which key, which filter, which sort, how often) and design the tables and indexes so each common query is one cheap lookup or one range scan.
Common misunderstanding: "Normalise first, add indexes when it gets slow." That is fine for a single relational database at modest scale, and it is how most teams start. It fails as soon as the data is partitioned, because a query that does not include the partition key fans out to every shard, and it fails in DynamoDB and Cassandra, where a query without the key is a full scan.
Definition: an access-pattern table has one row per query with: actor, operation, key(s), filter, sort, result size, frequency (avg/peak), latency target, consistency. The schema is then derived: each pattern maps to a primary key, an index or a denormalised copy.
Timeline (deriving the schema from patterns):
1 AP1 GET /:code key=code 1 row 19k/s peak -> UNIQUE(code)
2 AP2 POST /links owner+url 1 row 190/s peak -> UNIQUE(owner_id, url_hash) for idempotency
3 AP3 list my links owner, newest 50 rows 20/s -> INDEX(owner_id, created_at DESC)
4 AP4 clicks per day code, day range 30 rows 5/s -> PK(code, day) in a rollup table
5 AP5 expire links expires_at < now batch 1/min -> partial INDEX(expires_at) WHERE NOT NULL
6 check: every AP is one index seek or one range scan -> schema doneReal scenarios: an e-commerce "orders by customer, newest first" page that does a sort on 2M rows because the index is on customer_id only; a Cassandra table keyed by user_id that must answer "messages in a channel" and ends up with ALLOW FILTERING; a DynamoDB design with one table per entity that needs four round trips to render one page.
| Model | How patterns map to storage | What a missing pattern costs |
|---|---|---|
| Relational (PostgreSQL, MySQL, SQL Server, Oracle) | Tables normalised; patterns become indexes and joins | A new index, usually online (CREATE INDEX CONCURRENTLY) |
| Document (MongoDB) | Embed what is read together; reference what grows unboundedly | A new index; or a reshape of documents |
| Key-value / single-table (DynamoDB) | Partition key + sort key per pattern; GSIs for alternates; overloaded PK/SK | A new GSI (backfilled), or a scan |
| Wide-column (Cassandra, ScyllaDB) | One table per query; partition key = the equality, clustering key = the sort | A new table written in parallel (or a materialised view) |
| Search (Elasticsearch, OpenSearch) | Denormalised documents per search screen | Reindex |
Fix / how to use it: write the table before the schema, mark the top three patterns by frequency, and make sure those three are single-partition, single-index operations. In DynamoDB single-table design, items of different types share a table and are distinguished by key prefixes (PK = CUSTOMER#42, SK = ORDER#2026-11-25#9001), so "customer and their last 10 orders" is one Query.
Back-of-envelope sizing Must-know
In plain words: turn the requirements into four numbers: requests per second at peak, bytes stored per year, bytes moved per second, and the size of the data that is touched often (the working set).
Common misunderstanding: "Storage = rows × row size." Real storage includes per-row overhead (PostgreSQL tuple header is 23 bytes plus alignment), every index, free space (fillfactor, bloat), WAL and binlogs, replicas (×2 or ×3), backups, and the replication factor in Cassandra (RF=3 triples everything).
Definition (the four formulas):
| Quantity | Formula | Example (URL shortener) |
|---|---|---|
| Write QPS | events/day ÷ 86,400 × peak factor | 100M/month ÷ 2.6M s = 39/s avg; ×5 = ~190/s |
| Read QPS | write QPS × read/write ratio | 39 × 100 = 3.9k/s avg; ~19k/s peak |
| Storage/year | rows/year × (row + index + overhead) × copies | 1.2B × 500 B = 600 GB per copy |
| Bandwidth | QPS × bytes per request/response | 19k/s × 500 B ≈ 10 MB/s ≈ 80 Mbit/s |
| Working set | hot fraction × total, or recent window × rate | last 30 days, 20M hot codes × 250 B ≈ 5 GB in Redis |
Sequence (a sizing sheet, line by line):
1 events 100M links/month; 100 redirects per link
2 writes 100e6 / 2.6e6 s = 38.6/s peak x5 -> 190/s
3 reads 38.6 x 100 = 3,860/s peak x5 -> 19,300/s
4 row id 8 + code 8 + owner 8 + url ~100 + hash 65 + 2 ts 16 + header 24 ~= 230 B
5 indexes PK + UNIQUE(code) + UNIQUE(owner,hash) ~= 150 B; bloat/fillfactor -> ~500 B/row
6 storage 1.2e9 rows/year x 500 B = 600 GB/year/copy; 5 years = 3 TB/copy
7 copies primary + 2 replicas = 1.8 TB/year; backups + WAL archive extra
8 bandwidth 19,300/s x 500 B = 9.7 MB/s egress
9 working set 20M hot codes x ~250 B (key+value+overhead) = 5 GB -> one Redis nodeReal scenarios: sizing tells you that the URL shortener's whole first year fits on one PostgreSQL primary, so sharding is a year-three item; that chat at 73 TB/year raw does not fit one node and needs a partitioned store from day one; that a 5 GB working set means a cache hit ratio near 100% is cheap.
| Engine | What to add to raw row size |
|---|---|
| PostgreSQL | 23-byte tuple header + alignment, 4-byte line pointer, TOAST for values > ~2 KB, each B-tree index entry ≈ key + 8–16 bytes, dead tuples until VACUUM |
| MySQL InnoDB | Clustered PK; every secondary index stores the PK, so a wide PK (UUID string) inflates all indexes; ~5–6 bytes record header + transaction id and roll pointer |
| MongoDB (WiredTiger) | Field names stored in each document; block compression (snappy by default) reduces on-disk size |
| Cassandra / ScyllaDB | × replication factor; compaction needs free disk headroom (up to 2× for STCS); compression typically helps |
| Redis | Per-key overhead of tens of bytes; small hashes and sets use compact encodings; plan memory, not disk |
How to use it: keep the sheet next to the design and update it with measured row sizes from the lab: pg_total_relation_size after inserting 1M representative rows beats any estimate.
Choosing a data model Must-know
In plain words: pick the model whose natural query is your most important query: relational for joins and invariants, document for self-contained aggregates, key-value for lookups by key, wide-column for huge append-mostly partitions, graph for multi-hop relationships, time-series for timestamped metrics, search for text relevance.
Common misunderstanding: "Polyglot persistence from day one is best practice." Every extra store is another backup, failover, upgrade, security review and consistency boundary. Start with one general-purpose store (usually PostgreSQL or MySQL) and add a purpose-built one when a measured access pattern needs it.
Definition:
| Model | Natural query | Strong at | Weak at | Products |
|---|---|---|---|---|
| Relational | Joins, ad-hoc filters, multi-row transactions | Invariants (constraints), flexible queries | Horizontal write scale without extra layers | PostgreSQL, MySQL, SQL Server, Oracle, SQLite; distributed: CockroachDB, Spanner, YugabyteDB, Vitess, Citus |
| Document | Fetch/update one aggregate by id | Nested, evolving structures | Cross-document joins and invariants | MongoDB, Firestore, Couchbase |
| Key-value | Get/put by key | Latency, scale, simplicity | Anything but the key | Redis, DynamoDB, Memcached, etcd |
| Wide-column | Range scan inside one partition | Write throughput, huge data, multi-DC | Secondary access paths, ad-hoc queries | Cassandra, ScyllaDB, Bigtable, HBase |
| Graph | Traverse k hops | Recommendations, fraud rings, permissions graphs | Bulk aggregation, sharding | Neo4j, Amazon Neptune, Spanner Graph |
| Time-series | Aggregate by time window | Ingest rate, downsampling, retention | Updates, joins to OLTP data | TimescaleDB, InfluxDB, Prometheus, ClickHouse |
| Search | Relevance-ranked text, facets | Full-text, fuzzy, aggregations | Being the source of truth | Elasticsearch, OpenSearch, PostgreSQL FTS |
| Columnar (OLAP) | Scan few columns of many rows | Analytics, reports | Point updates | ClickHouse, BigQuery, Redshift, Snowflake |
Sequence (choosing for the order sketch):
1 top pattern: "decrement stock and create order atomically" -> multi-row transaction
2 invariant: available >= 0, one order per idempotency key -> constraints
3 scale: 230 tx/s peak, 730 GB/year -> one primary is enough
4 => relational (PostgreSQL or MySQL); analytics -> columnar later via CDCReal scenarios: Discord stored messages in MongoDB with "a single compound index on channel_id and created_at" until, at 100 million messages, "the data and the index could no longer fit in RAM", and moved to Cassandra whose partition-per-channel matched the pattern; Instagram evaluated NoSQL stores and "ultimately decided that the solution that best suited our needs would be to shard our data across a set of PostgreSQL servers".
| Requirement | Pushes towards |
|---|---|
| Cross-entity invariants, money | Relational (or distributed SQL at scale) |
| Writes > ~50k/s sustained, append-mostly | Wide-column / LSM-based store |
| Single-digit-ms reads at any scale, known keys | Key-value (DynamoDB, Redis as cache) |
| Global strong consistency | Spanner, CockroachDB |
| Text relevance | Search engine fed by CDC |
Fix / how to use it: choose by the top three access patterns, then check that the chosen model can do the other patterns acceptably (an index, a secondary store fed by CDC, or a batch job). Details per family: NoSQL Families, Redis, MongoDB, Wide-Column & Key-Value, Graph Databases, Full-Text Search, OLTP vs OLAP.
The scale ladder Must-know
In plain words: when load grows, climb one rung at a time, starting with the cheapest: fix queries and indexes, buy a bigger machine, pool connections, add read replicas, add a cache, partition tables, split by function, and only then shard.
Common misunderstanding: "We will need sharding eventually, so we should shard now." Sharding costs you cross-shard joins, cross-shard transactions, resharding and operational tooling for the life of the system. Shopify only sharded when "it was no longer possible to continue buying a larger database server", and Figma first did vertical partitioning, "we always knew that vertical partitioning could only get us so far", before horizontal sharding.
Definition: the rungs, each with its trigger and cost (full treatment in Storage & Data Scaling):
| Rung | Trigger (measured) | What it buys | Cost |
|---|---|---|---|
| 0. Query and index fixes | Top pg_stat_statements entries do sequential scans | Often 10–100× on the hot query | Engineering time |
| 1. Vertical scaling | CPU > 60–70% at peak, buffer hit ratio falling | 2–4× per step, no code change | Price grows faster than linearly; a ceiling exists |
| 2. Connection pooling | Connection count near max_connections, many idle | Stable memory, more clients | Transaction-mode pooling breaks session features |
| 3. Read replicas | Reads dominate, primary CPU from reads | Read throughput × replicas | Replica lag; read-your-writes routing |
| 4. Cache | Repeated reads of the same keys | 10–100× on hot reads | Invalidation, stampedes, stale data |
| 5. Partitioning (one node) | Tables > hundreds of GB, retention by time | Pruning, cheap DROP/DETACH | Partition key in queries and unique keys |
| 6. Functional (vertical) partitioning | Distinct table groups compete for one primary | Separate primaries per domain | Cross-database joins and transactions disappear |
| 7. Sharding (horizontal) | Writes or data exceed the biggest primary | Linear write scale | Shard key forever; cross-shard queries; resharding |
| 8. Distributed SQL / purpose-built store | Need both SQL and scale-out, or a pattern the RDBMS cannot serve | Automatic sharding and replication | Latency per transaction, cost, new failure modes |
Sequence (the URL shortener climbing):
1 year 1 one PostgreSQL primary + PgBouncer; 600 GB rungs 0-2
2 year 1 redirects 19k/s: Redis cache-aside, 2 replicas rungs 3-4
3 year 2 clicks table 2 TB: monthly partitions, drop >13 mo rung 5
4 year 3 10x links: shard links by hash(code) into 16 logical rung 7
shards on 4 hosts (or move AP1 to DynamoDB)Real scenarios: Notion chose 480 logical shards because "480 is divisible by a lot of numbers — which provides flexibility to add or remove physical hosts while preserving uniform shard distribution", ending with "32 physical databases, each containing 15 logical shards"; Instagram's IDs embed "13 bits that represent the logical shard ID", so the shard is derivable from any ID; Shopify's Shop app moved to Vitess where "Sharded keyspaces require a sharding key to be defined for each table which determines what shard a row will be stored on."
| Product | Built-in rung 5 | Rung 7 option |
|---|---|---|
| PostgreSQL | Declarative partitioning | Citus, application sharding, FDW |
| MySQL | Partitioning | Vitess, application sharding |
| SQL Server / Oracle | Table partitioning | Oracle Sharding; application sharding |
| MongoDB | — | Native sharding (hashed or ranged shard key) |
| CockroachDB / Spanner | Automatic ranges/splits | Built in |
| Cassandra / DynamoDB | Partition key | Built in |
Fix / how to use it: write the trigger metric and threshold for each rung into the design document. "We add a replica when primary CPU from reads exceeds 50% at peak" is a plan; "we will scale horizontally" is not.
The consistency menu Must-know
In plain words: decide, per operation, how fresh a read must be and how safe a write must be, then route each operation to the cheapest place that meets it: the primary, a replica, a cache, or a quorum.
Common misunderstanding: "Our system is strongly consistent" or "our system is eventually consistent", as one property of the whole system. A real design mixes them: stock decrement on the primary under a lock, the product page from a 5-second cache, the order history from a replica with read-your-writes for the buyer.
Definition (the menu, strongest to weakest; full models in Eventual Consistency in Database Systems):
| Guarantee | What the reader sees | Typical mechanism | Use for |
|---|---|---|---|
| Strict serializable / linearizable | The latest committed write, in real-time order | Single primary; Spanner TrueTime; consensus reads | Money movement, stock, uniqueness |
| Serializable (one database) | Result equals some serial order | PostgreSQL SSI, InnoDB/SQL Server 2PL, CockroachDB default | Multi-row business rules |
| Read-your-writes | Your own writes, maybe not others' | Pin user to primary after a write; wait for LSN/GTID on replica | Profile edits, "my orders" |
| Monotonic reads | Never older than what you saw before | Sticky replica per session | Timelines, paging |
| Bounded staleness | At most N seconds or versions old | Replica with lag check; cache TTL | Product pages, counters |
| Eventual | Converges if writes stop | Async replicas, caches, CDC copies, LWW in Cassandra | Feeds, analytics, search index |
Timeline (why per-operation matters):
Buyer (session S) Replica R (lag 800 ms)
1 POST /orders -> primary COMMIT (LSN 0/5A00)
2 GET /orders -> routed to R R has replayed 0/59F0: order missing
3 -- buyer sees "no orders" and pays again
fix: after a write, store LSN in the session; read from R only if R.replay_lsn >= 0/5A00,
else read from the primary (read-your-writes)Real scenarios: a double payment because "my orders" read from a lagging replica; a search index that shows a deleted product for 30 s (acceptable, eventual); a Cassandra chat that reads at ONE and briefly misses the message the user just sent (fixed by LOCAL_QUORUM writes and reads, R + W > RF).
| Product | Strong read | Weaker, cheaper read |
|---|---|---|
| PostgreSQL / MySQL | Primary | Replica (async; lag), hot_standby_feedback for long queries |
| MongoDB | readConcern: "majority" / "linearizable", readPreference: primary | readPreference: secondary, causal sessions for read-your-writes |
| DynamoDB | ConsistentRead: true (base table) | Default eventually consistent reads (half the read cost); GSIs are always eventual |
| Cassandra / ScyllaDB | QUORUM/LOCAL_QUORUM both sides | ONE, LOCAL_ONE |
| CockroachDB / Spanner | Default | Follower reads / stale reads with bounded staleness |
| Redis | Primary | Replicas are async; WAIT gives a best-effort count |
Fix / how to use it: add a "consistency" column to the access-pattern table and route each pattern accordingly; for every "strong" cell, name the mechanism (row lock, constraint, serializable transaction, conditional write).
HA, backup and multi-tenancy decisions Important
In plain words: decide how much committed data you may lose (RPO), how long you may be down (RTO), how you will get yesterday's data back after a bad DELETE, and whether customers share tables, schemas or whole databases.
Common misunderstanding: "We have replicas, so we have backups." A replica replays your DROP TABLE in milliseconds. High availability protects against machine loss; backups and point-in-time recovery protect against human and software error. You need both.
Definition:
| Decision | Options | Owner page |
|---|---|---|
| RPO for each data class | 0 (sync replica), seconds (async), minutes (WAL archive) | Backup, PITR & DR |
| RTO | Seconds (automatic failover: Patroni, RDS Multi-AZ, Orchestrator), minutes (manual), hours (restore) | Replication & Failover |
| Backups | Physical base backup + continuous WAL/binlog archive; logical dumps for portability; restore drills | Backup, PITR & DR |
| Topology | Single AZ, multi-AZ, multi-region active-passive, multi-region active-active | Distributed SQL |
| Tenancy | Pool (shared tables + tenant_id + RLS), bridge (schema per tenant), silo (database per tenant), cells/pods | Multi-Tenancy |
Sequence (a failover with async replication):
1 10:00:00.000 primary commits order 9001; replica has replayed up to order 8998
2 10:00:00.050 primary host dies
3 10:00:15 failover manager promotes replica (RTO ~15-30 s)
4 10:00:15 orders 8999-9001 are gone (RPO > 0); customers have confirmation emails
fix: synchronous standby for orders (PostgreSQL synchronous_commit=on + synchronous_standby_names,
MySQL semi-sync AFTER_SYNC), or reconcile from the payment provider by idempotency keyReal scenarios: Shopify isolates failures with pods: "A pod consists of a set of shops that live on a fully isolated set of datastores", and its Pod Mover moves a pod to its recovery data centre; a SaaS with one shared database for all tenants restores the whole database to undo one tenant's mistake; a team discovers in an incident that its backups were never restored and the WAL archive had a gap.
| Product | HA mechanism | PITR mechanism |
|---|---|---|
| PostgreSQL | Streaming replication + Patroni / cloud Multi-AZ | Base backup + WAL archive (pgBackRest, WAL-G), recovery_target_time |
| MySQL | Group Replication / InnoDB Cluster, semi-sync + Orchestrator | Backup (XtraBackup/MySQL Enterprise Backup) + binlog replay |
| SQL Server | Always On availability groups | Full + log backups, STOPAT |
| Oracle | Data Guard, RAC | RMAN + archived redo logs |
| MongoDB | Replica set elections | Oplog-based PITR (Atlas, Ops Manager) |
| CockroachDB / Spanner | Raft/Paxos replicas | Backups with revision history / PITR versions |
| Cassandra / ScyllaDB | RF=3 across racks/DCs | Snapshots + incremental backups (nodetool), Scylla Manager |
| DynamoDB | Multi-AZ built in; global tables | PITR (continuous backups, 35 days) |
Fix / how to use it: write RPO and RTO per data class (orders 0/30 s, clicks 1 min/1 h), choose the mechanism, and schedule a restore drill. For tenancy, start pooled with tenant_id leading every index and RLS as a backstop; move the largest tenants to silos or cells when one tenant can hurt the others.
Capacity headroom Important
In plain words: never plan to run near 100% of anything; leave room for peaks, failover, maintenance and growth until the next upgrade can be delivered.
Common misunderstanding: "The database is at 50% CPU, so we can double traffic." Queueing delay grows non-linearly with utilisation: as utilisation approaches 100%, wait time goes towards infinity. And after a failover, the survivors carry the dead node's load.
Definition: headroom = capacity − peak load, expressed as a time-to-exhaustion at the current growth rate. Rules of thumb used in capacity reviews:
| Resource | Plan to stay below at peak | Why |
|---|---|---|
| CPU | 60–70% | Latency knee; room for vacuum, backups, failover |
| Disk space | 70–80% | Compaction, index rebuilds, WAL bursts, VACUUM FULL needs a copy |
| Connections | 70% of max_connections | Deploy storms, retries |
| IOPS / throughput | 70% of provisioned | Checkpoints and compaction spikes |
| Memory (Redis) | maxmemory with 20–30% slack | Fork for RDB/AOF rewrite copies pages |
| N+1 | Each AZ/node can absorb one peer's load | Failover doubles load on survivors |
Sequence:
1 now: primary CPU 45% at peak; traffic +8%/month
2 months to 70%: log(70/45)/log(1.08) = 5.7 months
3 lead time for next rung (replica + routing): 2 months
4 => trigger the work at month 3; record in the capacity planReal scenarios: a Black Friday where the replica that served reports is promoted and the reports now run on the primary; a Cassandra cluster at 85% disk that cannot compact; a Redis cache at 95% memory whose BGSAVE fork triggers the OOM killer.
Fix / how to use it: state headroom as "months until threshold" per resource in the design; alert on the threshold, not on 100%.
Cost estimation Important
In plain words: the sizing sheet also prices the design: compute, storage times copies, I/O, backups, network egress and cross-zone replication, licences, and the people who run it.
Common misunderstanding: "Storage is cheap, keep everything." Hot storage on replicated SSD costs several times object storage per GB, every byte is stored on every replica and in every backup, and a large table makes every migration, vacuum and restore slower.
Definition (monthly cost model):
cost = Σ instances × hours × price/hour
+ GB × copies × price/GB-month (hot) + archived GB × price/GB-month (cold)
+ provisioned IOPS/throughput
+ backup GB × retention
+ egress GB + cross-AZ/region replication GB
+ licences (SQL Server, Oracle, enterprise tooling)
+ people (on-call, DBA time) -- usually the largest line for self-managed clusters| Line | URL shortener year 1 (illustrative round numbers, not a quote) |
|---|---|
| Primary + 2 replicas, 16 vCPU / 64 GB each | 3 instances × 730 h × instance price |
| Hot storage | 600 GB × 3 copies = 1.8 TB SSD |
| Backups | base backups + WAL ≈ 1–2× database size in object storage |
| Redis | one 8–16 GB node + replica |
| Egress | ~1.9 MB/s average (10 MB/s at peak) ≈ 5 TB/month (often the surprise line at a CDN or load balancer) |
Sequence: compute the cost at 1×, 10× and 100× and look at which line grows fastest; that line decides the next design change (for chat it is storage × RF, for the shortener it is egress and cache).
Real scenario: DynamoDB on-demand vs provisioned: a spiky workload is cheaper on on-demand, a flat one on provisioned with auto scaling; eventually consistent reads cost half of strongly consistent reads, so the consistency menu is also a cost menu.
Fix / how to use it: put one cost line per environment in the design, with the unit prices and the date you looked them up; revisit when the sizing sheet changes.
Schema evolution plan Good to know
In plain words: decide on day one how the schema will change without downtime: every change is additive first (expand), the code moves, then the old shape is removed (contract).
Common misunderstanding: "Schemaless databases do not need migrations." A document store moves the migration into the application: every reader must handle every historical shape, forever, unless you backfill. A schemaVersion field and a lazy or batch upgrade is a migration plan.
Definition: the expand/contract (parallel change) pattern: add nullable column or new table → dual-write → backfill in batches → switch reads → stop writing the old → drop. Online DDL per engine: PostgreSQL CREATE INDEX CONCURRENTLY, ADD COLUMN with a constant default is metadata-only since PostgreSQL 11, NOT VALID constraints then VALIDATE CONSTRAINT; MySQL ALGORITHM=INSTANT / INPLACE, gh-ost, pt-online-schema-change; Vitess and PlanetScale coordinate DDL across shards. Full playbook: Zero-Downtime Schema Migrations.
1 deploy A: ADD COLUMN orders.currency text NULL (expand, instant)
2 deploy B: app writes currency on new orders
3 job: UPDATE orders SET currency='EUR' WHERE id BETWEEN ... (batches of 10k)
4 deploy C: ALTER ... SET NOT NULL via CHECK (currency IS NOT NULL) NOT VALID; VALIDATE
5 deploy D: app reads currency everywhere; old code path removed (contract)Real scenarios: Shopify's Shop app saw "schema migrations would take weeks" on a multi-terabyte MySQL before Vitess; a NOT NULL column added with a volatile default rewrote a 500 GB table under an ACCESS EXCLUSIVE lock.
Fix / how to use it: in the design, name the migration tool (Laravel migrations, goose/atlas/golang-migrate for Go, or the embedded runner in this page's snippets), the batch size for backfills, and who reviews DDL that takes strong locks.
Observability plan Important
In plain words: decide which numbers tell you the design still holds: latency and errors per access pattern, saturation of each resource on the scale ladder, replication lag, and the business invariants.
Common misunderstanding: "CPU and disk graphs are database monitoring." They tell you the machine is busy, not which query, which tenant or which invariant is in trouble.
Definition: three layers. (1) Golden signals per access pattern (latency, traffic, errors, saturation) from the application. (2) Database internals: pg_stat_statements, pg_stat_activity, pg_stat_replication, buffer cache hit ratio, deadlocks and 40001 counts, autovacuum progress, InnoDB SHOW ENGINE INNODB STATUS, Performance Schema, slow query log, MongoDB profiler, Cassandra nodetool tablestats and partition size histograms. (3) Invariant checks: reconciliation queries ("stock + sold = received", "orders paid without a payment record"). Details: Database Observability.
1 alert p99(AP1 redirect) > 50 ms for 5 min
2 look cache hit ratio 97% -> 70% (a viral link expired from cache?)
3 look pg_stat_statements: AP1 calls x10, mean 2 ms -> replicas saturated
4 act raise TTL / Cache::flexible, add request coalescing; capacity reviewReal scenario: Discord saw that "One channel and bucket pair received a large amount of traffic, and latency in the node would increase as the node tried harder and harder to serve traffic"; per-partition metrics, not cluster averages, found it.
Fix / how to use it: for every access pattern in the table, name its SLI and alert; for every rung trigger, name its metric; for every invariant, name a reconciliation query and a schedule.
Per-product behaviour
What each product gives a designer, with defaults named. Use it after the access-pattern table, not before.
| Product | Model | Scale-out story | Default consistency / isolation | HA | Sweet spot |
|---|---|---|---|---|---|
| PostgreSQL | Relational + JSONB, extensions | Replicas; partitioning; Citus or app sharding | Read Committed; SSI available | Streaming replication + Patroni / managed | General OLTP up to multi-TB, rich queries |
| MySQL InnoDB | Relational | Replicas; Vitess for sharding | Repeatable Read | Semi-sync, Group Replication | Web OLTP, huge sharded fleets |
| SQL Server | Relational | Read replicas (AGs), partitioning | Read Committed (RCSI optional) | Always On AGs | Enterprise OLTP + reporting |
| Oracle | Relational | RAC, partitioning, Oracle Sharding | Read Committed | Data Guard | Enterprise OLTP |
| SQLite | Embedded relational | None (one writer) | Serializable | File copy, Litestream | Edge, mobile, single-node apps |
| MongoDB | Document | Native sharding | Read concern local, write concern majority (default since 5.0) | Replica sets | Aggregates with evolving shape |
| CockroachDB | Distributed SQL | Automatic range splitting | Serializable | Raft | SQL + scale-out + multi-region |
| Spanner | Distributed SQL | Automatic splits | Strict serializable (external consistency) | Paxos | Global strong consistency |
| Redis | In-memory KV + structures | Redis Cluster (16384 hash slots) | Async replication | Sentinel / Cluster | Cache, counters, timelines, rate limits |
| Cassandra / ScyllaDB | Wide-column | Built-in partitioning, multi-DC | Tunable per query (ONE…ALL) | RF across racks/DCs | Massive append-mostly writes |
| DynamoDB | Key-value / document | Automatic partitions | Eventually consistent reads by default | Multi-AZ, global tables | Known access patterns, serverless scale |
| Elasticsearch / OpenSearch | Search | Shards + replicas | Near real-time (refresh interval) | Replica shards | Text search, facets (not source of truth) |
| Neo4j | Graph | Read replicas; Fabric/sharding in enterprise | ACID on primary | Clustering | Multi-hop traversals |
| TimescaleDB / ClickHouse | Time-series / columnar | Hypertables / distributed tables | Batch inserts | Replicas | Metrics, events, analytics |
Mechanics: the arithmetic underneath
Latency numbers and round-trip budgets Must-know
From Norvig's table (quoted verbatim in the source) and the Berkeley model:
| Operation | Time | Source |
|---|---|---|
| fetch from L1 cache memory | 0.5 ns | Norvig |
| fetch from L2 cache memory | 7 ns | Norvig |
| Mutex lock/unlock | 25 ns | Norvig |
| fetch from main memory | 100 ns | Norvig |
| send 2K bytes over 1Gbps network | 20,000 ns (20 µs) | Norvig |
| read 1MB sequentially from memory | 250,000 ns (250 µs) | Norvig |
| round trip within same data centre | 500,000 ns (0.5 ms) | Berkeley model source |
| fetch from new disk location (seek) | 8 ms | Norvig |
| read 1MB sequentially from disk | 20 ms | Norvig |
| send packet US to Europe and back | 150 ms | Norvig; Berkeley WAN RTT |
Budget rule: a p99 of 50 ms with a 0.5 ms in-DC round trip allows many round trips, but each N+1 query loop, each synchronous call to another service and each cross-region hop eats it fast. A cross-region synchronous commit costs ~150 ms by physics before any work.
Little's Law: connections and concurrency Must-know
L = λ × W: the average number of requests in the system equals arrival rate times time in system. For a database: busy connections = queries/s × mean query time.
1 AP1 redirects that miss the cache: 19,300/s x 3% miss = 580 queries/s
2 mean query time 2 ms -> 580 x 0.002 = 1.2 busy connections on average
3 checkout: 230 tx/s x 15 ms per transaction = 3.5 busy connections
4 => a pool of 20-30 server connections (PgBouncer, transaction mode) is plenty;
1,000 app processes each holding a connection is the real dangerSee Connection Pooling.
Hot rows and the per-row throughput ceiling Must-know
A row updated by every transaction serialises them: throughput on that row ≤ 1 / lock hold time. If the stock row is locked from the UPDATE until COMMIT and that takes 5 ms (remaining statements + WAL flush), the ceiling is ~200 updates/s for that product, whatever the hardware.
| Fix | How | Cost |
|---|---|---|
| Shorten the hold | Do the decrement last, right before COMMIT; keep the transaction free of network calls | Code order matters |
| Split the counter | inventory_buckets(product_id, bucket, available); decrement a random bucket with stock | Reads sum buckets; rebalancing |
| Pre-allocate tokens | Redis DECR gate in front, DB confirms | Two systems; reconcile on crash |
| Group commit / batching | Queue requests, apply in batches | Latency for throughput |
Fan-out arithmetic Important
Fan-out on write cost = posts/s × average followers. Fan-out on read cost = feed reads/s × followees per reader (bounded by merge limits). Celebrity cost = followers of one account per post. With 58 posts/s and 200 followers: 11.6k timeline inserts/s; one account with 10M followers adds 10M inserts per post, minutes of lag at 50k inserts/s. Hence the hybrid in sketch 3.
Code-space and collision arithmetic Good to know
62^7 = 3.52 × 10^12 codes. After five years at 1.2B/year (6 × 10^9 used), a fresh random code collides with probability 6e9 / 3.52e12 ≈ 0.17%, so retrying on conflict costs almost nothing. Counter-based codes (sequence or Snowflake → base62) never collide but are guessable unless shuffled; see ID Generation.
Knobs a design names explicitly Important
| Knob | Product | Design decision it encodes |
|---|---|---|
shared_buffers, effective_cache_size | PostgreSQL | Working set in memory |
innodb_buffer_pool_size | MySQL | Working set in memory (often 50–75% of RAM on a dedicated host) |
max_connections; PgBouncer pool_mode, default_pool_size | PostgreSQL | Concurrency limit (Little's Law) |
synchronous_commit, synchronous_standby_names | PostgreSQL | RPO 0 for chosen data |
rpl_semi_sync_source_wait_point = AFTER_SYNC | MySQL | Lossless semi-sync |
statement_timeout, idle_in_transaction_session_timeout, lock_timeout | PostgreSQL | Bound damage of slow or stuck work |
innodb_lock_wait_timeout | MySQL | Same, for row locks |
default_time_to_live, gc_grace_seconds, compaction strategy | Cassandra / ScyllaDB | Retention and tombstone lifetime |
maxmemory, maxmemory-policy | Redis | Cache size and eviction (allkeys-lru, volatile-ttl) |
readConcern, writeConcern, readPreference | MongoDB | Consistency menu per operation |
| Provisioned vs on-demand capacity | DynamoDB | Cost model and throttling behaviour |
Error codes the design must handle Must-know
| Error | Product | Meaning | Design response |
|---|---|---|---|
40001 serialization_failure | PostgreSQL, CockroachDB | Serializable/RR conflict | Retry whole transaction |
40P01 deadlock_detected | PostgreSQL | Deadlock victim | Retry; fix lock order |
23505 unique_violation | PostgreSQL | Duplicate key | Business answer (idempotent replay, "taken") |
23514 check_violation | PostgreSQL | Invariant (e.g. available >= 0) | Reject; investigate if reached |
53300 too_many_connections | PostgreSQL | Connection limit | Pooler, backoff |
57014 query_canceled | PostgreSQL | statement_timeout fired | Fail fast; investigate query |
1213 ER_LOCK_DEADLOCK | MySQL | Deadlock | Retry |
1205 ER_LOCK_WAIT_TIMEOUT | MySQL | Lock wait timeout | Retry or fail |
1062 ER_DUP_ENTRY | MySQL | Duplicate key | Business answer |
1040 Too many connections | MySQL | Connection limit | Pooler |
ProvisionedThroughputExceededException | DynamoDB | Partition or table throttled | Backoff; fix hot key |
ConditionalCheckFailedException | DynamoDB | Condition false (e.g. stock) | Business answer |
WriteTimeoutException / UnavailableException | Cassandra | Not enough replicas answered | Retry idempotent writes; check consistency level |
OOM command not allowed when used memory > 'maxmemory' | Redis | Memory full with noeviction | Eviction policy or more memory |
Solving it: the three worked sketches
Each sketch follows the method: requirements → access patterns → numbers → model → schema and indexes → key queries → code → scaling path → failure analysis. The SQL is PostgreSQL; MySQL differences are named where they matter. The Go code uses database/sql (register github.com/jackc/pgx/v5/stdlib), the Laravel code uses Laravel 13's query builder.
Sketch 1: URL shortener
Requirements. 100M new links/month (+50%/year), ~100 redirects per link (100:1), redirect p99 ≤ 50 ms server-side, create p99 ≤ 200 ms, a redirect may be seconds stale but a deleted link must stop within one minute, links kept 5 years unless they expire earlier, clicks per link per day kept 13 months, GDPR erasure of an owner's links.
Access patterns.
| # | Pattern | Key / filter | Rows | Peak/s | Consistency |
|---|---|---|---|---|---|
| AP1 | Redirect GET /:code | code | 1 | 19,300 | Bounded staleness (cache TTL, delete invalidates) |
| AP2 | Create POST /links | owner_id, url_hash | 1 | 190 | Strong (unique code; idempotent per owner + URL) |
| AP3 | My links | owner_id, newest first | 50 | 20 | Read-your-writes |
| AP4 | Clicks per day | code, day range | ≤ 400 | 5 | Eventual (minutes) |
| AP5 | Expire / erase | expires_at < now(), owner_id | batches | 1/min | — |
Numbers. From the sizing sheet: 190 writes/s and 19,300 reads/s at peak; ~500 B per link including indexes; 600 GB per copy per year, 3 TB after 5 years; ~10 MB/s egress; a 5 GB hot set. Clicks: 19,300/s at peak must not become 19,300 row writes/s.
Model. The hot path is a pure key-value lookup, which every store does well. Year 1 fits one PostgreSQL primary with two replicas and Redis in front; PostgreSQL also gives the unique constraints that make AP2 idempotent. The natural year-3 alternative is DynamoDB (PK = code, conditional put attribute_not_exists(PK)) or Cassandra, because nothing in AP1/AP2 needs joins.
The diagram shows the read path (Redis first, replica on a miss), the write path (primary), the click path (counted in a buffer, flushed as one upsert per code per day) and the expiry sweeper.
Schema and indexes (the migration the Go runner embeds):
-- 0001: URL shortener (PostgreSQL 13+)
CREATE TABLE links (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
code varchar(10) NOT NULL,
owner_id bigint NOT NULL,
long_url text NOT NULL CHECK (length(long_url) <= 2048),
url_hash char(64) NOT NULL, -- hex sha256 of the normalised URL
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz,
CONSTRAINT links_code_uk UNIQUE (code), -- the redirect lookup
CONSTRAINT links_owner_url_uk UNIQUE (owner_id, url_hash) -- same owner + URL -> same code
);
-- AP3 "my links, newest first" with keyset pagination.
CREATE INDEX links_owner_created_idx ON links (owner_id, created_at DESC, id DESC);
-- Expiry sweeper only scans rows that can expire.
CREATE INDEX links_expires_at_idx ON links (expires_at) WHERE expires_at IS NOT NULL;
-- Clicks are aggregated in memory or Redis and flushed here, never one row per click.
CREATE TABLE link_clicks_daily (
code varchar(10) NOT NULL,
day date NOT NULL,
clicks bigint NOT NULL DEFAULT 0,
PRIMARY KEY (code, day)
);Key queries.
-- AP1 redirect (index seek on links_code_uk)
SELECT long_url FROM links WHERE code = $1 AND (expires_at IS NULL OR expires_at > now());
-- AP2 create: one statement, no race; nothing returned = owner+URL exists or code collided
INSERT INTO links (code, owner_id, long_url, url_hash) VALUES ($1, $2, $3, $4)
ON CONFLICT DO NOTHING RETURNING code;
-- AP3 my links, keyset pagination (links_owner_created_idx)
SELECT code, long_url, created_at FROM links
WHERE owner_id = $1 AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC LIMIT 50;
-- AP4 click rollup flush
INSERT INTO link_clicks_daily (code, day, clicks) VALUES ($1, $2, $3)
ON CONFLICT (code, day) DO UPDATE SET clicks = link_clicks_daily.clicks + EXCLUDED.clicks;
-- AP5 expiry in batches (partial index), then invalidate the cache keys returned
DELETE FROM links WHERE id IN (
SELECT id FROM links WHERE expires_at < now() ORDER BY expires_at LIMIT 1000)
RETURNING code;MySQL: INSERT IGNORE or INSERT ... ON DUPLICATE KEY UPDATE id = id replaces ON CONFLICT DO NOTHING, and there are no partial indexes (index expires_at fully). AP3 is served by links_owner_created_idx; the unique (owner_id, url_hash) index cannot serve that sort. A B-tree scanned backwards serves DESC, so the Laravel index without explicit DESC works too.
Go: create, resolve with cache-aside and negative caching (TTL capped at 60 s and at expires_at), delete with invalidation after commit, and batched click counting.
// Package main sketches the URL shortener's data access: create a code
// (idempotent per owner and URL, collision-safe), resolve it through a
// cache-aside layer with negative caching, and batch click counters.
package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"errors"
"log"
"math/big"
"os"
"strings"
"sync"
"time"
)
const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// codeLen 7 gives 62^7 = 3.5e12 codes: about 2,900 years of 100M links per month.
const codeLen = 7
var ErrNotFound = errors.New("link not found or expired")
// maxTTL bounds staleness: a deleted or changed link stops redirecting within a minute
// even if an invalidation is lost or races with a reader that refills the cache.
const maxTTL = time.Minute
// Cache is the slice of Redis (or any KV cache) the shortener needs.
type Cache interface {
Get(ctx context.Context, key string) (val string, ok bool, err error)
Set(ctx context.Context, key, val string, ttl time.Duration) error
Del(ctx context.Context, key string) error
}
type Store struct {
db *sql.DB
cache Cache
}
// EncodeBase62 turns a numeric ID (sequence or Snowflake) into a short code.
// Sequential IDs give guessable codes; use randomCode when that matters.
func EncodeBase62(n uint64) string {
if n == 0 {
return "0"
}
var b []byte
for n > 0 {
b = append(b, alphabet[n%62])
n /= 62
}
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func randomCode() (string, error) {
var sb strings.Builder
max := big.NewInt(int64(len(alphabet)))
for i := 0; i < codeLen; i++ {
k, err := rand.Int(rand.Reader, max)
if err != nil {
return "", err
}
sb.WriteByte(alphabet[k.Int64()])
}
return sb.String(), nil
}
func urlHash(normalised string) string {
sum := sha256.Sum256([]byte(normalised))
return hex.EncodeToString(sum[:])
}
// Create returns the existing code when this owner already shortened this URL,
// and retries on the rare random-code collision.
func (s *Store) Create(ctx context.Context, ownerID int64, longURL string) (string, error) {
normalised := strings.TrimSpace(longURL)
hash := urlHash(normalised)
for attempt := 0; attempt < 5; attempt++ {
code, err := randomCode()
if err != nil {
return "", err
}
var got string
err = s.db.QueryRowContext(ctx, `
INSERT INTO links (code, owner_id, long_url, url_hash)
VALUES ($1, $2, $3, $4)
ON CONFLICT DO NOTHING
RETURNING code`, code, ownerID, normalised, hash).Scan(&got)
if err == nil {
return got, nil
}
if !errors.Is(err, sql.ErrNoRows) {
return "", err
}
// Nothing inserted: either (owner_id, url_hash) exists, or the code collided.
err = s.db.QueryRowContext(ctx,
`SELECT code FROM links WHERE owner_id = $1 AND url_hash = $2`, ownerID, hash).Scan(&got)
if err == nil {
return got, nil // idempotent: same owner + same URL -> same code
}
if !errors.Is(err, sql.ErrNoRows) {
return "", err
}
// Code collision: loop and try a new random code.
}
return "", errors.New("could not allocate a unique code after 5 attempts")
}
// Resolve is the hot path: ~20k/s at peak, served mostly from the cache.
func (s *Store) Resolve(ctx context.Context, code string) (string, error) {
key := "link:" + code
if v, ok, err := s.cache.Get(ctx, key); err == nil && ok {
if v == "" {
return "", ErrNotFound // negative cache entry
}
return v, nil
}
// Cache miss or cache down: fall through to the database (a replica is fine here).
var longURL string
var expiresAt sql.NullTime
err := s.db.QueryRowContext(ctx, `
SELECT long_url, expires_at FROM links
WHERE code = $1 AND (expires_at IS NULL OR expires_at > now())`, code).Scan(&longURL, &expiresAt)
switch {
case errors.Is(err, sql.ErrNoRows):
_ = s.cache.Set(ctx, key, "", maxTTL) // negative entry: stop scanners hammering the DB
return "", ErrNotFound
case err != nil:
return "", err
}
ttl := maxTTL
if expiresAt.Valid && time.Until(expiresAt.Time) < ttl {
ttl = time.Until(expiresAt.Time) // never serve a link past its expiry
}
_ = s.cache.Set(ctx, key, longURL, ttl)
return longURL, nil
}
// Delete removes the link, then invalidates the cache AFTER the delete committed.
// A reader that refilled the key in between is bounded by maxTTL.
func (s *Store) Delete(ctx context.Context, ownerID int64, code string) error {
res, err := s.db.ExecContext(ctx,
`DELETE FROM links WHERE owner_id = $1 AND code = $2`, ownerID, code)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return s.cache.Del(ctx, "link:"+code)
}
// ClickBuffer aggregates clicks in memory and flushes one upsert per code per day,
// turning 20k writes/s into a few hundred.
type ClickBuffer struct {
mu sync.Mutex
counts map[string]int64
}
func NewClickBuffer() *ClickBuffer { return &ClickBuffer{counts: map[string]int64{}} }
func (b *ClickBuffer) Add(code string) {
b.mu.Lock()
b.counts[code]++
b.mu.Unlock()
}
func (b *ClickBuffer) Flush(ctx context.Context, db *sql.DB, day time.Time) error {
b.mu.Lock()
batch := b.counts
b.counts = map[string]int64{}
b.mu.Unlock()
for code, n := range batch {
if _, err := db.ExecContext(ctx, `
INSERT INTO link_clicks_daily (code, day, clicks) VALUES ($1, $2, $3)
ON CONFLICT (code, day) DO UPDATE SET clicks = link_clicks_daily.clicks + EXCLUDED.clicks`,
code, day.Format("2006-01-02"), n); err != nil {
return err // at-least-once is acceptable for analytics; callers may re-add
}
}
return nil
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Println("demo:", EncodeBase62(1_000_000_000), "is the code for ID 1e9")
return
}
}Laravel: migration and service. insertOrIgnore compiles to ON CONFLICT DO NOTHING on PostgreSQL and INSERT IGNORE on MySQL; Cache::flexible serves the stale value while one request recomputes it, which is the stampede protection AP1 needs.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('links', function (Blueprint $table) {
$table->id();
$table->string('code', 10)->unique(); // redirect lookup
$table->unsignedBigInteger('owner_id');
$table->text('long_url');
$table->char('url_hash', 64); // hex sha256 of the normalised URL
$table->timestampTz('created_at')->useCurrent();
$table->timestampTz('expires_at')->nullable();
$table->unique(['owner_id', 'url_hash']); // same owner + URL -> same code
$table->index(['owner_id', 'created_at', 'id']); // AP3: my links, newest first
});
if (DB::connection()->getDriverName() === 'pgsql') {
// Partial index: the schema builder has no WHERE clause for indexes.
DB::statement('CREATE INDEX links_expires_at_idx ON links (expires_at) WHERE expires_at IS NOT NULL');
} else {
Schema::table('links', fn (Blueprint $table) => $table->index('expires_at'));
}
Schema::create('link_clicks_daily', function (Blueprint $table) {
$table->string('code', 10);
$table->date('day');
$table->unsignedBigInteger('clicks')->default(0);
$table->primary(['code', 'day']);
});
}
public function down(): void
{
Schema::dropIfExists('link_clicks_daily');
Schema::dropIfExists('links');
}
};<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use RuntimeException;
final class LinkService
{
/** Same owner + same URL returns the same code; random-code collisions are retried. */
public function create(int $ownerId, string $longUrl): string
{
$normalised = trim($longUrl);
$hash = hash('sha256', $normalised);
for ($attempt = 0; $attempt < 5; $attempt++) {
$code = Str::random(7); // [A-Za-z0-9]: base62, 62^7 = 3.5e12 codes
$inserted = DB::table('links')->insertOrIgnore([
'code' => $code,
'owner_id' => $ownerId,
'long_url' => $normalised,
'url_hash' => $hash,
]);
if ($inserted === 1) {
return $code;
}
// Nothing inserted: either this owner already has this URL, or the code collided.
$existing = DB::table('links')
->where('owner_id', $ownerId)
->where('url_hash', $hash)
->value('code');
if ($existing !== null) {
return $existing;
}
}
throw new RuntimeException('Could not allocate a unique short code.');
}
/**
* Hot path. Cache::flexible serves a stale value while one request refreshes it.
* Fresh for 30 s, stale-but-served up to 60 s: a deleted link stops within a minute.
*/
public function resolve(string $code): ?string
{
$url = Cache::flexible("link:{$code}", [30, 60], function () use ($code) {
return DB::table('links')
->where('code', $code)
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
->value('long_url') ?? ''; // '' is cached too: a negative entry
});
return $url === '' ? null : $url;
}
/** Delete first, then forget the cache key: the delete is committed before invalidation. */
public function delete(int $ownerId, string $code): bool
{
$deleted = DB::table('links')->where('owner_id', $ownerId)->where('code', $code)->delete() === 1;
if ($deleted) {
Cache::forget("link:{$code}");
}
return $deleted;
}
/** One HINCRBY per click; a scheduled job flushes the hash into PostgreSQL. */
public function recordClick(string $code): void
{
Redis::hincrby('clicks:'.now()->toDateString(), $code, 1);
}
public function flushClicks(string $day): void
{
$key = "clicks:{$day}";
$work = "{$key}:flushing";
if (! Redis::exists($key)) {
return;
}
Redis::rename($key, $work); // new clicks go to a fresh hash while we flush
foreach (Redis::hgetall($work) as $code => $clicks) {
DB::statement(
'INSERT INTO link_clicks_daily (code, day, clicks) VALUES (?, ?, ?)
ON CONFLICT (code, day) DO UPDATE SET clicks = link_clicks_daily.clicks + EXCLUDED.clicks',
[$code, $day, (int) $clicks],
);
}
Redis::del($work);
}
}302 or 301? A 301 Moved Permanently is cached by browsers, so repeat clicks never reach you: cheaper, but you lose click counts and cannot change or delete the target for that browser. Most shorteners answer 302 Found (or 307) and let the CDN cache for a short TTL.
Scaling path.
| Load | Change | Trigger |
|---|---|---|
| 1× (19k redirects/s) | One primary + 2 replicas + Redis; PgBouncer | — |
| 10× (190k/s, 6 TB/year) | Redis Cluster; CDN caching of redirects (short TTL); clicks to Kafka → ClickHouse; monthly partitions for click rollups | Replica CPU > 50%; Redis memory > 70% |
| 100× | Shard links by hash(code) into logical shards (Notion-style 480) or move AP1/AP2 to DynamoDB/Cassandra; owner index as a separate table keyed by owner_id | Primary write IOPS or storage > biggest instance |
Failure analysis.
| Failure | Effect | Mitigation |
|---|---|---|
| Viral link expires from cache | Thousands of misses at once (cache stampede / thundering herd) | Cache::flexible / stale-while-revalidate, request coalescing (singleflight), jittered TTLs |
| Redis down | All 19k/s hit replicas | Replicas sized for it, or degrade: in-process LRU for the top 10k codes |
| Primary failover (~30 s) | Creates fail; redirects continue from cache and replicas | Clients retry AP2 with the same URL (idempotent) |
| Scanner enumerating codes | Misses flood the DB | Negative caching, rate limits per IP, random (non-sequential) codes |
| Deleted link still redirects | Cache TTL; a reader refilling the key just before the delete | Delete key after commit; cap TTL at 60 s (maxTTL in Go, Cache::flexible(..., [30, 60]) in Laravel) and at expires_at |
| Click flush fails | Undercount | At-least-once flush with retry; analytics accepts small error |
Sketch 2: Order / inventory system
Requirements. 1M orders/day (average 3 lines), flash sales at 20× normal on a handful of SKUs, never oversell, per-customer purchase limits on limited items ("max 2 per customer"), a retried checkout must not create a second order, unpaid orders release stock after 15 minutes, order history 7–10 years (confirm with finance and the applicable tax law), PCI DSS scope kept out of this database (card data stays at the payment provider).
Access patterns.
| # | Pattern | Key / filter | Peak/s | Consistency |
|---|---|---|---|---|
| AP1 | Place order (decrement stock, create order, emit event) | idempotency_key, product_ids | 230 | Strong, atomic |
| AP2 | Product page stock badge | product_id | 20,000 | Bounded staleness (5 s) |
| AP3 | My orders | customer_id, newest first | 200 | Read-your-writes |
| AP4 | Expire unpaid orders | status, expires_at | 10 batches/min | Strong |
| AP5 | Payment confirmed → paid | order_id | 230 | Strong, idempotent |
| AP6 | Reports (sales per day/SKU) | time range | low | Eventual (replica / OLAP) |
Numbers. 1M/day ÷ 86,400 = 11.6 orders/s; flash peak ×20 ≈ 230/s. Per order ≈ 12 row changes (order insert and update, 3 lines, 3 stock updates, outbox insert and mark, status change) → ~2,800 row changes/s at peak, comfortably one primary. ~2 KB per order with indexes → 2 GB/day → ~730 GB/year per copy. Reads: product pages ~100 per order → ~1.2k/s average, 20k/s in a flash sale → cache and replicas, never the primary.
Model. Relational: the top pattern is a multi-row transaction with invariants. PostgreSQL here; MySQL InnoDB works with the same statements (note InnoDB Repeatable Read is its default and does not stop lost updates on plain reads; the atomic update below is correct at any level).
One transaction does four things in a fixed order: locks the customer row, claims the idempotency key, decrements stock atomically per product in ascending id order, and writes lines plus an outbox row. The customer lock must come first: the orders insert's foreign key takes FOR KEY SHARE on the customer row, and two tabs that each hold KEY SHARE and then ask for FOR UPDATE deadlock (40P01) instead of queueing. A synchronous standby makes committed orders survive a primary loss; the relay publishes order.placed; the sweeper returns stock from unpaid orders without blocking checkouts.
Schema and indexes:
-- 0002: orders and inventory (PostgreSQL 13+)
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price_cents bigint NOT NULL CHECK (price_cents >= 0),
max_per_customer int NOT NULL DEFAULT 0 CHECK (max_per_customer >= 0) -- 0 = no limit
);
-- One row per product: the stock counter that every order decrements atomically.
CREATE TABLE inventory (
product_id bigint PRIMARY KEY REFERENCES products (id),
available int NOT NULL CHECK (available >= 0), -- last line of defence against oversell
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
idempotency_key uuid NOT NULL UNIQUE, -- client retry returns the same order
customer_id bigint NOT NULL REFERENCES customers (id),
status text NOT NULL DEFAULT 'pending_payment'
CHECK (status IN ('pending_payment', 'paid', 'shipped', 'cancelled', 'expired')),
total_cents bigint NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL DEFAULT now() + interval '15 minutes'
);
CREATE INDEX orders_customer_created_idx ON orders (customer_id, created_at DESC);
CREATE INDEX orders_pending_expiry_idx ON orders (expires_at) WHERE status = 'pending_payment';
CREATE TABLE order_lines (
order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
product_id bigint NOT NULL REFERENCES products (id),
qty int NOT NULL CHECK (qty > 0),
unit_price_cents bigint NOT NULL,
PRIMARY KEY (order_id, product_id)
);
CREATE INDEX order_lines_product_idx ON order_lines (product_id);
-- Transactional outbox: written in the same transaction as the order.
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
topic text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_unpublished_idx ON outbox (id) WHERE published_at IS NULL;The two concurrency bugs and their fixes (the anomalies are taught in Isolation Levels; here is how the design closes them).
Lost update (oversell). Read stock, decide in the application, write the new value:
T1 (order A, qty 1) T2 (order B, qty 1) -- PostgreSQL READ COMMITTED
1 BEGIN; BEGIN;
2 SELECT available FROM inventory WHERE product_id=7; -- 1
3 SELECT available FROM inventory WHERE product_id=7; -- 1
4 UPDATE inventory SET available = 0 WHERE product_id=7;
5 COMMIT;
6 UPDATE inventory SET available = 0 WHERE product_id=7; -- waits, then overwrites
7 COMMIT; -- two orders, one unit
fix: UPDATE inventory SET available = available - 1 WHERE product_id = 7 AND available >= 1;
-- T2 re-reads the committed row after T1, finds 0, updates 0 rows -> ErrOutOfStockWrite skew (purchase limit). Each transaction checks "this customer bought fewer than 2" and inserts a different order line; no row is written by both, so neither the atomic update nor a row lock on the lines helps:
T1 (tab 1: buy 1 of product 7) T2 (tab 2: buy 1 of product 7) -- limit 2, already bought 1
1 BEGIN; BEGIN;
2 SELECT sum(qty) ... customer 42, product 7; -- 1
3 SELECT sum(qty) ... customer 42, product 7; -- 1
4 1 + 1 <= 2 -> INSERT order_lines (order 501)
5 1 + 1 <= 2 -> INSERT order_lines (order 502)
6 COMMIT; COMMIT; -- customer now has 3
fix A (used here): SELECT 1 FROM customers WHERE id = 42 FOR UPDATE before the check
-- materialises the conflict: T2 waits at step 2 until T1 commits, then sees 2
fix B: run the transaction at SERIALIZABLE (PostgreSQL SSI) and retry on 40001
fix C: keep a counter row customer_product_purchases(customer_id, product_id, qty)
and UPDATE ... SET qty = qty + 1 WHERE ... AND qty + 1 <= 2 (atomic, like stock)| Bug | Fix in this design | Alternative | Why not only raise the level |
|---|---|---|---|
| Oversell (lost update) | Atomic conditional UPDATE, CHECK (available >= 0) | SELECT ... FOR UPDATE; version column | Atomic update is correct at Read Committed in every engine and costs no retries |
| Purchase limit (write skew) | Lock the customer row (FOR UPDATE) | Serializable + retry; counter row | Serializable works but adds 40001 retries on every checkout under load |
| Double submit | UNIQUE (idempotency_key) + ON CONFLICT DO NOTHING | Idempotency table with stored response (Stripe model) | Isolation cannot dedupe two separate requests |
| Deadlock between carts | Lock products in ascending product_id | Retry on 40P01 / 1213 | Ordering removes the cycle; retry is the safety net |
Stripe describes the idempotency key the design uses: "When performing a request, a client generates a unique ID to identify just that operation and sends it up to the server along with the normal payload." Its API docs add that keys "are up to 255 characters long" and suggest V4 UUIDs; this schema stores a uuid.
Key queries are in the Go and Laravel code; the stock-badge read (AP2) is SELECT available FROM inventory WHERE product_id = $1 on a replica, cached for 5 s, and the payment webhook (AP5) is UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'pending_payment' (0 rows = already paid or expired: idempotent).
Go: place an order and expire unpaid ones.
// Package main sketches the order/inventory write path on PostgreSQL:
// idempotent order creation, a per-customer purchase limit protected from
// write skew, oversell protected from lost updates, an outbox event, and
// a SKIP LOCKED sweeper that returns stock from unpaid orders.
package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"log"
"math/rand/v2"
"os"
"sort"
"time"
)
var (
ErrOutOfStock = errors.New("out of stock")
ErrLimitExceeded = errors.New("per-customer purchase limit exceeded")
)
type Line struct {
ProductID int64 `json:"product_id"`
Qty int `json:"qty"`
}
type PlaceOrder struct {
IdempotencyKey string // UUID sent by the client in the Idempotency-Key header
CustomerID int64
Lines []Line
}
// sqlState matches drivers that expose the SQLSTATE (pgx's *pgconn.PgError does).
type sqlState interface{ SQLState() string }
func retryable(err error) bool {
var e sqlState
if errors.As(err, &e) {
switch e.SQLState() {
case "40001", "40P01": // serialization_failure, deadlock_detected
return true
}
}
return false
}
// withTx runs fn in a transaction and retries the whole thing on 40001/40P01.
func withTx(ctx context.Context, db *sql.DB, opts *sql.TxOptions, fn func(*sql.Tx) error) error {
backoff := 10 * time.Millisecond
for attempt := 1; ; attempt++ {
tx, err := db.BeginTx(ctx, opts)
if err != nil {
return err
}
err = fn(tx)
if err == nil {
err = tx.Commit()
} else {
tx.Rollback()
}
if err == nil || !retryable(err) || attempt == 5 {
return err
}
sleep := backoff + time.Duration(rand.Int64N(int64(backoff))) // jitter
select {
case <-time.After(sleep):
case <-ctx.Done():
return ctx.Err()
}
backoff *= 2
}
}
// Place runs at READ COMMITTED. Correctness comes from three statements, not the level:
// 1. SELECT ... FOR UPDATE on the customer row, FIRST: serialises this customer's
// checkouts, so the "max N per customer" rule cannot be broken by write skew.
// It must come before the orders INSERT: that INSERT's foreign key takes
// FOR KEY SHARE on the customer row, and two tabs holding KEY SHARE that then
// both ask for FOR UPDATE deadlock (40P01).
// 2. INSERT ... ON CONFLICT (idempotency_key): a retried request returns the first order.
// 3. UPDATE inventory ... WHERE available >= qty: atomic decrement, no lost update.
func Place(ctx context.Context, db *sql.DB, req PlaceOrder) (orderID int64, err error) {
lines := append([]Line(nil), req.Lines...)
// Lock products in one global order (ascending id) so two carts cannot deadlock.
sort.Slice(lines, func(i, j int) bool { return lines[i].ProductID < lines[j].ProductID })
err = withTx(ctx, db, &sql.TxOptions{Isolation: sql.LevelReadCommitted}, func(tx *sql.Tx) error {
// Materialise the conflict: every checkout of this customer queues here.
if _, err := tx.ExecContext(ctx,
`SELECT 1 FROM customers WHERE id = $1 FOR UPDATE`, req.CustomerID); err != nil {
return err
}
err := tx.QueryRowContext(ctx, `
INSERT INTO orders (idempotency_key, customer_id) VALUES ($1, $2)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id`, req.IdempotencyKey, req.CustomerID).Scan(&orderID)
if errors.Is(err, sql.ErrNoRows) {
// Replay: the first attempt committed. Return its id, change nothing.
return tx.QueryRowContext(ctx,
`SELECT id FROM orders WHERE idempotency_key = $1`, req.IdempotencyKey).Scan(&orderID)
}
if err != nil {
return err
}
var total int64
for _, l := range lines {
var limit, already int
var price int64
if err := tx.QueryRowContext(ctx, `
SELECT p.max_per_customer, p.price_cents,
COALESCE((SELECT sum(ol.qty)
FROM order_lines ol JOIN orders o ON o.id = ol.order_id
WHERE o.customer_id = $1 AND ol.product_id = p.id
AND o.status NOT IN ('cancelled', 'expired')), 0)
FROM products p WHERE p.id = $2`, req.CustomerID, l.ProductID).
Scan(&limit, &price, &already); err != nil {
return err
}
if limit > 0 && already+l.Qty > limit {
return ErrLimitExceeded
}
res, err := tx.ExecContext(ctx, `
UPDATE inventory SET available = available - $1, updated_at = now()
WHERE product_id = $2 AND available >= $1`, l.Qty, l.ProductID)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrOutOfStock // whole transaction rolls back, earlier lines included
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO order_lines (order_id, product_id, qty, unit_price_cents)
VALUES ($1, $2, $3, $4)`, orderID, l.ProductID, l.Qty, price); err != nil {
return err
}
total += price * int64(l.Qty)
}
if _, err := tx.ExecContext(ctx,
`UPDATE orders SET total_cents = $1 WHERE id = $2`, total, orderID); err != nil {
return err
}
payload, _ := json.Marshal(map[string]any{"order_id": orderID, "customer_id": req.CustomerID, "lines": lines})
_, err = tx.ExecContext(ctx,
`INSERT INTO outbox (topic, payload) VALUES ('order.placed', $1)`, payload)
return err
})
return orderID, err
}
// ExpireUnpaid returns stock held by orders that were never paid. Several workers
// can run it at once: SKIP LOCKED hands each worker different orders.
func ExpireUnpaid(ctx context.Context, db *sql.DB, batch int) (int, error) {
expired := 0
err := withTx(ctx, db, nil, func(tx *sql.Tx) error {
expired = 0
rows, err := tx.QueryContext(ctx, `
UPDATE orders SET status = 'expired'
WHERE id IN (SELECT id FROM orders
WHERE status = 'pending_payment' AND expires_at < now()
ORDER BY expires_at
LIMIT $1
FOR UPDATE SKIP LOCKED)
RETURNING id`, batch)
if err != nil {
return err
}
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
rows.Close()
return err
}
ids = append(ids, id)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, id := range ids {
// Give each line's quantity back to stock.
if _, err := tx.ExecContext(ctx, `
UPDATE inventory i SET available = i.available + ol.qty, updated_at = now()
FROM order_lines ol
WHERE ol.order_id = $1 AND i.product_id = ol.product_id`, id); err != nil {
return err
}
}
expired = len(ids)
return nil
})
return expired, err
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Println("set DATABASE_URL and register a driver (for example github.com/jackc/pgx/v5/stdlib)")
return
}
}Laravel: migration and service. decrement() returns the affected-row count, lockForUpdate() emits FOR UPDATE, lock('FOR UPDATE SKIP LOCKED') passes the clause through, and DB::transaction(..., attempts: 3) re-runs the closure on deadlocks.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestampTz('created_at')->useCurrent();
});
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('sku')->unique();
$table->string('name');
$table->unsignedBigInteger('price_cents');
$table->unsignedInteger('max_per_customer')->default(0); // 0 = no limit
});
Schema::create('inventory', function (Blueprint $table) {
$table->foreignId('product_id')->primary()->constrained('products');
$table->integer('available');
$table->timestampTz('updated_at')->useCurrent();
});
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->uuid('idempotency_key')->unique();
$table->foreignId('customer_id')->constrained('customers');
$table->string('status', 20)->default('pending_payment');
$table->unsignedBigInteger('total_cents')->default(0);
$table->timestampTz('created_at')->useCurrent();
$table->timestampTz('expires_at');
$table->index(['customer_id', 'created_at']);
$table->index(['status', 'expires_at']);
});
Schema::create('order_lines', function (Blueprint $table) {
$table->foreignId('order_id')->constrained('orders')->cascadeOnDelete();
$table->foreignId('product_id')->constrained('products');
$table->unsignedInteger('qty');
$table->unsignedBigInteger('unit_price_cents');
$table->primary(['order_id', 'product_id']);
$table->index('product_id');
});
Schema::create('outbox', function (Blueprint $table) {
$table->id();
$table->string('topic');
$table->jsonb('payload');
$table->timestampTz('created_at')->useCurrent();
$table->timestampTz('published_at')->nullable();
});
// CHECK constraints: PostgreSQL and MySQL 8.0.16+ both enforce them.
DB::statement('ALTER TABLE inventory ADD CONSTRAINT inventory_available_nonneg CHECK (available >= 0)');
DB::statement('ALTER TABLE order_lines ADD CONSTRAINT order_lines_qty_pos CHECK (qty > 0)');
DB::statement("ALTER TABLE orders ADD CONSTRAINT orders_status_chk CHECK (status IN ('pending_payment','paid','shipped','cancelled','expired'))");
}
public function down(): void
{
Schema::dropIfExists('outbox');
Schema::dropIfExists('order_lines');
Schema::dropIfExists('orders');
Schema::dropIfExists('inventory');
Schema::dropIfExists('products');
Schema::dropIfExists('customers');
}
};<?php
namespace App\Services;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;
use RuntimeException;
final class InventoryService
{
/**
* @param array<int, int> $lines product_id => qty
*/
public function placeOrder(string $idempotencyKey, int $customerId, array $lines): int
{
ksort($lines); // lock products in ascending id order: no deadlocks between carts
try {
return DB::transaction(function () use ($idempotencyKey, $customerId, $lines) {
// Write-skew fix: serialise this customer's checkouts on one row. Take it
// BEFORE inserting the order: the orders FK takes FOR KEY SHARE on this row,
// and KEY SHARE then FOR UPDATE in two tabs deadlocks (40P01).
DB::table('customers')->where('id', $customerId)->lockForUpdate()->first();
$replay = DB::table('orders')->where('idempotency_key', $idempotencyKey)->value('id');
if ($replay !== null) {
return (int) $replay; // client retried: same answer, no second order
}
$orderId = DB::table('orders')->insertGetId([
'idempotency_key' => $idempotencyKey,
'customer_id' => $customerId,
'expires_at' => now()->addMinutes(15),
]);
$total = 0;
foreach ($lines as $productId => $qty) {
$product = DB::table('products')->where('id', $productId)->first(['max_per_customer', 'price_cents']);
$already = (int) DB::table('order_lines')
->join('orders', 'orders.id', '=', 'order_lines.order_id')
->where('orders.customer_id', $customerId)
->where('order_lines.product_id', $productId)
->whereNotIn('orders.status', ['cancelled', 'expired'])
->sum('order_lines.qty');
if ($product->max_per_customer > 0 && $already + $qty > $product->max_per_customer) {
throw new PurchaseLimitExceeded("product {$productId}");
}
// Lost-update fix: one conditional, atomic decrement. 0 rows = sold out.
$ok = DB::table('inventory')
->where('product_id', $productId)
->where('available', '>=', $qty)
->decrement('available', $qty, ['updated_at' => now()]) === 1;
if (! $ok) {
throw new OutOfStock("product {$productId}");
}
DB::table('order_lines')->insert([
'order_id' => $orderId,
'product_id' => $productId,
'qty' => $qty,
'unit_price_cents' => $product->price_cents,
]);
$total += $product->price_cents * $qty;
}
DB::table('orders')->where('id', $orderId)->update(['total_cents' => $total]);
DB::table('outbox')->insert([
'topic' => 'order.placed',
'payload' => json_encode(['order_id' => $orderId, 'customer_id' => $customerId, 'lines' => $lines]),
]);
return $orderId;
}, attempts: 3); // re-runs the closure on deadlock
} catch (UniqueConstraintViolationException) {
// Two concurrent requests with the same key: the loser reads the winner's order.
return (int) DB::table('orders')->where('idempotency_key', $idempotencyKey)->value('id');
}
}
/** Return stock from unpaid orders. Safe to run on several workers at once. */
public function expireUnpaid(int $batch = 100): int
{
return DB::transaction(function () use ($batch) {
$ids = DB::table('orders')
->where('status', 'pending_payment')
->where('expires_at', '<', now())
->orderBy('expires_at')
->limit($batch)
->lock('FOR UPDATE SKIP LOCKED')
->pluck('id');
foreach ($ids as $id) {
$lines = DB::table('order_lines')->where('order_id', $id)->orderBy('product_id')->get();
foreach ($lines as $line) {
DB::table('inventory')->where('product_id', $line->product_id)->increment('available', $line->qty);
}
}
DB::table('orders')->whereIn('id', $ids)->update(['status' => 'expired']);
return $ids->count();
});
}
}
final class OutOfStock extends RuntimeException {}
final class PurchaseLimitExceeded extends RuntimeException {}Hot SKU. In a flash sale one inventory row receives most of the 230 decrements/s. With a ~5 ms lock hold the ceiling is ~200/s for that row (hot rows). In order: move the decrement to the end of the transaction, split the SKU's stock into 8–16 bucket rows, or put a Redis DECR gate in front that admits only as many buyers as there are units and let the database confirm.
Scaling path.
| Load | Change | Trigger |
|---|---|---|
| 1× (35 orders/s peak) | One primary + sync standby + async replica; Redis for product pages | — |
| 10× (2,300/s) | Monthly partitions on orders/order_lines (archive > 2 years to object storage); bucketed stock for hot SKUs; reports via CDC to a columnar store | Primary CPU > 60%; table > 1 TB |
| 100× / multi-merchant | Shard by merchant_id (Shopify pods: every request served by one pod) or move to CockroachDB/Spanner if one merchant outgrows a node | Biggest instance at 70% |
Failure analysis.
| Failure | Effect | Mitigation |
|---|---|---|
| Client retries after timeout | Duplicate order | Idempotency key unique constraint |
| Payment captured, order transaction rolled back | Money without order | Create order first (pending), pay second; reconcile by idempotency key with the provider |
| Async replica promoted | Last orders lost | Sync standby for this database (RPO 0); reconcile from outbox consumers |
| Outbox relay down | Events delayed, not lost | Alert on oldest unpublished age; consumers dedupe by event id |
| Sweeper and payment race on one order | Paid order expired | Both use WHERE status = 'pending_payment'; whoever commits first wins, the other updates 0 rows |
| Flash sale | Lock queue on one row, p99 explodes | Bucketed stock, Redis gate, queue-based admission |
Sketch 3: Chat and feed
Requirements. 10M daily active users. Chat: 40 messages per user per day, ordered within a channel, history kept indefinitely, open a channel and see the last 50 messages in p99 ≤ 100 ms, delivery to online members in ≤ 1 s. Feed: 0.5 posts per user per day, average 200 followers, a few accounts with 10M followers, opening the home feed shows the newest 50 items in p99 ≤ 200 ms, a few seconds of staleness is fine.
Access patterns.
| # | Pattern | Key / filter | Peak/s | Consistency |
|---|---|---|---|---|
| C1 | Send message | channel_id | 14,000 | Durable, ordered per channel |
| C2 | Open channel, last 50 | channel_id, newest first | 10,000 | Read-your-writes for the sender |
| C3 | Scroll back | channel_id, message_id < cursor | 2,000 | Eventual |
| F1 | Post | author_id | 175 | Durable |
| F2 | Home feed | user_id, newest 50 | 7,000 | Eventual (seconds) |
| F3 | Profile feed | author_id, newest 50 | 3,000 | Eventual |
Numbers. Chat: 10M × 40 = 400M messages/day = 4,630/s average, ~14k/s at a 3× peak; ~500 B per message stored (text, ids, metadata, overhead) → 200 GB/day → ~73 TB/year raw, ~220 TB with RF=3 before compression. Feed: 5M posts/day = 58/s; fan-out on write at 200 followers = 11.6k timeline inserts/s average, ~35k/s peak; feed opens 10M × 20/day = 2.3k/s average, ~7k/s peak.
Model. Chat is append-mostly, partitioned by channel, read as "latest N in one partition": a wide-column store matches it exactly. Discord's design is the reference: "Cassandra partition keys can be compounded, so our new primary key became ((channel_id, bucket), message_id)", with buckets sized because "if we stored about 10 days of messages within a bucket that we could comfortably stay under 100MB". Timelines are capped lists of post ids per user: Redis sorted sets (or a Cassandra table keyed by user_id). Posts themselves can live in PostgreSQL (58 writes/s) or the wide-column store.
Left: a message gets a Snowflake id, is appended to its (channel_id, bucket) partition and pushed to online members; reads walk buckets newest first. Right: the three feed strategies; the hybrid pushes ordinary posts into followers' timelines and merges celebrity posts at read time.
Schema (CQL for Cassandra / ScyllaDB; PostgreSQL for posts and follows):
-- Cassandra / ScyllaDB
CREATE TABLE messages (
channel_id bigint,
bucket int, -- e.g. days since epoch / 10, derived from the Snowflake timestamp
message_id bigint, -- Snowflake: time-ordered, unique
author_id bigint,
content text,
PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC)
AND compaction = {'class': 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS', 'compaction_window_size': 10};
-- C2/C3: newest first inside one partition; walk older buckets if fewer than 50 rows
SELECT message_id, author_id, content FROM messages
WHERE channel_id = ? AND bucket = ? AND message_id < ? LIMIT 50;
-- PostgreSQL: posts and the follow graph
CREATE TABLE posts (id bigint PRIMARY KEY, author_id bigint NOT NULL, body text, created_at timestamptz NOT NULL);
CREATE INDEX posts_author_idx ON posts (author_id, id DESC);
CREATE TABLE follows (follower_id bigint, followee_id bigint, PRIMARY KEY (follower_id, followee_id));
CREATE INDEX follows_followee_idx ON follows (followee_id, follower_id);Fan-out trade-off.
| Strategy | Write cost per post | Read cost per feed open | Staleness | Breaks on |
|---|---|---|---|---|
| Fan-out on write (push) | followers × 1 insert | 1 range read of the user's timeline | Seconds of queue lag | Celebrities: 10M inserts per post |
| Fan-out on read (pull) | 1 insert | N followees × query + k-way merge | None | Users following thousands; read QPS × N |
| Hybrid | Push only for authors under a threshold (e.g. 100k followers) | 1 timeline read + merge of a few celebrity profile feeds | Low | Threshold tuning; two code paths |
Author A (200 followers) Celebrity C (10M followers)
1 POST -> posts row + enqueue fan-out job POST -> posts row only (no fan-out)
2 workers: ZADD timeline:<f> <id> <id> for 200 f --
3 ZREMRANGEBYRANK timeline:<f> 0 -801 (cap 800) --
Reader R opens feed
4 ids = ZREVRANGE timeline:R 0 49 celeb = followees of R with > 100k followers
5 merge(ids, newest posts of each celeb) -> top 50 -> hydrate posts by id (cache)Code sketch (bucket from a Snowflake id, Go; fan-out job, Laravel):
// Bucket = 10-day window derived from the Snowflake timestamp (Twitter epoch 1288834974657 ms).
func bucketOf(messageID int64) int32 {
ms := (messageID >> 22) + 1288834974657
return int32(ms / (10 * 24 * 3600 * 1000))
}// Fan-out on write for non-celebrity authors (Laravel job body).
public function handle(): void
{
DB::table('follows')->where('followee_id', $this->authorId)
->orderBy('follower_id')
->chunkById(1000, function ($rows) {
Redis::pipeline(function ($pipe) use ($rows) {
foreach ($rows as $row) {
$pipe->zadd("timeline:{$row->follower_id}", $this->postId, $this->postId);
$pipe->zremrangebyrank("timeline:{$row->follower_id}", 0, -801);
}
});
}, 'follower_id');
}Scaling path.
| Load | Change | Trigger |
|---|---|---|
| 1× | 6–9 node ScyllaDB/Cassandra cluster RF=3; Redis Cluster for timelines; PostgreSQL for posts/follows | — |
| 10× | More nodes (linear); request coalescing in a data-service layer in front of the store; timelines only for active users | Node disk > 60%, p99 read > target |
| 100× | Multi-DC with LOCAL_QUORUM; tiered storage for old buckets; follows graph sharded by follower_id | Cross-region users; storage cost |
Failure analysis.
| Failure | Effect | Mitigation |
|---|---|---|
Hot channel (an @everyone announcement) | Hot partition; node latency spreads to the cluster | Discord's answer: request coalescing in data services, cache the last page, rate-limit mentions |
| Large partition (busy channel, no bucketing) | Slow reads, compaction pain | Time buckets sized to ~100 MB |
| Deletes | Tombstones slow reads until gc_grace_seconds | Avoid delete-heavy patterns; run repairs within gc_grace_seconds |
| Celebrity post | Fan-out queue lag of minutes | Hybrid; threshold by follower count |
| Redis timeline loss | Empty feeds | Rebuild on demand from posts of followees (pull path) |
| Edit races with delete | Partial rows (all Cassandra writes are upserts) | Discord: check existence / write only changed columns; LWW semantics understood |
Migration runner (Go)
The two SQL files above are embedded and applied once each, in order, under an advisory lock, each in its own transaction (PostgreSQL DDL is transactional; MySQL DDL is not and commits implicitly, so a MySQL runner must make each file idempotent):
// Command migrate applies the embedded SQL files in order, once each,
// holding a PostgreSQL advisory lock so two deploys cannot migrate at once.
package main
import (
"context"
"database/sql"
"embed"
"fmt"
"io/fs"
"log"
"os"
"sort"
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver for database/sql
)
//go:embed sql/*.sql
var files embed.FS
// migratorLockID is an arbitrary constant shared by every instance of this tool.
const migratorLockID = 727274
func migrate(ctx context.Context, db *sql.DB) error {
conn, err := db.Conn(ctx) // advisory locks belong to one session
if err != nil {
return err
}
defer conn.Close()
if _, err := conn.ExecContext(ctx, `SELECT pg_advisory_lock($1)`, migratorLockID); err != nil {
return err
}
defer conn.ExecContext(context.Background(), `SELECT pg_advisory_unlock($1)`, migratorLockID)
if _, err := conn.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now())`); err != nil {
return err
}
names, err := fs.Glob(files, "sql/*.sql")
if err != nil {
return err
}
sort.Strings(names)
for _, name := range names {
var applied bool
if err := conn.QueryRowContext(ctx,
`SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&applied); err != nil {
return err
}
if applied {
continue
}
body, err := files.ReadFile(name)
if err != nil {
return err
}
// PostgreSQL DDL is transactional: the file and its bookkeeping row commit together.
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, string(body)); err != nil {
tx.Rollback()
return fmt.Errorf("%s: %w", name, err)
}
if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return err
}
log.Printf("applied %s", name)
}
return nil
}
func main() {
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
log.Println("set DATABASE_URL, e.g. postgres://postgres:pg@localhost:5432/postgres")
return
}
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := migrate(context.Background(), db); err != nil {
log.Fatal(err)
}
}Retries and failure handling
| Error / event | Retry? | Rule |
|---|---|---|
40001, 40P01, MySQL 1213 | Yes, whole transaction | Backoff with jitter; 3–5 attempts; no side effects inside the transaction |
MySQL 1205 lock wait timeout | Usually | Only the statement rolled back unless innodb_rollback_on_timeout; safest to retry the whole transaction |
23505 / 1062 duplicate | No | Translate: idempotent replay, or "already taken" |
23514 / MySQL 3819 check violation | No | Business rejection; alert if it means a bug |
Connection reset during COMMIT | Only if idempotent | The commit may have happened: re-check by idempotency key |
| DynamoDB throttling | Yes | SDK retries with backoff; fix the hot key |
| Cassandra write timeout | Only idempotent writes | Upserts with explicit ids are idempotent; counters are not |
Rules: retry at the transaction boundary, not the statement; make every write request carry an idempotency key or a natural unique key; never send email or call a payment API inside a database transaction (use the outbox); cap retries so a storm does not amplify an outage. The Go withTx in the inventory snippet and Laravel's attempts: implement the first rule.
Choosing: the decision checklist
Decision table.
| Workload / situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Read-heavy point lookups (shortener, sessions, profiles) | PostgreSQL/MySQL + Redis; DynamoDB at large scale | Cache-aside, negative caching, stale-while-revalidate | Hot set fits in memory; DB only sees misses |
| Money, stock, bookings | Relational primary, Read Committed | Atomic updates, constraints, FOR UPDATE, idempotency keys, sync standby | Invariants enforced where the data lives |
| Multi-row rules (limits, quotas, rotas) | Same | Materialise the conflict or Serializable + retry | Write skew is invisible otherwise |
| Append-mostly, huge volume, per-key ranges (chat, IoT, events) | Cassandra/ScyllaDB, DynamoDB, or partitioned PostgreSQL below ~10 TB | Time buckets, TWCS, TTL | Partition-local writes scale linearly |
| Feeds / timelines | Redis or wide-column timelines + relational posts | Hybrid fan-out | Bounded write and read cost |
| Analytics on OLTP data | Columnar store via CDC | Partition by time | OLTP primary stays for OLTP |
| Text search | Elasticsearch/OpenSearch or PostgreSQL FTS | CDC/outbox to index | Search is a derived view |
| Global users needing strong consistency | Spanner, CockroachDB | Regional tables / locality | Consensus per write; pay the latency knowingly |
| Many tenants, a few huge | Pool + RLS, silo/cell for the largest | tenant_id leading every key | Noisy neighbours and blast radius |
The checklist before a design review.
- Requirements table filled, with owners for every assumption (read/write ratio, p99 per operation, RPO/RTO, retention per data class, compliance).
- Access-pattern table with frequency and consistency per pattern; the top three are single-index or single-partition operations.
- Sizing sheet: peak QPS per pattern, GB/year per copy and in total, bandwidth, working set, connection count (Little's Law).
- Model and engine named, with the reason tied to the top patterns; every extra store justified by a pattern.
- Schema with primary keys, unique constraints for every natural key and idempotency key,
CHECKs for invariants, and the index for each pattern. - Concurrency: each invariant mapped to its mechanism (atomic update, constraint, lock, Serializable + retry); lock order stated.
- Scale ladder: the current rung and the next two, each with a trigger metric and threshold.
- Consistency per operation; replica reads have read-your-writes where needed.
- RPO/RTO per data class, HA mechanism, PITR, restore drill date; tenancy model.
- Headroom in months per resource; cost at 1×, 10×, 100×.
- Schema evolution: tool, expand/contract rules, backfill batch size.
- Observability: SLIs per pattern, rung triggers as alerts, reconciliation queries for invariants.
- Failure analysis table: each component down, slow, or wrong, and what the user sees.
In architecture: from a single process to a distributed system
The method does not change with the architecture; the number of databases and the places where a guarantee stops do.
Monolith: one process, one database
How it shows up: every sketch on this page starts here, and most products should stay here longer than they expect. One PostgreSQL or MySQL primary, one connection pool, transactions that span every table.
Simplest correct usage: invariants as constraints and atomic updates, one transaction per request that changes data, outbox table for side effects, replicas only for reads that tolerate lag.
Example (simple): the URL shortener year 1: Laravel app, PostgreSQL primary + replica, Redis cache; AP2 idempotent by a unique constraint.
Example (complex): the order sketch in a monolith: checkout, payment webhook, sweeper and reports in one codebase; reports run on a replica with statement_timeout; the outbox feeds email and search.
Modular monolith and multiple databases
How it shows up: modules (Catalogue, Ordering, Payments) own their tables; Figma's vertical partitioning is this at database level: "We split groups of related tables—like 'Figma files' or 'Organizations'—into their own vertical partitions".
Example: Ordering and Inventory share a database so the checkout stays one transaction; Analytics moves to its own database fed by CDC. Rule: an invariant must live inside one module's database; anything that spans two becomes an event.
Microservices: per-service databases, outbox and sagas
What survives: each service's local transaction and its constraints. What does not: atomicity and isolation across services.
Order service Inventory service Payment service
1 BEGIN; INSERT order(PENDING) + outbox(OrderPlaced); COMMIT
2 consume OrderPlaced
UPDATE stock ... WHERE available >= qty (atomic; 0 rows -> StockRejected)
INSERT outbox(StockReserved); COMMIT
3 consume StockReserved -> charge with Idempotency-Key = order id
4 consume PaymentCaptured -> UPDATE order SET status='paid' WHERE status='PENDING'
on PaymentFailed: publish ReleaseStock (compensation)Each step is the single-database technique from sketch 2; the saga adds compensations, timeouts and idempotent consumers. See Saga Pattern, Transactional Outbox and Idempotent Consumers.
Distributed data: replicas, caches, shards and regions
Replicas: lag breaks read-your-writes (the "my orders" timeline in the consistency menu); route by session LSN/GTID. Caches: invalidate after commit, use TTLs and versioned values; a cache is never the source of truth for an invariant. Shards: choose the shard key so every invariant and every top access pattern is shard-local (Shopify: every request "only requires a single pod to be online"; Notion and Instagram: workspace/user id determines the logical shard). Regions: a synchronous cross-region commit costs ~150 ms US↔Europe; either accept it for the data that needs it (Spanner, CockroachDB) or home each user's data in one region and replicate asynchronously.
Scaling path: 1×, 10×, 100×
| Load | URL shortener | Order / inventory | Chat / feed |
|---|---|---|---|
| 1× | 1 primary + 2 replicas + Redis | 1 primary + sync standby + replica | Wide-column cluster RF=3 + Redis timelines |
| 10× | Redis Cluster, CDN, clicks to ClickHouse | Monthly partitions, bucketed hot SKUs, CDC to OLAP | More nodes, request coalescing, active-user timelines |
| 100× | Sharded by hash(code) or DynamoDB | Shard by merchant (pods) or distributed SQL | Multi-DC LOCAL_QUORUM, tiered storage |
The same rule holds at every step: keep each invariant inside one transaction on one database, and design explicitly what happens outside it.
Lab
Measure instead of guessing. Expected output is approximate; your sizes will differ by version and hardware.
Setup.
docker run -d --name dsd -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
cd docs/snippets/database/database-system-design/go
# apply both migrations with psql (or build the Go runner with a pgx/stdlib import):
for f in migrate/sql/*.sql; do docker exec -i dsd psql -U postgres -v ON_ERROR_STOP=1 < "$f"; doneExperiment 1: measure bytes per row and extrapolate the sizing sheet.
INSERT INTO links (code, owner_id, long_url, url_hash)
SELECT lpad(to_hex(g), 7, '0'), g % 100000, -- unique codes; md5 prefixes would collide
'https://example.com/some/path/' || md5(g::text) || '?utm_source=newsletter',
encode(sha256(g::text::bytea), 'hex')
FROM generate_series(1, 1000000) g;
SELECT pg_size_pretty(pg_total_relation_size('links')) AS total,
pg_total_relation_size('links') / 1000000 AS bytes_per_row;
-- expect roughly 300-450 bytes per row including indexes -> x 1.2e9/year = your GB/yearExperiment 2: reproduce the lost update, then the fix. Two terminals (docker exec -it dsd psql -U postgres):
INSERT INTO products (sku, name, price_cents, max_per_customer) VALUES ('P7', 'Lamp', 1000, 2);
INSERT INTO inventory (product_id, available) VALUES (1, 1);
-- A: BEGIN; SELECT available FROM inventory WHERE product_id = 1; -- 1
-- B: BEGIN; SELECT available FROM inventory WHERE product_id = 1; -- 1
-- A: UPDATE inventory SET available = 0 WHERE product_id = 1; COMMIT;
-- B: UPDATE inventory SET available = 0 WHERE product_id = 1; COMMIT; -- both "sold" the last lamp
-- fix: UPDATE inventory SET available = available - 1 WHERE product_id = 1 AND available >= 1;
-- the second session reports UPDATE 0Experiment 3: reproduce the write skew on the purchase limit, then the fix.
INSERT INTO customers (email) VALUES ('c@example.com');
UPDATE inventory SET available = 10 WHERE product_id = 1;
-- A and B: BEGIN; SELECT coalesce(sum(ol.qty),0) FROM order_lines ol JOIN orders o ON o.id = ol.order_id
-- WHERE o.customer_id = 1 AND ol.product_id = 1; -- both see 0 (limit is 2)
-- A: INSERT INTO orders (idempotency_key, customer_id) VALUES (gen_random_uuid(), 1) RETURNING id; -- say 1
-- INSERT INTO order_lines VALUES (1, 1, 2, 1000); COMMIT;
-- B: INSERT INTO orders (idempotency_key, customer_id) VALUES (gen_random_uuid(), 1) RETURNING id; -- say 2
-- INSERT INTO order_lines VALUES (2, 1, 2, 1000); COMMIT; -- customer now has 4
-- fix: start both with SELECT 1 FROM customers WHERE id = 1 FOR UPDATE; B waits, then sees 2 and refusesExperiment 4: idempotent create. Run the same INSERT INTO orders (idempotency_key, customer_id) VALUES ('6f1c...', 1) ON CONFLICT (idempotency_key) DO NOTHING RETURNING id; twice: the second returns no row, and SELECT count(*) FROM orders WHERE idempotency_key = '6f1c...' is 1.
Experiment 5: hot-row ceiling with pgbench.
cat > /tmp/hot.sql <<'SQL'
BEGIN;
UPDATE inventory SET available = available - 1 WHERE product_id = 1 AND available > 0;
SELECT pg_sleep(0.005);
COMMIT;
SQL
docker exec dsd psql -U postgres -c "UPDATE inventory SET available = 1000000 WHERE product_id = 1"
docker cp /tmp/hot.sql dsd:/tmp/hot.sql
docker exec dsd pgbench -U postgres -n -c 32 -j 4 -T 20 -f /tmp/hot.sql postgres
# expect tps just under 200 (1 / 5 ms) regardless of -c: the row lock serialises everyoneExperiment 6: cache-hit ratio as working-set evidence.
SELECT sum(heap_blks_hit)::float / nullif(sum(heap_blks_hit) + sum(heap_blks_read), 0) AS heap_hit_ratio
FROM pg_statio_user_tables;
-- near 0.99 under steady load = working set fits in shared_buffers + OS cacheCommon misconceptions
| Belief | Reality |
|---|---|
| "NoSQL is for scale, SQL is for small apps" | One relational primary handles thousands of writes/s; Instagram, Notion, Figma and Shopify scaled PostgreSQL/MySQL by sharding |
| "Start with microservices and a database each" | You lose transactions for invariants on day one; start with one database and modules |
| "Average load is what we size for" | Peaks (2–5×, flash events 20×) and hot keys decide capacity |
| "Replicas are backups" | Replicas copy mistakes instantly; only backups + PITR undo them |
| "Strong consistency everywhere is safest" | It costs latency and availability for operations that do not need it; choose per operation |
| "Serializable fixes every concurrency bug" | Within one database, at the cost of retries; it does nothing across services, caches or two requests |
| "A cache makes the database faster" | It removes load; a stampede or a cold cache can send the full load back at once |
| "Schemaless means no migrations" | It moves migrations into every reader |
| "The shard key can be changed later" | Changing it is a full data migration; choose it from the invariants and top patterns |
| "UUIDv4 primary keys are free" | Random keys spread B-tree inserts and inflate InnoDB secondary indexes; consider time-ordered ids |
| "Storage is cheap" | Every byte is multiplied by replicas, RF and backups, and slows restore and migrations |
| "Back-of-envelope numbers must be exact" | They must be within a factor of 2–3 and show which resource runs out first |
Cheat sheet
| Topic | Remember |
|---|---|
| Method | Requirements → access patterns → sizing → model → scale ladder → consistency → HA/backup/tenancy → operate |
| Seconds | Day 86,400 ≈ 10^5; month ≈ 2.6M; year ≈ 31.5M |
| Latency | Memory 100 ns; in-DC RTT 0.5 ms; HDD seek 8 ms; US↔EU 150 ms |
| QPS | events/day ÷ 86,400 × peak factor |
| Storage | rows × (row + indexes + overhead) × copies; measure with pg_total_relation_size |
| Connections | Little's Law: busy = QPS × mean time |
| Hot row | Throughput ≤ 1 / lock hold time |
| Model | Pick by top three access patterns; one general store first |
| Scale ladder | Index → bigger box → pool → replicas → cache → partition → split by function → shard |
| Consistency | Per operation: strong, read-your-writes, bounded, eventual |
| Lost update | Atomic conditional UPDATE; CHECK as backstop |
| Write skew | Lock/materialise the rule's row, or Serializable + retry |
| Idempotency | Unique key + ON CONFLICT DO NOTHING; same key returns same result |
| HA vs backup | Replicas for machines, PITR for mistakes; drill restores |
| Fan-out | Push for normal authors, pull for celebrities |
| Headroom | CPU ≤ 70%, disk ≤ 80%, N+1 capacity |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A product brief says "10M links per month, mostly reads". Which three numbers do you derive first, and what are they? Must-know
Answer
Answer: Write QPS (10M ÷ 2.6M s ≈ 3.9/s average, ~20/s at a 5× peak), read QPS (with a 100:1 ratio ≈ 390/s average, ~2k/s peak) and storage per year (120M rows × ~500 B ≈ 60 GB per copy). Then bandwidth and working set. See sizing.
2 — Why is "design tables first, queries later" acceptable in a single PostgreSQL but not in DynamoDB or a sharded system? Must-know
Answer
Answer: In one relational database any query can be served later by adding an index. In DynamoDB, Cassandra or a sharded system the partition key decides which queries are single-partition; a query without it scans or fans out to every shard. See access-pattern-first modelling.
3 — Your stock decrement reads available, checks it in PHP, and writes the new value. Name the bug and the fix that needs no level change. Must-know
Answer
Answer: A lost update (oversell). Use one atomic conditional statement: UPDATE inventory SET available = available - :q WHERE product_id = :p AND available >= :q and treat 0 affected rows as out of stock; keep CHECK (available >= 0) as the backstop. See sketch 2.
4 — Two tabs of the same customer both pass the "max 2 per customer" check. Why doesn't the atomic stock update stop it, and what does? Important
Answer
Answer: It is write skew: both transactions read the same set and write different rows (new order lines), so no row conflict occurs. Lock a row both must touch (SELECT ... FROM customers WHERE id = ? FOR UPDATE), keep a per-customer counter row with an atomic update, or run Serializable with retry.
5 — A hot SKU gets 400 checkouts/s in a flash sale and p99 explodes although CPU is 30%. Why, and what are two fixes? Important
Answer
Answer: The stock row's lock serialises the transactions: throughput ≤ 1 / lock hold time (~200/s at 5 ms). Shorten the hold (decrement last, no network calls in the transaction), split stock into bucket rows, or gate buyers with Redis DECR before the database. See hot rows.
6 — When is fan-out on write the wrong choice, and what replaces it? Important
Answer
Answer: For authors with huge follower counts: one post becomes millions of timeline writes and minutes of lag. Use the hybrid: push for ordinary authors, pull celebrity posts at read time and merge. See fan-out trade-off.
7 — A user places an order and the next page says "no orders". The database is fine. What happened and how do you fix it? Must-know
Answer
Answer: The read went to a lagging async replica. Provide read-your-writes: route that user's reads to the primary for a short window after a write, or record the commit LSN/GTID and read from a replica only once it has replayed past it. See consistency menu.
8 — You have two async replicas and nightly logical dumps. A developer runs DELETE FROM orders without WHERE at 14:05. What can you recover, and what should the design have had? Important
Answer
Answer: Replicas already applied the delete; the dump restores last night, losing the day. The design needed continuous WAL/binlog archiving with PITR to 14:04:59, plus a tested restore procedure. See HA, backup and multi-tenancy.
9 — How many database connections does a checkout at 230 transactions/s with 15 ms per transaction need, and why do teams still run out? Must-know
Answer
Answer: Little's Law: 230 × 0.015 ≈ 3.5 busy connections on average; a pool of 20–30 covers peaks. Teams run out because every app process opens its own connections or holds them during network calls; a pooler such as PgBouncer and short transactions fix it. See Little's Law.
10 — Why did Discord bucket chat partitions by time, and how big were the buckets? Good to know
Answer
Answer: A partition per channel grows without limit; large partitions make reads and compaction slow. They used ((channel_id, bucket), message_id) with about 10 days per bucket, so the largest channels stayed under ~100 MB per partition.
11 — What is the cheapest rung to try before adding read replicas, and why? Must-know
Answer
Answer: Query and index fixes (rung 0), then a larger instance and pooling. They need no new consistency model; replicas add lag and read-your-writes routing. See the scale ladder.
12 — In an interview you have 45 minutes for "design a URL shortener". What do you put on the board, in order? Must-know
Answer
Answer: Requirements with numbers (ratio, SLO, retention), the access-pattern table, the sizing sheet (QPS, GB/year, bandwidth, working set), the schema with UNIQUE(code) and the idempotency key, the read path with cache-aside and stampede protection, code generation and collision math, 302 vs 301, the scaling path with triggers, and the failure table. See sketch 1.
Glossary
| Term | Meaning |
|---|---|
| Access pattern | One query the system must serve: actor, key, filter, sort, size, frequency, consistency |
| Access-pattern table | The list of all access patterns, written before the schema |
| Back-of-envelope estimate | Order-of-magnitude arithmetic for QPS, storage, bandwidth and memory |
| Read/write ratio | Reads per write for an entity or system; decides replicas and caches |
| QPS | Queries (or requests) per second; always state average and peak |
| Peak factor | Ratio of peak to average load |
| Latency SLO | Target for a latency percentile (e.g. p99 ≤ 50 ms) of one operation |
| SLI | The measured indicator behind an SLO |
| p99 | 99th percentile: 1 request in 100 is slower |
| Working set | Data touched often enough that it should be in memory |
| Buffer pool / shared_buffers | The database's page cache (InnoDB / PostgreSQL) |
| Cache hit ratio | Fraction of reads served from memory or cache |
| Retention | How long a data class is kept before deletion or archive |
| Compliance | Legal and contractual rules on data: GDPR, PCI DSS, residency, audit |
| Data residency | Requirement that data stays in a jurisdiction |
| Right to erasure | GDPR right to have personal data deleted |
| Crypto-shredding | Deleting data by destroying its encryption key (useful for backups) |
| Data model | Relational, document, key-value, wide-column, graph, time-series, search, columnar |
| Single-table design | DynamoDB practice of storing several item types in one table with overloaded keys |
| GSI | DynamoDB global secondary index; another partition/sort key, eventually consistent |
| Partition key / clustering key | Wide-column keys: which node and partition; order inside the partition |
| Hot partition / hot key | One key receiving disproportionate traffic |
| Hot row | One row updated by most transactions; throughput ≤ 1 / lock hold |
| Scale ladder | Ordered list of scaling steps from query fixes to sharding |
| Vertical scaling | A bigger machine |
| Read replica | Copy of the primary serving reads, usually asynchronously |
| Cache-aside | App reads cache, on miss reads DB and fills cache |
| Cache stampede / thundering herd | Many requests miss the same key at once and all hit the DB |
| Stale-while-revalidate | Serve the old value while one request refreshes it (Cache::flexible) |
| Negative caching | Caching "not found" so repeated misses do not reach the DB |
| Request coalescing / singleflight | Many identical concurrent requests share one backend call |
| Partitioning | Splitting a table into parts on one server (by range, list, hash) |
| Functional (vertical) partitioning | Moving groups of tables to separate databases |
| Sharding | Splitting data across servers by a shard key |
| Logical shard | A small unit of data mapped to a physical host; moved without re-hashing |
| Cell / pod | Fully isolated stack (app + datastores) serving a subset of tenants |
| Consistency menu | Choosing a guarantee per operation |
| Read-your-writes | A user always sees their own writes |
| Monotonic reads | A session never reads older data than it already saw |
| Bounded staleness | Reads lag by at most a known time or number of versions |
| Eventual consistency | Replicas converge if writes stop |
| Quorum | R + W > RF so reads overlap the latest write |
| RPO | Recovery point objective: how much committed data may be lost |
| RTO | Recovery time objective: how long recovery may take |
| PITR | Point-in-time recovery from base backup + log archive |
| Synchronous standby | Replica that must confirm before commit returns (RPO 0) |
| Semi-sync | MySQL replication where a replica acknowledges receipt before commit returns |
| Pool / bridge / silo | Tenancy models: shared tables / schema per tenant / database per tenant |
| RLS | Row-level security: per-row access policies (PostgreSQL) |
| Headroom | Spare capacity before a threshold, expressed in time at current growth |
| N+1 capacity | Enough capacity to lose one node or zone at peak |
| Little's Law | L = λ × W: concurrency = arrival rate × time in system |
| Egress | Network traffic leaving a provider or zone; often billed |
| Expand/contract | Additive schema change, migrate code and data, then remove the old shape |
| Online DDL | Schema change without blocking reads/writes (CONCURRENTLY, ALGORITHM=INSTANT, gh-ost) |
| Backfill | Batch job filling a new column or table |
| Golden signals | Latency, traffic, errors, saturation |
| Reconciliation query | Periodic check that an invariant holds across tables or systems |
| Idempotency key | Client-generated id that makes retries return the first result |
| Lost update | Two read-modify-writes where the second overwrites the first |
| Write skew | Two transactions check one rule, write different rows, rule breaks |
| Materialising the conflict | Adding a row both transactions must lock so write skew becomes a lock conflict |
| Transactional outbox | Events written in the same transaction as the change, published later |
| Saga | Sequence of local transactions with compensations |
| CDC | Change data capture: streaming committed changes from the log |
| SKIP LOCKED | Locking read that skips rows locked by others (job queues, sweepers) |
| Fan-out on write / read | Push items into followers' timelines vs merge followees at read time |
| Hybrid fan-out | Push for most authors, pull for celebrities |
| Celebrity problem | An account whose follower count makes push fan-out too expensive |
| Snowflake id | 64-bit time-ordered id: timestamp, machine/shard bits, sequence |
| Base62 | Encoding with 0-9A-Za-z, used for short codes |
| TWCS | Cassandra Time Window Compaction Strategy for time-bucketed data |
| Tombstone | Deletion marker in LSM stores, removed after gc_grace_seconds |
| Replication factor (RF) | Number of copies of each partition in Cassandra/ScyllaDB |
| 301 / 302 | Permanent (cached by browsers) vs temporary redirect |
References
- Peter Norvig, Teach Yourself Programming in Ten Years, section "Answers" with the timing table (Jeff Dean's numbers). norvig.com/21-days.html
- Colin Scott, Latency Numbers Every Programmer Should Know (interactive, Berkeley). colin-scott.github.io
- Martin Kleppmann, Designing Data-Intensive Applications, chapters 1–3 (secondary source). dataintensive.net
- AWS Well-Architected Framework, Performance Efficiency Pillar: Data management, PERF03-BP01 purpose-built data store
- Amazon DynamoDB Developer Guide: NoSQL design for DynamoDB, Data modeling, Relational modeling
- Google Cloud: Your Google Cloud database options, explained, Databases products overview
- Stripe: Designing robust and predictable APIs with idempotency, API reference: Idempotent requests
- Shopify Engineering: A Pods Architecture To Allow Shopify To Scale, Horizontally scaling the Rails backend of Shop app with Vitess
- Notion: Herding elephants: Lessons learned from sharding Postgres at Notion
- Figma: How Figma's databases team lived to tell the scale
- Instagram Engineering: Sharding & IDs at Instagram (archived)
- Discord: How Discord Stores Billions of Messages, How Discord Stores Trillions of Messages (archived copies)
- Laravel 13: Cache (
Cache::flexible), Database transactions, Query builder locking, Migrations - PostgreSQL: INSERT ... ON CONFLICT, Explicit locking, Table partitioning, Error codes, pgbench
- Go:
database/sql,embed