Skip to content
Preptima
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

Further reading