The page fires at 02:14. The payment provider’s settlement webhooks are timing out at p99, the provider is retrying them, and the retries are arriving faster than the originals are finishing. The database connection pool is pinned at its limit. Nothing was deployed tonight; the only thing that changed is that a large merchant’s end-of-day batch settled, and a few thousand webhooks arrived in the same minute.
The webhook handler does one read before it writes anything:
SELECT * FROM payments WHERE lower(provider_ref) = lower($1);
There is an index on provider_ref. Somebody checked for it when the table was created, and
it is still there. EXPLAIN ANALYZE on production says Seq Scan on payments, four seconds,
twenty million rows read to return one.
This is the most common way a payment backend falls over, and it is almost never a missing index. It is an index that exists, next to a query that cannot use it.
The index was there
A few weeks earlier, a support ticket showed a merchant pasting a provider reference in
lowercase and getting “payment not found”. The fix was reasonable-looking: make the lookup
case-insensitive by wrapping both sides in lower(). The tests passed against a fixture of
three thousand rows, where a sequential scan takes under a millisecond and nobody can tell
the difference.
A B-tree is a sorted copy of one expression. The index on provider_ref is sorted by
provider_ref, and the only questions it can answer are questions about provider_ref itself:
equal to, less than, between. lower(provider_ref) is a different expression, and Postgres has
no way to know that sorting by one tells you anything about the other. So it does the only
thing left: compute lower() on every row of the table and compare.
A predicate the index can answer is called sargable — search-argument-able — and the
difference is visible in any plan. A sargable predicate appears as an Index Cond; a
non-sargable one appears as a Filter, which means it ran against every row something else
handed it.
Same column, same index, different WHERE clause
—
—
Pick a predicate and an index set below.
The same failure has several costumes, and payment code wears all of them:
Functions on the column. lower(), date(created_at), coalesce(ref, ''), amount / 100.
Either move the arithmetic to the parameter side (created_at >= $1 AND created_at < $2
instead of date(created_at) = $1), or index the expression itself. Better still, normalize on
write: if provider references are case-insensitive, store them lowercased and the lookup never
needs a function.
Type mismatches. A bigint column compared with a numeric parameter is resolved by
casting the column, and id::numeric is not what the primary key indexes. This happens without
anyone writing a cast — a driver that binds JavaScript numbers or decimals as numeric is
enough. MySQL does the same thing in the other direction: a VARCHAR column compared with an
integer literal converts every row to a number.
Wildcards. LIKE '%8F3Q2' has no starting point in any ordering. A prefix is subtler: under
the default non-C collation, a plain B-tree will not serve LIKE 'txn8F3%' at all, and you need
an index with text_pattern_ops. Note too that _ is a single-character wildcard in LIKE,
so a Stripe-style pi_… prefix only narrows the range to pi.
OR across columns. WHERE provider_ref = $1 OR merchant_ref = $1 needs an index on both
sides to become a BitmapOr; with one missing, the whole predicate is a filter.
The immediate fix that night was one statement, and the last section explains why it was created the way it was:
CREATE INDEX CONCURRENTLY payments_provider_ref_lower_idx
ON payments (lower(provider_ref));
The permanent fix was to lowercase references at the API boundary and drop the lower().
Fixing it moved the problem
With webhooks fast again, the next slowest query in pg_stat_statements surfaced: the merchant
dashboard’s “recent payments” list.
SELECT * FROM payments
WHERE merchant_id = $1 AND status = $2
ORDER BY created_at DESC
LIMIT 50;
It had an index too — (created_at, merchant_id), added when the dashboard only sorted by time
and someone reasoned that both columns in the query should be in the index. Both are. The order
is wrong.
A composite B-tree is sorted by its first column, then by the second within ties of the first,
and so on — a phone book sorted by surname, then first name. You can find every “Smith” quickly;
you cannot find every “John” without reading the whole book. The rule that falls out of this is
the leftmost prefix: an index can narrow its descent only on a leading run of columns
compared with =, and can hand rows back already sorted only if the ORDER BY column comes
immediately after that run.
For this query that means equality columns first, sort column last: (merchant_id, status, created_at). The descent lands on exactly one merchant’s rows in one status, already in time
order, and LIMIT 50 stops after fifty entries. Every other ordering does more work, and how
much more depends on the data — which is why these regressions hide in staging.
The merchant dashboard query under six indexes
—
Pick an index and a status below.
Two things are worth taking from the figure. First, (merchant_id, created_at) looks good for
the common case and degrades fifty-fold for rare statuses, because it walks this merchant’s history
until it finds fifty matching ones. Second, the order among the equality columns barely matters
for this query, but it decides which other queries the index can serve. (merchant_id, status, created_at) also serves “all payments for this merchant”; (status, merchant_id, created_at)
does not. Lead with the column the most queries filter on.
The status column trap
The third slow query was the reconciler, which polls every few seconds for work:
SELECT id, provider_ref FROM payments
WHERE status = 'pending' AND created_at < now() - interval '15 minutes';
A plain index on status is almost useless. It has four distinct values over twenty million
rows, so it is as large as any other single-column index while telling the planner very little.
For succeeded, 90% of the table, the planner is right to ignore it — a sequential scan beats
millions of random heap reads, for the reasons covered in
what Postgres actually does with your data.
But the reconciler only ever asks about pending, which is a fraction of a percent of rows at
any moment. A partial index indexes only those:
CREATE INDEX CONCURRENTLY payments_pending_idx
ON payments (created_at) INCLUDE (provider_ref)
WHERE status = 'pending';
It holds tens of thousands of entries instead of twenty million, so it stays in memory. Rows
leave it as soon as they settle. INCLUDE (provider_ref) stores the one extra column the
reconciler reads in the index leaf, so the query can be answered as an index-only scan without
visiting the table at all. The query’s WHERE must imply the index’s WHERE for the planner to
use it — status = 'pending' literally, not a parameter that happens to hold 'pending' in a
generic plan.
Every index is a write tax
The tempting conclusion is to index everything. On a payments table that is the wrong one, because every insert and every status transition has to update every index on the table, inside the transaction that moves money. Seven indexes means eight writes per payment, and the write-ahead log, replication stream and backups all grow with them.
The primary key deserves particular thought. A random UUIDv4 key puts each new row’s index
entry at a random point in the B-tree, so inserts touch pages all over the index, split them
half-empty, and keep far more of the index hot in cache than the workload needs. A
time-ordered key — a bigint sequence, or UUIDv7 if identifiers must be generated outside the
database — appends to the right-hand edge of the tree instead. On a table this size the
difference is measured in how many index pages the insert path has to keep resident.
Some indexes are not optional, though, and they are not about speed. The idempotency key from
Part 3 needs UNIQUE (merchant_id, idempotency_key),
because the constraint is what makes two concurrent retries collide rather than both succeed.
Scoping it by merchant matters: two merchants’ clients can generate the same key, and a global
unique constraint turns that into one of them getting the other’s response.
Shipping an index on a hot payments table
A plain CREATE INDEX takes a lock that blocks every write to the table for as long as the build
runs, which on twenty million rows is minutes of no payments. CREATE INDEX CONCURRENTLY builds
without blocking writes, at the cost of scanning the table twice and taking longer. It has its
own sharp edges:
It cannot run inside a transaction, so most migration tools need it marked as non-transactional.
A failure leaves an INVALID index behind. A deadlock or a duplicate in a unique build
aborts it, but the half-built index stays, is updated on every write, and is never used for
reads. Check pg_index.indisvalid, drop it, and retry.
It still waits for old transactions. A long-running report holding a snapshot will stall
the build, and a lock_timeout on the migration keeps it from queueing behind that report while
everything else queues behind it.
Then verify, in production, with EXPLAIN (ANALYZE, BUFFERS) — the plan in a small staging
database is not evidence of anything. A month later, check pg_stat_user_indexes.idx_scan and
drop indexes that are still at zero. An unused index still costs a write on every payment.
The short version
An index is a sorted copy of one expression, and it helps only a query that asks about that
exact expression with an operator it supports. Functions, casts, leading wildcards and
mismatched types all turn an index lookup into a scan of the whole table, and the tell is
Filter where you expected Index Cond. Normalize data on write so lookups don’t need
functions, and match parameter types to column types.
In a composite index, put the equality columns first and the sort column last, so the descent
lands on the exact slice and LIMIT can stop early. For queue-like queries on a rare status, a
small partial index beats a large full one.
Every index is paid for on every write, so keep the ones that earn it, make the ones that
enforce correctness unique, build them CONCURRENTLY, and prove each one with a production
plan rather than a staging one. The payment lookup that took down the webhooks had an index the
whole time. It was just asking the index a question it could not answer.