Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 5

Googlebot Arrived, the Database Fell Over: Finding a Missing Index with pg_stat_statements and EXPLAIN

Postgres CPU is at 100%, every endpoint waits for seconds, and the API itself is idle. We trace, step by step, how an innocent purchase counter on product pages scans 1.2 million rows, how Googlebot turns that into an outage, and how to add the index to a live table without locking it.

25 min read60 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 5 · Difficulty ★☆☆ · Reading ~20 min · Lab ~30–60 min

On the morning of January 6, 2026, merge requests on GitLab.com slowed down, pipelines were delayed, and 600–700 thousand jobs piled up in the Sidekiq queue. According to GitLab’s incident review, a recently run migration had removed a needed index from the ssh_signatures table. Queries filtering on that column slowed down, CPU on the primary database spiked, and the PgBouncer connection pool hit 100%. The outage lasted about two and a half hours; the fix was to rebuild the index by hand (GitLab, INC-6458 incident review).

This part’s incident is that one’s more common sibling: the index wasn’t removed, it was never added. A new feature brought a new access path, nobody noticed on the small table in the development environment, and in production the query took “only” 16 ms. Then the Google Shopping feed went live, Googlebot started hitting product pages 24 times a second, and those 16 ms ate the database’s entire CPU.

In Part 4 we saw how an API with an idle CPU waited in an invisible queue. This time the queue is again inside the API, but the resource is somewhere else: in the database.

What you’ll learn

  • Finding the bottleneck when “everything is slow”: is the API working, or waiting?
  • Answering “what is the database spending its time on?” at a glance with pg_stat_statements
  • Reading EXPLAIN (ANALYZE, BUFFERS): Parallel Seq Scan, Rows Removed by Filter, buffer counts
  • Why a 16 ms query can stop the whole system when it runs often enough (capacity math)
  • Covering indexes (INCLUDE) and index-only scans
  • CREATE INDEX CONCURRENTLY: adding an index to a live table without blocking writes, and shipping it as a migration
  • Separating the trigger (a crawler) from the root cause (a missing index); why blocking legitimate traffic is not a fix

Prerequisites

You can read this article without the lab. These help:

TopicWhySource
What an index is and when it helpsThe foundation of the articlePostgreSQL docs, Indexes: Introduction
Reading EXPLAIN outputTo interpret the planPostgreSQL docs, Using EXPLAIN
pg_stat_statementsTotal time per queryPostgreSQL docs, pg_stat_statements
Connection poolTo read the pool panelPart 1, Step 2 (why “pool exhausted” can be a consequence)

1. Concept: cheap query, expensive total

The cost of a query is the product of two numbers: its duration per execution × how many times per second it runs. We always look at the first (“the query takes 16 ms, that’s fine”), but what fills the database’s CPU is the product.

That product is called database time per second. A query that runs 35 times a second and burns ~40 ms of CPU each time (16 ms of wall-clock time, but three processes scan in parallel) needs more than 1.3 seconds of CPU per second. A 1-vCPU server can give at most 1 second of CPU per second. The difference turns into a queue, the queue makes every query longer still, and the system slides instead of settling into an equilibrium.

An index changes the first factor of that equation. Without an index, PostgreSQL reads the whole table to find one product’s ~50 order items and throws away 1,199,950 of 1.2 million rows. With an index, it descends a few levels of a B-tree and goes straight to those ~50 rows.

See it yourself: a 1-CPU Postgres, 1.2 million rows

Anyone with Docker can try this in two minutes. A simplified copy of the lab’s table:

docker run -d --rm --name idxdemo --cpus 1 -e POSTGRES_PASSWORD=demo postgres:17-alpine
docker exec -it idxdemo psql -U postgres
CREATE TABLE order_items (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id   bigint  NOT NULL,
  product_id integer NOT NULL,
  quantity   integer NOT NULL
);
-- 1.2 million order items, 20,000 products
INSERT INTO order_items (order_id, product_id, quantity)
SELECT g / 3, 1 + (random() * 19999)::int, 1 + (random() * 3)::int
  FROM generate_series(1, 1200000) AS g;
CREATE INDEX order_items_order_idx ON order_items (order_id);   -- only order_id is indexed
VACUUM ANALYZE order_items;

EXPLAIN (ANALYZE, BUFFERS)
SELECT coalesce(sum(quantity), 0) FROM order_items WHERE product_id = 4242;

A single query’s duration looks deceptively innocent:

Parallel Seq Scan on order_items ... (actual ... rows=20 loops=3)
  Filter: (product_id = 4242)
  Rows Removed by Filter: 399980
  Buffers: shared hit=7644
Execution Time: 15.991 ms

Now let’s run the same query with 8 concurrent clients, for random products, for 20 seconds. pgbench ships inside the Postgres image:

# bench.sql
\set pid random(1, 20000)
SELECT coalesce(sum(quantity), 0) FROM order_items WHERE product_id = :pid;
docker cp bench.sql idxdemo:/bench.sql
docker exec idxdemo pgbench -U postgres -n -f /bench.sql -c 8 -j 2 -T 20 postgres

Then add the index and repeat the measurement:

CREATE INDEX CONCURRENTLY order_items_product_id_idx ON order_items (product_id) INCLUDE (quantity);
VACUUM order_items;

On my machine:

Single query (EXPLAIN ANALYZE)8 clients, 1 CPU: queries per secondAverage latency
No index16 ms35228 ms
(product_id) INCLUDE (quantity)0.057 ms22,5070.36 ms

Notice three things:

  1. The capacity ceiling is 35 queries per second. This 1-CPU database can’t handle more than 35 of these queries per second. Product page traffic in the lab is ~35/s: right at the limit, and the database has other work to do too.
  2. 16 ms on its own, 228 ms under load. The query didn’t get slower; it waited its turn for the CPU. Latency under load is queueing time, not the query’s own duration.
  3. 640 times more capacity with the index. On the same hardware the index raised capacity from 35 to 22,507. The index itself was built on the 1.2-million-row table in half a second (493 ms).

2. The incident: everything’s been slow since Tuesday afternoon

🔥 [FIRING] DatabaseBusy: PostgreSQL has spent more than 2 s per second executing queries for 2 minutes

It’s mid-September and you’re on call for ShopFlow. Since Tuesday afternoon the database has been at full CPU and every endpoint is slow: product pages, checkout, order history. The DBA writes:

“Postgres is at 100% CPU on the shop database. Nothing changed on our side. Can you check what the API is sending us?”

What you know:

  • Customer traffic is normal (~38 req/s).
  • On Tuesday the SEO team opened the product feed to Google Shopping. Googlebot has been crawling product pages ever since, and the SEO team is delighted: please don’t block it.
  • The database runs on a 1-vCPU instance. Until now that was more than enough.
  • Recent deploys:
VersionWhenChange
2.20.0Mondayproduct pages show how many times a product was bought (“Bought 83 times”)
2.19.2last weekschema changes as SQL migrations, applied at startup
2.19.1last weektax quotes over pooled connections (the fix from Part 4)

If you’ve set up the lab, start the incident:

git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 005

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000) and ./lab psql, and investigate on your own for 30 minutes. The results of the steps below are in collapsed boxes. For the lab’s own hints: ./lab hint 005.


3. Investigation, step by step

Step 1: Who’s working, who’s waiting?

When someone says “everything is slow”, the first question is: is the API itself busy, or is it waiting for something? On the dashboard, put latency at the edge next to the API’s CPU.

What do we see?
  • At the edge, p50 is ~6.6 s and p95 is stuck at the chart’s ceiling of ~10 s. Normally both are a few milliseconds.
  • Latency isn’t flat, it’s growing: 2 s, 5 s, 10 s. A system settling into equilibrium doesn’t behave like this; it’s the signature of a queue where more work comes in than goes out.
  • The API’s CPU, meanwhile, is ~0.12 cores. If the owner of multi-second requests at 61 req/s (~38 req/s of customer traffic plus ~24 req/s of Googlebot crawling) is burning this little CPU, the API isn’t working, it’s waiting.

Grafana: on the left, latency at the edge; p50, p95 and p99 climb in steps from a few milliseconds to 6–10 seconds within minutes. On the right, the API's CPU flat between 0.1 and 0.2 cores

While latency climbs step by step to 10 seconds, the API’s CPU doesn’t budge from around 0.1 cores. The work is being done somewhere else.

Step 2: What is the API waiting for?

In the dashboard’s Inside the API row, look at latency by route and the query times the API sees. Then, in Jaeger, open a trace of one of the simplest endpoints, for example placing an order (POST /api/orders).

What do we see?
  • Every route is slow: /api/orders, /api/products, /api/customers/:id/orders, even the product list. This isn’t one endpoint’s problem; it’s a shared resource’s problem.
  • In the query times the API measures, every query is at the level of seconds too. This panel includes the time a query waits for a connection from the pool.
  • The order trace in Jaeger tells the real story: 11.4 s inside the API. Almost all of it is five separate pg-pool.connect spans, each 2.0–2.5 s. The queries themselves take 1.5–11 ms.

Grafana: on the left, p95 by route measured by the API, every route rising from 2 s to 10 s. On the right, query times seen by the API, every query climbing together from 1 s to 5 s

Not just product pages: every route and every query slows down at the same time. The signature of a shared bottleneck.

Jaeger: a POST /api/orders trace, API span 11.4 s; child spans include pg-pool.connect lasting 2.3 s, 2.0 s, 2.4 s, 2.1 s, 2.5 s, with 1.5–11 ms queries between them

Placing an order takes 11.4 seconds, but the queries take a few milliseconds. The time goes into waiting for a connection from the pool before every query.

Remember the lesson from Part 1 here: “pool exhausted” is a consequence. In Part 1 the pool was filled by a blocked event loop. This time the event loop is relaxed (API CPU is 0.12 cores); the connections really are busy. The question: what are all 10 connections doing in the database?

Step 3: What is the database spending its time on?

The alert already tells us what to look at: database time per second. That number comes from pg_stat_statements: for every normalized query PostgreSQL keeps the call count and total execution time (constants become $1, $2; the same query with different product ids is aggregated into one row). Look at Database time per second, by query in the dashboard’s Database row and at the Top queries by total time table at the bottom. You can also ask directly with ./lab psql:

SELECT left(query, 70) AS query, calls,
       round(total_exec_time::numeric / 1000) AS total_s,
       round(mean_exec_time::numeric, 1)       AS mean_ms,
       round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct
  FROM pg_stat_statements
 ORDER BY total_exec_time DESC
 LIMIT 5;
What does the database say?
  • Total database time is ~9.4 s/s. On a 1-vCPU server, on average ~9 queries are running (or waiting for the CPU) at any moment. The database sessions panel says the same: 15–17 sessions active.

  • 97.4% of it is a single query:

    SELECT coalesce(sum(quantity), $2)::int AS purchases FROM order_items WHERE product_id = $1

    Average 291 ms, 16,693 calls in a few minutes. All the other queries together come to 0.2–0.3 s/s.

  • This is the purchase counter introduced in 2.20.0. Every product page calls it once.

Grafana Explore: database time per second. The green "all queries" and yellow "purchase-count query" lines rise together from 0 to ~9.4 s/s and stay there; the blue "all other queries" line stays below 0.3

The yellow line (purchase counter) sits almost on top of the green total. The blue line, the sum of all the application’s other queries, is at the floor.

Grafana: pg_stat_statements table; the first row is the purchase-counter query, 16,693 calls, mean 291 ms, total 4,864,106 ms; the second row is the sales report, 130 calls, total 122,611 ms

The first row is 4,864 seconds, the second 123 seconds. A fortyfold difference. The report query is slow on its own (943 ms) but rare; the counter looks cheap on its own but runs on every product page.

Lesson: “The slowest query” and “the query keeping the database busiest” are different things. Sorting by mean time would have found the sales report (943 ms). Sort by total time.

Step 4: Why is this query so expensive?

There are two more clues. Look at the Rows read by sequential scans, by table panel on the dashboard. Then run the query under EXPLAIN (ANALYZE, BUFFERS) with a real product id:

EXPLAIN (ANALYZE, BUFFERS)
SELECT coalesce(sum(quantity), 0)::int AS purchases FROM order_items WHERE product_id = 4242;

\d order_items
What does the plan say?
  • Rows read by sequential scan: ~39 million per second from the order_items table. The table has 1.2 million rows, so it’s being read end to end ~32 times a second.
  • Plan: Parallel Seq Scan on order_items. Three processes (leader + 2 workers) split the table between them; each throws away 403,555 rows via the filter and keeps 16 on average. The result is 47 rows; ~1.2 million were read.
  • Buffers: shared hit=7714: 7,714 pages of 8 KB, i.e. the whole table (~60 MB). All in memory (hit, not read); that’s why the problem is CPU, not disk.
  • Under load, Execution Time: 193 ms. As in the demo, the query itself is ~16 ms; the rest is waiting for the CPU.
  • \d order_items: the indexes are order_items_pkey (id) and order_items_order_idx (order_id). There is no index on product_id.

Grafana: on the left, rows read by sequential scans, rising for order_items from ~0 to ~39 million per second and staying there. On the right, requests waiting in the connection pool rising linearly from 0 to ~570

Left: a single table being read at 39 million rows per second. Right: the number waiting in the pool keeps growing without pause. More work is coming in than the database can finish.

Terminal: EXPLAIN (ANALYZE, BUFFERS) output, first a Parallel Seq Scan, Rows Removed by Filter 403555, shared hit 7714, Execution Time 193 ms; then a Bitmap Index Scan, shared hit 50, Execution Time 0.205 ms

Top, today’s plan: 7,714 pages for 47 rows, 193 ms. Bottom, the plan after the fix below: 50 pages, 0.2 ms.

Why didn’t anyone notice in development? There order_items has a few hundred rows; a sequential scan is the best plan there. On Monday in production the query was also taking ~16 ms, and nobody looked at its plan.

Step 5: Cross-check with a product page trace

Confirm the diagnosis on a single request: open a GET /api/products/:id trace in Jaeger.

The product page trace

The trace is 6.0 s. First a 3.2 s wait for the pool, the query that fetches the product (0.8 ms), then another 2.6 s pool wait for two parallel queries. At the end, two queries: related products 8.4 ms, purchase counter 188 ms. The counter is where every request that does get a connection holds it the longest; the longer it holds the connection, the longer the queue behind it grows.

Jaeger: a GET /api/products/:id trace, 6.0 s total; pg-pool.connect spans of 3.2 s and 2.6 s, and at the end two queries of 8.4 ms and 188 ms

~5.8 of the product page’s 6 seconds are spent in the pool queue. And what feeds that queue is the 188 ms purchase-counter query at the bottom.

Step 6: Why this week?

The counter shipped on Monday; the problem started Tuesday afternoon. You need to explain that one-day gap.

The trigger

In the dashboard’s Requests per second by route panel, /api/products/:id is getting ~35 requests per second. Product pages from customers browsing the catalog account for ~10/s; the remaining ~24/s is Googlebot (User-Agent: ... Googlebot/2.1), crawling product links since Tuesday. The product page rate tripled and crossed the ceiling from the demo (~35/s for this query).

So why doesn’t the 60-second product page cache help? The cache is keyed by product id, and both customers and the crawler spread across 20,000 products. The same product being requested twice within 60 seconds is rare; nearly every request misses the cache. Crawlers, by definition, defeat caches tuned for popular products.

  • Root cause: a new access path (reaching order_items by product_id) shipped without the index it needs.
  • Trigger: Googlebot crawling product pages tripled how often that path runs.
The lab’s diagnosis questions and answers (./lab submit 005)
QuestionAnswer
What is the database spending its time on?Counting purchases for product pages
Why is that query so expensive?It reads the whole order_items table: nothing indexes product_id
What turned a slow query into an outage this week?Googlebot crawling product pages from the new Shopping feed

4. Mitigation

  • Create the index by hand. In ./lab psql:

    CREATE INDEX CONCURRENTLY order_items_product_id_idx ON order_items (product_id);

    It takes seconds and the database recovers immediately. In production this is a legitimate first move, on one condition: the same index must go into the code as a migration right afterwards. Otherwise it won’t exist in staging, in a new environment, or after restoring from a backup. (In the lab, verify resets the database to its original state before each measurement; an index added by hand doesn’t count.)

  • Or hide the counter behind a feature flag until the fix ships.

  • Don’t: block or throttle Googlebot, or grow the pool or max_connections. The reasons are in section 7.

5. The fix: make the index part of the code

In this codebase schema changes ship as SQL files under app/src/migrations; at startup the API runs the ones that haven’t been applied yet, in order (platform/migrations.ts). A new migration:

-- app/src/migrations/0003_order_items_product_index.sql
-- no-transaction
CREATE INDEX CONCURRENTLY IF NOT EXISTS order_items_product_id_idx
  ON order_items (product_id) INCLUDE (quantity);

Every part has a reason:

  • (product_id): instead of “read 1.2 million rows”, “go to this product’s ~50 rows”. This is what turns the plan from Parallel Seq Scan into an Index Scan.
  • INCLUDE (quantity): puts quantity inside the index as a “payload” column that isn’t part of the search key. When everything the query needs is in the index, PostgreSQL can do an index-only scan: answer without touching the table at all. On one condition: the table’s pages must be marked “all visible” in the visibility map, i.e. the table must have been vacuumed. In the demo, after VACUUM, the plan is Index Only Scan ... Heap Fetches: 0, 4 pages, 0.057 ms. In the lab, right after the deploy, before vacuum has run, the plan is Bitmap Index Scan + 47 table pages: still 0.2 ms. (Index-Only Scans and Covering Indexes)
  • CONCURRENTLY: a plain CREATE INDEX locks the table against writes; INSERT, UPDATE, DELETE wait until the build finishes. So while the index is being built, checkout stops. CONCURRENTLY scans the table twice and doesn’t block writes; the price is a longer build and more total work.
  • -- no-transaction: CREATE INDEX CONCURRENTLY can’t run inside a transaction block. The migration runner normally wraps each file in a transaction; this header on the first line tells it to run the file outside one. If you try anyway: ERROR: CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
  • IF NOT EXISTS: if someone created the index by hand during the incident, the migration still passes cleanly.

A warning: if CONCURRENTLY fails halfway (deadlock, cancellation) it leaves behind an index marked INVALID. Queries don’t use it, but every write keeps updating it. If you see INVALID in \d order_items, drop the index and try again. (CREATE INDEX: Building Indexes Concurrently)

The cost: a 26 MB index next to the 60 MB table, and a little more write work on every new order item. In the lab the migration was applied in 395 ms while order traffic kept flowing.

6. Verification

./lab deploy
./lab verify 005

verify resets the database to its original state, deploys your code (the migration is applied at this point) and runs today’s traffic (customers + Googlebot) for 60 seconds:

MeasurementTargetBeforeAfter
Catalog p95< 250 ms8.52 s11 ms
Checkout p95< 400 ms19.69 s59 ms
Error rate< 0.5%2.53%0%
Database time per second< 19.150.05
Waiting in pool (max)5420
Event loop utilization35%21%

On live traffic, a few minutes after the deploy, from Prometheus and docker stats:

BeforeAfter
Edge p50 / p956.6 s / ~10 s (ceiling)3.5 ms / 40 ms
Database time per second9.4 s/s0.04 s/s
order_items sequential scan~39 million rows/s~0.2 million rows/s
PostgreSQL container CPU100%7%
API CPU0.12 cores0.17 cores

The API’s CPU went up a little: it’s processing requests now instead of waiting. The small sequential scan left after the fix is the legitimate full-table read of the finance report, which runs every four seconds.

The charts say the same thing. The dashed orange line is the moment of the deploy:

Before and after the fix: latency at the edge drops from 6–10 s to near zero at the deploy; database sessions go from 15–17 active to ~12 idle

With the deploy, latency drops from seconds to milliseconds. On the right, sessions: green “active” gives way to yellow “idle”. The connections are still open, but now they’re waiting idle.

Before and after the fix: database time per second drops from ~9.4 s/s to near zero

The purchase counter (yellow) drops to near zero along with the total within a minute of the deploy: the same query, at the same frequency, but now taking 0.2 ms.

Before and after the fix: the order_items sequential scan drops from ~39 million rows per second to almost zero, and requests waiting in the pool from ~600 to zero

Look at the pool chart: the waiting count went from ~600 to zero, yet we never touched the pool size. Connections are now held for milliseconds per query.


7. Fixes that look right but aren’t

AttemptWhy it falls short
Blocking Googlebot with robots.txt or rate-limiting itIt’s legitimate traffic the business wants. It hides the problem until the next traffic spike (a campaign, a sale day). And Google already crawls less on sites that slow down or return 5xx/429 (Crawl budget management); that’s where this incident’s SEO cost comes from.
Growing the pool from 10 to 20, raising max_connectionsThe bottleneck is CPU, not the number of connections. More connections means more concurrent full-table scans on the same single CPU: every query takes even longer.
Scaling up the database (2 → 8 vCPU)Carries today’s scan rate, for an extra bill every month. The demo measurement: the index raised capacity 640-fold on the same CPU. No instance upgrade does that.
Extending the product page cache TTLThe crawler spreads across 20,000 products; the cache still scans the table for every new product. With a cold cache (deploy, restart) the same load comes back. A complement, not a substitute.
Adding the index with a plain CREATE INDEXWrites to order_items are locked for the duration of the build: you can’t place orders. Half a second on this table; minutes on a table a hundred times larger.
Adding the index only by hand in psqlThat rescues production, but it never enters the codebase. The problem comes back with the next environment, restore or rebuild.

8. In production: alternatives and prevention

Alternative designs:

ApproachAssessment
A purchase_count column on products, incremented on every orderConstant-cost reads. The price: a write to a hot row on every order, and having to keep the count right through refunds and bulk imports.
Caching the counter in memory or Redis for a few minutesRemoves repeated work, but a cold cache or a broad crawl still sends full scans to the database. A good complement to the index.
A periodically refreshed materialized viewGood for analytics; clunky for a number shown on every product page.

Alert on the cause, not the symptom. A latency alert says “something is slow”; database time says “the database is full”, and usually fires earlier:

- alert: DatabaseBusy
  expr: sum(rate(pg_stat_statements_seconds_total{datname="shop"}[2m])) > 2
  for: 2m
  labels:
    severity: page
  annotations:
    summary: "PostgreSQL is executing {{ $value | humanize }} s of queries per second"

- alert: LargeTableSeqScans
  expr: sum by (relname) (rate(pg_stat_user_tables_seq_tup_read{datname="shop"}[5m])) > 5e6
  for: 10m
  labels:
    severity: ticket

The second alert is driven by the seq_scan / seq_tup_read counters in the pg_stat_user_tables view (Cumulative Statistics System). Millions of rows per second read sequentially from a large table almost always means a missing index.

Log slow plans automatically. The auto_explain module writes the plan of queries exceeding a given duration to the log; the next time there’s an incident, the EXPLAIN is already in the logs (auto_explain):

session_preload_libraries = 'auto_explain'
auto_explain.log_min_duration = '200ms'

Code review checklist:

  • Does a new query bring a new access path (reaching a table through a column it has never been filtered on before)? Is that column indexed?
  • Does the PR include EXPLAIN (ANALYZE, BUFFERS) output taken with production-sized data? If you see a Seq Scan and a large Rows Removed by Filter, stop.
  • How often will the query run? On paths crawlers and campaigns can multiply (product pages, search, the home page), do the “single query duration × worst-day request rate” math.
  • Is the index migration CONCURRENTLY? Can your migration tool run it outside a transaction?
  • If an index is being removed (the GitLab lesson), have the queries that use it been checked?

Add the crawler shape to your load tests. Real users pile onto popular products and the cache does its job. Crawlers spread evenly across the whole catalog and miss the cache. If your load test only models the first, you’ll learn about the second in production.

Marketing and SEO launches are deploys too. Opening a feed, starting a campaign, getting linked from an app all change the shape of traffic. Launches like these should be done with engineering in the loop.


Key takeaways

  • A query’s cost is its duration times its frequency. A 16 ms query running 35 times a second uses up 1 CPU.
  • If “everything is slow and the API is idle”, the API is waiting. Traces (the pool) and the database (time) tell you what it’s waiting for.
  • Sort pg_stat_statements by total time. Sorting by mean time leads you to the wrong query.
  • In EXPLAIN (ANALYZE, BUFFERS), Seq Scan + a huge Rows Removed by Filter = missing index.
  • On a live table, indexes are built CONCURRENTLY and always go into the code as a migration.
  • The trigger (Googlebot) and the root cause (a missing index) are different. Blocking legitimate traffic just postpones the root cause until the next traffic spike.

Test yourself

1. The query shipped on Monday took 16 ms and no alert fired. Why did it become an outage on Tuesday?

Because total cost is multiplied by frequency. While customers alone opened ~10 product pages per second, the query used part of 1 CPU. When Googlebot added ~24 pages per second, the request rate crossed the ceiling the database could handle for this query (~35/s). From that point on the queue grows without pause and every query gets longer still.

2. In pg_stat_statements one query averages 943 ms, another 291 ms. Which one keeps the database busier?

You can’t tell; you need to look at the call count. In this incident the 943 ms report ran 130 times (123 s total), the 291 ms counter 16,693 times (4,864 s total). What keeps the database busy is total_exec_time.

3. More than 500 requests are waiting in the connection pool. Why would growing the pool to 20 make things worse?

The connections aren’t idle; they’re full of queries waiting for CPU in the database. A bigger pool sends more concurrent full-table scans to the same single CPU: each query takes longer, and total work doesn’t shrink. The bottleneck isn’t the number of connections, it’s the work done per query.

4. Your migration contains CREATE INDEX CONCURRENTLY and the deploy fails with “cannot run inside a transaction block”. Why, and what do you do?

CONCURRENTLY builds the index by scanning the table more than once and waiting for other transactions to finish, so it can’t run inside a transaction block. Make your migration tool run that file outside a transaction (in this lab, the -- no-transaction header on the first line; Rails has the equivalent disable_ddl_transaction!, and so on), and remember that if it stops halfway it can leave an INVALID index behind.

Further reading

Basics

Deep dives

Real-world incidents


Next up: Slow order history. The mobile app’s new “My orders” screen takes half a second, yet the database is relaxed, every query is fast, and this part’s index is in place. We’ll learn the story behind dozens of short queries in Jaeger, the N+1 query pattern, and how a 6 ms network round trip turns into half a second inside a loop.

The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, you can generate the postmortem template with ./lab report 005 and compare it with your own write-up.