Databases
What an index is and how it speeds up queries
A team’s “filter by status” dashboard takes 50ms on 100k rows in staging. In production with 50M rows it takes 8 seconds. The schema is correct. The query is correct. One DDL line — CREATE INDEX CONCURRENTLY ON orders(status) — brings it back to 20ms. That line is the entirety of this lesson.
What an index is
An index is a separate data structure — usually a B-tree — that stores a sorted copy of one or more column values plus pointers to the actual rows. When a query filters by an indexed column, Postgres navigates the tree in O(log n) steps instead of scanning every row.
The book-index metaphor holds precisely: a book’s back-matter index is a sorted list of terms with page numbers. To find “MVCC”, you open the index (one O(log n) lookup), read the page number, and jump there. Without the index you scan every page. A database index is identical — a copy of column values, organized for fast lookup by one specific question.
| Without index | With index |
|---|---|
| Sequential scan — every row touched | B-tree walk — O(log n) then fetch matching rows |
| 1M rows: ~10ms; 100M rows: ~2–10s | 1M or 100M rows: ~1–5ms |
| No extra storage, no write overhead | ~10–30% table size per index; every write maintains the index |
The cost: indexes tax every write
Every index is a separate on-disk structure that must stay synchronized with the table. Every INSERT, UPDATE, or DELETE that touches an indexed column must also update the index — costing CPU and I/O. A table with ten unused indexes on a write-heavy workload spends 10× more on writes than necessary.
Typical per-index write overhead: 5–50 µs per write. At 10,000 inserts/second with ten indexes, that is an extra 0.5–5ms of overhead per second of clock time — measurable, and often the bottleneck when teams over-index.
Index storage on disk: roughly bytes_per_key × row_count × 1.3. For a BIGINT key (8 bytes), a 100M-row table produces a ~1 GB index. Each index beyond the first multiplies this.
A concrete scenario
Consider: SELECT * FROM orders WHERE user_id = 42 on a table with 10M rows. Without an index: sequential scan, ~2 seconds. After CREATE INDEX ON orders(user_id): index lookup plus heap fetch, ~3 milliseconds. Same query, 600× speedup, one DDL line.
Postgres ships six index types. B-tree is the default and handles 95% of production use — equality, range, ORDER BY, LIKE 'abc%'. The other five (GIN, GiST, BRIN, Hash, Bloom) serve specific data shapes and are covered in lesson 04.
Production rule: always use CONCURRENTLY
CREATE INDEX takes an ACCESS EXCLUSIVE lock — all reads and writes are blocked for the duration. On a table with active traffic, even a 5-minute lock is an incident.
CREATE INDEX CONCURRENTLY uses a multi-phase build that does not take the exclusive lock. It scans the table twice and waits for in-flight transactions between phases. It is 2–3× slower and cannot be wrapped in a transaction, but it produces no visible impact on application traffic.
If a CONCURRENTLY build fails (e.g., a unique-index encounters a duplicate, or the process is killed), the index is left in an INVALID state (indisvalid = false in pg_indexes). The planner treats it as non-existent. Fix: DROP INDEX CONCURRENTLY and retry.
Why this works
Why does Postgres not just index every column by default? Because every index on a write-heavy table is a write tax. A table with 20 indexes and 50k inserts/second can spend more time maintaining indexes than writing rows. The discipline is intentional: measure the hot queries, add indexes for those, audit and drop the unused. Over-indexing and under-indexing are equally damaging production patterns.
Order the steps to add an index correctly in production:
- 1 Run EXPLAIN ANALYZE on the slow query to confirm a seq scan is the bottleneck
- 2 Identify the columns being filtered or sorted
- 3 Pick the index type (B-tree default; GIN for JSONB; GiST for geo)
- 4 Use CREATE INDEX CONCURRENTLY to avoid locking the table
- 5 Wait for the build to complete (can take minutes to hours on large tables)
- 6 Re-run EXPLAIN ANALYZE to confirm the planner now uses the index
- 7 Monitor write latency after deploy — every index adds a small write cost
An index is created on the column users(email). Which query benefits from it?
What is the cost of adding an index?
Fill in the blank: a database index is to a SQL query what a book _______ is to finding a topic — a copy of part of the content, organised for fast lookup.
- 01In two sentences, why are indexes not free and why do production teams not just index every column?
- 02What happens if CREATE INDEX CONCURRENTLY fails mid-way, and how do you recover?
- 03A query does a sequential scan on a 50M-row table. You add an index. What does EXPLAIN ANALYZE show before and after?
An index is a separate sorted data structure — typically a B-tree — that stores copies of one or more column values with pointers to the matching heap rows. It turns full-table sequential scans (O(n)) into tree walks (O(log n)), reducing a 2-second query on 10M rows to 3ms. The tradeoff: every index costs 10–30% of table size in storage and 5–50 µs per write per index. Always add indexes with CREATE INDEX CONCURRENTLY to avoid table-level locks in production. If the build fails, check pg_indexes for indisvalid = false and retry after dropping the invalid entry.
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