Skip to content

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 forGo to
The method and the numbers on one screenEverything in one minute
Why design from access patterns, not from a favourite databaseWhy a method
Dean's latency numbers, DDIA, Well-Architected, DynamoDB, Google CloudWhere the method comes from
Read/write ratio, SLOs, retention, complianceRequirements that matter
Listing every query before the schemaAccess-pattern-first modelling
QPS, GB/year, bandwidth, working setBack-of-envelope sizing
Relational vs document vs KV vs wide-column vs graph vs time-series vs searchChoosing a data model
Index, vertical, pool, replicas, cache, partition, shardThe scale ladder
Strong, read-your-writes, bounded staleness, eventualThe consistency menu
RPO/RTO, replicas, PITR, pool vs siloHA, backup and multi-tenancy
Headroom, cost, schema evolution, observabilityHeadroom, Cost, Schema evolution, Observability
What each product gives youPer-product behaviour
Formulas, Little's Law, hot-row limits, knobs, error codesMechanics
URL shortener, order/inventory, chat/feed with numbers, schema, codeThe three worked sketches
The checklist before a design reviewChoosing: the decision checklist
Monolith to multi-regionIn architecture
Measure your own numbersLab
Interview-style questionsSelf-check
Wrong beliefs, cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The method. Each step produces an artefact; the next step consumes it.

StepQuestion it answersArtefactTypical mistake
1. RequirementsWhat 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 patternsWhich exact queries run, how often, with which keys?Access-pattern tableDesigning tables first, queries later
3. SizingHow many requests, bytes and hot rows?QPS avg/peak, GB/year, bandwidth, working setAverage instead of peak; forgetting indexes and replicas
4. Data modelWhich model serves the patterns with the fewest moving parts?Model + engine + schema + indexesPicking NoSQL for "scale" at 50 writes/s
5. Scale ladderWhat do we do at 10× and 100×, and what triggers it?Trigger list per rungSharding on day one
6. Consistency menuWhich operation needs which guarantee?Consistency per operationOne global level for everything
7. HA / backup / tenancyWhat can we lose, how long can we be down, who shares what?RPO/RTO, replica plan, PITR, tenancy modelReplicas mistaken for backups
8. OperateWhat does it cost, how does it change, how do we see it?Cost line, migration plan, dashboards and alertsNo 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.

ThingValueUse it to
Main memory reference100 nsCached lookups are effectively free
Round trip inside one data centre500 µs (0.5 ms)Each DB round trip costs ~0.5 ms before any work: count round trips
Disk seek (spinning)8 msWhy random I/O on HDD killed OLTP; SSD random read is tens of µs
Read 1 MB sequentially from disk20 ms (HDD)Scans are bandwidth-bound
US ↔ Europe round trip150 msCross-region synchronous writes cost this per commit
1 day86,400 s (≈ 10^5)1M/day ≈ 12/s
1 month≈ 2.6M s100M/month ≈ 39/s
1 year≈ 31.5M s (≈ π × 10^7)1 KB/s for a year ≈ 31.5 GB
Peak factor2–5× normal, 10–50× for flash eventsSize for peak, not average

The sketches in one table.

SketchShapePeak loadStorage/yearModelHard part
URL shortener100:1 read-heavy point lookups~20k reads/s, ~200 writes/s~600 GBKV access on PostgreSQL + Redis (or DynamoDB)Cache stampede on a viral link; analytics writes
Order / inventoryWrite-critical transactions~230 checkouts/s (flash sale)~730 GBRelational (PostgreSQL/MySQL)Oversell (lost update), purchase limits (write skew), hot SKU row
Chat / feedWrite-heavy append + fan-out~14k messages/s; ~35k timeline inserts/s~73 TB rawWide-column (Cassandra/ScyllaDB) + Redis timelinesHot 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 toolsOne extra hour of tables and arithmetic
Access patterns discovered by incidentsAccess patterns listed before the schema
Scaling decisions taken under pressureScaling triggers written down in advance
One consistency level for every operationA consistency choice per operation
Cost discovered on the first invoiceCost 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 ​

  1. "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.
  2. "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.
  3. "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 method: each step produces an artefact the next step consumes1. Requirementsread/write ratio, SLOs,consistency, retention, law2. Access patternsevery query with key,filter, sort, frequency3. SizingQPS avg/peak, GB/year,bandwidth, working set4. Data modelrelational, document, KV,wide-col, graph, TS, search8. Operateobservability, cost,schema evolution plan7. HA / backup / tenancyRPO/RTO, PITR, replicas,pool vs silo vs bridge6. Consistency menustrong, read-your-writes,bounded, eventual5. Scale ladderindex, vertical, replicas,cache, partition, shardnumbers do not fit: revisitOutputs: an access-pattern table, a sizing sheet, a schema with indexes, a scaling trigger list,a consistency choice per operation, RPO/RTO targets, a cost line, and the dashboards and alerts.

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:

RequirementAskWhy it changes the designExample answer
Read/write ratioReads per write, per entityRead-heavy → replicas and caches; write-heavy → LSM engines, batching, partitioningURL shortener 100:1; chat ≈ 1:1 on storage
Latency SLOp50/p99 per operation, from whereNumber of round trips and which tier may serve the readRedirect p99 ≤ 50 ms server-side
ThroughputAverage and peak per operationInstance size, pool size, partition countCheckout peak 230/s
ConsistencyPer operation: may it be stale, by how much?Primary vs replica vs cache; isolation; quorumStock decrement strong; product page 5 s stale OK
Durability / RPOHow many committed writes may be lost?Sync vs async replication, fsync policyOrders: 0; click counts: 1 minute
Availability / RTOHow long may writes be down?Failover automation, multi-AZ, multi-region99.95% ≈ 22 min/month
RetentionHow long is each data class kept, then what?Partitioning by time, TTL, archive tiersOrders 7–10 years (confirm with finance); chat forever; clicks 13 months raw
ComplianceWhich regimes apply?Encryption, residency, erasure, auditGDPR right to erasure, PCI DSS for card data, data residency for EU users
GrowthRows/day now and in 2 yearsWhen each rung of the scale ladder triggers100M links/month, +50%/year

Sequence (how a requirements interview goes):

text
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 patterns

Real 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:

RequirementPostgreSQLMySQL InnoDBDynamoDBCassandra / ScyllaDB
Retention by timeDeclarative partitioning + DETACH PARTITIONRange partitioning + DROP PARTITIONItem TTL attributeTable default_time_to_live, TWCS compaction
RPO 0synchronous_commit = on + synchronous_standby_namesSemi-sync replication (AFTER_SYNC)Multi-AZ by designWrite consistency QUORUM/LOCAL_QUORUM
ErasureDELETE + VACUUM; crypto-shredding for backupsDELETE + purgeDeleteItemTombstones 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):

text
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 done

Real 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.

ModelHow patterns map to storageWhat a missing pattern costs
Relational (PostgreSQL, MySQL, SQL Server, Oracle)Tables normalised; patterns become indexes and joinsA new index, usually online (CREATE INDEX CONCURRENTLY)
Document (MongoDB)Embed what is read together; reference what grows unboundedlyA new index; or a reshape of documents
Key-value / single-table (DynamoDB)Partition key + sort key per pattern; GSIs for alternates; overloaded PK/SKA new GSI (backfilled), or a scan
Wide-column (Cassandra, ScyllaDB)One table per query; partition key = the equality, clustering key = the sortA new table written in parallel (or a materialised view)
Search (Elasticsearch, OpenSearch)Denormalised documents per search screenReindex

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):

QuantityFormulaExample (URL shortener)
Write QPSevents/day ÷ 86,400 × peak factor100M/month ÷ 2.6M s = 39/s avg; ×5 = ~190/s
Read QPSwrite QPS × read/write ratio39 × 100 = 3.9k/s avg; ~19k/s peak
Storage/yearrows/year × (row + index + overhead) × copies1.2B × 500 B = 600 GB per copy
BandwidthQPS × bytes per request/response19k/s × 500 B ≈ 10 MB/s ≈ 80 Mbit/s
Working sethot fraction × total, or recent window × ratelast 30 days, 20M hot codes × 250 B ≈ 5 GB in Redis

Sequence (a sizing sheet, line by line):

text
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 node

Real 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.

EngineWhat to add to raw row size
PostgreSQL23-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 InnoDBClustered 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
RedisPer-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:

ModelNatural queryStrong atWeak atProducts
RelationalJoins, ad-hoc filters, multi-row transactionsInvariants (constraints), flexible queriesHorizontal write scale without extra layersPostgreSQL, MySQL, SQL Server, Oracle, SQLite; distributed: CockroachDB, Spanner, YugabyteDB, Vitess, Citus
DocumentFetch/update one aggregate by idNested, evolving structuresCross-document joins and invariantsMongoDB, Firestore, Couchbase
Key-valueGet/put by keyLatency, scale, simplicityAnything but the keyRedis, DynamoDB, Memcached, etcd
Wide-columnRange scan inside one partitionWrite throughput, huge data, multi-DCSecondary access paths, ad-hoc queriesCassandra, ScyllaDB, Bigtable, HBase
GraphTraverse k hopsRecommendations, fraud rings, permissions graphsBulk aggregation, shardingNeo4j, Amazon Neptune, Spanner Graph
Time-seriesAggregate by time windowIngest rate, downsampling, retentionUpdates, joins to OLTP dataTimescaleDB, InfluxDB, Prometheus, ClickHouse
SearchRelevance-ranked text, facetsFull-text, fuzzy, aggregationsBeing the source of truthElasticsearch, OpenSearch, PostgreSQL FTS
Columnar (OLAP)Scan few columns of many rowsAnalytics, reportsPoint updatesClickHouse, BigQuery, Redshift, Snowflake

Sequence (choosing for the order sketch):

text
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 CDC

Real 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".

RequirementPushes towards
Cross-entity invariants, moneyRelational (or distributed SQL at scale)
Writes > ~50k/s sustained, append-mostlyWide-column / LSM-based store
Single-digit-ms reads at any scale, known keysKey-value (DynamoDB, Redis as cache)
Global strong consistencySpanner, CockroachDB
Text relevanceSearch 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):

RungTrigger (measured)What it buysCost
0. Query and index fixesTop pg_stat_statements entries do sequential scansOften 10–100× on the hot queryEngineering time
1. Vertical scalingCPU > 60–70% at peak, buffer hit ratio falling2–4× per step, no code changePrice grows faster than linearly; a ceiling exists
2. Connection poolingConnection count near max_connections, many idleStable memory, more clientsTransaction-mode pooling breaks session features
3. Read replicasReads dominate, primary CPU from readsRead throughput × replicasReplica lag; read-your-writes routing
4. CacheRepeated reads of the same keys10–100× on hot readsInvalidation, stampedes, stale data
5. Partitioning (one node)Tables > hundreds of GB, retention by timePruning, cheap DROP/DETACHPartition key in queries and unique keys
6. Functional (vertical) partitioningDistinct table groups compete for one primarySeparate primaries per domainCross-database joins and transactions disappear
7. Sharding (horizontal)Writes or data exceed the biggest primaryLinear write scaleShard key forever; cross-shard queries; resharding
8. Distributed SQL / purpose-built storeNeed both SQL and scale-out, or a pattern the RDBMS cannot serveAutomatic sharding and replicationLatency per transaction, cost, new failure modes

Sequence (the URL shortener climbing):

text
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."

ProductBuilt-in rung 5Rung 7 option
PostgreSQLDeclarative partitioningCitus, application sharding, FDW
MySQLPartitioningVitess, application sharding
SQL Server / OracleTable partitioningOracle Sharding; application sharding
MongoDB—Native sharding (hashed or ranged shard key)
CockroachDB / SpannerAutomatic ranges/splitsBuilt in
Cassandra / DynamoDBPartition keyBuilt 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):

GuaranteeWhat the reader seesTypical mechanismUse for
Strict serializable / linearizableThe latest committed write, in real-time orderSingle primary; Spanner TrueTime; consensus readsMoney movement, stock, uniqueness
Serializable (one database)Result equals some serial orderPostgreSQL SSI, InnoDB/SQL Server 2PL, CockroachDB defaultMulti-row business rules
Read-your-writesYour own writes, maybe not others'Pin user to primary after a write; wait for LSN/GTID on replicaProfile edits, "my orders"
Monotonic readsNever older than what you saw beforeSticky replica per sessionTimelines, paging
Bounded stalenessAt most N seconds or versions oldReplica with lag check; cache TTLProduct pages, counters
EventualConverges if writes stopAsync replicas, caches, CDC copies, LWW in CassandraFeeds, analytics, search index

Timeline (why per-operation matters):

text
     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).

ProductStrong readWeaker, cheaper read
PostgreSQL / MySQLPrimaryReplica (async; lag), hot_standby_feedback for long queries
MongoDBreadConcern: "majority" / "linearizable", readPreference: primaryreadPreference: secondary, causal sessions for read-your-writes
DynamoDBConsistentRead: true (base table)Default eventually consistent reads (half the read cost); GSIs are always eventual
Cassandra / ScyllaDBQUORUM/LOCAL_QUORUM both sidesONE, LOCAL_ONE
CockroachDB / SpannerDefaultFollower reads / stale reads with bounded staleness
RedisPrimaryReplicas 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:

DecisionOptionsOwner page
RPO for each data class0 (sync replica), seconds (async), minutes (WAL archive)Backup, PITR & DR
RTOSeconds (automatic failover: Patroni, RDS Multi-AZ, Orchestrator), minutes (manual), hours (restore)Replication & Failover
BackupsPhysical base backup + continuous WAL/binlog archive; logical dumps for portability; restore drillsBackup, PITR & DR
TopologySingle AZ, multi-AZ, multi-region active-passive, multi-region active-activeDistributed SQL
TenancyPool (shared tables + tenant_id + RLS), bridge (schema per tenant), silo (database per tenant), cells/podsMulti-Tenancy

Sequence (a failover with async replication):

text
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 key

Real 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.

ProductHA mechanismPITR mechanism
PostgreSQLStreaming replication + Patroni / cloud Multi-AZBase backup + WAL archive (pgBackRest, WAL-G), recovery_target_time
MySQLGroup Replication / InnoDB Cluster, semi-sync + OrchestratorBackup (XtraBackup/MySQL Enterprise Backup) + binlog replay
SQL ServerAlways On availability groupsFull + log backups, STOPAT
OracleData Guard, RACRMAN + archived redo logs
MongoDBReplica set electionsOplog-based PITR (Atlas, Ops Manager)
CockroachDB / SpannerRaft/Paxos replicasBackups with revision history / PITR versions
Cassandra / ScyllaDBRF=3 across racks/DCsSnapshots + incremental backups (nodetool), Scylla Manager
DynamoDBMulti-AZ built in; global tablesPITR (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:

ResourcePlan to stay below at peakWhy
CPU60–70%Latency knee; room for vacuum, backups, failover
Disk space70–80%Compaction, index rebuilds, WAL bursts, VACUUM FULL needs a copy
Connections70% of max_connectionsDeploy storms, retries
IOPS / throughput70% of provisionedCheckpoints and compaction spikes
Memory (Redis)maxmemory with 20–30% slackFork for RDB/AOF rewrite copies pages
N+1Each AZ/node can absorb one peer's loadFailover doubles load on survivors

Sequence:

text
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 plan

Real 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):

text
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
LineURL shortener year 1 (illustrative round numbers, not a quote)
Primary + 2 replicas, 16 vCPU / 64 GB each3 instances × 730 h × instance price
Hot storage600 GB × 3 copies = 1.8 TB SSD
Backupsbase backups + WAL ≈ 1–2× database size in object storage
Redisone 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.

text
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.

text
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 review

Real 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.

ProductModelScale-out storyDefault consistency / isolationHASweet spot
PostgreSQLRelational + JSONB, extensionsReplicas; partitioning; Citus or app shardingRead Committed; SSI availableStreaming replication + Patroni / managedGeneral OLTP up to multi-TB, rich queries
MySQL InnoDBRelationalReplicas; Vitess for shardingRepeatable ReadSemi-sync, Group ReplicationWeb OLTP, huge sharded fleets
SQL ServerRelationalRead replicas (AGs), partitioningRead Committed (RCSI optional)Always On AGsEnterprise OLTP + reporting
OracleRelationalRAC, partitioning, Oracle ShardingRead CommittedData GuardEnterprise OLTP
SQLiteEmbedded relationalNone (one writer)SerializableFile copy, LitestreamEdge, mobile, single-node apps
MongoDBDocumentNative shardingRead concern local, write concern majority (default since 5.0)Replica setsAggregates with evolving shape
CockroachDBDistributed SQLAutomatic range splittingSerializableRaftSQL + scale-out + multi-region
SpannerDistributed SQLAutomatic splitsStrict serializable (external consistency)PaxosGlobal strong consistency
RedisIn-memory KV + structuresRedis Cluster (16384 hash slots)Async replicationSentinel / ClusterCache, counters, timelines, rate limits
Cassandra / ScyllaDBWide-columnBuilt-in partitioning, multi-DCTunable per query (ONE…ALL)RF across racks/DCsMassive append-mostly writes
DynamoDBKey-value / documentAutomatic partitionsEventually consistent reads by defaultMulti-AZ, global tablesKnown access patterns, serverless scale
Elasticsearch / OpenSearchSearchShards + replicasNear real-time (refresh interval)Replica shardsText search, facets (not source of truth)
Neo4jGraphRead replicas; Fabric/sharding in enterpriseACID on primaryClusteringMulti-hop traversals
TimescaleDB / ClickHouseTime-series / columnarHypertables / distributed tablesBatch insertsReplicasMetrics, 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:

OperationTimeSource
fetch from L1 cache memory0.5 nsNorvig
fetch from L2 cache memory7 nsNorvig
Mutex lock/unlock25 nsNorvig
fetch from main memory100 nsNorvig
send 2K bytes over 1Gbps network20,000 ns (20 µs)Norvig
read 1MB sequentially from memory250,000 ns (250 µs)Norvig
round trip within same data centre500,000 ns (0.5 ms)Berkeley model source
fetch from new disk location (seek)8 msNorvig
read 1MB sequentially from disk20 msNorvig
send packet US to Europe and back150 msNorvig; 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.

text
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 danger

See 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.

FixHowCost
Shorten the holdDo the decrement last, right before COMMIT; keep the transaction free of network callsCode order matters
Split the counterinventory_buckets(product_id, bucket, available); decrement a random bucket with stockReads sum buckets; rebalancing
Pre-allocate tokensRedis DECR gate in front, DB confirmsTwo systems; reconcile on crash
Group commit / batchingQueue requests, apply in batchesLatency 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 ​

KnobProductDesign decision it encodes
shared_buffers, effective_cache_sizePostgreSQLWorking set in memory
innodb_buffer_pool_sizeMySQLWorking set in memory (often 50–75% of RAM on a dedicated host)
max_connections; PgBouncer pool_mode, default_pool_sizePostgreSQLConcurrency limit (Little's Law)
synchronous_commit, synchronous_standby_namesPostgreSQLRPO 0 for chosen data
rpl_semi_sync_source_wait_point = AFTER_SYNCMySQLLossless semi-sync
statement_timeout, idle_in_transaction_session_timeout, lock_timeoutPostgreSQLBound damage of slow or stuck work
innodb_lock_wait_timeoutMySQLSame, for row locks
default_time_to_live, gc_grace_seconds, compaction strategyCassandra / ScyllaDBRetention and tombstone lifetime
maxmemory, maxmemory-policyRedisCache size and eviction (allkeys-lru, volatile-ttl)
readConcern, writeConcern, readPreferenceMongoDBConsistency menu per operation
Provisioned vs on-demand capacityDynamoDBCost model and throttling behaviour

Error codes the design must handle Must-know ​

ErrorProductMeaningDesign response
40001 serialization_failurePostgreSQL, CockroachDBSerializable/RR conflictRetry whole transaction
40P01 deadlock_detectedPostgreSQLDeadlock victimRetry; fix lock order
23505 unique_violationPostgreSQLDuplicate keyBusiness answer (idempotent replay, "taken")
23514 check_violationPostgreSQLInvariant (e.g. available >= 0)Reject; investigate if reached
53300 too_many_connectionsPostgreSQLConnection limitPooler, backoff
57014 query_canceledPostgreSQLstatement_timeout firedFail fast; investigate query
1213 ER_LOCK_DEADLOCKMySQLDeadlockRetry
1205 ER_LOCK_WAIT_TIMEOUTMySQLLock wait timeoutRetry or fail
1062 ER_DUP_ENTRYMySQLDuplicate keyBusiness answer
1040 Too many connectionsMySQLConnection limitPooler
ProvisionedThroughputExceededExceptionDynamoDBPartition or table throttledBackoff; fix hot key
ConditionalCheckFailedExceptionDynamoDBCondition false (e.g. stock)Business answer
WriteTimeoutException / UnavailableExceptionCassandraNot enough replicas answeredRetry idempotent writes; check consistency level
OOM command not allowed when used memory > 'maxmemory'RedisMemory full with noevictionEviction 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.

#PatternKey / filterRowsPeak/sConsistency
AP1Redirect GET /:codecode119,300Bounded staleness (cache TTL, delete invalidates)
AP2Create POST /linksowner_id, url_hash1190Strong (unique code; idempotent per owner + URL)
AP3My linksowner_id, newest first5020Read-your-writes
AP4Clicks per daycode, day range≤ 4005Eventual (minutes)
AP5Expire / eraseexpires_at < now(), owner_idbatches1/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.

URL shortener: read-heavy key-value lookup (100:1), ~20k redirects/s peak, ~600 GB/yearBrowserGET /aZ3kQ9xPOST /linksLoad balanceror CDN edge302 + LocationAPI (stateless)Go / LaravelN replicasRedis cachelink:code -> url~5 GB hot set1. GETPostgreSQL primarylinks: UNIQUE(code)writes ~200/s peakRead replicas x2cache missesasync, lag okcreate2. missWAL streamClick bufferin-memory / RedisHINCRBY per click3. countlink_clicks_dailyone upsert percode per dayflush every 10 sSweeperdelete expiredbatchedHot path budget (p99 50 ms):Redis hit ~0.5 ms in-DC RTTmiss: index lookup 1-3 ms302 keeps analytics;301 is cached by browsers

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):

sql
-- 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.

sql
-- 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.

go
// 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
<?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
<?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.

LoadChangeTrigger
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 rollupsReplica 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_idPrimary write IOPS or storage > biggest instance

Failure analysis.

FailureEffectMitigation
Viral link expires from cacheThousands of misses at once (cache stampede / thundering herd)Cache::flexible / stale-while-revalidate, request coalescing (singleflight), jittered TTLs
Redis downAll 19k/s hit replicasReplicas sized for it, or degrade: in-process LRU for the top 10k codes
Primary failover (~30 s)Creates fail; redirects continue from cache and replicasClients retry AP2 with the same URL (idempotent)
Scanner enumerating codesMisses flood the DBNegative caching, rate limits per IP, random (non-sequential) codes
Deleted link still redirectsCache TTL; a reader refilling the key just before the deleteDelete key after commit; cap TTL at 60 s (maxTTL in Go, Cache::flexible(..., [30, 60]) in Laravel) and at expires_at
Click flush failsUndercountAt-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.

#PatternKey / filterPeak/sConsistency
AP1Place order (decrement stock, create order, emit event)idempotency_key, product_ids230Strong, atomic
AP2Product page stock badgeproduct_id20,000Bounded staleness (5 s)
AP3My orderscustomer_id, newest first200Read-your-writes
AP4Expire unpaid ordersstatus, expires_at10 batches/minStrong
AP5Payment confirmed → paidorder_id230Strong, idempotent
AP6Reports (sales per day/SKU)time rangelowEventual (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).

Order / inventory: correctness first, ~230 checkouts/s at flash-sale peak, ~730 GB/yearClientPOST /ordersIdempotency-KeyOrder APIGo / Laravelretry 40001/40P01One transaction (READ COMMITTED)SELECT customer FOR UPDATEINSERT orders ON CONFLICTUPDATE stock WHERE avail >= qtyINSERT lines + outboxPostgreSQL primaryorders by monthpartitionsCOMMITSync standbysynchronous_commitRPO = 0Async replicascatalogue + reports+ Redis cacheOutbox relaypoll or CDC (Debezium)at-least-onceKafka: order.placedPayment, shipping,search consumersdedup by event idExpiry sweeperFOR UPDATESKIP LOCKEDInvariants:available >= 0 (CHECK)one order per key (UNIQUE)qty per customer <= max

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:

sql
-- 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:

text
     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 -> ErrOutOfStock

Write 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:

text
     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)
BugFix in this designAlternativeWhy not only raise the level
Oversell (lost update)Atomic conditional UPDATE, CHECK (available >= 0)SELECT ... FOR UPDATE; version columnAtomic 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 rowSerializable works but adds 40001 retries on every checkout under load
Double submitUNIQUE (idempotency_key) + ON CONFLICT DO NOTHINGIdempotency table with stored response (Stripe model)Isolation cannot dedupe two separate requests
Deadlock between cartsLock products in ascending product_idRetry on 40P01 / 1213Ordering 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.

go
// 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
<?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
<?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.

LoadChangeTrigger
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 storePrimary CPU > 60%; table > 1 TB
100× / multi-merchantShard by merchant_id (Shopify pods: every request served by one pod) or move to CockroachDB/Spanner if one merchant outgrows a nodeBiggest instance at 70%

Failure analysis.

FailureEffectMitigation
Client retries after timeoutDuplicate orderIdempotency key unique constraint
Payment captured, order transaction rolled backMoney without orderCreate order first (pending), pay second; reconcile by idempotency key with the provider
Async replica promotedLast orders lostSync standby for this database (RPO 0); reconcile from outbox consumers
Outbox relay downEvents delayed, not lostAlert on oldest unpublished age; consumers dedupe by event id
Sweeper and payment race on one orderPaid order expiredBoth use WHERE status = 'pending_payment'; whoever commits first wins, the other updates 0 rows
Flash saleLock queue on one row, p99 explodesBucketed 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.

#PatternKey / filterPeak/sConsistency
C1Send messagechannel_id14,000Durable, ordered per channel
C2Open channel, last 50channel_id, newest first10,000Read-your-writes for the sender
C3Scroll backchannel_id, message_id < cursor2,000Eventual
F1Postauthor_id175Durable
F2Home feeduser_id, newest 507,000Eventual (seconds)
F3Profile feedauthor_id, newest 503,000Eventual

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.

Chat (left): write-heavy, append-only, ordered per channel. Feed (right): fan-out trade-off.SenderWebSocketChat serviceSnowflake idCassandra / ScyllaDBPK ((channel_id, bucket),message_id) RF=3appendOnline memberspub/sub fan-outper channelpushRead newest bucket, page by message_idSELECT ... WHERE channel_id=? AND bucket=?ORDER BY message_id DESC LIMIT 50~14k msgs/s peak; ~73 TB/year raw before RF.Hot channel = hot partition: coalesce reads,cache the last page, rate-limit @everyone.New postauthor AFan-out workersqueuepushTimelinesRedis ZSETper followerFan-out on write: 200 followers = 200 inserts; read = 1 range readOpen feedreader RFeed servicemerge k-wayPosts tableby author_id,created_atpullFan-out on read: 0 extra writes; read = N followees queries, mergedHybrid (what large feeds do)push for accounts under the follower threshold;pull celebrity posts at read time and mergeCelebrity, 10M followers: push = 10M writes per post.Pull = every reader pays a query; hybrid caps both costs.Cap timelines (~800 ids); rebuild cold users on demand.

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):

sql
-- 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.

StrategyWrite cost per postRead cost per feed openStalenessBreaks on
Fan-out on write (push)followers × 1 insert1 range read of the user's timelineSeconds of queue lagCelebrities: 10M inserts per post
Fan-out on read (pull)1 insertN followees × query + k-way mergeNoneUsers following thousands; read QPS × N
HybridPush only for authors under a threshold (e.g. 100k followers)1 timeline read + merge of a few celebrity profile feedsLowThreshold tuning; two code paths
text
     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):

go
// 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))
}
php
// 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.

LoadChangeTrigger
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 usersNode disk > 60%, p99 read > target
100×Multi-DC with LOCAL_QUORUM; tiered storage for old buckets; follows graph sharded by follower_idCross-region users; storage cost

Failure analysis.

FailureEffectMitigation
Hot channel (an @everyone announcement)Hot partition; node latency spreads to the clusterDiscord's answer: request coalescing in data services, cache the last page, rate-limit mentions
Large partition (busy channel, no bucketing)Slow reads, compaction painTime buckets sized to ~100 MB
DeletesTombstones slow reads until gc_grace_secondsAvoid delete-heavy patterns; run repairs within gc_grace_seconds
Celebrity postFan-out queue lag of minutesHybrid; threshold by follower count
Redis timeline lossEmpty feedsRebuild on demand from posts of followees (pull path)
Edit races with deletePartial 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):

go
// 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 / eventRetry?Rule
40001, 40P01, MySQL 1213Yes, whole transactionBackoff with jitter; 3–5 attempts; no side effects inside the transaction
MySQL 1205 lock wait timeoutUsuallyOnly the statement rolled back unless innodb_rollback_on_timeout; safest to retry the whole transaction
23505 / 1062 duplicateNoTranslate: idempotent replay, or "already taken"
23514 / MySQL 3819 check violationNoBusiness rejection; alert if it means a bug
Connection reset during COMMITOnly if idempotentThe commit may have happened: re-check by idempotency key
DynamoDB throttlingYesSDK retries with backoff; fix the hot key
Cassandra write timeoutOnly idempotent writesUpserts 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 / situationRecommendationExtra techniqueReason
Read-heavy point lookups (shortener, sessions, profiles)PostgreSQL/MySQL + Redis; DynamoDB at large scaleCache-aside, negative caching, stale-while-revalidateHot set fits in memory; DB only sees misses
Money, stock, bookingsRelational primary, Read CommittedAtomic updates, constraints, FOR UPDATE, idempotency keys, sync standbyInvariants enforced where the data lives
Multi-row rules (limits, quotas, rotas)SameMaterialise the conflict or Serializable + retryWrite skew is invisible otherwise
Append-mostly, huge volume, per-key ranges (chat, IoT, events)Cassandra/ScyllaDB, DynamoDB, or partitioned PostgreSQL below ~10 TBTime buckets, TWCS, TTLPartition-local writes scale linearly
Feeds / timelinesRedis or wide-column timelines + relational postsHybrid fan-outBounded write and read cost
Analytics on OLTP dataColumnar store via CDCPartition by timeOLTP primary stays for OLTP
Text searchElasticsearch/OpenSearch or PostgreSQL FTSCDC/outbox to indexSearch is a derived view
Global users needing strong consistencySpanner, CockroachDBRegional tables / localityConsensus per write; pay the latency knowingly
Many tenants, a few hugePool + RLS, silo/cell for the largesttenant_id leading every keyNoisy neighbours and blast radius

The checklist before a design review.

  1. Requirements table filled, with owners for every assumption (read/write ratio, p99 per operation, RPO/RTO, retention per data class, compliance).
  2. Access-pattern table with frequency and consistency per pattern; the top three are single-index or single-partition operations.
  3. Sizing sheet: peak QPS per pattern, GB/year per copy and in total, bandwidth, working set, connection count (Little's Law).
  4. Model and engine named, with the reason tied to the top patterns; every extra store justified by a pattern.
  5. Schema with primary keys, unique constraints for every natural key and idempotency key, CHECKs for invariants, and the index for each pattern.
  6. Concurrency: each invariant mapped to its mechanism (atomic update, constraint, lock, Serializable + retry); lock order stated.
  7. Scale ladder: the current rung and the next two, each with a trigger metric and threshold.
  8. Consistency per operation; replica reads have read-your-writes where needed.
  9. RPO/RTO per data class, HA mechanism, PITR, restore drill date; tenancy model.
  10. Headroom in months per resource; cost at 1×, 10×, 100×.
  11. Schema evolution: tool, expand/contract rules, backfill batch size.
  12. Observability: SLIs per pattern, rung triggers as alerts, reconciliation queries for invariants.
  13. 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.

text
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× ​

LoadURL shortenerOrder / inventoryChat / feed
1×1 primary + 2 replicas + Redis1 primary + sync standby + replicaWide-column cluster RF=3 + Redis timelines
10×Redis Cluster, CDN, clicks to ClickHouseMonthly partitions, bucketed hot SKUs, CDC to OLAPMore nodes, request coalescing, active-user timelines
100×Sharded by hash(code) or DynamoDBShard by merchant (pods) or distributed SQLMulti-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.

bash
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"; done

Experiment 1: measure bytes per row and extrapolate the sizing sheet.

sql
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/year

Experiment 2: reproduce the lost update, then the fix. Two terminals (docker exec -it dsd psql -U postgres):

sql
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 0

Experiment 3: reproduce the write skew on the purchase limit, then the fix.

sql
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 refuses

Experiment 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.

bash
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 everyone

Experiment 6: cache-hit ratio as working-set evidence.

sql
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 cache

Common misconceptions ​

BeliefReality
"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 ​

TopicRemember
MethodRequirements → access patterns → sizing → model → scale ladder → consistency → HA/backup/tenancy → operate
SecondsDay 86,400 ≈ 10^5; month ≈ 2.6M; year ≈ 31.5M
LatencyMemory 100 ns; in-DC RTT 0.5 ms; HDD seek 8 ms; US↔EU 150 ms
QPSevents/day ÷ 86,400 × peak factor
Storagerows × (row + indexes + overhead) × copies; measure with pg_total_relation_size
ConnectionsLittle's Law: busy = QPS × mean time
Hot rowThroughput ≤ 1 / lock hold time
ModelPick by top three access patterns; one general store first
Scale ladderIndex → bigger box → pool → replicas → cache → partition → split by function → shard
ConsistencyPer operation: strong, read-your-writes, bounded, eventual
Lost updateAtomic conditional UPDATE; CHECK as backstop
Write skewLock/materialise the rule's row, or Serializable + retry
IdempotencyUnique key + ON CONFLICT DO NOTHING; same key returns same result
HA vs backupReplicas for machines, PITR for mistakes; drill restores
Fan-outPush for normal authors, pull for celebrities
HeadroomCPU ≤ 70%, disk ≤ 80%, N+1 capacity

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Access patternOne query the system must serve: actor, key, filter, sort, size, frequency, consistency
Access-pattern tableThe list of all access patterns, written before the schema
Back-of-envelope estimateOrder-of-magnitude arithmetic for QPS, storage, bandwidth and memory
Read/write ratioReads per write for an entity or system; decides replicas and caches
QPSQueries (or requests) per second; always state average and peak
Peak factorRatio of peak to average load
Latency SLOTarget for a latency percentile (e.g. p99 ≤ 50 ms) of one operation
SLIThe measured indicator behind an SLO
p9999th percentile: 1 request in 100 is slower
Working setData touched often enough that it should be in memory
Buffer pool / shared_buffersThe database's page cache (InnoDB / PostgreSQL)
Cache hit ratioFraction of reads served from memory or cache
RetentionHow long a data class is kept before deletion or archive
ComplianceLegal and contractual rules on data: GDPR, PCI DSS, residency, audit
Data residencyRequirement that data stays in a jurisdiction
Right to erasureGDPR right to have personal data deleted
Crypto-shreddingDeleting data by destroying its encryption key (useful for backups)
Data modelRelational, document, key-value, wide-column, graph, time-series, search, columnar
Single-table designDynamoDB practice of storing several item types in one table with overloaded keys
GSIDynamoDB global secondary index; another partition/sort key, eventually consistent
Partition key / clustering keyWide-column keys: which node and partition; order inside the partition
Hot partition / hot keyOne key receiving disproportionate traffic
Hot rowOne row updated by most transactions; throughput ≤ 1 / lock hold
Scale ladderOrdered list of scaling steps from query fixes to sharding
Vertical scalingA bigger machine
Read replicaCopy of the primary serving reads, usually asynchronously
Cache-asideApp reads cache, on miss reads DB and fills cache
Cache stampede / thundering herdMany requests miss the same key at once and all hit the DB
Stale-while-revalidateServe the old value while one request refreshes it (Cache::flexible)
Negative cachingCaching "not found" so repeated misses do not reach the DB
Request coalescing / singleflightMany identical concurrent requests share one backend call
PartitioningSplitting a table into parts on one server (by range, list, hash)
Functional (vertical) partitioningMoving groups of tables to separate databases
ShardingSplitting data across servers by a shard key
Logical shardA small unit of data mapped to a physical host; moved without re-hashing
Cell / podFully isolated stack (app + datastores) serving a subset of tenants
Consistency menuChoosing a guarantee per operation
Read-your-writesA user always sees their own writes
Monotonic readsA session never reads older data than it already saw
Bounded stalenessReads lag by at most a known time or number of versions
Eventual consistencyReplicas converge if writes stop
QuorumR + W > RF so reads overlap the latest write
RPORecovery point objective: how much committed data may be lost
RTORecovery time objective: how long recovery may take
PITRPoint-in-time recovery from base backup + log archive
Synchronous standbyReplica that must confirm before commit returns (RPO 0)
Semi-syncMySQL replication where a replica acknowledges receipt before commit returns
Pool / bridge / siloTenancy models: shared tables / schema per tenant / database per tenant
RLSRow-level security: per-row access policies (PostgreSQL)
HeadroomSpare capacity before a threshold, expressed in time at current growth
N+1 capacityEnough capacity to lose one node or zone at peak
Little's LawL = λ × W: concurrency = arrival rate × time in system
EgressNetwork traffic leaving a provider or zone; often billed
Expand/contractAdditive schema change, migrate code and data, then remove the old shape
Online DDLSchema change without blocking reads/writes (CONCURRENTLY, ALGORITHM=INSTANT, gh-ost)
BackfillBatch job filling a new column or table
Golden signalsLatency, traffic, errors, saturation
Reconciliation queryPeriodic check that an invariant holds across tables or systems
Idempotency keyClient-generated id that makes retries return the first result
Lost updateTwo read-modify-writes where the second overwrites the first
Write skewTwo transactions check one rule, write different rows, rule breaks
Materialising the conflictAdding a row both transactions must lock so write skew becomes a lock conflict
Transactional outboxEvents written in the same transaction as the change, published later
SagaSequence of local transactions with compensations
CDCChange data capture: streaming committed changes from the log
SKIP LOCKEDLocking read that skips rows locked by others (job queues, sweepers)
Fan-out on write / readPush items into followers' timelines vs merge followees at read time
Hybrid fan-outPush for most authors, pull for celebrities
Celebrity problemAn account whose follower count makes push fan-out too expensive
Snowflake id64-bit time-ordered id: timestamp, machine/shard bits, sequence
Base62Encoding with 0-9A-Za-z, used for short codes
TWCSCassandra Time Window Compaction Strategy for time-bucketed data
TombstoneDeletion marker in LSM stores, removed after gc_grace_seconds
Replication factor (RF)Number of copies of each partition in Cassandra/ScyllaDB
301 / 302Permanent (cached by browsers) vs temporary redirect

References ​

Built by Morteza Negahi