Databases
Index-only scans, the Visibility Map, and INCLUDE
EXPLAIN ANALYZE shows “Index Only Scan” on one query and “Index Scan” on another — identical index, different tables. The difference is not the index. It is the Visibility Map. One table was VACUUMed yesterday; the other has 12% dead tuples. Understanding why this matters is the difference between a 1 ms query and a 10 ms query on the same data.
What an index scan vs index-only scan costs
A regular index scan for a query like SELECT id, status FROM orders WHERE user_id = 42:
- Walk the B-tree to the matching leaf entries — O(log n), a few page reads.
- For each matching TID, fetch the heap row to get
idandstatus— one heap page read per row if the rows are scattered.
Step 2 is the bottleneck at scale. For 10,000 matching rows across 10,000 scattered heap pages, that is 10,000 random I/O operations.
An index-only scan eliminates step 2 entirely. If the index contains all columns the query needs, Postgres reads only the index leaf pages. For dense ranges (1,000 rows on 10 index leaf pages), the I/O drops from thousands to tens.
| Scan type | I/O pattern | When used |
|---|---|---|
| Index scan | Index walk + heap fetch per row | Columns not all in index |
| Bitmap heap scan | Index walk + sorted heap read (batched) | Many rows; reduces random I/O |
| Index only scan | Index leaves only — no heap | All needed columns in index AND VM bits set |
| Sequential scan | Full heap read | No usable index, or low selectivity |
The Visibility Map: why index-only scans need it
Postgres uses MVCC — each row may have multiple versions (old and new tuples from concurrent updates). To know whether a row is visible to the current transaction, Postgres normally reads the row’s system columns (xmin, xmax, transaction status bits). These columns are in the heap, not the index.
An index-only scan does not read the heap. So how does it know if a row is visible?
The Visibility Map (VM) is a per-table bitmap with one bit per heap page. The bit is set to 1 (“all visible”) when every tuple on that page is visible to every current and future transaction — meaning no concurrent updates or deletes are pending. VACUUM sets these bits after cleaning dead tuples. Any write that touches the page clears the bit.
When Postgres executes an index-only scan and encounters a matching TID:
- If the VM bit for that page is set: the row is known-visible without reading the heap. No heap fetch.
- If the VM bit is clear: Postgres must fetch the heap page to check visibility. This heap fetch is counted in
EXPLAIN ANALYZEas “Heap Fetches: N”.
A high “Heap Fetches” count in an index-only scan means the VM is not current — the “index-only” scan is actually doing heap fetches for most rows.
VACUUM keeps the VM current
VACUUM reclaims dead tuples and sets VM bits. Autovacuum runs it automatically (triggered when dead tuples exceed autovacuum_vacuum_scale_factor × table size, default 20%). For tables that depend on index-only scans:
- 20% dead tuples is far too tolerant. Set
autovacuum_vacuum_scale_factor = 0.05andautovacuum_analyze_scale_factor = 0.02. - Long-running transactions prevent VACUUM from reclaiming tuples — a single transaction open for hours can block VM updates for that entire duration.
- Monitor
pg_stat_user_tables.n_dead_tupas the leading indicator of VM freshness.
-- Tune autovacuum per-table on hot OLTP tables
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.05,
autovacuum_analyze_scale_factor = 0.02
);The INCLUDE clause: covering indexes
Postgres 11+ supports CREATE INDEX ... INCLUDE (cols) — the INCLUDE columns are stored in the index leaf pages but are not part of the sort key. The result: the index is “covering” for queries that need those extra columns in the SELECT projection.
Without INCLUDE, to make a query covering you would have to add the projection columns to the key — which changes the sort order and may harm other queries that rely on that index’s sort for ORDER BY.
-- Key columns: workspace_id, created_at DESC (sort key for ORDER BY)
-- INCLUDE: id, total_cents (payload for the projection — not in sort key)
CREATE INDEX CONCURRENTLY idx_orders_ws_recent_covering
ON orders (workspace_id, created_at DESC)
INCLUDE (id, total_cents);Query SELECT id, total_cents FROM orders WHERE workspace_id = $1 ORDER BY created_at DESC LIMIT 50 now hits only the index. No heap fetch. 50 leaf entries read in order.
The trade: INCLUDE columns increase index size (they are stored in every leaf entry). Large INCLUDE payloads can make the index approach table size. Keep INCLUDE columns to the projection columns actually needed by the hot query, not everything.
When index-only scans work — and when they do not
Works well: insert-only or append-mostly tables (events, logs, audit trails). VM bits stay set because there are no updates clearing them. VACUUM rarely needed for visibility purposes.
Degrades: heavily-updated tables. Every update clears the VM bit for the updated page. Until VACUUM runs and sets the bit again, every index-only scan for that page must do a heap fetch. On a table with 50,000 updates/second, VM bits are cleared faster than autovacuum can set them — the “index-only scan” becomes an “index scan with extra steps.”
Diagnosis: EXPLAIN (ANALYZE, BUFFERS) on the query. Look for:
Index Only ScanwithHeap Fetches: 0— ideal.Index Only ScanwithHeap Fetches: N(high N) — VM not current, tune autovacuum.Index Scaninstead ofIndex Only Scan— columns not all in the index; add INCLUDE.
Concurrency and index build timing
CREATE INDEX CONCURRENTLY on a 100M-row table takes 10-30 minutes. During the build:
- Postgres scans the table twice.
- Between phases, it waits for all current transactions to finish (to ensure the index is consistent with all recent writes).
- The index is replicated to standbys via WAL.
Implications:
- Long-running analytic queries on the same table can stall the build for hours (the build waits for them).
- Multiple concurrent builds on the same database compete for I/O — schedule large index builds in low-traffic windows.
- After the build, check
pg_indexes.indisvalid— a failed build leaves an INVALID index that is invisible to the planner but still uses storage.
-- Check for invalid indexes after a CONCURRENTLY build
SELECT indexrelid::regclass, indisvalid
FROM pg_index
WHERE NOT indisvalid;Recovery from INVALID: DROP INDEX CONCURRENTLY idx_name; then retry.
- Index-only scan benefit vs index scan
- 10-100x on hot reads
- Heap Fetches: 0 in EXPLAIN ANALYZE
- ideal — VM is current
- autovacuum_vacuum_scale_factor default
- 20% dead tuples
- Recommended scale_factor for IOS-dependent tables
- 5%
- INCLUDE supported since
- Postgres 11 (2018)
- Long-running transaction impact on VM
- blocks VM bit-setting for pages it touched
- CREATE INDEX CONCURRENTLY on 100M rows
- ~10-30 min
- INVALID index after failed CONCURRENTLY build
- invisible to planner; still uses storage
- Monitor: n_dead_tup in pg_stat_user_tables
- leading indicator of VM freshness
An analytics query on an orders table shows Index Only Scan but Heap Fetches: 12,000. Diagnose and fix.
A query is showing 'Index Only Scan' but Heap Fetches: 8,000 in EXPLAIN ANALYZE. What is the most likely cause?
What is the purpose of the INCLUDE clause in CREATE INDEX?
lesson.inset.warning
The EXPLAIN plan label “Index Only Scan” is misleading when Heap Fetches is high. The plan node name reflects the intended scan type — the actual behaviour depends on VM state at runtime. Always check Heap Fetches in EXPLAIN ANALYZE output, not just the scan type label. A query that “works perfectly in staging” can degrade in production if the production table has a worse autovacuum schedule.
- 01Articulate why index-only scans need the Visibility Map and what operational discipline keeps them firing correctly.
- 02When should you use INCLUDE vs adding columns to the sort key in a composite index?
- 03What happens when CREATE INDEX CONCURRENTLY fails, and how do you recover?
An index-only scan reads column values directly from the index leaves, skipping the heap entirely — cutting I/O by 10-100x for queries that access only indexed columns. The Visibility Map enables this: a per-table bitmap where a set bit means all tuples on that page are visible without a heap check. VACUUM sets VM bits; writes clear them. Stale VM causes index-only scans to degrade: “Index Only Scan” with high Heap Fetches is a symptom of insufficient vacuuming.
Use the INCLUDE clause to add projection columns to index leaves without making them part of the sort key. This creates a “covering index” that answers queries entirely from the index when combined with current VM bits.
Operational rules: tune autovacuum_vacuum_scale_factor to 0.05 on tables that depend on index-only scans; monitor n_dead_tup in pg_stat_user_tables; kill long-running transactions that block VACUUM. After CREATE INDEX CONCURRENTLY, verify indisvalid = true in pg_index before considering the migration complete.
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