↓ Skip to main content

Video 8 min

Cloudflare 520, nginx 499 and Postgres Stalls: Keeping Webhooks Alive

A 20-second Postgres stall timed out a chatbot's webhooks. How I held and retried them, and fixed Cloudflare 520 errors, nginx 499s and an exhausted PgBouncer pool.

Narrated in English Subtitles: English

Transcript

Nothing crashed. Postgres came back by itself, the app came back with it, and the error rate barely moved. But twice, the database behind a chatbot service I look after stalled, for about twenty seconds. Acknowledgements that are normally quick took ten to twenty seconds. The partner's system doesn't wait that long.

It gave up on those messages. And nothing on our side told anyone.

What I built after those stalls got a real test a few days later, one I hadn't planned. What caused the stalls is still under investigation. This is about the other half: what the service does while the database isn't answering. The partner sends each chat message to a webhook. We answer two oh two Accepted with a job ID, and a worker writes the reply.

Creating the job needs the database. Normally, that takes about zero point four seconds. There's also a browser extension that waits for its reply in the same request.

The first fix was the cheapest: know when it happens. Our checks watched uptime, connections and locks. A stall tripped none of them. So I added a probe that does what the app does: every two seconds, it commits a transaction through the same proxy. It runs on the host, not inside the app, so it still works when the app is the thing that's stuck.

Knowing about a stall doesn't save the requests in it. For that, the API has to answer the partner within its patience, even when the database can't. Django middleware runs the real view in a thread, and waits up to four seconds. That's well above the normal ninety-ninth percentile. If the view runs over, the raw request is written to disk, and the partner gets a two oh two of its own, marked held.

A separate process replays the held requests through the real endpoint once the database answers, oldest first. The hard part is "exactly once". When the database returns, the original thread, still waiting, and the replay may both create the same job. Handing over in memory doesn't work. A sandbox test showed the stall can start after the thread has sent its insert.

It can't take back a write it's waiting on. So the database decides. A unique index on the hold key means whichever insert comes second fails. Then, a false alarm. Within hours of going live, the spool held three requests an hour, with no stall anywhere.

For some requests, the view described an image before creating the job. That moved into the worker. A spool with a short budget turns out to be a good way to find everything slow that sits in front of an acknowledgement.

Our own logs only see requests that reach the app. Cloudflare sees every request first, and its analytics API can tell you which side failed. It shows errors Django never sees: four ninety-nines, where the client hung up, and five twenty to five twenty-six, where Cloudflare couldn't get a good answer from us. The app now stores Cloudflare's CF-Ray header on every trace. An edge error with no matching trace never reached the app.

That test found two problems. One day, Cloudflare returned three five twenties on the webhook endpoint, with no trace in the app. So it was the proxy. Cloudflare reuses idle connections for up to nine hundred seconds. nginx closed them after ninety.

Now and then a request arrived just as nginx hung up, and got nothing back. The fix is one line: nginx now keeps idle connections open longer than Cloudflare reuses them. Months before, I'd fixed the same kind of bug lower down: HAProxy closing PgBouncer's idle connections, and the app seeing "server closed the connection unexpectedly". The rule is the same at both layers: whoever holds an idle connection open must keep it longer than whoever reuses it. When a client hangs up, Django still records a two hundred.

Only nginx knows the client was gone, and logs a four ninety-nine. Logging those showed one office losing about sixty percent of its replies in the browser extension, to page reloads in the middle of a reply. Raising nginx's timeouts won't fix that. The client is the one that gave up. The fix is on its side, or in answering sooner.

Then someone opened a statistics page. It sent sixty-nine requests at once, each pulling a whole history across the internet. Every connection in the pool was taken. For one minute and forty-six seconds, nothing that needed the database could get it. The spool held eighty webhook requests.

All were accounted for: seventy-four delivered, six replaced by newer ones. The extension has no spool. Fourteen of its replies were lost. So the spool worked. And the cause was ours.

The page now makes one request, not sixty-nine. And a text comparison score is saved with each row, not computed in Python every time. Reports now read from the Postgres node on the same machine, read-only. And at most two run at once per process. One mistake is worth repeating: a report that hit its statement timeout was retried on the primary, through the shared pool, for another two minutes.

Now only a lost connection falls back.

Most of what went wrong was two settings that only make sense together, set in different places, by different people, at different times. So I wrote them all down, from the outside in. One pair is still under investigation: if reports go through Cloudflare's proxy, a slow one could outlast Cloudflare's hundred seconds, and end in a five twenty-four. Two rules cover nearly all of it. Idle timeouts get longer as you go inwards.

Waiting times get shorter, so each hop answers before the one in front gives up on it. That four-second budget is the second rule at work. But PgBouncer still queues a request for two minutes, longer than either client waits.

Next time, I'd start with the probe. It costs an hour, and tells you what you're dealing with. Then the Cloudflare analytics, to know which hop to look at. The spool came third, and it's the part I'm happiest with, but it only made sense once I knew stalls were real and how long they lasted. And I'd take those fourteen lost replies as a hint.

Giving the extension a job ID and a way to pick its answer up later would let it ride out the next stall too. The full post, with the code, the whole timeout table and its links, is on jared.lynskey.co.nz.

More videos

Claude Code Worktrees: Running Parallel Agents Without Collisions

pytest-testmon: Run Only the Tests Affected by Your Code Change

Replacing My Self-Hosted Expo Update Server with Codemagic Patch

How to Debug an iOS App in Xcode: Breakpoints, LLDB, Instruments and the Simulator