Interview: the new branch’s dashboard takes 38 seconds

A value loaded after the last ANALYZE is estimated as one row, so the planner nested-loops 180,000 times. Cardinality, pg_stats, and autovacuum.

More on Ticket interviews

Keep learning

Overview

stats from before the load ANALYZE after the load estimated rows actual rows Hash Join Nested Loop Now the planner sees SF, expects many rows, and picks a hash join. NY and LA were always in the stats. SF is missing from the stats, so the planner guesses 1 row. A loop that is cheap for 1 row is brutal for 180,000.

The new branch’s dashboard takes 38 seconds. The old ones take 40 ms.

The index is used, but the planner thinks SF has one sale. Nobody refreshed the stats after the load. EXPLAIN ANALYZE New branch dashboard: 38 s. Old branches: 40 ms. Stale stats: planner guesses 1 row, picks nested loop. Run ANALYZE after every bulk load.

SF branch dashboard timed out after last night’s import

Store ops NY and LA load in 40 ms. SF, imported at 2 am, takes 38 s. The import: COPY of 180k sales into an 80M-row table. The branch index already existed. rows loaded Restated: new value slow, known values fast. Same query, same index.

The plan believes a number the table no longer supports

COPY does not refresh planner stats. 180k rows is only 0.2% of the table. EXPLAIN ANALYZE Estimated 1, actual 180,000. The index runs once per row, in a loop meant to run once. Auto-analyze waits for ~10% of rows to change. This load was 0.2%. rows the planner expects rows actually there of table changed (auto-analyze needs ~10%)

Compare the estimate to the actual before you touch the index

Is the index missing? Read the plan, not a guess. No: the index is used, and NY is fast on it. An index can’t explain the gap. Where do the estimate and the actual disagree? EXPLAIN (ANALYZE) Outer scan: estimated 1, actual 180,000. Every step above multiplies that error. Why would the planner say 1? pg_stats for branch Stats know only NY and LA. An unseen value is estimated at 1 row. Why didn’t autovacuum notice? Scale factor vs rows loaded. It waits for ~8M changed rows. 180k never trips it, and the job’s ANALYZE is commented out.

Refresh the stats. Leave the planner switches alone.

COPY 180k rows ANALYZE sale refresh planner stats Estimate ≈ 1e5 hash join chosen Alert if est vs actual > 10× Make ANALYZE part of the load, then watch for drift. Fixes the wrong number that chose the nested loop. Bans a planner switch that would hurt every other query. Adds an alert for estimate-vs-actual drift.

No AI from here

A sequential scan of this table is cost 0.00..1751 for 100,000 rows. Where does 1751 come from? Cost is an abstract unit for comparing plans, not milliseconds. Wrong stats make the winning cost wrong too. abstract units pages + tuples × 0.01 compare, don’t time 751 pages × 1.0 100,000 rows × 0.01 total cost What do null_frac, n_distinct and correlation tell the planner? How many NULLs, how many distinct values, and how sorted the column is. correlation near 1: index ranges read pages in order. Near 0: random reads. NULL fraction −1 means unique correlation → random vs sequential Share of rows that are NULL Column order vs disk order Walk the three steps you use when a plan looks suspicious. Run EXPLAIN ANALYZE, find the first big estimate miss, then ask why. EXPLAIN (ANALYZE) shows estimated and actual rows per node. The bug is usually at the first diverging node, not the top. Typical causes: stale stats, unseen value, expression, correlated filters. estimate vs actual first lying node a reason, not a hint EXPLAIN ANALYZE Find first est ≠ actual Ask why stats? value? expression? When the columns are related, so the filters are not independent. If all shoe sales are in NY, multiplying badly underestimates. CREATE STATISTICS on the pair, then ANALYZE, teaches the joint pattern. independence assumption CREATE STATISTICS + ANALYZE estimate ≠ access path No: it changes every query, and ANALYZE is the real fix. Good one-row nested loops would stop being chosen too. The switch tends to stay in config after stats are fresh. If needed short-term, use a session setting with a clear undo. ANALYZE is the fix temporary needs an undo

The import window is closing and SF is still down

What do you run first? ANALYZE sale, then put it back in the import The estimate and join fix themselves, now and for future branches. ANALYZE does not block reads. SF latency Other queries Will recur This dashboard may improve. Every other lookup changes plan, and the estimate is still wrong. Wait for autovacuum The next auto-analyze is millions of rows away. SF stays slow. Add a second index on (branch, sold_at)

Have one ready

Tell me about a query that got worse right after a load. ANALYZE, wired into the load. Alert on estimate drift.

Did you show these?

Read the plan before indexing Est 1 vs actual 180,000 Unseen value → estimate of 1 Load size vs auto-analyze threshold Derived seq-scan cost Correlation and independence ANALYZE, not a planner switch

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.