Haskell Timeouts and Deadline Propagation in Services
A service I helped run went dark for 41 minutes without crashing. Every pod answered its liveness probe, CPU sat at 3 percent, and the request queue grew until the load balancer gave up.

A service I helped run went dark for 41 minutes without crashing. Every pod answered its liveness probe, CPU sat at 3 percent, and the request queue grew until the load balancer gave up. The cause was a single upstream that stopped sending bytes after the response headers. Our code had a timeout. It was wrapped around the wrong thing, and the thread sat inside a socket read that the timeout could not reach.
Timeouts in Haskell look like a solved problem because System.Timeout.timeout exists and takes two arguments. The function is good. The trouble is that it delivers an asynchronous exception, which means it only works where the target thread can receive one, and it tells you nothing about how long the whole request has left. Those two gaps account for most of the hung services I have been asked to look at.
What timeout actually does to a thread
The implementation is short enough to describe in a sentence. It forks a watchdog, the watchdog sleeps for the number of microseconds you passed, and then it throws a private exception to the original thread. Your action runs in the original thread the whole time. Nothing is killed, nothing is preempted; an exception is delivered and normal unwinding happens.
That design has three consequences people meet in production.
The first is that a thread inside a safe foreign call cannot be interrupted. The exception is queued and sits there until the C function returns. Name resolution through getAddrInfo is the classic example: if your resolver is unreachable, the glibc default is five seconds per attempt with two attempts per nameserver, so a DNS lookup can block for 20 seconds and a 2 second timeout wrapped around it does nothing at all. The same applies to most of libpq and to any unsafe call, which cannot be interrupted even in principle.
The second is that masked regions delay delivery. Code inside the acquire or release phase of bracket runs masked, so a timeout that fires during cleanup waits for cleanup to finish. That is usually what you want, and it is also how a 5 second timeout turns into a 30 second stall when the release action is itself a network call.
The third is the nesting bug. Because the exception is private to each timeout call, an inner timeout will not swallow an outer one, but a handler that catches SomeException inside your action absolutely will. I have found that pattern in retry loops more than anywhere else: the loop catches everything, treats the timeout as a transient failure, and retries forever inside a timeout that already expired. If you have a retry wrapper, check it against the rules in our piece on retry with exponential backoff for flaky services before you trust any number you set.
The advice to put a timeout on every call, and why I argue with it
Most guidance stops at one rule: never make a network call without a timeout. I agree with the rule and I think it is nowhere near enough, because per call timeouts compose by multiplication rather than by addition.
Take a shape I see constantly. An HTTP handler calls a service client. The client sets a 5 second response timeout and retries three times with backoff. That client sits behind a cache lookup with its own 2 second timeout, and the handler itself has a 10 second timeout from the web framework. Each number looks conservative. The worst case path is 5 plus 5 plus 5 seconds of upstream waiting plus roughly 3 seconds of backoff sleeps, so 18 seconds inside a 10 second handler budget. The handler timeout fires, the client keeps retrying because nobody told it to stop, and the connection it holds stays checked out of the pool until the retry loop finishes.
The fix is to stop thinking in durations and start thinking in deadlines. A duration is relative and resets at every layer. A deadline is an absolute instant, computed once at the edge, and every layer below reads it instead of inventing its own. The question a deadline answers is the one that matters: how much time is left before the caller stops caring about this answer.
A deadline budget in about twenty lines
Use a monotonic clock. Wall clock time moves when NTP corrects it, and I have watched a leap smear turn a 3 second timeout into an immediate failure. In GHC the right primitive is getMonotonicTimeNSec from GHC.Clock, which is cheap and never goes backwards.
The shape is a newtype holding the deadline as nanoseconds since an arbitrary origin, carried in your application environment next to the connection pool and the logger. Two helpers do all the work. One creates a deadline from a duration at the edge of the system. The other reports how many microseconds remain, clamped at zero, so it can be handed straight to timeout.
Then every call site changes from a constant to a computed value. Instead of wrapping a database query in a 3 second timeout, you ask the environment for the remaining budget, subtract a small reserve so you have time to serialise an error response, and use that. When the budget is gone, you fail fast without opening a socket at all, which is the behaviour that actually sheds load during an incident.
Two refinements earn their keep. Reserve a slice for your own work: I use 150 milliseconds, measured from how long our handlers took to render a JSON error plus a safety factor. And propagate the deadline outward in a header when you call your own services. Most teams pick a header carrying the remaining milliseconds, because an absolute instant requires both sides to agree on a clock and they will not.
The timeouts that live outside your Haskell code
Some waits can only be bounded by the layer that owns the socket or the session. Setting them is dull, one time work, and it removes the cases where a deadline cannot help you.
| Wait | Where to set it | Value I use | Why timeout cannot do it |
|---|---|---|---|
| DNS resolution | resolv.conf options, or a pure Haskell resolver | timeout 1, attempts 2 | Blocking safe FFI call |
| TCP connect | Socket option, or connect in a separate thread | 2 seconds | Interruptible on Linux, not everywhere |
| Waiting for response headers | http-client responseTimeout | 5 seconds | Works, but does not cover the body |
| Slow response body | Your own loop with a per chunk deadline | Chunk every 10 seconds | No library setting covers it |
| Postgres query | statement_timeout on the session | Deadline minus reserve | libpq blocks in C |
| Idle transaction | idle_in_transaction_session_timeout | 30 seconds | Server side only |
| Pool acquisition | Pool configuration | 1 second | Blocks on an MVar, not a socket |
The Postgres row is the one worth doing today if you do nothing else. Issue a SET statement_timeout on every checkout with the remaining budget in milliseconds, and the database will cancel the query for you when the clock runs out. That converts an uninterruptible C wait into a normal query error you can handle. Sizing the pool so acquisition rarely queues is a related exercise, and the arithmetic is in the guide to connection pooling for Postgres services.
One honest limit: I do not know a clean way to bound a stuck getaddrinfo without either moving resolution into a pure Haskell resolver or accepting the operating system settings. Both are real choices. We moved to a Haskell resolver with a cache after the second DNS incident, and it added a dependency I would rather not have. The alternative was a 20 second floor on failure that no amount of application code could shorten, and that floor is also the reason a graceful shutdown can overrun its grace period.
FAQ
Is timeout safe to use around arbitrary code?
Mostly. It is safe around code that handles asynchronous exceptions correctly, which means acquiring resources with bracket and never catching SomeException without rethrowing what it does not understand. Around code that swallows exceptions, it does nothing useful.
What timeout should I put on a background worker?
A worker has no caller, so it has no inherited deadline. Pick a per job ceiling from the observed duration distribution: I use the 99th percentile times four, which has caught genuinely stuck jobs without killing slow but healthy ones.
Does threadDelay have a maximum?
On 64 bit platforms the practical limit is enormous, but timeout takes an Int of microseconds, so on a 32 bit build the ceiling is about 35 minutes. Anything longer needs a different mechanism, usually a registered delay or a scheduler.
Should a deadline be a header or part of the payload?
A header, carrying milliseconds remaining as an integer. Proxies and sidecars can read it, it survives payload schema changes, and it does not require the two services to share a clock.
More in Systems
Systems
Haskell Bounded Concurrency for Background Workers
A worker that drains a job queue is the first Haskell service most teams ship, and it is also the first one that gets killed by...
Systems
Haskell Health Check Endpoints for Kubernetes Probes
A student of mine shipped her first Haskell service to a small Kubernetes cluster last spring, and it restarted itself 41 times...
Systems
Haskell Structured Logging for Production Services
Your Haskell service crashed at 03:12, and the only clue is a wall of putStrLn output with no request id, no timestamp...