mediumConceptCodingMidSeniorStaff
A client hangs up halfway through a request. How do you structure a Go HTTP service so it stops doing the work?
Go context cancellation stops wasted request work when the client disconnects or a timeout expires. Pass the request context into database, HTTP and worker calls, and make goroutines return when ctx.Done closes.
7 min readUpdated 2026-08-15
Answer
Short answer
Start from r.Context(), pass it down every blocking dependency, and select on ctx.Done inside goroutines. Cancellation is only useful if every layer observes the same context and stops producing unused work.
Mention net http where it changes the risk, the owner, or the next check. A useful net http point should make the answer more testable, not merely longer.
Was this answer helpful?
Likely follow-ups
- Your handler returns as soon as the context is cancelled, but the database query it started keeps running. Whose problem is that?
- Shutdown returned its deadline error and requests are still in flight. What do you do next?
- How would you enforce one total budget across three sequential upstream calls instead of a timeout per call?
- When would you want work started by a request to survive that request being cancelled, and how do you get a context for it?
Related questions
- A gRPC call three services deep hangs, and so does everything waiting on it. What was missing?hardAlso on cancellation and timeouts5 min
- An asyncio call times out and you handle the TimeoutError, but the background task keeps running and mutates shared state a few seconds later. What happened, and how do you make the timeout actually stop the work?hardAlso on cancellation and timeouts4 min
- How do goroutines leak, and how would you find a leak in a running service?mediumAlso on context5 min
- You run ten coroutines concurrently and one of them raises. What happens to the other nine?hardAlso on cancellation5 min