The job that opened the database six thousand times
A scheduled job that listed every tenant while already running per tenant, plus an autoscaler that added pods in response. A postmortem of a connection storm on a shared Postgres.
The first three posts in this series were about queries. This one is about a mistake that no query plan would reveal: a background job that did the right work in the wrong place. This is a postmortem of our own job, and it is about the design mistake and the fix, not the people involved.
The setup
One Postgres instance is shared by several services. Under normal load it holds a few hundred connections. max_connections is finite, and a slice of it is reserved for superusers.
The payments service is multi-tenant, with each tenant stored as its own schema. A unit of work in that service often opens its own datasource, and with it its own connection pool, for the tenant it is working on. That is a reasonable way to keep tenants isolated. It also means connection count is a function of how many tenants one process touches at once.
The incident
For about a minute, the connection count jumped from a few hundred to a bit over 8,600, then fell back.
During that minute, other services on the same database started failing with “too many clients” and “remaining slots are reserved for superuser”. They were victims. They had done nothing different. The payments role held the connections, and it had taken nearly all of them.
The cause
A scheduled status job is invoked once per tenant by an external scheduler. That is the intended design: the scheduler owns fan-out, and each invocation handles one tenant.
The handler ignored the tenant it was given. Instead it listed every tenant again and processed all of them. With about 80 tenants, each of the 80 invocations initialized datasources for 80 tenants. That is 80 times 80, on the order of 6,400 datasource opens, in one cycle.
CPU rose under that load, and the autoscaler did what autoscalers do. It added pods, going from 2 to 4. But every new pod initialized datasources for every schema at startup. That second wave of connections, from the new pods, is what actually hit the ceiling. The bug and the autoscaler amplified each other: the job created load, the platform answered the load with more clients, and the database had a fixed number of slots.
It is worth being plain about the second effect. Scaling out in response to a connection-heavy spike does not add capacity to the database. It adds clients to a system whose bottleneck is the number of clients.
Why it was hard to see
The first signal was not in the payments service at all. It was other services reporting that they could not get a connection. If you start from the victims, you go looking for a problem in the victims: a leak, a slow query, a bad deploy.
What pointed at the real cause was looking at connections grouped by database role. The count for the payments role had jumped and the others had not moved. That one grouping turned a vague “the database is out of connections” into “one service holds nearly all of them”. If your shared database does not already have a dashboard that breaks connections down by role, build it before you need it. It costs nothing on a quiet day and saves a lot of guessing on a bad one.
The second thing that made it hard was timing. A scheduled job that misbehaves does so on a schedule, and a one-minute spike is easy to dismiss as noise unless something fails during it. Here other services did fail during it, which is the only reason we looked.
The arithmetic is the diagnosis
It is worth writing the multiplication down, because it is what we should have done at review time. Each of roughly 80 invocations processed roughly 80 tenants. Each tenant means initializing a datasource, and each datasource means at least one connection. That is a few thousand opens from the job alone, before counting the pods the autoscaler added in response and the connections each of their datasources held at startup.
Once you have the product of the loop bounds, you can compare it with the database’s limit and see that the design could never fit. No profiler is needed for that. A short comment on any per-tenant job stating how many tenants it touches per call, and who calls it how many times, would have made the mistake obvious on the day it was written.
A quieter twin of the same bug
While we were reading the job code we found a second version of the same mistake. A midnight job mapped over every tenant with Promise.all, opening every pool in the same instant. Eighty tenants, several connections each, one thundering herd every night. It had not caused an outage, because at midnight nothing else was competing for slots. It was the same failure shape waiting for a busier night.
What we changed
The handler processes the tenant it was given. Fan-out belongs to the scheduler, once. If the caller already iterates tenants, the callee must not.
Midnight work runs in chunks. We process 5 tenants at a time with a short pause between chunks, so connections open over seconds and not in one instant.
for (const chunk of chunked(tenants, 5)) {
await Promise.all(chunk.map(runForTenant));
await sleep(pauseMs);
}
Every tenant datasource has an explicit pool ceiling and a short idle timeout. Without a max, a pod that touches many schemas multiplies default pool size by schema count by replica count. We set a small per-datasource maximum, on the order of 5 to 15, and close idle connections after about 10 seconds. A pod that has finished with a tenant gives its connections back almost immediately.
Every service that shares the database needs the same ceiling. Fixing the payments service does nothing if the next service on the instance still opens unlimited pools on boot. The database is a shared resource, and its limit is a property of the whole estate.
What we did not do
We did not raise max_connections as the fix. The connection count was the symptom. A higher limit would have let the same bug open more connections for longer, with more memory pressure on the instance, and it would have hidden the next occurrence behind a bigger number.
The lesson, stated plainly
In a schema-per-tenant application, “list all tenants and open a connection” inside a function that is already called once per tenant is quadratic. It is easy to write and it looks harmless in code review, because each line is reasonable. It only shows up as a shape when you multiply it out: tenants, times tenants, times pods.
Three rules fell out of this.
- Decide who owns fan-out, and let only that component do it. If the scheduler already called you per tenant, do not list tenants again.
- If you must loop over tenants, chunk the loop and cap each pool. A hundred connections opened over a minute are a different problem from a hundred opened in a second.
- Cap pools before you raise the replica count. Autoscaling during a connection spike is more clients, not more capacity.
How we would find it earlier
Two cheap checks would have caught this before production. First, a test that runs the per-tenant handler against a fixture with several tenants and asserts that it touches exactly one. Second, a startup check that counts datasources initialized per pod and fails loudly above a threshold. Both are small, and both would have turned a minute of outage on a shared database into a red build.
The fix here was a few lines. The harder part was recognising that a job can be correct in what it computes and still be wrong about where it runs. The next post is about the same idea applied to a different job: a refresh that did exactly the right work, with no limits on how much of it ran at once.
Previous: A summary table for an operational grid. Next: The hourly rebuild that pinned the database.