Storage & Data Scaling: The Scale Ladder
"Query performance and upkeep processes often begin to degrade well before a table reaches the maximum hardware-bound size; our stalling Postgres auto-vacuum was an example of this soft limitation." — Garrett Fidalgo, "Herding elephants: Lessons learned from sharding Postgres at Notion", Notion blog, October 2021
Summary: Scaling a data layer is a ladder of nine steps ordered by cost and reversibility; you climb one rung only when a measurement says the current rung is out of room. Focus: What to measure, the nine rungs (indexes to polyglot/CQRS), read/write splitting with read-your-writes, caching without stampedes, hot keys, the Universal Scalability Law, and the Notion and Figma stories. Learning goal: Given a graph of p99, QPS and resource saturation, name the next rung, its cost, its rollback path, and the trigger that tells you to stop.
This page is the conceptual map of data-layer scaling. It teaches the ladder, the measurements that justify each step, the laws that predict where adding capacity stops helping (Amdahl, Little's law, the Universal Scalability Law), and the two published company stories that document the climb. The hands-on mechanics live on sibling pages: Partitioning & Sharding in PostgreSQL, Replication, Read Replicas & Failover, Connection Pooling, Indexing, Query Planning, Consistent Hashing, Redis, NoSQL: Families & Data Models and OLTP vs OLAP & Columnar Storage. Here each of those is one sentence and a link; this page is about choosing between them.
Page map
| If you are looking for | Go to |
|---|---|
| The nine rungs, the metrics and the three laws in one table each | Everything in one minute |
| Why a ladder and not "just shard" | Why a ladder |
| Primary sources and what each actually says | Where it comes from |
p50/p99, QPS, working set vs RAM, cache hit ratio, pg_stat_io | Measure first |
| Rows per day, peak factors, connection budgets | Capacity estimation |
| Little's law, Amdahl, USL with a plotted curve | The three laws |
| Each rung with plain words, misunderstanding, timeline | The ladder, rung by rung |
| Read/write split, stickiness, replication lag | Read replicas and read-your-writes |
TTL jitter, stampede, singleflight, Cache::flexible | Caching tiers |
| One key melting one node | Hot keys |
| Group commit, batching, write buffers | Write buffering and batching |
| NUMA, IOPS, cloud ceilings | Vertical limits |
| Knobs, views and error messages | Mechanics |
| Notion and Figma with quotes, "shard earlier" vs "premature" | Two stories |
| Cost and rollback of every rung | Cost and rollback table |
| When a different store wins | When a different store wins |
| Go and Laravel code | Solving it in code |
| Which rung for which symptom | Choosing the next rung |
| Monolith to 100x | In architecture |
| pgbench, add a replica, watch lag | Lab |
Everything in one minute
The ladder. Each row is unpacked in the ladder section.
| # | Rung | What it buys | What it costs | Trigger to climb |
|---|---|---|---|---|
| 1 | Fix queries and indexes | Less work per request, no new machines | Index write cost, maintenance | p99 high with sequential scans or N+1 |
| 2 | Vertical scaling | More CPU, RAM, IOPS, no app change | Money; ceilings; restarts | CPU or IOPS near the ceiling, working set above RAM |
| 3 | Connection pooling | Fewer backends, steadier latency | Another hop; session-state limits | Hundreds of connections, context-switch storms |
| 4 | Caching tiers | Removes repeat reads | Staleness, invalidation, stampedes | Read QPS concentrated on few rows |
| 5 | Read replicas | Read capacity, HA standby | Replica lag, read-your-writes logic | Read CPU-bound, primary still has write headroom |
| 6 | Partitioning | Cheap retention, small hot set | Key design, no extra write capacity | Table size, vacuum time, retention |
| 7 | Functional decomposition | Independent databases per domain | No cross-domain joins or transactions | Write IOPS of one table group dominates |
| 8 | Sharding | Write scale-out | Joins, FKs, transactions, resharding | One primary cannot absorb writes |
| 9 | Polyglot stores, CQRS | Each workload on a fitting engine | Eventual consistency, pipelines | A workload the engine is structurally bad at |
What to measure before climbing.
| Metric | Why it matters | Where to get it (PostgreSQL) |
|---|---|---|
| p50, p95, p99 latency per endpoint | Averages hide the tail users feel | APM, pg_stat_statements (mean_exec_time, max_exec_time) |
| QPS, split into reads and writes | Reads and writes scale by different rungs | pg_stat_database (xact_commit, tup_returned, tup_inserted) |
| Working set vs RAM | In memory vs on disk is a 100x latency step | pg_buffercache, table and index sizes |
| Cache hit ratio (buffer and application) | Low ratio means disk or database is the bottleneck | blks_hit / (blks_hit + blks_read), Redis keyspace_hits |
pg_stat_io | Reads, writes, hits, evictions by backend type and context (PostgreSQL 16+) | SELECT * FROM pg_stat_io |
| Saturation: CPU, IOPS, WAL, locks, connections | The one that hits 100% first is the next rung | node_exporter, pg_stat_activity, pg_stat_wal |
| Replication lag | Bounds how stale a replica read can be | pg_stat_replication.replay_lag |
The three laws.
| Law | Formula | One-line meaning |
|---|---|---|
| Little's law | L = λ × W | Requests in flight = arrival rate × time each spends in the system |
| Amdahl's law | S(N) = 1 / (s + (1 − s) / N) | The serial fraction s caps speedup at 1/s |
| Universal Scalability Law | C(N) = N / (1 + α(N − 1) + βN(N − 1)) | Contention α flattens the curve; coherency β bends it down (retrograde) |
Where it comes from
There is no single paper behind "scaling the data layer". It is a body of practice, and the best primary sources are the postmortems of teams that did it. The PostgreSQL manual states the underlying difficulty in the introduction to its high-availability chapter:
"This synchronization problem is the fundamental difficulty for servers working together."
Read-only data can be copied anywhere; the moment there are writes, a write to any server has to be propagated to all servers so that future reads return consistent results. Every rung of the ladder is a different answer to that sentence.
| Source | What it documents | What to take, and what not |
|---|---|---|
| Notion, October 2021 (Fidalgo) | Sharding a Postgres monolith into 480 logical shards on 32 physical databases | The reasoning for 480, double-write plus audit log, dark reads. Their numbers are theirs |
| Figma, March 2024 (Steele) | One RDS Postgres on "AWS's largest physical instance" in 2020, then caching, read replicas, a dozen vertical partitions, then horizontal sharding | The staging: each step bought runway for the next |
| Gunther, Universal Scalability Law | A two-parameter model of scalability, a generalisation of Amdahl | Fit α and β to your data; do not treat the curve as a forecast |
| PostgreSQL docs, High Availability | Synchronous vs asynchronous, stale results, read-your-writes | The vocabulary used in this page |
| Laravel 13 docs, database and cache | read/write/sticky, usingWritePdo, Cache::flexible | Exact API names |
Neil Gunther's USL, as stated on his page, is:
"C(N) = N / (1 + α(N − 1) + βN(N − 1))"
Why a ladder
Every rung trades something. The ladder exists because the cheap trades are reversible and the expensive ones are not, so you spend the reversible ones first.
| Cheaper, reversible rung | Expensive, hard-to-undo rung |
|---|---|
| Application code does not change (bigger instance) | Application learns the shard key, routing, partial failure |
| One database, one transaction, all joins | Many databases; joins and transactions become your problem |
| Rollback is a config flag or a resize | Rollback is a project (Figma: logical sharding rolls back by config, physical sharding "requires more complex coordination") |
| Failure modes you already know | New failure modes: partial commits, skewed shards, stale reads |
The analogy we reuse on this page: a restaurant that gets busy. First the chef fixes the slow dish (queries and indexes). Then a bigger stove (vertical). Then a pass-through window so waiters do not crowd the kitchen door (connection pooling). Then the popular sauce is made in batches and kept at the pass (cache); it must be thrown out when the recipe changes. Then a second counter serves cold dishes (replicas), though it only knows the menu as of a moment ago. Then the kitchen is split into grill and pastry (functional decomposition). Opening a second restaurant with its own kitchen and its own regulars (sharding) is the last step, because nobody can order from both menus on one bill. A sushi bar next door (a different store) is for the dishes this kitchen is bad at.
Three common misunderstandings, up front
- "Scaling means sharding." Sharding is rung 8 of 9. Most systems that "need to scale" are missing an index, a pool or a cache.
- "More replicas means more write capacity." Replicas replay every write. They add read capacity only, and under the USL they add coherency cost.
- "A cache is free speed." It is a second copy of the truth with an invalidation problem, a cold-start problem and a stampede problem.
Measure first
Measuring before climbing Must-know
In plain words: Find out which resource runs out first, in how many months, before you buy anything or write any routing code.
Common misunderstanding: "The database is slow, so we need a bigger database." Often the slow part is one query, one missing index, an N+1 loop in the ORM or a connection storm; a bigger machine hides that for a quarter and then you are back, with a larger bill.
Definition: A bottleneck is the resource at 100% utilisation (or the lock queue) that sets throughput. The working set is the data and indexes touched regularly within some window; if it fits in RAM (shared_buffers plus the OS page cache) reads are memory-speed, if not, every miss is a disk read. Saturation is a resource with a queue in front of it.
1 Symptom: p99 of GET /orders jumps from 80 ms to 900 ms at 10:00 every day
2 Check: QPS split -> reads 2,300/s, writes 150/s (read-heavy)
3 Check: buffer hit ratio -> 99.4% at 09:00, 91% at 10:00 (working set no longer fits)
4 Check: pg_stat_io -> reads from disk up 12x, evictions up 9x
5 Check: table + index size -> 118 GB vs 64 GB RAM (working set > RAM)
6 Next rung: not shards. Drop two unused indexes (-9 GB), add a partial index,
then move from 64 GB to 128 GB RAM. p99 back to 85 ms.Real scenarios: a nightly report evicts the hot working set from the buffer cache and the morning rush reads from disk; a new feature adds an ORM N+1 and QPS triples without any new users; a marketing push doubles connections and the CPU is spent on context switches; autovacuum falls behind (Notion's "soft limitation") long before the disk is full.
| Measurement | Healthy sign | Unhealthy sign | Likely next rung |
|---|---|---|---|
| Buffer hit ratio (OLTP) | above 99% | below 95% | Indexes, then vertical (RAM) |
| CPU, reads dominate | below 60% at peak | above 80% with idle IOPS | Cache, then read replicas |
| IOPS or WAL throughput | below 70% of provisioned | at the provisioned limit | Vertical (storage class), batching, then decomposition or sharding |
| Active connections | max_connections not approached | Hundreds, with idle in transaction | Pooling |
| Replication lag p99 | well below your staleness budget | seconds, growing | Fix replica I/O, or stop adding read load |
Autovacuum / VACUUM duration | finishes between peaks | runs for days; wraparound warnings | Partitioning, decomposition, sharding (see MVCC & VACUUM) |
Fix / how to use it:
-- Top time consumers (needs the pg_stat_statements extension)
SELECT queryid, calls, round(mean_exec_time::numeric, 1) AS mean_ms,
round(total_exec_time::numeric / 1000) AS total_s, left(query, 80) AS q
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;
-- Buffer cache hit ratio per database
SELECT datname, round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_database WHERE datname = current_database();
-- Where I/O really happens (PostgreSQL 16+); times need track_io_timing = on
SELECT backend_type, object, context, reads, writes, hits, evictions, read_time
FROM pg_stat_io WHERE reads > 0 OR writes > 0 ORDER BY reads DESC LIMIT 10;
-- Biggest tables and indexes: the working-set suspects
SELECT relname, pg_size_pretty(pg_total_relation_size(oid)) AS total
FROM pg_class WHERE relkind = 'r' ORDER BY pg_total_relation_size(oid) DESC LIMIT 10;Go: export p50/p99 as a histogram (prometheus/client_golang) around every db.QueryContext, and db.Stats() (open connections, WaitCount, WaitDuration) as gauges. Laravel: DB::listen() for slow queries, Laravel Pulse or Telescope for per-route timings. Details of each knob live in Database Observability.
Figma describes the same discipline: they "used a combination of historical data and load-testing to quantify database scaling limits from CPU and IO to table size and rows written", so each shard had a known runway.
Capacity estimation
Back-of-envelope capacity Important
In plain words: A five-minute calculation that says which resource runs out first and in how many months.
Common misunderstanding: "Average load is the number to design for." Systems break at the peak and at the tail; the average is only the starting point of the calculation.
Definition: peak QPS = average QPS × peak factor. The peak factor is 2 to 3 for steady B2B traffic, 5 to 10 for consumer apps with daily rhythms, and 20 or more for flash sales and TV-driven spikes. Disk = rows per day × bytes per row × index overhead × retention. Always add headroom (aim to run below 60 to 70% of the measured ceiling) so that a failover or a deploy does not push you over.
1 Traffic 20,000,000 requests/day / 86,400 s = 231 QPS average
2 Peak 231 x peak factor 6 = ~1,400 QPS (read:write = 90:10)
3 Writes 1,400 x 10% = 140 writes/s at peak
4 Rows 5,000,000 orders/day x 300 B = 1.5 GB/day raw
5 Indexes x 2 (heap + 3 indexes) = 3 GB/day
6 Retention 3 years x 365 x 3 GB = 3.3 TB
7 Connections Little: 1,400 QPS x 0.015 s = 21 busy backends (pool of 40, not 2,000)
8 Verdict Disk fills before IOPS or CPU do: partitioning (retention) comes before sharding.| Resource | Estimate with | Typical first limit for OLTP |
|---|---|---|
| Disk | rows/day × row size × index overhead × retention | Disk full or vacuum time, months to years ahead |
| IOPS | writes/s × (WAL + heap + index writes), plus cache misses/s | Often before CPU on cloud block storage |
| CPU | QPS × CPU time per query (pg_stat_statements) | Reads dominate: replicas and caches help |
| RAM | working set (hot rows + their indexes) | A step change in latency when exceeded |
| Connections | Little's law: QPS × latency | Pool, do not raise max_connections |
| Network | rows returned × width × QPS | Large result sets and replication traffic |
Notion sized its fleet against a two-year projection and per-table and per-database ceilings ("an upper bound of 500 GB per table and 10 TB per physical database" in their post). The point is not accuracy; it is knowing which resource runs out first and when.
The three laws
Little's law and connection budgets Important
In plain words: The number of things in the system equals how fast they arrive times how long each one stays.
Common misunderstanding: "More connections means more throughput." Throughput is capped by what the database can run in parallel (cores, IOPS); extra connections only lengthen the queue and add context switching.
Definition: L = λW. With λ = 2,000 queries per second and W = 15 ms in the database, L = 30 backends are busy at any instant. A pool of 40 serves that load; 2,000 open connections do not make it faster. When W doubles (a slow query, a lock), L doubles, so a latency spike becomes a connection spike; this is how a slow query takes down the whole pool. See Connection Pooling for PgBouncer modes and sizing.
Amdahl's law Good to know
In plain words: If 5% of the work cannot be parallelised, you can never go more than 20 times faster, no matter how many machines you add.
Common misunderstanding: "Doubling the nodes doubles the speed." Only the parallel part speeds up; the serial part (a single primary taking every write, a global lock, one hot row) stays.
Definition: S(N) = 1 / (s + (1 − s) / N). With s = 0.05, S(16) = 9.1 and S(∞) = 20. For databases s is the work that must go through one place: the primary's WAL, a sequence, a row-level lock, a coordinator.
The Universal Scalability Law Must-know
In plain words: Adding machines helps less and less, and past some point it makes things slower, because the machines spend their time agreeing with each other.
Common misunderstanding: "Worst case, extra capacity does nothing." It can do harm. A non-zero coherency term means throughput goes down when you add nodes, connections or writers past the peak.
Definition: Gunther models relative capacity C(N) = X(N)/X(1) at load or size N with three effects: concurrency (ideal linear speedup), contention α (waiting for shared resources, which is Amdahl's serial fraction) and coherency β (the cost of making distributed copies agree). When β = 0 the USL reduces to Amdahl's law. Gunther's page states that "a non-zero value of β is associated with measured throughput that goes retrograde, i.e., decreases with increasing load or platform configuration", and that "The objective of using eqn.(3) is NOT to produce a curve that passes through every data point". The peak is at N* = √((1 − α) / β). The generalised form with γ is X(N) = γN / (1 + α(N − 1) + βN(N − 1)), which lets the regression estimate X(1) too.
The plotted curve uses α = 0.05 and β = 0.002 (an illustration, not a measurement). Linear speedup is the dotted line; Amdahl keeps climbing towards 20; the USL peaks at N = 22 with C ≈ 7.4 and then declines.
| Symptom in a database | USL term | Typical cause | Lever |
|---|---|---|---|
| Throughput flattens with more clients | α (contention) | One hot row, one lock, one WAL writer, one sequence | Remove the shared thing: shard the key, batch, use SKIP LOCKED |
| Throughput falls with more clients | β (coherency) | Connection storms, lock-manager and buffer-mapping contention, cross-shard coordination | Pool, reduce N, avoid cross-node chatter |
| More replicas do not reduce primary load | β rising | Each replica adds WAL sender work and feedback | Cascading replicas, fewer larger replicas |
| Cross-shard queries slower than single-shard | β | Scatter-gather: every shard must answer | Shard key aligned with the access pattern |
Fit α and β by load-testing at several N (see the lab); the go run ./usl snippet below prints the curve and the peak.
// Command usl prints the Universal Scalability Law curve, its peak, and
// Little's law for a connection budget. Run: go run ./usl
package main
import (
"fmt"
"math"
)
// capacity is Gunther's C(N) = N / (1 + a(N-1) + b*N*(N-1)).
func capacity(n, alpha, beta float64) float64 {
return n / (1 + alpha*(n-1) + beta*n*(n-1))
}
// peak is the N where C(N) is maximal; beyond it throughput goes retrograde.
func peak(alpha, beta float64) float64 {
return math.Sqrt((1 - alpha) / beta)
}
// amdahl is the beta = 0 special case.
func amdahl(n, serial float64) float64 {
return 1 / (serial + (1-serial)/n)
}
func main() {
const alpha, beta = 0.05, 0.002
fmt.Printf("peak at N = %.1f\n", peak(alpha, beta))
for _, n := range []float64{1, 2, 4, 8, 16, 22, 32, 48, 64} {
fmt.Printf("N=%-3.0f usl=%5.2f amdahl=%5.2f\n", n, capacity(n, alpha, beta), amdahl(n, alpha))
}
// Little's law: L = lambda * W. 2000 queries/s at 15 ms in the database
// means about 30 connections busy at once, however many the app opens.
const lambda, w = 2000.0, 0.015
fmt.Printf("busy connections = %.0f\n", lambda*w)
}The ladder, rung by rung
Rung 1: fix queries and indexes Must-know
In plain words: Make each request do less work before you add machines to do the same wasteful work.
Common misunderstanding: "Indexes are free speed." Each index costs write amplification, disk, RAM and vacuum work; too many indexes can be the reason writes are slow.
Definition: Index design, query rewrites, removing N+1 loops, pagination without large OFFSET, selecting only needed columns. A missing index or an N+1 loop is a bigger lever than hardware. Owned by Indexing, Query Planning, ORM Pitfalls and Pagination.
1 Before SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;
2 Seq Scan on orders (rows=48,000,000) ... Execution Time: 6,100 ms
3 Fix CREATE INDEX CONCURRENTLY orders_cust_created ON orders (customer_id, created_at DESC);
4 After Index Scan using orders_cust_created ... Execution Time: 0.4 ms
5 Effect CPU 85% -> 12% at the same QPS; no new hardware, no new rung.Real scenarios: a dashboard doing 200 lookups per page view (N+1); an OFFSET 900000 export; LIKE '%term%' on a large column; a WHERE lower(email) = ... without an expression index; unused indexes that slow every INSERT.
Cost and rollback: cost is write overhead; rollback is DROP INDEX CONCURRENTLY. This is the most reversible rung there is.
Rung 2: vertical scaling Important
In plain words: Move to a bigger machine. Nothing in the application changes.
Common misunderstanding: "Vertical scaling is not real scaling." It is the cheapest change in application terms and it often buys a year. Its ceiling arrives earlier than the hardware limit, though; see Vertical limits.
Definition: More vCPUs, more RAM (a bigger working set in memory), faster or more provisioned storage IOPS and throughput. Notion's name for the habit is "playing Cookie Clicker with the RDS 'Resize Instance' button". Figma's reason to leave it was specific: tables with "several terabytes and billions of rows", "reliability impact during Postgres vacuums", and highest-write tables that "would soon exceed the maximum IO operations per second (IOPS) supported by Amazon's Relational Database Service".
Cost and rollback: cost is money, a restart or failover, and a bigger blast radius per node; rollback is another resize, but cloud storage usually cannot shrink.
Rung 3: connection pooling Must-know
In plain words: Let many application workers share a small, steady set of database connections.
Common misunderstanding: "Raise max_connections when you see too many clients." Each PostgreSQL backend is a process with its own memory; more of them means more context switching and lock-manager pressure (the β term). Pool instead.
Definition: PgBouncer (transaction or session mode), pgcat or Odyssey for PostgreSQL; ProxySQL for MySQL; the application's own pool (sql.DB, Hikari, Laravel's persistent connections or Octane). Size by Little's law. Full treatment: Connection Pooling. Figma's applications "talked directly to our connection pooling layer, PGBouncer" before they built DBProxy.
Cost and rollback: another hop and some session-state limits (transaction-mode pooling breaks session SET, advisory locks and prepared statements unless configured); rollback is pointing the DSN back.
Rung 4: caching tiers Must-know
Covered in depth in Caching tiers: in-process cache, shared cache (Redis, Memcached), CDN and HTTP caching, with TTL, jitter, stampede protection and invalidation.
Rung 5: read replicas and read/write splitting Must-know
Covered in depth in Read replicas and read-your-writes.
Rung 6: partitioning Important
In plain words: Cut one huge table into smaller pieces inside the same database so old data can be dropped cheaply and hot data stays small.
Common misunderstanding: "Partitioning makes writes scale." It does not: one server still performs every write. It helps retention (drop a partition instead of a giant DELETE), vacuum (smaller units), and queries that prune to a few partitions.
Definition: Declarative range, list or hash partitioning in PostgreSQL; PARTITION BY in MySQL; partition keys in SQL Server and Oracle. Mechanics, pruning and pitfalls: Partitioning & Sharding in PostgreSQL and Billion-Row Tables.
1 CREATE TABLE events (id bigint, tenant_id int, at timestamptz, body jsonb) PARTITION BY RANGE (at);
2 CREATE TABLE events_2026_11 PARTITION OF events FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
3 -- retention: instant, no table-wide DELETE, no bloat
4 ALTER TABLE events DETACH PARTITION events_2024_11 CONCURRENTLY;
5 DROP TABLE events_2024_11;Cost and rollback: the key must appear in queries or pruning does not happen; unique constraints must include the partition key; rollback is ATTACH/DETACH or a copy back. Partitioning is also the on-ramp to sharding: a partition boundary can later become a shard boundary.
Rung 7: functional decomposition (vertical partitioning) Important
In plain words: Give each business area its own database, so one area's write load no longer shares a disk with another's.
Common misunderstanding: "This is microservices." It can exist inside a monolith (several connections, one deploy); it is a data-ownership decision, not a deployment one. Full microservices add network calls and sagas on top.
Definition: Split groups of related tables onto separate servers. Figma split "groups of related tables—like 'Figma files' or 'Organizations'—into their own vertical partitions", and called it "a relatively easy and very impactful scaling lever", noting its limit: "the smallest unit of partitioning is a single table". Joins and foreign keys across the split disappear; transactions across it need a saga or an outbox (messaging: Saga, Outbox).
1 Before one Postgres: users, files, comments, billing, audit_log (all share WAL and IOPS)
2 Step 1 find cross-domain joins: SELECT ... FROM files f JOIN billing b ON ... -> replace by an ID lookup
3 Step 2 add second connection: 'billing' => [...] (Laravel) / billingDB *sql.DB (Go)
4 Step 3 logical replication copies billing tables to the new server; dual-read, then cut over
5 After two WAL streams, two sets of IOPS; billing outages no longer stall file writesCost and rollback: loses cross-domain joins and atomic transactions; rollback is a reverse copy and is a project, not a flag.
Rung 8: sharding Must-know
In plain words: Split one table's rows across several databases by a key, so each database takes a share of the writes.
Common misunderstanding: "Sharding spreads load evenly." It spreads keys, not load. One huge tenant or one viral item sends most traffic to one shard (see Hot keys).
Definition: Application-level or proxy-level routing of each row to a shard by a shard key (hash, range or directory/lookup). What you lose, in Figma's list: certain SQL "becomes inefficient or impossible", "Foreign keys and globally unique indexes can no longer be enforced by Postgres", and "writes to some databases will succeed while others fail". A query without the shard key must visit every shard (scatter-gather). IDs must not depend on one sequence (ID Generation at Scale). Resharding is its own project: use many logical shards over fewer physical ones (Consistent Hashing).
| Choice | Option | Strength | Weakness |
|---|---|---|---|
| Shard key | hash(tenant_id) | Even spread; tenant queries stay on one shard | One giant tenant is still one shard |
| Shard key | Range on time or ID | Range scans stay local | Newest range takes all writes (hotspot) |
| Shard key | Directory (lookup table) | Move any tenant anywhere | Lookup is a dependency and a cache |
| Where routing lives | In the app | No extra hop | Every service must embed it |
| Where routing lives | Proxy (Figma DBProxy, Vitess, Citus coordinator) | One place for routing, load-shedding, observability | Another service to run |
| Engine | Distributed SQL (CockroachDB, Spanner, YugabyteDB, TiDB) | Sharding and transactions inside the database | Latency of consensus; cost; ecosystem differences |
| Engine | Built in (MongoDB sharded clusters, Cassandra, DynamoDB) | No application routing | Different data model and consistency |
Notion chose 480 logical shards because the number "is divisible by a lot of numbers" so that hosts could go "from 32 to 40 to 48" instead of doubling. Figma separates "logical sharding" from "physical sharding" so that a shard split is a failover, not an application change.
Cost and rollback: highest cost on the ladder. Figma's logical sharding "was a simple configuration change" to roll back; rolling back a physical shard operation "requires more complex coordination". Plan the rollback before you start.
Rung 9: polyglot storage and CQRS Important
In plain words: Let each kind of question be answered by the engine that is good at it, fed by copies of the data.
Common misunderstanding: "CQRS means event sourcing and two databases from day one." CQRS only means the write model and the read models are separate; the read model can be a materialised view or a denormalised table. Event sourcing is a separate, optional choice (Event Sourcing & CQRS).
Definition: Search to a search engine (Full-Text Search), analytics to a columnar store (OLTP vs OLAP), a denormalised read model for a hot screen, a key-value or wide-column store for a firehose (NoSQL families), all fed from the primary by events or change data capture (CDC). The write model stays normalised; read models are disposable copies. The price is eventual consistency between them.
Cost and rollback: pipelines to operate, lag to monitor, reconciliation jobs; rollback is dropping the read model and reading from the source again, which only works if the source stayed authoritative.
Read replicas and read-your-writes
Read/write splitting Must-know
In plain words: Send writes to one server and spread reads over copies of it.
Common misunderstanding: "A replica is the same as the primary, just another server." Replicas are asynchronous by default, so they are slightly behind; a read right after a write can return the old value.
Definition: The primary streams its write-ahead log to one or more standbys that apply it. The PostgreSQL manual states that asynchronous solutions "allow some delay between the time of a commit and its propagation to the other servers", with the result that load-balanced servers "might return slightly stale results". The chapter has a dedicated section, "Read-Your-Writes Consistency". Mechanics, lag measurement and failover are in Replication, Read Replicas & Failover.
T1 (user) Primary Replica (lag ~ 300 ms)
1 POST /profile name = 'Ada' -> UPDATE ... COMMIT
2 302 redirect to /profile
3 GET /profile SELECT name ... -> 'Alan' (old value!)
4 user: "my change was lost"
5 ... 300 ms later the replica replays the WAL; the next GET returns 'Ada'Real scenarios: profile edit then redirect; "order placed" page that lists orders; a login that creates a session row then reads it; a checkout confirmation page; admin saves a setting and the next API call still uses the old one.
| Technique | How it works | Strength | Weakness |
|---|---|---|---|
| Sticky window | After a write, pin this user's reads to the primary for T seconds (cookie or session) | Simple, no replica queries | T must exceed worst lag; load on primary |
Sticky per request (Laravel sticky) | Reads after a write in the same request use the write connection | One config key | Does not survive a redirect |
| LSN / GTID token | Remember the commit LSN; read from a replica only if pg_last_wal_replay_lsn() >= token (MySQL: WAIT_FOR_EXECUTED_GTID_SET) | Exact | More code; a query per read or a lag cache |
| Read own data from primary | Reads of what the user just wrote go to the primary by design | Targeted | Needs a per-query decision |
synchronous_commit = remote_apply | Commit waits until a synchronous standby has applied it | Replica reads are current | Slower commits; a standby outage can stall writes |
| Monotonic reads pinning | Hash the user to one replica | Time never goes backwards for a user | Not read-your-writes; one replica gets all of a user's load |
| Client-side merge | Overlay recently written values on a replica result | No primary load | Complex, easy to get wrong |
Per-product defaults: PostgreSQL streaming replication is asynchronous by default (synchronous_commit = on waits only for local flush unless synchronous_standby_names is set). MySQL uses asynchronous replication with optional semi-synchronous plugins and reports Seconds_Behind_Source. SQL Server offers asynchronous and synchronous availability-group replicas, Oracle has Active Data Guard with real-time apply, MongoDB uses readPreference and readConcern, and CockroachDB and Spanner serve consistent follower reads at a chosen staleness. Aurora and RDS expose reader endpoints with lag measured in tens of milliseconds, still asynchronous in the application's eyes.
Recovery conflicts. Long queries on a hot standby can be cancelled when WAL replay needs to remove rows they still see: ERROR: canceling statement due to conflict with recovery (SQLSTATE 40001). Knobs: max_standby_streaming_delay (default 30 s), hot_standby_feedback (replica tells the primary to keep old row versions, at the price of bloat on the primary). Run reporting queries on a dedicated replica with a larger delay.
Go code for a sticky router with an LSN check (CaughtUp) is below; the earlier after/store.go shows the in-request form.
// Package sticky routes reads to a replica unless the caller wrote recently.
// The "wrote at" marker travels in a cookie, so it survives a redirect and
// lands on any app instance (Laravel's sticky option only covers one request).
package sticky
import (
"context"
"database/sql"
"net/http"
"strconv"
"sync/atomic"
"time"
)
const cookieName = "wrote_at"
type ctxKey struct{}
// Router owns one primary handle and a list of replica handles.
type Router struct {
Primary *sql.DB
Replicas []*sql.DB
// Window must exceed the replica lag you are willing to tolerate (p99
// lag plus a margin). Pin to the primary for this long after a write.
Window time.Duration
next atomic.Uint64
}
// Middleware turns the cookie into a context flag for the request.
func (r *Router) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
if c, err := req.Cookie(cookieName); err == nil {
if ms, err := strconv.ParseInt(c.Value, 10, 64); err == nil {
if time.Since(time.UnixMilli(ms)) < r.Window {
ctx = context.WithValue(ctx, ctxKey{}, true)
}
}
}
next.ServeHTTP(w, req.WithContext(ctx))
})
}
// MarkWrite refreshes the cookie after a successful write.
func (r *Router) MarkWrite(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: strconv.FormatInt(time.Now().UnixMilli(), 10),
Path: "/",
MaxAge: int(r.Window.Seconds()) + 1,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
// Reader picks the handle for a read: primary if the request is pinned or
// no replica is configured, otherwise a replica chosen round-robin.
func (r *Router) Reader(ctx context.Context) *sql.DB {
pinned, _ := ctx.Value(ctxKey{}).(bool)
if pinned || len(r.Replicas) == 0 {
return r.Primary
}
i := r.next.Add(1)
return r.Replicas[int(i%uint64(len(r.Replicas)))]
}
// CaughtUp is the precise alternative to a time window: compare the LSN of
// your last write with the replica's replay position (PostgreSQL).
func CaughtUp(ctx context.Context, replica *sql.DB, writeLSN string) (bool, error) {
var ok bool
err := replica.QueryRowContext(ctx,
`SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn`, writeLSN).Scan(&ok)
return ok, err
}Caching tiers
Cache-aside, TTL, jitter and stampede protection Must-know
In plain words: Look in a fast store first; on a miss, read the database, put the answer in the fast store, and let it expire after a while.
Common misunderstanding: "A TTL makes the cache correct." A TTL bounds staleness; it does not remove it. And a TTL that is the same for many keys is a stampede waiting for a clock to strike.
Definition: Cache-aside (lazy loading): the application reads the cache, on a miss loads from the database and writes the cache; on a write it deletes the key (delete, not update, so a racing reader cannot re-insert stale data forever). Read-through has the cache library do the load. Write-through writes the cache and the database together. Write-behind (write-back) buffers writes in the cache and flushes later, which risks losing buffered writes. A cache stampede (dogpile, thundering herd) is many concurrent misses for one key (or many keys expiring together) all hitting the database.
T1 T2 T3 Database
1 GET product:7 miss
2 GET product:7 miss
3 GET product:7 miss
4 SELECT ... ------------------------------------------------------------------> (3 identical queries)
5 SELECT ... ---------------------------------------->
6 SELECT ... ------------->
7 SET product:7 ttl=300 SET product:7 ttl=300 SET product:7 ttl=300
-- With 5,000 concurrent readers of a hot key, that is 5,000 queries at once: the stampede.| Defence | How | Cost |
|---|---|---|
| TTL jitter | ttl + random(0, 20%) so keys cached together do not expire together | None |
| Request coalescing (singleflight) | One caller loads, the others wait for its result | Waiting callers share its latency and failure |
| Stale-while-revalidate | Serve a slightly stale value while one deferred task refreshes (Cache::flexible; HTTP stale-while-revalidate, RFC 5861) | Bounded staleness |
| Distributed lock on rebuild | Cache::lock() or Redis SET key value NX PX so one process rebuilds | Lock expiry and failure handling |
| Probabilistic early expiration | Each reader may refresh early with a probability that grows near expiry (the XFetch scheme, Vattani et al. 2015) | A little extra load before expiry |
| Pre-warming | Fill known hot keys before a deploy or a sale | Needs a list of keys |
| Negative caching | Cache "not found" briefly so missing keys (cache penetration) do not reach the database; a Bloom filter (Bloom Filters) screens non-existent IDs | A new row can be hidden until the TTL ends |
| Cache avalanche guard | Spread TTLs; keep a rate limit or circuit breaker in front of the database when the cache is down | Complexity |
| Tier | Example | Latency | Scope | Invalidation difficulty |
|---|---|---|---|---|
| In-process | Go map + mutex, Ristretto; Laravel array/APCu store | nanoseconds to microseconds | One process | Hard: every instance has its own copy |
| Shared cache | Redis, Memcached (Redis) | sub-millisecond to 1 ms | All instances | One DEL |
| Database-side | PostgreSQL buffer cache, MySQL buffer pool | n/a | One server | Automatic |
| HTTP / CDN | Cache-Control, ETag, CDN edge (RFC 9111) | tens of ms, from the edge | Many users | Purge APIs, versioned URLs |
Hit ratio arithmetic: with a 1 ms cache and a 20 ms database, 99% hit gives 1.19 ms average and 1% of the load on the database; 90% hit gives 2.9 ms and 10% of the load. Ten points of hit ratio is a tenfold change in database load, which is why monitoring Redis keyspace_hits and keyspace_misses matters.
1 t=0 cache cold after deploy; 3,000 req/s for one hot key
2 Without defences: 3,000 identical SELECTs in the first second; replica CPU 100%, p99 -> 12 s
3 With singleflight: 1 SELECT; 2,999 callers wait ~20 ms and share the result
4 With jitter: the 40,000 keys loaded at deploy expire over 60 s, not in the same second
5 With flexible(): at t = fresh+1 s one deferred refresh runs; every caller still gets an answer in <1 msFix / how to use it (Go, with singleflight):
// Package singleflight shows cache-aside with the three stampede defences:
// TTL jitter, request coalescing (singleflight) and a bounded stale window.
package singleflight
import (
"context"
"math/rand/v2"
"sync"
"time"
"golang.org/x/sync/singleflight"
)
type entry struct {
value string
freshTill time.Time // serve without any check until here
staleTill time.Time // serve stale (and refresh in background) until here
}
// Loader reads the truth, normally from a read replica.
type Loader func(ctx context.Context, key string) (string, error)
type Cache struct {
load Loader
ttl time.Duration
stale time.Duration
group singleflight.Group
mu sync.RWMutex
m map[string]entry
}
func New(load Loader, ttl, stale time.Duration) *Cache {
return &Cache{load: load, ttl: ttl, stale: stale, m: map[string]entry{}}
}
// Get is cache-aside. Concurrent misses for one key collapse into one load.
func (c *Cache) Get(ctx context.Context, key string) (string, error) {
c.mu.RLock()
e, ok := c.m[key]
c.mu.RUnlock()
now := time.Now()
switch {
case ok && now.Before(e.freshTill):
return e.value, nil
case ok && now.Before(e.staleTill):
// Stale-while-revalidate: answer now, refresh once in the background.
go func() {
_, _, _ = c.group.Do(key, func() (any, error) {
return c.fill(context.WithoutCancel(ctx), key)
})
}()
return e.value, nil
}
v, err, _ := c.group.Do(key, func() (any, error) { return c.fill(ctx, key) })
if err != nil {
return "", err
}
return v.(string), nil
}
// Invalidate deletes the key after a write. Pair it with a TTL as a safety net.
func (c *Cache) Invalidate(key string) {
c.mu.Lock()
delete(c.m, key)
c.mu.Unlock()
}
func (c *Cache) fill(ctx context.Context, key string) (string, error) {
v, err := c.load(ctx, key)
if err != nil {
return "", err
}
// Up to 20% jitter so keys filled together do not expire together.
jitter := time.Duration(rand.Int64N(int64(c.ttl) / 5))
fresh := time.Now().Add(c.ttl + jitter)
c.mu.Lock()
c.m[key] = entry{value: v, freshTill: fresh, staleTill: fresh.Add(c.stale)}
c.mu.Unlock()
return v, nil
}Go note: golang.org/x/sync/singleflight is the standard way to collapse duplicate in-flight calls. Share the loaded value, and note that errors are shared too, so one transient error fails every waiter once; use group.Forget(key) to let the next caller retry sooner.
Fix / how to use it (Laravel): Cache::flexible is Laravel's stale-while-revalidate; the docs describe it as accepting "an array that specifies how long the cached value is considered 'fresh' and when it becomes 'stale'", registering "a deferred function" to refresh after the response is sent. Cache::lock(...)->block(5, ...) is the atomic-lock alternative when staleness is not acceptable.
<?php
namespace App\Services;
use App\Models\Product;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class HotCatalog
{
// Fresh for 60 s, then served stale for up to 120 s more while one deferred
// task refreshes it. Nobody waits for the database unless both windows pass.
public function productName(int $id): string
{
return Cache::flexible(
"product:{$id}:name",
[60 + random_int(0, 12), 180 + random_int(0, 36)], // jittered fresh / stale
fn () => Product::findOrFail($id)->name,
);
}
// For data that must not be served stale, take an atomic lock so only one
// process rebuilds an expired key; the others wait up to 5 s, then read it.
public function leaderboard(): array
{
$key = 'leaderboard:top100';
$cached = Cache::get($key);
if ($cached !== null) {
return $cached;
}
return Cache::lock("lock:{$key}", 10)->block(5, function () use ($key) {
// Another process may have filled it while we waited for the lock.
return Cache::remember($key, 30 + random_int(0, 6), fn () => DB::table('scores')
->orderByDesc('points')
->limit(100)
->get()
->all());
});
}
// Read-your-writes across a redirect: `sticky` only covers one request, so
// the follow-up request reads explicitly from the write connection.
public function orderAfterCheckout(int $orderId): ?object
{
return DB::connection()->usingWritePdo(
fn ($connection) => $connection->table('orders')->where('id', $orderId)->first(),
);
}
}-- Invalidation by write: delete, never "update the cache value from the application"
-- (a slow writer can overwrite a newer value). PostgreSQL can notify caches of changes:
CREATE FUNCTION notify_product() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN PERFORM pg_notify('product_changed', NEW.id::text); RETURN NEW; END $$;
CREATE TRIGGER product_changed AFTER UPDATE ON products
FOR EACH ROW EXECUTE FUNCTION notify_product();Caches also cannot see transactions: a cache filled from a replica or from inside an uncommitted transaction can store a value that never becomes true. Fill the cache only from committed, current reads, and delete after commit, not before.
Hot keys Important
In plain words: A hot key is one key that gets a huge share of the traffic, so the machine that owns it melts while the others idle.
Common misunderstanding: "More nodes fixes a hot key." Hashing sends a given key to one node regardless of cluster size; adding nodes does not split a single key.
Definition: Skew in access. In caches: one viral item on one Redis node (Redis Cluster maps a key to one of 16,384 hash slots, owned by one primary). In databases: one huge tenant or a monotonic key with range routing. Notion notes that "a single large enterprise customer … generates more load than many average personal workspaces combined"; Figma hashes the shard key because auto-incrementing and timestamp-prefixed IDs "would have resulted in significant hotspots", at the price that range scans on the shard key become scatter-gather.
| Cause | Where | Fix |
|---|---|---|
| One viral item | Cache node | In-process copy with short TTL; replicate the key under N suffixes (item:7#0..#7) and read a random one |
| Huge tenant | Sharded database | Give it its own shard (directory sharding), or a composite key (tenant_id, hash(user_id)) |
| Monotonic ID with range routing | Newest shard | Hash the shard key; or time-bucket plus hash |
| Counter row | One primary row lock | Sharded counters (N rows, sum on read), or buffer increments (see write buffering) |
| Single queue head | Job table | FOR UPDATE SKIP LOCKED (Locks) |
-- Sharded counter: 16 rows instead of one hot row
UPDATE page_views SET n = n + 1 WHERE page_id = 7 AND slot = (random() * 15)::int;
SELECT sum(n) FROM page_views WHERE page_id = 7;Write buffering and batching
Absorbing write bursts Important
In plain words: Collect many small writes and apply them as one bigger operation, so the database does less per-write work.
Common misunderstanding: "Buffering writes in a queue makes them safe." A buffer in memory is lost on a crash; a queue gives you durability and a place to apply backpressure, but the database must still absorb the average rate.
Definition: Per-statement overhead (round trip, parse, WAL flush) dominates tiny writes. Batching amortises it.
| Technique | Mechanism | Durability | When |
|---|---|---|---|
Multi-row INSERT / COPY | One statement, many rows | Normal | Bulk loads, ingestion (Billion-Row Tables) |
Group commit (commit_delay, commit_siblings) | Several transactions share one WAL flush | Normal | Many small concurrent commits |
synchronous_commit = off | Do not wait for the WAL flush | Can lose the last few hundred ms; no corruption | Metrics, logs, non-critical rows |
| Queue then batch consumer | Producer enqueues; consumer writes batches of N or every T ms | Durable if the queue is | Event ingestion; see Backpressure & Flow Control |
| Write-behind cache | Accumulate in Redis, flush periodically | Risk of loss | View counters, "last seen" |
| Sharded counters | Many rows, sum on read | Normal | Hot counters |
UNLOGGED tables | Skip WAL | Lost after a crash | Staging, scratch |
// Flush on size or time, whichever comes first.
func flush(ctx context.Context, db *sql.DB, in <-chan Event) {
batch := make([]Event, 0, 500)
t := time.NewTicker(200 * time.Millisecond)
defer t.Stop()
write := func() {
if len(batch) == 0 {
return
}
insertMany(ctx, db, batch) // one multi-row INSERT or pgx CopyFrom
batch = batch[:0]
}
for {
select {
case e, ok := <-in:
if !ok {
write()
return
}
if batch = append(batch, e); len(batch) == cap(batch) {
write()
}
case <-t.C:
write()
}
}
}Laravel equivalents: DB::table('events')->insert($rows) (multi-row insert), upsert() for idempotent loads, Model::insert instead of create in loops, queue workers with Bus::batch, and Redis INCR plus a scheduled flush for counters.
Mechanics: knobs, views and error messages
The exact settings the ladder touches, so nothing on this page stays abstract.
| Area | Knob or view | Meaning | Typical use |
|---|---|---|---|
| Memory | shared_buffers, effective_cache_size, work_mem | Buffer cache, planner's idea of total cache, per-sort memory | Keep the working set in RAM |
| Connections | max_connections (default 100), PgBouncer pool_mode, default_pool_size | Backend limit; pooling mode (session, transaction, statement) | Pool instead of raising the limit |
| WAL and writes | wal_level, max_wal_senders, synchronous_commit, commit_delay, commit_siblings | What is logged, how many replicas, when a commit returns | Replication, group commit |
| Replication | synchronous_standby_names, hot_standby, hot_standby_feedback, max_standby_streaming_delay | Which standbys are synchronous; query conflict handling | Lag versus cancelled queries |
| Lag views | pg_stat_replication (write_lag, flush_lag, replay_lag), pg_last_xact_replay_timestamp(), pg_last_wal_replay_lsn() | How far behind | Alerts, LSN-based routing |
| I/O | pg_stat_io, track_io_timing, pg_stat_wal, pg_stat_bgwriter | Where blocks are read and written | Locating the bottleneck |
| Partitioning | PARTITION BY, enable_partition_pruning | Declarative partitions and pruning | Retention, small hot sets |
| MySQL | Seconds_Behind_Source, semi-sync plugin, innodb_buffer_pool_size, ProxySQL | Lag, durability of acknowledged commits, cache, routing | Same ladder, different names |
| Redis | maxmemory, maxmemory-policy, keyspace_hits/keyspace_misses, 16,384 hash slots | Eviction, hit ratio, key-to-node mapping | Cache sizing and hot keys |
| Go pool | SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, db.Stats() | Per-handle pool limits and wait counters | Sizing by Little's law |
| Laravel | read, write, sticky, usingWritePdo, withoutAffectingStickiness, Cache::flexible, Cache::lock | Routing and cache primitives | The code above |
| Message or code | Where | Meaning | Action |
|---|---|---|---|
FATAL: sorry, too many clients already (53300) | PostgreSQL | max_connections reached | Pool; find leaks and idle in transaction |
ERROR: canceling statement due to conflict with recovery (40001) | Hot standby | Replay needed to remove rows the query still sees | Retry; raise max_standby_streaming_delay or use a reporting replica |
ERROR: cannot execute INSERT in a read-only transaction (25006) | Replica or misrouted write | A write went to a standby | Fix routing; ensure writes use the primary handle |
ERROR: terminating connection due to conflict with recovery | Hot standby | Same, connection dropped | Retry with a fresh connection |
WARNING: database "x" must be vacuumed within N transactions | PostgreSQL | Transaction-ID wraparound approaching (what hit Notion) | Vacuum, partition, shard (MVCC & VACUUM) |
MySQL 1040 Too many connections | MySQL | max_connections reached | ProxySQL, pooling |
| MySQL 1290 / 1836 | MySQL | Write on a read-only replica | Fix routing |
Redis OOM command not allowed when used memory > 'maxmemory' | Redis | Eviction policy noeviction and memory full | Set a policy such as allkeys-lru; size the cache |
Redis CLUSTERDOWN / MOVED | Redis Cluster | Slot owner changed or unavailable | Cluster-aware client |
Vertical limits
Where the "just buy a bigger box" rung ends Important
In plain words: A bigger server helps until a part of it stops growing in proportion: memory bandwidth, the storage limit, the largest instance the provider sells.
Common misunderstanding: "Twice the cores gives twice the throughput." Locks, buffer-pool mappings and cross-socket memory traffic mean returns diminish (the USL); on large multi-socket machines it can fall.
Definition:
| Limit | What happens | What to do |
|---|---|---|
| NUMA (non-uniform memory access) | On multi-socket servers, memory attached to the other CPU socket is slower; a database whose buffers span nodes pays latency and bandwidth | Prefer one large socket or interleave (numactl --interleave=all), vm.zone_reclaim_mode = 0, benchmark with and without |
| Huge pages and shared buffers | Large shared_buffers with 4 KB pages means a huge page table | huge_pages = on (PostgreSQL), Linux huge pages configured |
| IOPS and throughput caps | Cloud block storage has provisioned IOPS and throughput per volume and per instance | Check both the volume and the instance limit; io2/Provisioned IOPS, local NVMe for temp |
| Single WAL stream | All writes serialise through one WAL writer | Batch, group commit; ultimately split databases |
| Lock manager, buffer mapping | Partitioned lock tables, but contention rises with cores (β) | Pooling, fewer active backends |
| Cloud instance ceiling | The largest instance (Figma: "AWS's largest physical instance") and maximum storage per database are fixed | Check the provider's current limits; plan the next rung before you reach them |
| Failover and restore time | A 20 TB node takes hours to restore or re-seed a replica | Smaller nodes recover faster (Backup, PITR & DR) |
| Blast radius | Everything on one box fails together | Decomposition, replicas across zones |
| Soft limits | Vacuum, backups, schema changes degrade "well before" the hardware maximum (Notion) | Track maintenance duration as a metric |
Two stories: Notion and Figma
Notion: sharding a monolith Must-know
Notion (October 2021): application-level sharding of the block tree and related tables by workspace ID into 480 logical shards over 32 physical databases, after Postgres VACUUM "began to stall consistently" and transaction-ID wraparound became a risk. They set "an upper bound of 500 GB per table and 10 TB per physical database". Their migration used a double-write with an audit log and a catch-up script, then "dark reads" that compared old and new data and logged discrepancies, and a switch-over. Their hindsight list begins:
"Shard earlier."
Their reasoning: they "waited until our existing database was heavily strained, which meant we had to be very frugal with migrations lest we add even more load". The workspace ID was not yet populated in the old database, and "backfilling this column would have exacerbated the load on our monolith". And: "Double-write throughput was the primary bottleneck in our final switch-over".
Figma: climbing the ladder, then sharding Must-know
Figma (March 2024): "In 2020, we were running a single Postgres database hosted on AWS's largest physical instance, and by the end of 2022, we had built out a distributed architecture with caching, read replicas, and a dozen vertically partitioned databases." Then, because some tables "containing several terabytes and billions of rows" were too large for one database and the highest write tables would "soon exceed the maximum IO operations per second (IOPS) supported by Amazon's Relational Database Service", they built horizontal sharding: colocations ("colos") sharing a shard key, a Go service DBProxy between the application and PgBouncer with a query engine, load-shedding and request hedging, logical sharding done first through views and rolled back by configuration, and physical sharding afterwards. They "chose not to support atomic cross-shard transactions because we could work around cross-shard transaction failures" and allow joins only "when joining two tables in the same colo and the join is on the sharding key".
"Shard earlier" versus "premature sharding"
Notion's own footnote warns that premature sharding "can constrain the product model before it has been well-defined", for example sharding by user and later pivoting to a team product. Both statements are true; they refer to different things.
| Shard earlier | Premature sharding | |
|---|---|---|
| What it is | Start the migration while the primary still has headroom, because the migration itself adds load | Run sharded production before a measured need and before the access pattern is known |
| Evidence | A projected ceiling (disk, IOPS, vacuum) with a date | A guess |
| Cost of being wrong | Expensive if too late: no spare capacity for double-writes | Expensive if too early: wrong key, permanent joins and transactions lost |
| What to do | Set the trigger (for example, 60% of measured IOPS ceiling, or 12 months of runway) and start then | Do the cheap preparation instead |
The cheap preparation ("sharding-ready", not sharded): carry the tenant or workspace ID on every table and populate it from day one; avoid cross-tenant joins on hot paths; avoid reliance on global sequences; keep queries shard-key-aware; write down the trigger. That gives you most of Notion's regret-avoidance without Notion's product-model risk.
When a different store wins
| Workload | Why the primary struggles | Better fit | Link |
|---|---|---|---|
| Relevance search, fuzzy match, facets | LIKE and trigram have limits; ranking is poor | Elasticsearch / OpenSearch, or PostgreSQL FTS first | Full-Text Search |
| Large scans, aggregations, dashboards | Row store reads whole rows; analytics steal IOPS from OLTP | ClickHouse, BigQuery, a columnar warehouse, fed by CDC | OLTP vs OLAP |
| Write firehose, time series, known-key lookups | One primary's WAL; B-tree write amplification | Cassandra, ScyllaDB, DynamoDB, a time-series DB (LSM-based) | NoSQL families, Wide-column & key-value, Storage Engines |
| Session data, counters, leaderboards, rate limits | Row locks and durability you do not need | Redis | Redis |
| Documents of varying shape, built-in sharding | Schema churn, large JSONB | MongoDB | MongoDB |
| Deep relationship traversal | Recursive joins | A graph database | Graph Databases |
| Similarity search | Not what B-trees do | pgvector or a vector database | Vector Search |
| Transactions across regions | Single-primary latency | CockroachDB, Spanner, YugabyteDB | Distributed SQL |
Rule of thumb: add a specialised store when the workload is structurally wrong for the engine (not merely slow), when you can feed it from the source of truth, and when the team can operate it. Otherwise first exhaust the relational options (partial indexes, partitioning, materialised views, pg_trgm, FTS, pgvector).
Cost and rollback of every rung
| Rung | Build cost | Run cost | Rollback path | Reversibility |
|---|---|---|---|---|
| 1 Indexes and queries | Hours to days | Write overhead | DROP INDEX CONCURRENTLY; revert the query | Very high |
| 2 Vertical | Minutes plus a failover | Money, bigger blast radius | Resize back (storage usually cannot shrink) | High, with a floor |
| 3 Pooling | Days | One more hop to operate | Point the DSN back at the database | High |
| 4 Caching | Days to weeks | Redis cluster, invalidation bugs | Feature flag off; flush; keep the TTL | High, if reads still work uncached and the database can survive the load |
| 5 Read replicas | Days | Replicas, lag monitoring | Routing flag back to the primary | High |
| 6 Partitioning | Weeks (migration of a big table) | Partition maintenance | ATTACH/DETACH, copy back | Medium |
| 7 Decomposition | Weeks to months | Cross-database consistency work | Reverse replication and cut-over | Medium to low |
| 8 Sharding | Months to years (Figma: "multi-year effort") | Routing layer, resharding, tooling | Logical: config switch; physical: reverse copy with coordination | Low |
| 9 Polyglot / CQRS | Weeks per read model | Pipelines, lag, reconciliation | Drop the read model; keep the source authoritative | High per store, low if the source of truth moved |
Solving it in code
Before: one handle for everything
One *sql.DB or one Laravel connection. Reads of rarely changing data compete with writes on the primary.
// Package before sends every read and write to one database handle.
// It works, until the single primary is the bottleneck for both.
package before
import (
"context"
"database/sql"
)
type Store struct {
db *sql.DB
}
func NewStore(db *sql.DB) *Store {
return &Store{db: db}
}
func (s *Store) Rename(ctx context.Context, id int64, name string) error {
_, err := s.db.ExecContext(ctx, `UPDATE products SET name = $1 WHERE id = $2`, name, id)
return err
}
// ProductName hits the primary on every call, even for data that
// changes once a month and is read thousands of times a second.
func (s *Store) ProductName(ctx context.Context, id int64) (string, error) {
var name string
err := s.db.QueryRowContext(ctx, `SELECT name FROM products WHERE id = $1`, id).Scan(&name)
return name, err
}<?php
namespace App\Services;
use App\Models\Product;
// Default config: one connection, so every read and write hits the primary.
// Nothing here is wrong, until reads outnumber writes by 100 to 1.
class CatalogService
{
public function rename(int $id, string $name): void
{
Product::whereKey($id)->update(['name' => $name]);
}
public function productName(int $id): string
{
return Product::findOrFail($id)->name;
}
}After: replica, flag and jittered cache
Go: separate primary and replica handles. Rename returns a context carrying a read-after-write flag, and ProductName honours it by skipping both cache and replica. The cache is an in-memory map to keep the example stdlib-only; in production it would be Redis, and invalidation would also need to cover other processes.
// Package after splits reads from writes, pins reads to the primary after a
// write in the same request, and puts a jittered cache-aside in front of the
// replica.
package after
import (
"context"
"database/sql"
"math/rand/v2"
"sync"
"time"
)
type ctxKey struct{}
// WithReadAfterWrite returns a context that routes reads to the primary.
// Call it (or let Rename do it) once a request has written.
func WithReadAfterWrite(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxKey{}, true)
}
func readAfterWrite(ctx context.Context) bool {
v, _ := ctx.Value(ctxKey{}).(bool)
return v
}
type entry struct {
value string
expires time.Time
}
type Store struct {
primary *sql.DB
replica *sql.DB
ttl time.Duration
mu sync.Mutex
cache map[int64]entry
}
func NewStore(primary, replica *sql.DB, ttl time.Duration) *Store {
return &Store{primary: primary, replica: replica, ttl: ttl, cache: map[int64]entry{}}
}
// Rename writes to the primary, drops the cached value, and returns a context
// that makes the rest of this request read from the primary.
func (s *Store) Rename(ctx context.Context, id int64, name string) (context.Context, error) {
_, err := s.primary.ExecContext(ctx, `UPDATE products SET name = $1 WHERE id = $2`, name, id)
if err != nil {
return ctx, err
}
s.mu.Lock()
delete(s.cache, id)
s.mu.Unlock()
return WithReadAfterWrite(ctx), nil
}
// ProductName is cache-aside around the replica. A request that has written
// skips both the cache and the replica, because either may be stale.
func (s *Store) ProductName(ctx context.Context, id int64) (string, error) {
if readAfterWrite(ctx) {
return s.query(ctx, s.primary, id)
}
s.mu.Lock()
e, ok := s.cache[id]
s.mu.Unlock()
if ok && time.Now().Before(e.expires) {
return e.value, nil
}
name, err := s.query(ctx, s.replica, id)
if err != nil {
return "", err
}
// Jitter spreads expiry so a burst of keys written together does not
// expire together and stampede the replica.
jitter := time.Duration(rand.Int64N(int64(s.ttl) / 5))
s.mu.Lock()
s.cache[id] = entry{value: name, expires: time.Now().Add(s.ttl + jitter)}
s.mu.Unlock()
return name, nil
}
func (s *Store) query(ctx context.Context, db *sql.DB, id int64) (string, error) {
var name string
err := db.QueryRowContext(ctx, `SELECT name FROM products WHERE id = $1`, id).Scan(&name)
return name, err
}database/sql describes DB as "a database handle representing a pool of zero or more underlying connections" that is "safe for concurrent use by multiple goroutines". It has no notion of replicas: one *sql.DB is one pool for one DSN, so read/write splitting is explicit. Size each handle's pool separately (SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime) and read db.Stats(). pgx adds host-level options (target_session_attrs=read-write picks the primary from a host list), but which query may be stale stays in your code.
Laravel: config/database.php gets read, write and sticky:
<?php
// config/database.php (excerpt). Laravel routes SELECTs to `read` and
// INSERT/UPDATE/DELETE to `write`, for raw queries, the query builder and Eloquent.
return [
'connections' => [
'mysql' => [
'driver' => 'mysql',
'read' => [
'host' => [
env('DB_READ_HOST_1', '192.168.1.1'),
env('DB_READ_HOST_2', '192.168.1.2'),
],
],
'write' => [
'host' => [env('DB_WRITE_HOST', '192.168.1.3')],
],
// After a write in this request, later reads use the write connection.
'sticky' => true,
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
],
],
];<?php
namespace App\Services;
use App\Models\Product;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class CatalogService
{
private const BASE_TTL = 300;
public function rename(int $id, string $name): void
{
// Goes to the write connection; `sticky` pins later reads in this request.
Product::whereKey($id)->update(['name' => $name]);
Cache::forget("product:{$id}:name");
}
public function productName(int $id): string
{
// Cache-aside; the miss path reads from a replica. Jitter spreads expiry
// so keys cached together do not all expire together.
return Cache::remember(
"product:{$id}:name",
self::BASE_TTL + random_int(0, 60),
fn () => Product::findOrFail($id)->name,
);
}
public function productNameForCheckout(int $id): string
{
// Must see the latest committed value, so force the write connection
// for this read and skip the cache.
return DB::connection()->usingWritePdo(
fn () => Product::findOrFail($id)->name,
);
}
}Laravel's docs say "the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM", and with several hosts "a database host will be randomly chosen for each request". The sticky option: "If the sticky option is enabled and a 'write' operation has been performed against the database during the current request cycle, any further 'read' operations will use the 'write' connection." It is per request, so a redirect needs usingWritePdo or the cookie approach from the Go router. withoutAffectingStickiness exists for writes that should not pin later reads (job progress, for example). Named connections give you functional decomposition: a model sets $connection to another database.
| Concern | Go | Laravel |
|---|---|---|
| Two pools | Two *sql.DB, own limits | read / write arrays on one connection |
| After-write consistency | Context flag, cookie window, LSN check | sticky, usingWritePdo, cookie-window middleware |
| Coalescing identical loads | singleflight.Group | Cache::lock()->block() or Cache::flexible |
| Stale-while-revalidate | Background refresh in the cache layer | Cache::flexible([fresh, stale], fn) |
| Functional decomposition | One *sql.DB per domain | $connection on the model, separate named connections |
| Sharded routing | Router picks *sql.DB by shard key | Custom connection resolver or a proxy (Vitess, Citus) |
Choosing the next rung
| Symptom (measured) | Likely cause | Next rung | Extra technique | Reason |
|---|---|---|---|---|
| p99 high, CPU high, seq scans | Missing index, N+1 | 1: indexes and queries | EXPLAIN (ANALYZE, BUFFERS) | Cheapest and most effective |
| Hit ratio dropped, disk reads up | Working set above RAM | 1, then 2: RAM | Drop unused indexes | Memory beats disk by 100x |
| Hundreds of connections, high load average | Too many backends | 3: pooling | Little's law sizing | Fewer backends are faster |
| Same rows read thousands of times | Repeat reads | 4: cache | Jitter, singleflight | Removes load, not just spreads it |
| Read CPU high, writes light | Read-bound | 5: replicas | Sticky, lag alert | Scales reads |
| Replica lag grows | Replay slower than write rate; long queries | Fix replicas or cut replica load | Dedicated reporting replica | Replicas are not infinite |
| Table at TBs, vacuum for days | Table too big for one unit | 6: partitioning | Detach for retention | Smaller maintenance units |
| One domain's writes saturate IOPS | Shared WAL/storage | 7: decomposition | Logical replication copy | Splits the write load by domain |
| Single table write IOPS at ceiling | One primary | 8: sharding | Tenant key, logical first | Only rung that scales writes of one table |
| Search/analytics queries hurt OLTP | Wrong engine for the job | 9: new store | CDC feed | Different data structures |
| Latency spikes at one hour of the day | Stampede or batch job | 4: jitter, 1: reschedule | Pre-warm | Not a capacity problem |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One application, one PostgreSQL. The correct usage is rungs 1 to 3 and, when needed, 4: add indexes, run PgBouncer, cache a few hot reads in Redis with jitter. Example: a Laravel shop with 300 QPS peak on a 16 vCPU / 64 GB instance. The wins are EXPLAIN fixes, a Cache::flexible on the category tree, and a pool. Nothing else is needed. Keep tenant_id on every table ("sharding-ready") and write down the trigger for the next rung.
Modular monolith and multiple databases
Modules own their tables; reads cross modules through interfaces, not joins. That is exactly the preparation rung 7 needs. Example: billing and catalog modules each with their own schema, then their own connection ('billing' in config/database.php, a second *sql.DB in Go). Because no query joins across them, moving billing to its own server later is a configuration change plus a data copy. Add read replicas for the catalog's read-heavy side with sticky on.
Microservices: each owns its data
Functional decomposition is a rule: a service's database is private. What survives the boundary is the API and events. What does not: joins, foreign keys, one transaction (saga, outbox, idempotent consumers). Example flow: orders publishes OrderPlaced from an outbox table; search consumes it into Elasticsearch; analytics loads it into ClickHouse; billing has its own Postgres. Each read model is a rung-9 copy; the only authoritative record stays in orders. Caches are per service and invalidated by events.
Distributed data: replicas, caches and sharded databases
This is where the ladder meets consistency: replicas are behind, caches are behind, shards do not share a transaction, and each read model is a copy. Monotonic reads, read-your-writes and staleness budgets become part of the API contract (Eventual Consistency in Databases). Multi-region: one primary region with local replicas (low read latency, writes cross the ocean), or a distributed SQL database with consensus per range (Distributed SQL, Consensus & 2PC). Example: a profile service writes in eu-west, replicas in us-east lag 150 ms; the writer's session is pinned for 2 s; a global cache is invalidated by CDC events.
Scaling path: 1x, 10x, 100x
| Load | Typical design | Rungs in use | What to watch |
|---|---|---|---|
| 1x (hundreds of QPS, GBs) | One PostgreSQL, one app, a pool | 1, 3 | Slow-query log, buffer hit ratio |
| 10x (thousands of QPS, 100s of GB) | Bigger instance, Redis cache, 1 to 3 replicas, partition the biggest append-only table | 1 to 6 | Lag, hit ratio, IOPS, vacuum time |
| 100x (tens of thousands of QPS, TBs) | Functional split into several databases, search and analytics stores, begin tenant-keyed sharding of the hottest table, pooling proxy | 1 to 9 | Per-shard runway, hot keys, cross-shard queries, topology correctness |
| Beyond | Distributed SQL or purpose-built stores; global routing; cell-based architecture | all, plus platform team | Operational cost, resharding frequency |
Lab
Goal: load-test one node and see which resource saturates, add a replica and route reads, and watch replication lag affect a read-after-write. You need Docker and pgbench (ships with PostgreSQL). Use PostgreSQL 16 or later for pg_stat_io.
Setup: a primary and a replica.
docker network create scale
docker run -d --name pg1 --network scale -e POSTGRES_PASSWORD=pw -p 5433:5432 postgres:17 \
-c wal_level=replica -c max_wal_senders=10 -c track_io_timing=on -c shared_preload_libraries=pg_stat_statements
docker exec pg1 psql -U postgres -c "CREATE ROLE rep REPLICATION LOGIN PASSWORD 'pw'"
docker exec pg1 bash -c "echo 'host replication rep all scram-sha-256' >> /var/lib/postgresql/data/pg_hba.conf && psql -U postgres -c 'select pg_reload_conf()'"
# replica: base backup with -R writes standby.signal and primary_conninfo
docker run -d --name pg2 --network scale -e PGPASSWORD=pw -p 5434:5432 --entrypoint bash postgres:17 -c \
"pg_basebackup -h pg1 -U rep -D /var/lib/postgresql/data -R -X stream -P && chown -R postgres /var/lib/postgresql/data && exec su postgres -c 'postgres -c hot_standby=on'"
docker exec pg1 psql -U postgres -c "select client_addr, state, sync_state from pg_stat_replication" -- one row, streaming, asyncExperiment 1: single node, find the saturating resource.
pgbench -i -s 100 -h localhost -p 5433 -U postgres postgres # about 1.5 GB of data
for c in 1 2 4 8 16 32 64 128; do
pgbench -c $c -j $(( c < 8 ? c : 8 )) -T 30 -P 10 -h localhost -p 5433 -U postgres postgres | grep -E "tps|latency average"
done
# Expected shape: tps rises almost linearly, flattens, and may fall at high c (contention, then retrograde).
# Watch the saturated resource while it runs:
docker stats pg1 # CPU% vs block I/O
docker exec pg1 psql -U postgres -c "select backend_type, object, context, reads, writes, hits, evictions from pg_stat_io where reads>0 or writes>0 order by writes desc limit 5"
docker exec pg1 psql -U postgres -c "select wait_event_type, wait_event, count(*) from pg_stat_activity where state='active' group by 1,2 order by 3 desc"
# CPU at 100%, wait_event NULL -> CPU-bound: queries/indexes, replicas for reads
# wait_event = WALWrite/WALSync -> write/IOPS-bound: batching, faster storage, then decomposition
# wait_event = Lock/transactionid -> contention (alpha): the hot row or lock is the problemExperiment 2: fit the USL. Record tps for each client count in a file n,tps, then fit α and β (regress N/C(N) = 1 + α(N−1) + βN(N−1)), or just compare the shape with the printed curve from go run ./usl. A falling tail means β is non-zero: stop adding clients and add a pool.
Experiment 3: read-only load, then route it to the replica.
pgbench -S -c 32 -j 8 -T 30 -h localhost -p 5433 -U postgres postgres # select-only on the primary: note tps
PGPASSWORD=pw pgbench -S -c 32 -j 8 -T 30 -h localhost -p 5434 -U postgres postgres # on the replica
# Expect: the replica serves SELECT-only (-S) load; run both at once and the primary's write tps (tpcb-like) is unaffected by read load
pgbench -c 8 -T 30 -h localhost -p 5433 -U postgres postgres & # writes to the primary
PGPASSWORD=pw pgbench -S -c 32 -j 8 -T 30 -h localhost -p 5434 -U postgres postgres # reads on the replica at the same timeExperiment 4: replication lag and read-your-writes.
-- On the primary (port 5433)
CREATE TABLE profile (id int PRIMARY KEY, name text);
INSERT INTO profile VALUES (1, 'Alan');
-- On the replica (port 5434): freeze replay to simulate lag
SELECT pg_wal_replay_pause();
-- On the primary
UPDATE profile SET name = 'Ada' WHERE id = 1;
-- On the replica: the read-after-write bug
SELECT name FROM profile WHERE id = 1; -- 'Alan' (stale)
SELECT now() - pg_last_xact_replay_timestamp(); -- the lag, growing
-- On the primary: the same SELECT returns 'Ada' (what sticky routing does)
SELECT pg_current_wal_lsn(); -- the write LSN, e.g. 0/3A000148
-- On the replica: has it caught up with that LSN?
SELECT pg_last_wal_replay_lsn() >= '0/3A000148'::pg_lsn; -- false -> route this read to the primary
SELECT pg_wal_replay_resume(); -- now it is true and the read returns 'Ada'
SELECT client_addr, write_lag, flush_lag, replay_lag FROM pg_stat_replication; -- run on the primaryExperiment 5: stampede. Write a Go program that starts 2,000 goroutines calling Cache.Get("hot") with an artificially slow loader (50 ms sleep, counter incremented per call). Without singleflight the counter reaches about 2,000; with the snippet above it is 1. Then fill 10,000 keys with and without jitter and plot the number of loads per second after the TTL.
Experiment 6: cleanup. docker rm -f pg1 pg2; docker network rm scale.
Common misconceptions
| Belief | Reality |
|---|---|
| "Scaling the database means sharding" | Sharding is rung 8 of 9; indexes, pooling, caching and replicas come first |
| "Add replicas and writes scale too" | Replicas replay every write; they add read capacity only, and add coherency cost |
| "A cache is free speed" | It adds invalidation, cold-start and stampede problems; know your acceptable staleness |
| "A TTL makes the cache correct" | A TTL bounds staleness; same-TTL keys expire together and stampede |
| "More connections give more throughput" | Throughput is capped by cores and IOPS; extra connections add queueing and context switches (Little's law, USL) |
| "Twice the nodes, twice the speed" | Amdahl caps speedup at 1/serial fraction; with coherency cost (USL) it can reverse |
| "Shard early so we never have to think about it" | Notion says shard earlier than they did, with measured need; Figma climbed several rungs first. Early wrong keys are permanent |
| "Sharding spreads load evenly" | It spreads keys; hot keys and giant tenants stay hot |
| "Partitioning scales writes" | One server still takes every write; it helps retention, vacuum and pruning |
| "Sticky sessions fix replica lag" | They hide it for one user for a while; other users and later reads still see lag |
| "Vertical scaling is not real scaling" | It is the cheapest rung and often buys a year; know the NUMA and IOPS ceilings |
| "NoSQL scales, SQL does not" | Figma and Notion scale Postgres; a different store wins for specific workloads, not as a general rule |
Cheat sheet
| Topic | What to remember |
|---|---|
| Order | Indexes, vertical, pooling, cache, replicas, partitioning, decomposition, sharding, polyglot; climb on measurement |
| Measure | p50/p99, QPS read vs write, working set vs RAM, hit ratio, pg_stat_io, saturation, lag |
| Peak | peak QPS = average × 3 to 10 (20+ for spikes); run below 60 to 70% of the ceiling |
| Little | L = λW; pool size = QPS × latency, with headroom |
| Amdahl | speedup is capped at 1/s |
| USL | C(N) = N / (1 + α(N−1) + βN(N−1)); peak N* = √((1−α)/β); β > 0 means retrograde |
| Cache-aside | read cache, miss to database, set with TTL + jitter; delete on write |
| Stampede | jitter + singleflight / lock + stale-while-revalidate (Cache::flexible) |
| Replicas | async; add read capacity; need read-your-writes routing and a lag alert |
| Read-your-writes | sticky window, LSN/GTID token, primary for own data, remote_apply |
| Hot keys | key splitting, local copies, own shard, sharded counters |
| Batching | multi-row insert, COPY, group commit, queue + batch consumer; synchronous_commit=off risks the last ms |
| Vertical limit | NUMA, IOPS/throughput caps, one WAL, instance ceiling, restore time |
| Sharding | key aligned with access pattern; logical before physical; many logical per physical; no free FKs/joins/transactions |
| Rollback | plan it per rung; logical sharding is a flag, physical is a project |
| Other store | wrong data structure for the engine, fed by CDC, operated by a team |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Your p99 doubled and the buffer hit ratio fell from 99% to 92%. What do you check first, and which rungs are candidates? Must-know
Answer
Answer: The working set likely no longer fits in RAM: check table and index sizes against memory, pg_stat_io reads and evictions, and recent changes (a report, a new index). Candidates are rung 1 (drop unused indexes, fix the heavy query) and rung 2 (more RAM). Replicas and sharding do not fix a single node's cache miss rate.
2 — 40 million requests per day with a peak factor of 5 and a 90:10 read:write split. What are the peak QPS and write rate? Must-know
Answer
Answer: Average 40,000,000 / 86,400 = 463 QPS; peak about 2,300 QPS; writes about 230 per second, reads about 2,100.
3 — At 3,000 QPS and 10 ms database time, how many connections are busy, and what happens when latency becomes 100 ms? Must-know
Answer
Answer: L = 3,000 × 0.010 = 30 busy; at 100 ms L = 300. A latency spike becomes a connection spike, which is why you pool and set timeouts.
4 — With contention 0.05 and coherency 0.002, where does the USL peak, and what does adding more nodes do after it? Good to know
Answer
Answer: N* = √(0.95 / 0.002) ≈ 22. Beyond it throughput falls (retrograde) because β grows with N².
5 — Why does a user not see their own edit after a redirect, and name three fixes. Must-know
Answer
Answer: The write went to the primary and the read to a replica that has not replayed it. Fixes: sticky window cookie, LSN or GTID token check, read the user's own data from the primary, synchronous_commit = remote_apply. Laravel sticky alone does not cover the redirect because it is per request.
6 — How do TTL jitter, singleflight and Cache::flexible each reduce a stampede? Must-know
Answer
Answer: Jitter spreads expiries over time; singleflight collapses concurrent misses on a key into one load; Cache::flexible serves a stale value while one deferred task refreshes, so nobody waits.
7 — Why does partitioning not scale writes, and what is it good for? Must-know
Answer
Answer: All partitions live on one server with one WAL. It makes retention (detach/drop), vacuum and pruned queries cheaper.
8 — What did Notion mean by "Shard earlier", and how does that differ from premature sharding? Good to know
Answer
Answer: Start while the database still has headroom for double-writes and backfills; they waited until it was heavily strained. Premature sharding means running sharded before a measured need or a known access pattern, which can fix a wrong shard key into the product.
9 — Name three things you lose when you shard, per Figma. Important
Answer
Answer: Efficient or possible arbitrary SQL, foreign keys and globally unique indexes enforced by Postgres, and atomic multi-shard transactions (partial commit failures). Also cross-shard joins become scatter-gather.
10 — A single Redis node is at 100% CPU while the cluster is idle. What is it, and what are two fixes? Important
Answer
Answer: A hot key, since a key maps to one slot on one primary. Fixes: replicate under N key suffixes and read randomly, keep a short-TTL in-process copy, or split the data model.
11 — When should a different store win over scaling PostgreSQL further? Important
Answer
Answer: When the workload is structurally wrong for the engine (relevance search, columnar analytics, a time-series firehose, graph traversal, vectors), you can feed the new store from the source of truth by CDC or events, and you can operate it.
12 — What is the rollback of each of: a read replica, a cache, logical sharding, physical sharding? Important
Answer
Answer: Replica: route flag back to the primary. Cache: flag off, with the database able to take the load. Logical sharding: a configuration change (Figma). Physical sharding: possible but needs complex coordination to keep data consistent.
Glossary
| Term | Meaning |
|---|---|
| Scale ladder | The ordered list of scaling steps from cheap and reversible to expensive |
| p50 / p95 / p99 | Latency percentiles: the value below which 50, 95 or 99% of requests fall |
| QPS | Queries (or requests) per second |
| Peak factor | Ratio of peak load to average load |
| Working set | Data and indexes touched regularly; should fit in RAM |
| Cache hit ratio | Hits divided by hits plus misses |
pg_stat_io | PostgreSQL 16+ view of reads, writes, hits, evictions by backend type and context |
pg_stat_statements | Extension that tracks execution statistics per normalised query |
| Saturation | A resource with a queue in front of it |
| Little's law | L = λW, requests in the system equal arrival rate times time in system |
| Amdahl's law | Speedup is limited by the serial fraction |
| USL | Universal Scalability Law: C(N) = N / (1 + α(N−1) + βN(N−1)) |
| Contention (α) | Waiting for a shared resource |
| Coherency (β) | Cost of keeping copies consistent; produces retrograde throughput |
| Retrograde | Throughput that decreases as load or nodes increase |
| Vertical scaling | A bigger machine |
| NUMA | Non-uniform memory access: memory near another socket is slower |
| IOPS | Input/output operations per second a disk or volume can serve |
| Connection pooling | Reusing a small set of database connections (PgBouncer, ProxySQL) |
| Cache-aside | Application reads cache, loads on miss, writes cache, deletes on write |
| Read-through / write-through / write-behind | Cache patterns where the cache loads, writes synchronously, or flushes later |
| TTL | Time to live of a cache entry |
| Jitter | Random variation added to a TTL or backoff |
| Cache stampede (dogpile, thundering herd) | Many concurrent misses on one key hitting the database |
| Cache penetration | Requests for keys that never exist, bypassing the cache |
| Cache avalanche | Many keys expiring together or the cache failing, overloading the database |
| Singleflight | Collapsing concurrent identical calls into one |
| Stale-while-revalidate | Serving a stale value while refreshing in the background (Cache::flexible, RFC 5861) |
| Negative caching | Caching "not found" |
| Hot key | One key receiving a disproportionate share of traffic |
| Read replica | Asynchronous copy serving reads |
| Replication lag | Delay between a commit on the primary and its replay on a replica |
| Read-your-writes | A reader sees its own earlier writes |
| Monotonic reads | A reader never sees time go backwards |
| Sticky | Pinning reads to the primary after a write (Laravel sticky, a cookie window) |
| LSN | PostgreSQL log sequence number, a position in the WAL |
| GTID | MySQL global transaction identifier |
| Recovery conflict | A replica query cancelled because WAL replay needs its row versions |
| Partitioning | Splitting a table into pieces within one database |
| Partition pruning | Skipping partitions that cannot match the query |
| Functional decomposition (vertical partitioning) | One database per group of tables or domain |
| Sharding | Spreading one table's rows across databases by a shard key |
| Logical / physical shard | The application-level bucket vs the database server that holds it |
| Scatter-gather | A query sent to every shard, results merged |
| Resharding | Moving data between shards to change their number or layout |
| Colo (Figma) | A group of tables sharing one shard key and layout |
| DBProxy | Figma's query-routing service between the application and PgBouncer |
| Polyglot persistence | Different stores for different workloads |
| CQRS | Separate write model and read models |
| CDC | Change data capture: a stream of committed changes from the database log |
| Group commit | Several transactions sharing one WAL flush |
| Dark read | Reading from the new system in parallel only to compare with the old |
| pgbench | PostgreSQL's built-in benchmark tool |
References
- Garrett Fidalgo, "Herding elephants: Lessons learned from sharding Postgres at Notion", 6 October 2021. notion.com
- Sammy Steele, "How Figma's databases team lived to tell the scale", 14 March 2024. figma.com
- Neil J. Gunther, "Universal Scalability Law" (Manifesto), Performance Dynamics. perfdynamics.com
- PostgreSQL documentation, "High Availability, Load Balancing, and Replication". postgresql.org
- PostgreSQL documentation:
pg_stat_io, pgbench, Hot Standby - Laravel 13 documentation: Read and Write Connections, Cache
- Go documentation:
database/sql,golang.org/x/sync/singleflight - RFC 5861 (stale-while-revalidate) and RFC 9111 (HTTP caching)
- Related pages: Partitioning & Sharding in PostgreSQL, Consistent Hashing, Storage Engines, Replication, Read Replicas & Failover, Distributed SQL, Consensus & 2PC, Connection Pooling