Skip to content

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 forGo to
The nine rungs, the metrics and the three laws in one table eachEverything in one minute
Why a ladder and not "just shard"Why a ladder
Primary sources and what each actually saysWhere it comes from
p50/p99, QPS, working set vs RAM, cache hit ratio, pg_stat_ioMeasure first
Rows per day, peak factors, connection budgetsCapacity estimation
Little's law, Amdahl, USL with a plotted curveThe three laws
Each rung with plain words, misunderstanding, timelineThe ladder, rung by rung
Read/write split, stickiness, replication lagRead replicas and read-your-writes
TTL jitter, stampede, singleflight, Cache::flexibleCaching tiers
One key melting one nodeHot keys
Group commit, batching, write buffersWrite buffering and batching
NUMA, IOPS, cloud ceilingsVertical limits
Knobs, views and error messagesMechanics
Notion and Figma with quotes, "shard earlier" vs "premature"Two stories
Cost and rollback of every rungCost and rollback table
When a different store winsWhen a different store wins
Go and Laravel codeSolving it in code
Which rung for which symptomChoosing the next rung
Monolith to 100xIn architecture
pgbench, add a replica, watch lagLab

Everything in one minute ​

The ladder. Each row is unpacked in the ladder section.

#RungWhat it buysWhat it costsTrigger to climb
1Fix queries and indexesLess work per request, no new machinesIndex write cost, maintenancep99 high with sequential scans or N+1
2Vertical scalingMore CPU, RAM, IOPS, no app changeMoney; ceilings; restartsCPU or IOPS near the ceiling, working set above RAM
3Connection poolingFewer backends, steadier latencyAnother hop; session-state limitsHundreds of connections, context-switch storms
4Caching tiersRemoves repeat readsStaleness, invalidation, stampedesRead QPS concentrated on few rows
5Read replicasRead capacity, HA standbyReplica lag, read-your-writes logicRead CPU-bound, primary still has write headroom
6PartitioningCheap retention, small hot setKey design, no extra write capacityTable size, vacuum time, retention
7Functional decompositionIndependent databases per domainNo cross-domain joins or transactionsWrite IOPS of one table group dominates
8ShardingWrite scale-outJoins, FKs, transactions, reshardingOne primary cannot absorb writes
9Polyglot stores, CQRSEach workload on a fitting engineEventual consistency, pipelinesA workload the engine is structurally bad at

What to measure before climbing.

MetricWhy it mattersWhere to get it (PostgreSQL)
p50, p95, p99 latency per endpointAverages hide the tail users feelAPM, pg_stat_statements (mean_exec_time, max_exec_time)
QPS, split into reads and writesReads and writes scale by different rungspg_stat_database (xact_commit, tup_returned, tup_inserted)
Working set vs RAMIn memory vs on disk is a 100x latency steppg_buffercache, table and index sizes
Cache hit ratio (buffer and application)Low ratio means disk or database is the bottleneckblks_hit / (blks_hit + blks_read), Redis keyspace_hits
pg_stat_ioReads, writes, hits, evictions by backend type and context (PostgreSQL 16+)SELECT * FROM pg_stat_io
Saturation: CPU, IOPS, WAL, locks, connectionsThe one that hits 100% first is the next rungnode_exporter, pg_stat_activity, pg_stat_wal
Replication lagBounds how stale a replica read can bepg_stat_replication.replay_lag

The three laws.

LawFormulaOne-line meaning
Little's lawL = λ × WRequests in flight = arrival rate × time each spends in the system
Amdahl's lawS(N) = 1 / (s + (1 − s) / N)The serial fraction s caps speedup at 1/s
Universal Scalability LawC(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.

SourceWhat it documentsWhat to take, and what not
Notion, October 2021 (Fidalgo)Sharding a Postgres monolith into 480 logical shards on 32 physical databasesThe 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 shardingThe staging: each step bought runway for the next
Gunther, Universal Scalability LawA two-parameter model of scalability, a generalisation of AmdahlFit α and β to your data; do not treat the curve as a forecast
PostgreSQL docs, High AvailabilitySynchronous vs asynchronous, stale results, read-your-writesThe vocabulary used in this page
Laravel 13 docs, database and cacheread/write/sticky, usingWritePdo, Cache::flexibleExact 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 rungExpensive, hard-to-undo rung
Application code does not change (bigger instance)Application learns the shard key, routing, partial failure
One database, one transaction, all joinsMany databases; joins and transactions become your problem
Rollback is a config flag or a resizeRollback is a project (Figma: logical sharding rolls back by config, physical sharding "requires more complex coordination")
Failure modes you already knowNew 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 ​

  1. "Scaling means sharding." Sharding is rung 8 of 9. Most systems that "need to scale" are missing an index, a pool or a cache.
  2. "More replicas means more write capacity." Replicas replay every write. They add read capacity only, and under the USL they add coherency cost.
  3. "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.

MeasurementHealthy signUnhealthy signLikely next rung
Buffer hit ratio (OLTP)above 99%below 95%Indexes, then vertical (RAM)
CPU, reads dominatebelow 60% at peakabove 80% with idle IOPSCache, then read replicas
IOPS or WAL throughputbelow 70% of provisionedat the provisioned limitVertical (storage class), batching, then decomposition or sharding
Active connectionsmax_connections not approachedHundreds, with idle in transactionPooling
Replication lag p99well below your staleness budgetseconds, growingFix replica I/O, or stop adding read load
Autovacuum / VACUUM durationfinishes between peaksruns for days; wraparound warningsPartitioning, decomposition, sharding (see MVCC & VACUUM)

Fix / how to use it:

sql
-- 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.
ResourceEstimate withTypical first limit for OLTP
Diskrows/day × row size × index overhead × retentionDisk full or vacuum time, months to years ahead
IOPSwrites/s × (WAL + heap + index writes), plus cache misses/sOften before CPU on cloud block storage
CPUQPS × CPU time per query (pg_stat_statements)Reads dominate: replicas and caches help
RAMworking set (hot rows + their indexes)A step change in latency when exceeded
ConnectionsLittle's law: QPS × latencyPool, do not raise max_connections
Networkrows returned × width × QPSLarge 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.

1816324064N: load, connections, cores or nodes0481216C(N), relative capacitylinear (ideal)Amdahl: contention only, flat at 1/alpha = 20peak N = 22, C = 7.4USL: alpha 0.05, beta 0.002; retrograde

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 databaseUSL termTypical causeLever
Throughput flattens with more clientsα (contention)One hot row, one lock, one WAL writer, one sequenceRemove 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 coordinationPool, reduce N, avoid cross-node chatter
More replicas do not reduce primary loadβ risingEach replica adds WAL sender work and feedbackCascading replicas, fewer larger replicas
Cross-shard queries slower than single-shardβScatter-gather: every shard must answerShard 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.

go
// 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 ​

1 Fix queries and indexes2 Vertical: bigger instance3 Connection pooling4 Caching tiers5 Read replicas (read/write split)6 Partitioning (one database)7 Functional decomposition8 Sharding by key9 Polyglot stores and CQRStrigger: p99 high, seq scans, N+1trigger: CPU/IOPS near ceiling, RAM < working settrigger: connection count, context switchestrigger: read QPS on hot rows, hit ratiotrigger: read load, lag budget knowntrigger: table size, retention, vacuum timetrigger: write IOPS of one table grouptrigger: one primary cannot absorb writestrigger: workload the engine is bad atcheap, reversiblecostly, hard to undo

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 writes

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

ChoiceOptionStrengthWeakness
Shard keyhash(tenant_id)Even spread; tenant queries stay on one shardOne giant tenant is still one shard
Shard keyRange on time or IDRange scans stay localNewest range takes all writes (hotspot)
Shard keyDirectory (lookup table)Move any tenant anywhereLookup is a dependency and a cache
Where routing livesIn the appNo extra hopEvery service must embed it
Where routing livesProxy (Figma DBProxy, Vitess, Citus coordinator)One place for routing, load-shedding, observabilityAnother service to run
EngineDistributed SQL (CockroachDB, Spanner, YugabyteDB, TiDB)Sharding and transactions inside the databaseLatency of consensus; cost; ecosystem differences
EngineBuilt in (MongoDB sharded clusters, Cassandra, DynamoDB)No application routingDifferent 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.

App requestcookie wrote_atRouterage < lag window?Primaryall writesReplica 1lag 5 to 500 msReplica 2lag 5 to 500 mswrite, or read while pinnedreplica readWALRule: a write sets the cookie.Reads inside the window go to the primary,later reads return to the replicas.
 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.

TechniqueHow it worksStrengthWeakness
Sticky windowAfter a write, pin this user's reads to the primary for T seconds (cookie or session)Simple, no replica queriesT must exceed worst lag; load on primary
Sticky per request (Laravel sticky)Reads after a write in the same request use the write connectionOne config keyDoes not survive a redirect
LSN / GTID tokenRemember the commit LSN; read from a replica only if pg_last_wal_replay_lsn() >= token (MySQL: WAIT_FOR_EXECUTED_GTID_SET)ExactMore code; a query per read or a lag cache
Read own data from primaryReads of what the user just wrote go to the primary by designTargetedNeeds a per-query decision
synchronous_commit = remote_applyCommit waits until a synchronous standby has applied itReplica reads are currentSlower commits; a standby outage can stall writes
Monotonic reads pinningHash the user to one replicaTime never goes backwards for a userNot read-your-writes; one replica gets all of a user's load
Client-side mergeOverlay recently written values on a replica resultNo primary loadComplex, 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.

go
// 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.
DefenceHowCost
TTL jitterttl + random(0, 20%) so keys cached together do not expire togetherNone
Request coalescing (singleflight)One caller loads, the others wait for its resultWaiting callers share its latency and failure
Stale-while-revalidateServe a slightly stale value while one deferred task refreshes (Cache::flexible; HTTP stale-while-revalidate, RFC 5861)Bounded staleness
Distributed lock on rebuildCache::lock() or Redis SET key value NX PX so one process rebuildsLock expiry and failure handling
Probabilistic early expirationEach 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-warmingFill known hot keys before a deploy or a saleNeeds a list of keys
Negative cachingCache "not found" briefly so missing keys (cache penetration) do not reach the database; a Bloom filter (Bloom Filters) screens non-existent IDsA new row can be hidden until the TTL ends
Cache avalanche guardSpread TTLs; keep a rate limit or circuit breaker in front of the database when the cache is downComplexity
TierExampleLatencyScopeInvalidation difficulty
In-processGo map + mutex, Ristretto; Laravel array/APCu storenanoseconds to microsecondsOne processHard: every instance has its own copy
Shared cacheRedis, Memcached (Redis)sub-millisecond to 1 msAll instancesOne DEL
Database-sidePostgreSQL buffer cache, MySQL buffer pooln/aOne serverAutomatic
HTTP / CDNCache-Control, ETag, CDN edge (RFC 9111)tens of ms, from the edgeMany usersPurge 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 ms

Fix / how to use it (Go, with singleflight):

go
// 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
<?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(),
        );
    }
}
sql
-- 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.

CauseWhereFix
One viral itemCache nodeIn-process copy with short TTL; replicate the key under N suffixes (item:7#0..#7) and read a random one
Huge tenantSharded databaseGive it its own shard (directory sharding), or a composite key (tenant_id, hash(user_id))
Monotonic ID with range routingNewest shardHash the shard key; or time-bucket plus hash
Counter rowOne primary row lockSharded counters (N rows, sum on read), or buffer increments (see write buffering)
Single queue headJob tableFOR UPDATE SKIP LOCKED (Locks)
sql
-- 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.

TechniqueMechanismDurabilityWhen
Multi-row INSERT / COPYOne statement, many rowsNormalBulk loads, ingestion (Billion-Row Tables)
Group commit (commit_delay, commit_siblings)Several transactions share one WAL flushNormalMany small concurrent commits
synchronous_commit = offDo not wait for the WAL flushCan lose the last few hundred ms; no corruptionMetrics, logs, non-critical rows
Queue then batch consumerProducer enqueues; consumer writes batches of N or every T msDurable if the queue isEvent ingestion; see Backpressure & Flow Control
Write-behind cacheAccumulate in Redis, flush periodicallyRisk of lossView counters, "last seen"
Sharded countersMany rows, sum on readNormalHot counters
UNLOGGED tablesSkip WALLost after a crashStaging, scratch
go
// 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.

AreaKnob or viewMeaningTypical use
Memoryshared_buffers, effective_cache_size, work_memBuffer cache, planner's idea of total cache, per-sort memoryKeep the working set in RAM
Connectionsmax_connections (default 100), PgBouncer pool_mode, default_pool_sizeBackend limit; pooling mode (session, transaction, statement)Pool instead of raising the limit
WAL and writeswal_level, max_wal_senders, synchronous_commit, commit_delay, commit_siblingsWhat is logged, how many replicas, when a commit returnsReplication, group commit
Replicationsynchronous_standby_names, hot_standby, hot_standby_feedback, max_standby_streaming_delayWhich standbys are synchronous; query conflict handlingLag versus cancelled queries
Lag viewspg_stat_replication (write_lag, flush_lag, replay_lag), pg_last_xact_replay_timestamp(), pg_last_wal_replay_lsn()How far behindAlerts, LSN-based routing
I/Opg_stat_io, track_io_timing, pg_stat_wal, pg_stat_bgwriterWhere blocks are read and writtenLocating the bottleneck
PartitioningPARTITION BY, enable_partition_pruningDeclarative partitions and pruningRetention, small hot sets
MySQLSeconds_Behind_Source, semi-sync plugin, innodb_buffer_pool_size, ProxySQLLag, durability of acknowledged commits, cache, routingSame ladder, different names
Redismaxmemory, maxmemory-policy, keyspace_hits/keyspace_misses, 16,384 hash slotsEviction, hit ratio, key-to-node mappingCache sizing and hot keys
Go poolSetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, db.Stats()Per-handle pool limits and wait countersSizing by Little's law
Laravelread, write, sticky, usingWritePdo, withoutAffectingStickiness, Cache::flexible, Cache::lockRouting and cache primitivesThe code above
Message or codeWhereMeaningAction
FATAL: sorry, too many clients already (53300)PostgreSQLmax_connections reachedPool; find leaks and idle in transaction
ERROR: canceling statement due to conflict with recovery (40001)Hot standbyReplay needed to remove rows the query still seesRetry; raise max_standby_streaming_delay or use a reporting replica
ERROR: cannot execute INSERT in a read-only transaction (25006)Replica or misrouted writeA write went to a standbyFix routing; ensure writes use the primary handle
ERROR: terminating connection due to conflict with recoveryHot standbySame, connection droppedRetry with a fresh connection
WARNING: database "x" must be vacuumed within N transactionsPostgreSQLTransaction-ID wraparound approaching (what hit Notion)Vacuum, partition, shard (MVCC & VACUUM)
MySQL 1040 Too many connectionsMySQLmax_connections reachedProxySQL, pooling
MySQL 1290 / 1836MySQLWrite on a read-only replicaFix routing
Redis OOM command not allowed when used memory > 'maxmemory'RedisEviction policy noeviction and memory fullSet a policy such as allkeys-lru; size the cache
Redis CLUSTERDOWN / MOVEDRedis ClusterSlot owner changed or unavailableCluster-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:

LimitWhat happensWhat 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 bandwidthPrefer one large socket or interleave (numactl --interleave=all), vm.zone_reclaim_mode = 0, benchmark with and without
Huge pages and shared buffersLarge shared_buffers with 4 KB pages means a huge page tablehuge_pages = on (PostgreSQL), Linux huge pages configured
IOPS and throughput capsCloud block storage has provisioned IOPS and throughput per volume and per instanceCheck both the volume and the instance limit; io2/Provisioned IOPS, local NVMe for temp
Single WAL streamAll writes serialise through one WAL writerBatch, group commit; ultimately split databases
Lock manager, buffer mappingPartitioned lock tables, but contention rises with cores (β)Pooling, fewer active backends
Cloud instance ceilingThe largest instance (Figma: "AWS's largest physical instance") and maximum storage per database are fixedCheck the provider's current limits; plan the next rung before you reach them
Failover and restore timeA 20 TB node takes hours to restore or re-seed a replicaSmaller nodes recover faster (Backup, PITR & DR)
Blast radiusEverything on one box fails togetherDecomposition, replicas across zones
Soft limitsVacuum, 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 earlierPremature sharding
What it isStart the migration while the primary still has headroom, because the migration itself adds loadRun sharded production before a measured need and before the access pattern is known
EvidenceA projected ceiling (disk, IOPS, vacuum) with a dateA guess
Cost of being wrongExpensive if too late: no spare capacity for double-writesExpensive if too early: wrong key, permanent joins and transactions lost
What to doSet the trigger (for example, 60% of measured IOPS ceiling, or 12 months of runway) and start thenDo 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 ​

WorkloadWhy the primary strugglesBetter fitLink
Relevance search, fuzzy match, facetsLIKE and trigram have limits; ranking is poorElasticsearch / OpenSearch, or PostgreSQL FTS firstFull-Text Search
Large scans, aggregations, dashboardsRow store reads whole rows; analytics steal IOPS from OLTPClickHouse, BigQuery, a columnar warehouse, fed by CDCOLTP vs OLAP
Write firehose, time series, known-key lookupsOne primary's WAL; B-tree write amplificationCassandra, ScyllaDB, DynamoDB, a time-series DB (LSM-based)NoSQL families, Wide-column & key-value, Storage Engines
Session data, counters, leaderboards, rate limitsRow locks and durability you do not needRedisRedis
Documents of varying shape, built-in shardingSchema churn, large JSONBMongoDBMongoDB
Deep relationship traversalRecursive joinsA graph databaseGraph Databases
Similarity searchNot what B-trees dopgvector or a vector databaseVector Search
Transactions across regionsSingle-primary latencyCockroachDB, Spanner, YugabyteDBDistributed 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 ​

RungBuild costRun costRollback pathReversibility
1 Indexes and queriesHours to daysWrite overheadDROP INDEX CONCURRENTLY; revert the queryVery high
2 VerticalMinutes plus a failoverMoney, bigger blast radiusResize back (storage usually cannot shrink)High, with a floor
3 PoolingDaysOne more hop to operatePoint the DSN back at the databaseHigh
4 CachingDays to weeksRedis cluster, invalidation bugsFeature flag off; flush; keep the TTLHigh, if reads still work uncached and the database can survive the load
5 Read replicasDaysReplicas, lag monitoringRouting flag back to the primaryHigh
6 PartitioningWeeks (migration of a big table)Partition maintenanceATTACH/DETACH, copy backMedium
7 DecompositionWeeks to monthsCross-database consistency workReverse replication and cut-overMedium to low
8 ShardingMonths to years (Figma: "multi-year effort")Routing layer, resharding, toolingLogical: config switch; physical: reverse copy with coordinationLow
9 Polyglot / CQRSWeeks per read modelPipelines, lag, reconciliationDrop the read model; keep the source authoritativeHigh 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.

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

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

ConcernGoLaravel
Two poolsTwo *sql.DB, own limitsread / write arrays on one connection
After-write consistencyContext flag, cookie window, LSN checksticky, usingWritePdo, cookie-window middleware
Coalescing identical loadssingleflight.GroupCache::lock()->block() or Cache::flexible
Stale-while-revalidateBackground refresh in the cache layerCache::flexible([fresh, stale], fn)
Functional decompositionOne *sql.DB per domain$connection on the model, separate named connections
Sharded routingRouter picks *sql.DB by shard keyCustom connection resolver or a proxy (Vitess, Citus)

Choosing the next rung ​

Which resource saturates first?p99, QPS split, pg_stat_io, working setReads dominateCPU or hit ratioWrites dominateIOPS, WAL, lock waitsWrong engine for the jobsearch, analytics, graphIndex, cache, replicathen partition by timeBatch, split by domainthen shard by keyRead model or new storefed by CDC / events
Symptom (measured)Likely causeNext rungExtra techniqueReason
p99 high, CPU high, seq scansMissing index, N+11: indexes and queriesEXPLAIN (ANALYZE, BUFFERS)Cheapest and most effective
Hit ratio dropped, disk reads upWorking set above RAM1, then 2: RAMDrop unused indexesMemory beats disk by 100x
Hundreds of connections, high load averageToo many backends3: poolingLittle's law sizingFewer backends are faster
Same rows read thousands of timesRepeat reads4: cacheJitter, singleflightRemoves load, not just spreads it
Read CPU high, writes lightRead-bound5: replicasSticky, lag alertScales reads
Replica lag growsReplay slower than write rate; long queriesFix replicas or cut replica loadDedicated reporting replicaReplicas are not infinite
Table at TBs, vacuum for daysTable too big for one unit6: partitioningDetach for retentionSmaller maintenance units
One domain's writes saturate IOPSShared WAL/storage7: decompositionLogical replication copySplits the write load by domain
Single table write IOPS at ceilingOne primary8: shardingTenant key, logical firstOnly rung that scales writes of one table
Search/analytics queries hurt OLTPWrong engine for the job9: new storeCDC feedDifferent data structures
Latency spikes at one hour of the dayStampede or batch job4: jitter, 1: reschedulePre-warmNot 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 ​

LoadTypical designRungs in useWhat to watch
1x (hundreds of QPS, GBs)One PostgreSQL, one app, a pool1, 3Slow-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 table1 to 6Lag, 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 proxy1 to 9Per-shard runway, hot keys, cross-shard queries, topology correctness
BeyondDistributed SQL or purpose-built stores; global routing; cell-based architectureall, plus platform teamOperational 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.

bash
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, async

Experiment 1: single node, find the saturating resource.

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

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

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

Experiment 4: replication lag and read-your-writes.

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

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

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

TopicWhat to remember
OrderIndexes, vertical, pooling, cache, replicas, partitioning, decomposition, sharding, polyglot; climb on measurement
Measurep50/p99, QPS read vs write, working set vs RAM, hit ratio, pg_stat_io, saturation, lag
Peakpeak QPS = average × 3 to 10 (20+ for spikes); run below 60 to 70% of the ceiling
LittleL = λW; pool size = QPS × latency, with headroom
Amdahlspeedup is capped at 1/s
USLC(N) = N / (1 + α(N−1) + βN(N−1)); peak N* = √((1−α)/β); β > 0 means retrograde
Cache-asideread cache, miss to database, set with TTL + jitter; delete on write
Stampedejitter + singleflight / lock + stale-while-revalidate (Cache::flexible)
Replicasasync; add read capacity; need read-your-writes routing and a lag alert
Read-your-writessticky window, LSN/GTID token, primary for own data, remote_apply
Hot keyskey splitting, local copies, own shard, sharded counters
Batchingmulti-row insert, COPY, group commit, queue + batch consumer; synchronous_commit=off risks the last ms
Vertical limitNUMA, IOPS/throughput caps, one WAL, instance ceiling, restore time
Shardingkey aligned with access pattern; logical before physical; many logical per physical; no free FKs/joins/transactions
Rollbackplan it per rung; logical sharding is a flag, physical is a project
Other storewrong data structure for the engine, fed by CDC, operated by a team

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 — 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 ​

TermMeaning
Scale ladderThe ordered list of scaling steps from cheap and reversible to expensive
p50 / p95 / p99Latency percentiles: the value below which 50, 95 or 99% of requests fall
QPSQueries (or requests) per second
Peak factorRatio of peak load to average load
Working setData and indexes touched regularly; should fit in RAM
Cache hit ratioHits divided by hits plus misses
pg_stat_ioPostgreSQL 16+ view of reads, writes, hits, evictions by backend type and context
pg_stat_statementsExtension that tracks execution statistics per normalised query
SaturationA resource with a queue in front of it
Little's lawL = λW, requests in the system equal arrival rate times time in system
Amdahl's lawSpeedup is limited by the serial fraction
USLUniversal 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
RetrogradeThroughput that decreases as load or nodes increase
Vertical scalingA bigger machine
NUMANon-uniform memory access: memory near another socket is slower
IOPSInput/output operations per second a disk or volume can serve
Connection poolingReusing a small set of database connections (PgBouncer, ProxySQL)
Cache-asideApplication reads cache, loads on miss, writes cache, deletes on write
Read-through / write-through / write-behindCache patterns where the cache loads, writes synchronously, or flushes later
TTLTime to live of a cache entry
JitterRandom variation added to a TTL or backoff
Cache stampede (dogpile, thundering herd)Many concurrent misses on one key hitting the database
Cache penetrationRequests for keys that never exist, bypassing the cache
Cache avalancheMany keys expiring together or the cache failing, overloading the database
SingleflightCollapsing concurrent identical calls into one
Stale-while-revalidateServing a stale value while refreshing in the background (Cache::flexible, RFC 5861)
Negative cachingCaching "not found"
Hot keyOne key receiving a disproportionate share of traffic
Read replicaAsynchronous copy serving reads
Replication lagDelay between a commit on the primary and its replay on a replica
Read-your-writesA reader sees its own earlier writes
Monotonic readsA reader never sees time go backwards
StickyPinning reads to the primary after a write (Laravel sticky, a cookie window)
LSNPostgreSQL log sequence number, a position in the WAL
GTIDMySQL global transaction identifier
Recovery conflictA replica query cancelled because WAL replay needs its row versions
PartitioningSplitting a table into pieces within one database
Partition pruningSkipping partitions that cannot match the query
Functional decomposition (vertical partitioning)One database per group of tables or domain
ShardingSpreading one table's rows across databases by a shard key
Logical / physical shardThe application-level bucket vs the database server that holds it
Scatter-gatherA query sent to every shard, results merged
ReshardingMoving data between shards to change their number or layout
Colo (Figma)A group of tables sharing one shard key and layout
DBProxyFigma's query-routing service between the application and PgBouncer
Polyglot persistenceDifferent stores for different workloads
CQRSSeparate write model and read models
CDCChange data capture: a stream of committed changes from the database log
Group commitSeveral transactions sharing one WAL flush
Dark readReading from the new system in parallel only to compare with the old
pgbenchPostgreSQL's built-in benchmark tool

References ​

Built by Morteza Negahi