The hourly rebuild that pinned the database
A correct backfill and a safe backfill are different things. A postmortem of a summary-table rebuild that held a shared Postgres near 100% CPU, and the budget we gave it afterwards.
This is the last post in the series. In the third post we moved the collections grid onto a summary table and said the refresh needed a budget. This is the story of the day we found out how much. As with the connection storm in the previous post, it is a postmortem of our own job, and it is about a design mistake, not a person.
The setup
The summary table has to be filled and kept fresh. An hourly cron inside the application process walked every tenant schema and enqueued backfill batches of 500 leases each. A worker drained those batches with little control over how many ran at once.
A full pass over every tenant is a legitimate thing to want. An unbounded full pass every hour, on the same Postgres that every other service uses, is not.
The incident
The shared production database sat near 100% CPU for two windows in a single day, one lasting about an hour and a half and the next under an hour. At the peak, CPU and the database load average were both near 100. For comparison, that instance runs at single-digit to low-teens percent overnight and roughly 20 to 40 percent during business hours.
The payments database user was the largest slice of that load. The statements responsible were the summary rebuild: read leases, properties and charges, and upsert summary rows. Nothing about any one statement was wrong. There were simply a great many of them running at the same time.
The damage reached well beyond payments. A health endpoint on another service started timing out. Kubernetes liveness probes failed, and on the order of 50 pods were restarted. Users saw server errors. The database was busy, and the application restarts made it worse, because restarting pods reconnect and warm caches at exactly the moment the database has least to give.
Reading the load by user
As with the connection storm, the attribution is what made the problem tractable. Total CPU said only that the database was busy. Breaking the load down by database user showed that one role was responsible for most of it, and breaking that down by statement showed that the heaviest queries were the rebuild’s reads and upserts.
That is a useful pattern for any shared database. Per-service database users are cheap, and they turn “something is hammering the database” into “this service, running this statement”. We had that separation, and it saved us from guessing. A service that connects as a shared superuser would have been much harder to pin down.
It also explains why the recurrence looked random from outside. The rebuild was not triggered by a user action. It ran on its own clock, so the pattern of load had no connection to anything an operator could see on a screen.
A contributing footgun
“All schemas” turned out to include non-production schemas that happened to live on the same server. A staging-sized tenant was being rebuilt on the production instance, in the same sweep, with the same priority as real customers.
What we changed
We removed the hourly in-process cron. Rebuilds are now triggered on purpose, by an external scheduler or by an operator, and not every hour by whichever replica happens to be leader. A trigger that fires from inside every deployment of the application is hard to reason about and hard to switch off.
Non-production schema names are excluded from the all-tenant run. The run is scoped by an explicit rule, not by “everything that exists on this server”.
Batches are smaller. We dropped from 500 leases to 50, so one job holds less work and releases it sooner. A smaller batch is easier to interleave with ordinary traffic, and a failed batch costs less to retry.
The queue has a ceiling. We set a rate limit on the queue, concurrency of 1 for the batch processor, and a small inner concurrency of 2 for the recompute itself. The goal is a load the database can survive while everyone else is using it, not maximum throughput. A rebuild that takes longer and never hurts anyone is the better rebuild.
queue.rate_limit = bounded
batch_worker.concurrency = 1
recompute.concurrency = 2
batch_size = 50
We drain before we deploy. Before shipping the new code, in-flight rebuild jobs are drained or paused. Otherwise the old, uncapped queue finishes the work that the new code has just forbidden. It is an easy step to forget, because the code that fixes the problem is not what is running the jobs.
Why a queue alone was not enough
The rebuild was already running through a queue, and it is tempting to think that made it safe. A queue decouples producing work from doing it, and that is all it does. It does not decide how much work is produced, and unless you configure it, it does not decide how fast the work is consumed.
Our queue happily accepted every batch the cron produced, and our worker happily ran as many as it was allowed to. Both behaved as designed. The missing piece was a statement of how much load the database could take from this job, expressed as numbers the queue could enforce: how many jobs, how fast, and how big. Once those numbers existed, the queue became a safety mechanism. Before, it was a buffer that postponed the problem to a worse moment.
The lesson
A correct backfill and a safe backfill are different things. The rebuild computed exactly the right numbers. It was unsafe because nothing limited how much of it ran, who could start it, or which schemas it touched.
Precompute is only a performance win if the refresh has a budget:
- Batch size. How much work one job holds.
- Concurrency. How many jobs run at once, and how many operations run inside each.
- Who may enqueue it. A person or a scheduler on purpose, not a loop in the application.
- Which tenants are in scope. An explicit rule, not “all of them”.
“It runs in a queue” is not a budget. A queue with unbounded concurrency is a way of running unbounded work somewhere you cannot see it.
What the whole series comes down to
Over five posts, the fixes were the same few habits applied in different places.
- Time the bad page. Page 1, a deep page, a selective filter, a search that matches nothing, and a few concurrent callers. Linear growth with offset is a design bug, not load.
- Parameters are not a table. Tens of thousands of ids in
INorANYmeans the scope should be a join. - Denormalize what you sort on. Compute it when the fact changes. Do not compute it in the list query, and do not sort it in the API process.
- Counts are queries too. A second full join for
COUNT, or aCOUNT(DISTINCT)that does not need to be distinct, can cost more than the page. - Caches need a budget. Batch size, concurrency, which tenants, and a trigger that is not “every replica, every hour”.
- Fan out once. If the scheduler already called you per tenant, do not list tenants again. If you must loop over tenants, chunk them and cap each pool.
- Separate database time from everyone else’s time. A contact lookup, a PDF render or a mail provider call will hide a fast query, or unfairly indict one. Log them apart.
None of it required a bigger instance or a clever cache. Most of it was deciding, in each place, who is allowed to do how much work at once, and writing that down as limits in the code.
Previous: The job that opened the database six thousand times. This is the last post in the series; it starts with Why page 40 took fourteen seconds.