Databases
Observability, anti-patterns, and production triage
You inherit a Postgres at 200M rows, p95 1500 ms, 600 concurrent backends, 40 GB bloat, no pooler, single node. Three weeks to stabilize. The seven-act model is not just a growth story — it is also the triage protocol. Work from the most acute failure mode to the most structural one, not the other way around.
USE + RED for Postgres
The USE method (Utilization, Saturation, Errors) maps to Postgres signals:
- Utilization: backend count vs
max_connections(pg_stat_activity), CPU frompg_stat_bgwriter.checkpoints_reqratio, buffer cache hit rate (pg_buffercache). - Saturation: autovacuum lag (
pg_stat_user_tables.last_autovacuum), replication lag (pg_stat_replication.replay_lag), connection queue depth (PgBouncerSHOW STATS). - Errors: deadlock count (
pg_stat_database.deadlocks), checksum failures, replication errors from server logs.
The RED method (Rate, Errors, Duration) on top of pg_stat_statements:
- Queries/second per
queryid. - Error rate from app logs (timeouts, deadlocks).
- p95/p99 duration per
queryid.
Together they tell you which lever to pull:
| Signal | Likely act |
|---|---|
| High backend count, low CPU | Act 5 (pooling problem) |
| High dead tuples, stable row count | Act 4 (vacuum/bloat problem) |
| Specific queryid with rising duration | Act 2 or 3 (index or stats problem) |
| Rising p95 + one tenant’s shards hot | Act 7 (hot shard problem) |
Diagnostic tooling per act
- Act 1 (schema): no good tooling — read the table definition and trace migrations.
\d+ tablenamein psql. - Act 2 (indexes):
pg_indexesfor existence;pg_stat_user_indexes(idx_scancolumn) to find unused indexes — an index with 0 scans after a week of traffic is a write-overhead tax. - Act 3 (planning):
pg_stat_statementsfor top-N queries by total time;EXPLAIN (ANALYZE, BUFFERS)for the actual plan;auto_explain.log_min_duration = '500ms'for tail-latency triage. - Act 4 (bloat):
pg_stat_user_tables.n_dead_tupvsn_live_tup;pg_table_size(relname)for actual disk;pgstattuplefor precise bloat percentage without a full scan. - Act 5 (pooling):
pg_stat_activityfor backend count,statedistribution,idle in transactionsessions; PgBouncerSHOW STATSfor queue depth and avg query time. - Act 6 (migrations):
pg_locksjoined topg_stat_activityto detect lock contention and blockers before running ALTER. - Act 7 (sharding): application-level metrics — tail latency per shard, write variance across shards, cross-shard join frequency. Missing or misinterpreted tooling is why teams skip acts: “We can’t see the bloat” means autovacuum visibility is off, not that bloat does not exist.
The three-week triage order
You inherit a Postgres at 200M rows, p95 1500 ms, 600 concurrent backends, 40 GB bloat, no pooler:
Week 1 — stop the bleeding:
- Kill long transactions:
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle in transaction' AND query_start < now() - interval '5 minutes'. - Set
idle_in_transaction_session_timeout = 60sso the problem cannot recur overnight. - Deploy PgBouncer in transaction-mode in front of Postgres. Size the pool on active concurrent transactions, not worker count (step 1 reveals actual concurrency).
- Run
pg_repackon the bloated tables online — no AccessExclusiveLock required.
Week 2 — re-establish plan quality:
ANALYZEon the most-queried tables.CREATE STATISTICSfor the top correlated column pairs frompg_stat_statementsslow queries.- Review
pg_stat_statementstop-N by total_time; drop unused indexes (idx_scan = 0); add obviously-missing ones.
Week 3 — capacity assessment:
- Measure actual single-node ceiling with the pool in place. Plot p95 vs QPS curve.
- If single node cannot keep up at expected load: evaluate declarative partitioning (single node, fewer ops) before sharding.
- Only then plan Act 7 — with shard key, co-location, and online resharding rehearsed in staging.
XID wraparound and autovacuum freeze
Every row carries a 32-bit transaction ID (xmin). Once the cluster reaches 2^31 transactions (~2.1 billion), IDs wrap around and rows can appear to be “from the future.” Postgres protects against this by freezing old rows (rewriting xmin to a special “frozen” value) before wraparound. autovacuum_freeze_max_age controls the trigger.
On a write-heavy cluster at 10K TPS, that is ~864M transactions per day — the freeze runs every ~2.5 days. A misconfiguration (very high autovacuum_freeze_max_age) can lead to anti-wraparound emergency vacuums that hold an exclusive lock on the table.
Monitor: SELECT datname, age(datfrozenxid) FROM pg_database; — alert at 80% of autovacuum_freeze_max_age.
The anti-pattern catalogue when an act is skipped
- Skip Act 1: a year later you spend three weeks renaming a column because the schema lacks a surrogate key and every FK must change.
- Skip Act 2: every dashboard query is a 30-second seq-scan; the app team adds caches everywhere; the cache becomes the new source of truth and goes inconsistent.
- Skip Act 3: you have indexes, but the planner ignores them half the time; you write a runbook that says “if slow, restart Postgres” because that flushes the plan cache.
- Skip Act 4: the OOM-killer takes Postgres down on Friday; the postmortem says “we’ll add monitoring”; it never happens.
- Skip Act 5: every deploy triggers a connection storm; CI now spreads pod rollouts across 10 minutes “as a workaround.”
- Skip Act 6: migrations only run during a quarterly maintenance window because nothing else is safe; the queue of pending migrations grows to 40 entries.
- Skip Act 7: you spend six months explaining to leadership that one tenant is using 40% of capacity and the only fix is a re-architecture.
- Cache hit ratio — alert threshold
- below 95–99%
- n_dead_tup / n_live_tup — bloat alert
- above 20%
- age(datfrozenxid) — wraparound alert
- 80% of autovacuum_freeze_max_age
- PgBouncer SHOW STATS: avg_wait_time alert
- above 5 ms sustained
- pg_stat_statements total_time alert
- queries > 1s consuming > 5% of total
- Replication lag alert
- above 30 seconds on async replica
Why this works
The seven-act model is both a growth framework (design levers in order) and a triage framework (apply fixes in reverse of failure acuteness). During an outage, you do not blame the schema (Act 1); you kill long transactions (Act 4), then deploy a pooler (Act 5), then optimize queries (Act 2–3). Once stability is restored, you postmortem and write runbooks for each act to prevent the next incident. The order of acts is not just a design constraint — it is an emergency protocol.
pg_stat_user_tables shows n_dead_tup = 80M on a table with n_live_tup = 100M. What is the correct diagnosis and first lever?
What is the role of backend_xmin in pg_stat_activity for diagnosing bloat?
Why does hot_standby_feedback = on shift bloat from the replica to the primary?
- 01Map the USE method to the Postgres signals that indicate each of the seven acts.
- 02You inherit a production Postgres at 200M rows, p95 1500 ms, 600 backends, 40 GB bloat, no pooler. Give the triage order for the first three weeks and justify each step.
- 03What is XID wraparound, why is it a correctness cliff (not a performance issue), and how do you monitor it?
The USE + RED framework maps directly to the seven acts: high backend count is Act 5, high dead-tuple ratio is Act 4, a specific query’s rising duration is Act 2 or 3, and diverging per-shard tail latency is Act 7. Each act has its diagnostic tool — pg_stat_user_tables for bloat, pg_stat_activity for connection storms, pg_stat_statements for slow queries, pg_locks for migration blockers, and application-level shard metrics for Act 7. When inheriting a degraded Postgres, the correct triage order is Act 4 first (kill long transactions, stop bleeding), then Act 5 (deploy pooler), then Acts 3 and 2 (plan quality), then structural Acts 1 and 7. XID wraparound is a correctness cliff — it does not slow queries, it corrupts them — monitor age(datfrozenxid) per database and alert at 80% of autovacuum_freeze_max_age. The seven-act model is simultaneously a growth framework and an emergency protocol: the order of acts is the order of triage when everything is on fire.
appears again in263
- 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
- HTTP: the request-response language of the webjunior
- HTTP/2: streams, frames, and HPACKmiddle
- HTTP/3 and QUIC: stream-level loss isolationmiddle
- HTTP/3 in production: QUIC internals, fallback, and observabilitysenior
- HTTP design: priorities, WebTransport, and semantic correctnesssenior
- 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