Databases
Join algorithms and the row-estimate cascade
A query returns 50 rows in 50ms on staging. In production with the same schema, identical indexes, same query — 4.2 seconds. EXPLAIN ANALYZE reveals Nested Loop ... loops=520000. The inner index scan ran half a million times. The planner thought the outer side had 50 rows. It had 520,000. One bad row estimate. One wrong join choice. 80× slowdown.
The three join algorithms
| Algorithm | Cost shape | Wins when | Danger |
|---|---|---|---|
| Nested Loop | outer_rows × inner_cost | Outer is small (10s of rows), inner has an index | Blows up if outer is misestimated as small |
| Hash Join | build_cost + probe_cost | Medium-to-large equi-joins; neither side has a sort index | Spills to disk if hash table exceeds work_mem |
| Merge Join | sort_cost + merge_cost | Both sides already sorted (matching index); large equi-joins | Requires sorted input; sort can spill if work_mem is low |
Nested Loop
For each row in the outer relation, look up matching rows in the inner relation — typically via index. Cost is outer_rows × inner_cost_per_lookup. It wins when the outer side is small (tens of rows) because the inner index lookup cost is paid only that many times. It catastrophically fails when the outer side is underestimated: if the planner thinks there are 10 outer rows but there are 10,000, the inner lookup runs 10,000 times instead of 10 — 1000× more work.
Diagnostic: loops count on the inner node. In a healthy Nested Loop: loops=50. In a blown-up one: loops=520000.
Hash Join
Builds a hash table from the smaller (build) side, then probes it with rows from the larger (probe) side. Cost is build + probe. Wins for medium-to-large equi-joins where neither side has an index aligned with the join key. The critical parameter is work_mem: the hash table must fit in memory. When it does not, Hash Batches exceeds 1 and the table spills to disk — look for Batches: 64 or similar in the plan output. Fix: SET work_mem = '64MB' for the session (not globally without accounting for max_connections).
Merge Join
Sorts both sides on the join key (or uses indexes that already provide sort order), then merges in parallel. Wins when both sides arrive sorted — for example, joining two tables where both have ORDER BY id and matching indexes. Adding no-extra-sort cost to the join. Useful for range joins and when sort order is also needed for the final result.
The row-estimate cascade
This is the most important concept in this lesson. A bad row estimate at one plan node cascades into every node above it:
- Planner thinks the filter
WHERE country='US' AND region='CA' AND status='shipped'returns 50 rows (independent probabilities: 50% × 5% × 20% = 0.5%) - Planner picks Nested Loop — cheap when outer is small
- Reality: the columns are correlated (all CA orders are in US), actual selectivity is 5% × 20% = 1% — not 0.5%, but the planner also missed the index cardinality; actual rows = 520,000
- The inner index scan runs 520,000 times instead of 50 — 10,400× more work
The wrong join algorithm (Nested Loop instead of Hash Join) is the symptom. The wrong row estimate is the cause. Forcing the algorithm (e.g., SET enable_nestloop = off) masks the symptom but leaves the root cause. Fix the estimate — the algorithm choice follows.
Non-sargable predicates
A predicate is “sargable” (Search ARGument-ABLE) if the planner can use an index for it. Non-sargable predicates force Seq Scans and corrupt row estimates.
Common offenders:
WHERE LOWER(email) = 'alice@x.com'— function on indexed column → use expression indexCREATE INDEX ON users (LOWER(email))WHERE created_at::date = '2026-01-01'— type coercion → rewrite asWHERE created_at >= '2026-01-01' AND created_at < '2026-01-02'WHERE EXTRACT(year FROM created_at) = 2026— function call → same range rewriteWHERE id::text = '42'— implicit cast →WHERE id = 42(fix the application type)WHERE name LIKE '%foo'— leading wildcard → pg_trgm GIN index for fuzzy match
EXPLAIN reveals these immediately: Seq Scan + Filter where you expected Index Scan. The Filter line shows what was applied after the scan rather than before — meaning the index could not help.
Diagnose and fix a row-estimate blowup
1/3An EXPLAIN ANALYZE shows `Nested Loop (cost=0..50 rows=10) ... -> Index Scan ... (loops=10000)`. What is the most likely cause?
A query plan shows `Hash Join ... Hash Batches: 64`. What does this indicate and what is the fix?
Which predicate is NON-sargable and will force a sequential scan even if an index exists on `created_at`?
- 01Explain the row-estimate cascade: why does a bad estimate at one node break the entire plan above it?
- 02When is Hash Join the right choice, and what makes it spill to disk?
- 03What is a non-sargable predicate, why does it matter for performance, and how do you fix the most common cases?
Postgres picks among three join algorithms: Nested Loop (outer_rows × inner_cost, wins for small outers with an inner index), Hash Join (build hash table + probe, wins for medium-to-large equi-joins, spills to disk when hash table exceeds work_mem), and Merge Join (sort both sides, merge in parallel, wins when both sides arrive sorted). The algorithm choice is driven by row estimates at each node — a 1000× underestimate on the outer side of a Nested Loop turns the inner lookup into 1000× more work than planned. The wrong algorithm is always a symptom; the wrong row estimate is always the root cause. Fix estimates (ANALYZE, extended statistics) and the algorithm choice corrects itself. Non-sargable predicates (functions on indexed columns, implicit casts) prevent index use and corrupt estimates — rewrite them as range predicates or add expression indexes.
Practice
Do these to turn recognition into skill.
- Extended statistics: fixing correlated-column estimate failuressenior
- Plan cache, cost-constant tuning, and planner internalssenior
- Production failure modes and plan stabilitysenior
- Execution plans: diagnose and stabilise a slow querysenior
- Execution plans: multiple-choice reviewsenior
- Execution plans: free-recall reviewsenior
appears again in174
- 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
- Retry strategies: backoff, jitter, and thundering herdmiddle
- Observability, production failures, and global-scale designsenior
- Tasks, microtasks, and scheduler.yield()middle
- Timer accuracy, throttling, and idle workmiddle
- Node.js event loop: phases, nextTick, and loop lagsenior
- Rendering strategies: SSG, SSR, ISR, streaming, and hydrationjunior
- SSG, SSR, ISR, streaming, and RSC — how each worksmiddle
- Hydration cost: selective, progressive, islands, resumabilitymiddle
- Core Web Vitals: what LCP, INP, and CLS measurejunior
- LCP: four phases, one dominant costmiddle
- INP: input delay, processing, presentationmiddle
- 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
- Bits on the wirejunior
- Latency mathmiddle
- Bufferbloat and congestionsenior
- The physical frontiersenior
- Sequence numbers and connection statemiddle
- Flow control and congestion controlmiddle
- BBR, production observability, and beyond TCPsenior
- 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 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
- 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
- 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
- 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
- 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
- Branch prediction and branchless codemiddle
- Hardware prefetcher, TLB, and memory-level parallelismsenior
- 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