Databases
The seven acts: from CREATE TABLE to Citus
Day 0 at a SaaS startup. The PM wants “search users by email.” One engineer, one Postgres, one table. Three years later: 1 billion rows, six Citus shards, and a runbook the size of a textbook. Between those two points are seven moments when the database broke and the team learned.
The seven pieces of this chapter map one-to-one onto seven acts of product growth. Each act has a trigger, a symptom, and a lever. Skip a lever and the next act costs more to resolve.
Act 1 — Day 0, schema design. “users(email, name, org_id).” Should email be UNIQUE? Should org_id be a foreign key? Should prefs be a side table or JSONB? Decisions: email is UNIQUE NOT NULL CITEXT. org_id is BIGINT REFERENCES orgs(id) ON DELETE CASCADE. prefs is JSONB with a GIN index when search demands it. A surrogate id BIGSERIAL insulates from email changes. Bend the rules only with measured throughput pressure, never as a default.
Act 2 — Week 1, 10K rows, the first slow query. Email-search endpoint p95 climbs from 30 ms to 800 ms. The planner does a sequential scan. CREATE INDEX users_email_idx ON users(email). The leading-column rule of B-tree means WHERE email = ? resolves with two page reads. p95 drops to 4 ms.
Act 3 — Month 1, 100K rows, the planner lies. Half the requests are fast, half take 600 ms. EXPLAIN ANALYZE shows the planner sometimes picks a seq-scan despite the index. Row estimate is off by 30×: stale statistics. ANALYZE users; rebuilds the histograms. The planner picks plans from statistics, not from data; statistics maintenance is the operational discipline.
Act 4 — Month 6, the silent bloat. A nightly report runner holds one transaction open for four hours. VACUUM cannot reclaim dead tuples below the xmin horizon. The users table swells from 200 MB to 80 GB. Fix: kill the long transaction, set idle_in_transaction_session_timeout = 60s, run pg_repack to reclaim disk. Permanent fix: replicate to a read replica for reporting.
Act 5 — Year 1, 1M users + 50 app pods, the connection storm. Each pod opens its own Postgres backend on cold-start. At pod-rollout the cluster sees 1000 concurrent backends; the kernel scheduler thrashes; 4 ms queries take 4 s. PgBouncer in transaction-mode: 100 server-side backends, 10000 client connections multiplexed. Sizing rule: pool_size = active_concurrent_transactions × safety_factor, not max_app_workers.
Act 6 — Year 2, the migration that froze prod. Multi-tenancy day. ALTER TABLE users ADD COLUMN tenant_id BIGINT NOT NULL DEFAULT 0 takes an AccessExclusiveLock and triggers a full table rewrite. Prod freezes for eight minutes. The expand-contract recipe: add nullable column, backfill in batches, add CHECK ... NOT VALID, VALIDATE CONSTRAINT, SET NOT NULL, drop the check.
Act 7 — Year 3, 1B rows, the hot shard. Citus is rolled out, shard key is tenant_id. Tenant Acme accounts for 40% of all queries. Acme’s shard saturates while the others idle. Fix: co-location of related tables on the same shard key; online resharding with citus_rebalance_table_shards.
- Act 1 — Day 0
- Schema: surrogate keys, FKs, constraints
- Act 2 — Week 1, 10K rows
- Index on the filtered column
- Act 3 — Month 1, 100K rows
- ANALYZE to refresh statistics
- Act 4 — Month 6, 200 MB → 80 GB
- Kill long tx, pg_repack, timeout
- Act 5 — Year 1, 50 pods
- PgBouncer transaction-mode pool
- Act 6 — Year 2, multi-tenancy
- Expand-contract migration recipe
- Act 7 — Year 3, 1B rows
- Citus sharding with co-location
Why the order matters.
A database is like a growing city. The schema is zoning. Indexes are the street map. Execution plans are the traffic dispatcher. MVCC is multiple lanes so cars pass without colliding. The connection pool is the parking garage. Migrations are construction crews who must not close every road at once. Sharding is annexing new districts when one city block can’t hold the traffic. A skipped lesson means the city keeps growing, but the wrong layer is overloaded.
Each act unlocks the next only if you nailed the previous one. Skip Act 1 (schema) and Acts 2–7 fight a losing battle against inefficient joins. Skip Act 2 (indexing) and Act 3 planning decisions are made blind. Skip Act 3 (stats) and Act 4 vacuum is the only lever left. Skip Act 4 (bloat) and Act 5 pool threads see table scans get slower. Skip Act 5 (pooling) and Act 6 migrations are starved by connection storms. Skip Act 6 (lock safety) and Act 7 sharding is impossible. The order is a constraint imposed by physics and Postgres internals.
Why this works
The price of a late fix is exponential: Act 1 mistakes cost days to fix; Act 7 mistakes cost months of resharding. Teams that skip early acts pay catastrophic costs later. Teams that over-engineer early acts (sharding a 10 GB dataset) waste resources on problems that do not exist yet. The art is knowing your growth trajectory and timing each act to land just before the prior act’s failure modes become production pain.
At 10K rows, the email-search endpoint is suddenly slow. Cheapest first lever?
The disk is full but the row count has not changed. Most likely cause?
Why is sharding a year-3 lever, not a year-1 lever?
Order the seven scale-tier levers from earliest (Day 0) to latest (Year 3):
- 1 Design the relational schema (tables, keys, constraints)
- 2 Add the right index for the query
- 3 Verify the execution plan uses the index; run ANALYZE
- 4 Hunt the long transaction blocking VACUUM
- 5 Put a connection pooler in front of Postgres
- 6 Migrate schema safely with expand-contract
- 7 Shard the largest table across nodes
- 01Name the seven levers in order and give one symptom that signals each tier.
- 02Why does the order of acts matter — why is skipping Act 2 not 'fine, I'll add indexes later'?
- 03Trace the city metaphor: match each layer (schema, index, plans, MVCC, pool, migrations, sharding) to its city element.
A product’s database passes through seven growth tiers, each with a distinct trigger and a single correct lever. Schema decisions made on Day 0 compound into every later act — a surrogate key and proper FK constraints are cheap greenfield choices that become expensive retrofits at scale. Indexes fix queries at 10K rows; missing one at 1B rows is a multi-hour concurrent build under traffic. Stale statistics cause the planner to ignore existing indexes; ANALYZE is the operational discipline. Bloat from a long-held transaction can grow a 200 MB table to 80 GB in days; the lever is killing the long transaction, not adding more disk. Connection storms at pod-rollout time require a connection pooler, not more backends. Schema migrations that take an AccessExclusiveLock queue every query behind them; expand-contract avoids the freeze. Sharding distributes load but multiplies every operational task — it is the last resort, entered deliberately after all prior levers are applied. The order is a constraint imposed by Postgres internals: skip one act and every subsequent act costs exponentially more.
- What a relation is: tables, rows, keys, and constraintsjunior
- What an index is and how it speeds up queriesjunior
- EXPLAIN and execution plans: what the planner decides and whyjunior
- Vacuum and bloat: keeping the storage tax boundedmiddle
- Connection pools: amortising the cost of a Postgres backendjunior
- What a schema migration is and why it replaces ad-hoc DDLjunior
- Why sharding exists: the single-Postgres ceilingjunior
appears again in258
- Why GraphQL gets N+1junior
- DataLoader mechanics: tick-boundary batchingmiddle
- Batch function contracts: ordering, shapes, errorsmiddle
- Federation and lookahead: batching beyond DataLoadermiddle
- Query complexity defences: depth, cost, persisted queriesmiddle
- Senior GraphQL API: scheduling contract, tenant isolation, observabilitysenior
- The journey of a request: seven stops from socket to responsejunior
- Accept and parse: from kernel queue to a typed requestmiddle
- Routing and middleware: choosing what runs, and in what ordermiddle
- Handler and response: from business logic to bytes on the wiremiddle
- Streaming and backpressure: when the client reads slower than you writesenior
- Timeouts and tail latency: budgets, deadlines, and the fan-out trapsenior
- Middleware and DI: the two patterns that shape every backendjunior
- Writing middleware: signatures, next(), and the three framework modelsmiddle
- Inversion of control: how dependencies reach a classmiddle
- DI scopes and lifecycles: singleton, request, transientmiddle
- DI as a testing seam: fakes, mocks, and the boundary that matterssenior
- DI containers in production: resolution graphs, circular deps, and when not tosenior
- Blocking vs non-blocking I/O: two ways to waitjunior
- The event loop: one thread, ordered phasesmiddle
- What blocks the loop: CPU work and sync callsmiddle
- Offloading CPU work: worker threads and the libuv poolmiddle
- Backpressure and bounded concurrencysenior
- Throughput under load: tail latency and saturationsenior
- Why pool: the cost of creating a connectionjunior
- Pool sizing: why bigger is not fastermiddle
- Acquisition and timeouts: the wait queue is the real latency dialmiddle
- Why idempotency: making retries safejunior
- Server-side state machine: four states of an idempotency keymiddle
- Retry strategies: backoff, jitter, and thundering herdmiddle
- Outbox and inbox: effectively-once across the dual-write boundarymiddle
- Concurrency and cache architecture for idempotency at scalesenior
- Observability, production failures, and global-scale designsenior
- The event loop: one thread, three queuesjunior
- Tasks, microtasks, and scheduler.yield()middle
- Timer accuracy, throttling, and idle workmiddle
- Microtask starvation, Long Tasks, and LoAFsenior
- Node.js event loop: phases, nextTick, and loop lagsenior
- React, Vue, and INP observability in productionsenior
- The render pipeline: six stages from bytes to pixelsjunior
- Stage costs and the renderer process modelmiddle
- Invalidation, dirty bits, and containmiddle
- Compositor layers: promotion, overlap, and GPU memorymiddle
- DevTools flame strip and the frame lifecyclemiddle
- Layout thrash: forced synchronous layoutsenior
- BeginMainFrame, compositor-driven animations, and GPU memorysenior
- Production observability: LoAF, INP, and the full attack surfacesenior
- What V8 is and why performance varies 100×junior
- V8''''s four-tier JIT pipeline and profile-guided tieringmiddle
- Hidden classes, transition trees, and memory layoutmiddle
- Inline caches, IC states, and deoptimizationmiddle
- Orinoco GC: parallel scavenger, concurrent marking, and write barriersmiddle
- TurboFan''''s speculative engine and the deopt-loop trapsenior
- V8 in production: isolates, pointer compression, and real failuressenior
- Service worker lifecycle and cache strategiesmiddle
- Service worker edge cases: version skew, durability, and navigation trapssenior
- What the reconciler does: render vs commitjunior
- The fiber object and the double-buffer treemiddle
- Render phase purity and commit phase sub-stepsmiddle
- Reconciliation: diffing heuristics and the key trapmiddle
- Priority lanes, time-slicing, and useTransitionmiddle
- Bailout, memoisation, and tearingsenior
- React Profiler, the Compiler, and production observabilitysenior
- Rendering strategies: SSG, SSR, ISR, streaming, and hydrationjunior
- SSG, SSR, ISR, streaming, and RSC — how each worksmiddle
- Hydration cost: selective, progressive, islands, resumabilitymiddle
- Hydration mismatch: causes, detection, and the determinism rulesenior
- RSC, per-route strategy, and production observabilitysenior
- Core Web Vitals: what LCP, INP, and CLS measurejunior
- LCP: four phases, one dominant costmiddle
- INP: input delay, processing, presentationmiddle
- CLS: why layout shifts happen and how to stop themmiddle
- Lab vs field: why the two disagree and how to use eachmiddle
- Metric tradeoffs, RUM attribution, and the CI+field loopsenior
- The full picture: URL to LCP to INP as a relay racejunior
- Eight layers traced: from the service worker to the second navigationmiddle
- Five canonical breaks: where production reliably diessenior
- The three-track method: reading traces and building a monitored systemsenior
- What is a cache stampede and why it makes things worsejunior
- Lock and single-flight: bounding concurrent rebuildsmiddle
- XFetch: coordination-free probabilistic early expirationmiddle
- Stale-while-revalidate and CDN request coalescingmiddle
- Detecting stampedes and designing TTL for productionmiddle
- Metastable failure, fencing tokens, and production postmortemssenior
- Raft roles, terms, and why majority quorums prevent split brainjunior
- How Raft replicates a log entry and decides it is safe to commitmiddle
- Raft leader election: timeouts, voting rules, and the four safety propertiesmiddle
- Raft in the real world: partitions, slow disks, and client routingmiddle
- Raft extensions: pre-vote, learners, snapshots, and linearizable readssenior
- Raft in production: membership changes, Multi-Raft, and observabilitysenior
- Where data fetching happens — and why it decides LCPjunior
- Fetch waterfalls — diagnosis and the Promise.all curemiddle
- React Server Components and Suspense streamingmiddle
- Client-side cache: TanStack Query, SWR, and stale-while-revalidatemiddle
- LCP, prefetch, and race conditions in interactive fetchingmiddle
- Senior internals: RSC payload, caching layers, and production failure modessenior
- Bits on the wirejunior
- Latency mathmiddle
- Bufferbloat and congestionsenior
- The physical frontiersenior
- The three-way handshakejunior
- Sequence numbers and connection statemiddle
- Flow control and congestion controlmiddle
- BBR, production observability, and beyond TCPsenior
- DNS: what it does and why it existsjunior
- The resolver walk: referrals, record types, and gluemiddle
- TTL, caching, and DNS propagationmiddle
- The 1-RTT handshake: key shares and ECDHEmiddle
- Session resumption and 0-RTTmiddle
- CDN: putting content next doorjunior
- Anycast and GeoDNS: routing to the nearest edgemiddle
- Tiered cache and Cache-Controlmiddle
- Vary header and cache keysmiddle
- Stale-while-revalidate and cache stampedesenior
- Edge workers and edge-side compositionsenior
- CDN operations and observabilitysenior
- WebSocket: the HTTP upgrade handshakejunior
- WebSocket frame format: opcodes, masking, fragmentationmiddle
- WebSocket vs SSE vs long-polling: choosing the right transportmiddle
- WebSocket backpressure: when clients can''''t keep upmiddle
- Reconnection: jittered backoff, thundering herd, message resumptionsenior
- WebSocket at scale: HTTP/2 multiplexing, permessage-deflate, C10Msenior
- WebSocket in production: proxies, security, and distributed architecturesenior
- What reverse proxies dojunior
- Balancing algorithms: round-robin to power-of-two-choicesmiddle
- L4 vs L7 load balancing and client-IP preservationmiddle
- Health checks, connection draining, and slow startmiddle
- Session affinity, consistent hashing, and the right fixmiddle
- Retry storms, circuit breakers, and load sheddingsenior
- Resilient LB architecture: anycast, zone-aware routing, and observabilitysenior
- Why QUIC and not TCP+TLSjunior
- QUIC streams and head-of-line blockingjunior
- Integrated handshake and 1-RTTmiddle
- Connection IDs and network migrationmiddle
- Loss detection and congestion controlmiddle
- 0-RTT resumption and packet encryptionsenior
- Deployment tradeoffs and CPU costsenior
- DDoS: what it is and why it worksjunior
- Amplification attacks and state exhaustionmiddle
- Rate limiting: algorithms and architecturemiddle
- WAFs, firewalls, mTLS, and HSTSmiddle
- DNS cache poisoning and BGP hijackingsenior
- Defense-in-depth architecture and attack economicssenior
- The twelve layers: one URL, seven actorsjunior
- DNS, TCP, TLS in sequence: where the milliseconds gomiddle
- Critical render path and Core Web Vitalsmiddle
- Proxy intercepts and security gates: rate limiters, WAF, mTLSmiddle
- Alternate paths: QUIC 0-RTT, WebSocket upgrade, connection migrationmiddle
- Observability: distributed traces, USE/RED, and samplingsenior
- Resilience: cascading retries, circuit breakers, and error budgetssenior
- What the three signals are: logs, metrics, and tracesjunior
- Metrics and cardinality: the cost model of a time-series databasemiddle
- Logs and volume: the cost model of structured loggingmiddle
- Traces and sampling: the cost model of distributed tracingmiddle
- Join keys and exemplars: making the three signals composemiddle
- Observability 2.0: wide events and the cost shiftsenior
- Failure modes and engineering practice: cardinality budgets, PII, and samplingsenior
- Why structured logs exist: the diary vs the spreadsheetjunior
- The production log schema: fields every line must carrymiddle
- Log levels and alert routingmiddle
- Sampling strategies and log costmiddle
- PII redaction and log injectionsenior
- Trace context propagation in logssenior
- OTel Logs Data Model and audit logs as a subsystemsenior
- OTel signals, Semantic Conventions, and the OTLP wire formatmiddle
- Auto-instrumentation and manual spans: the 80/20 of OTelmiddle
- The OTel Collector: receivers, processors, exporters, and deployment patternsmiddle
- Sampling strategies: head, tail, and parent-basedmiddle
- Vendor neutrality, eBPF instrumentation, the Operator, and browser/serverless OTelsenior
- Operating the OTel Collector: reliability, version skew, failure modes, and governancesenior
- RED and USE: two checklists, one triage disciplinejunior
- Instrumenting RED in Prometheus: counters, histograms, and cardinality disciplinemiddle
- USE on Linux: CPU, memory, disk, network, and PSImiddle
- Golden signals, dashboard layout, and service mesh auto-REDmiddle
- Cardinality as a cost driver: labels, PII, exemplars, and samplingmiddle
- Native histograms, SLO tie-in, and production failure patternsmiddle
- SLI, SLO, and the error budget: reliability by the numbersjunior
- Choosing SLIs and SLO targets: ratios, not feelingsmiddle
- Multi-window multi-burn-rate alerting: why AND beats ORmiddle
- Error budget policy, latency SLOs, and composite journeysmiddle
- Iceberg SLIs, composite SLO math, and SLA vs SLOsenior
- Production SLO failures, self-observability, security, and the big picturesenior
- Flame graphs: reading the picture that shows where time goesjunior
- Sampling vs instrumentation profiling: why 99 Hz wins in productionmiddle
- Profile types: CPU, memory, off-CPU, mutex — which one to reach formiddle
- Continuous profiling: always-on flame graphs with eBPF and trace-id correlationmiddle
- How flame graphs are built from samples, and the production workflows that use themmiddle
- Linux perf, eBPF internals, PGO, and the limits of samplingsenior
- Profiling in production: security, war stories, OTel profiles, and the infrastructure designsenior
- The debugging funnel: SLO → RED → trace → profilejunior
- OTel architecture: one SDK, four signals, one wire formatmiddle
- Cost discipline: keeping observability under 5% of infra spendmiddle
- The incident loop: from pager to postmortem to preventionmiddle
- Scale, security, and the ROI of observable systemssenior
- Why profile first: measure where time actually goesjunior
- Amdahl''''s law and self-time: the ceiling on every speedup you can shipmiddle
- The measurement loop: microbench, macrobench, prod profile, observer effectmiddle
- Reading flame graphs: shapes, per-language profilers, and the 60-second scanmiddle
- Statistical baselines: why one run is not a measurementmiddle
- Profiler history and microbenchmark pitfalls: Knuth to GWPsenior
- Hardware counters, cold-start profiles, and profile securitysenior
- Continuous profiling at scale: costs, CI gates, trace correlation, and anti-patternssenior
- What makes a hot path: symptom vs causejunior
- Five shapes of hotspot: CPU, alloc, cache, lock, syscallmiddle
- Reading parent and child chains: where to apply the fixmiddle
- JIT deopt, the fix-and-verify loop, and PR-time profilingmiddle
- Hardware counters and Intel TMA: sub-category diagnosissenior
- False sharing and native-bridge hot pathssenior
- Hot paths in production: security, tail latency, and tooling lineagesenior
- Memory hierarchy: why the same O(N) loop can be 17x slowerjunior
- Row-major vs column-major: access order and the 9x gapjunior
- Cache lines, struct layout, and false sharingmiddle
- Branch prediction and branchless codemiddle
- SIMD, SoA vs AoS, and memory bandwidthmiddle
- Hardware prefetcher, TLB, and memory-level parallelismsenior
- Cache-oblivious algorithms, PGO, and production failuressenior
- GC basics: what the runtime taxes you forjunior
- GC algorithms: generational, concurrent, and per-runtimemiddle
- GC tradeoffs: pause, throughput, heap — and object poolingmiddle
- GC tuning: pacing, heap shape, and allocation observabilitymiddle
- GC internals: tri-color invariant, write barriers, and per-runtime deep-divessenior
- GC in production: observability, security, edge cases, and fleet governancesenior
- N+1: one logical operation, many round-tripsjunior
- Fix families: JOIN, IN, preload, and DataLoadermiddle
- Detecting N+1: query logs, APM traces, and CI gatesmiddle
- DataLoader: batching across resolver treesmiddle
- Cross-protocol N+1: HTTP fan-out and Redis MGETmiddle
- N+1 at scale: pool exhaustion, plan changes, and denormalisationsenior
- Batching: amortize fixed cost per operationjunior
- The batching window: size and wait timemiddle
- Batching in Kafka and Postgresmiddle
- io_uring and observability of batchingmiddle
- From Nagle to io_uring: evolution of batchingmiddle
- Backpressure, failure isolation, and batch security in productionsenior
- What a bundle actually costs: download, parse, compile, executejunior
- Core Web Vitals: LCP, INP, and CLSmiddle
- Code splitting: route-level, component-level, vendor splittingmiddle
- Tree shaking and compression: removing what you don''''t usemiddle
- Third-party scripts: the silent budget killermiddle
- CI enforcement and RUM: making budgets stickmiddle
- V8 JIT pipeline, HTTP priorities, and bundle securitysenior
- The performance loop: discipline, not a projectjunior
- Classify and fix: matching bottleneck families to remediesmiddle
- Observability stack and CI gates: catching regressions before they shipmiddle
- Incident to enforcement: SLO burn to verified fix in 35 minutesmiddle
- Culture, economics, and org-scale performancesenior
- At-most-once, at-least-once, exactly-once: the three delivery contractsjunior
- The three failure legs — where duplicates and losses actually happenmiddle
- Consumer-side dedup: the cheapest path to exactly-once processingmiddle
- Kafka exactly-once semantics: idempotent producer and transactionsmiddle
- SQS visibility timeout, DLQ, and the outbox patternmiddle
- Exactly-once in production: impossibility proof, hybrid patterns, and real incidentssenior
- What OAuth is and why passwords are not the answerjunior
- Authorization code flow with PKCEmiddle
- ID token validation and JWKS cache managementmiddle
- Refresh token rotation and scope-based least privilegemiddle
- Sender-constrained tokens: DPoP and mTLSsenior
- OAuth in production: audience attacks, observability, and real failuressenior