Gin in production · 5 MIN READ
Request deadlines in Gin: one context budget, cooperative handlers, no writes from a second goroutine
Give each request a deadline that downstream calls inherit, map its expiry to 504, and avoid the timeout patterns that race on the response.
A request stuck on a slow dependency holds a goroutine, a connection and often a database slot. A deadline bounds that wait, but only if every call below the handler receives the context that carries it. Deadlines are cooperative: Go cannot stop a goroutine from outside, so the safe design lets the handler notice expiry and write the response itself instead of racing it from another goroutine.
gin · A MAP OF THE IDEA
- Derive WithTimeout
- Replace c.Request
- Pass ctx downstream
- Map expiry to 504
Useful when
- One budget per request, inherited by every cooperating call.
- A single goroutine writes the response, so nothing races.
Watch out
- Code that ignores ctx keeps running after the deadline.
- Passing c as a context drops the deadline unless fallback is on.
Implementation & operation cost: A timer per request and the discipline of threading ctx through every call; dependencies that cannot be canceled still need their own timeouts.
Decide who owns the budget
http.Server's ReadTimeout and WriteTimeout bound connection I/O; they do not cancel your handler or the query it started. net/http cancels the request context when the client disconnects, when an HTTP/2 stream is reset, or when ServeHTTP returns. How long an answer is still worth computing is an application decision, so set the deadline in middleware where it is uniform and visible. Keep it below the timeout of the client or proxy in front of you, so your own 504 arrives before their generic error, and leave time for writing the response. Downstream calls must receive c.Request.Context(), not context.Background(), or the budget stops at the handler. A child call may tighten the deadline with its own WithTimeout, but it can never extend the parent's.
Wrap the request context and pass it down
The middleware derives a context with a 20 ms budget, replaces c.Request with a copy that carries it, and cancels the context when the chain returns. The store models a dependency that respects its context; the hung variant never answers, so only the deadline can end the call. The last two requests inspect the context.Context methods of *gin.Context itself, with ContextWithFallback off and then on.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/gin-gonic/gin"
)
// Store models a dependency. A hung store never answers on its own.
type Store struct{ hung bool }
func (s Store) Lookup(ctx context.Context, id string) (string, error) {
if s.hung {
<-ctx.Done() // only the caller's deadline or cancellation ends the wait
return "", ctx.Err()
}
if err := ctx.Err(); err != nil {
return "", err
}
return "note " + id, nil
}
// deadline gives every request a budget that downstream calls inherit.
func deadline(d time.Duration) gin.HandlerFunc {
return func(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), d)
defer cancel()
c.Request = c.Request.WithContext(ctx)
c.Next()
}
}
func getNote(s Store) gin.HandlerFunc {
return func(c *gin.Context) {
note, err := s.Lookup(c.Request.Context(), c.Param("id"))
switch {
case errors.Is(err, context.DeadlineExceeded):
c.AbortWithStatusJSON(http.StatusGatewayTimeout, gin.H{"error": "dependency timed out"})
case errors.Is(err, context.Canceled):
c.AbortWithStatus(499) // client went away: a log label, nobody reads it
case err != nil:
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "internal"})
default:
c.JSON(http.StatusOK, gin.H{"note": note})
}
}
}
func inspect(c *gin.Context) {
_, hasDeadline := c.Deadline()
c.String(http.StatusOK, "deadline=%t done-nil=%t", hasDeadline, c.Done() == nil)
}
func newRouter(fallback bool) *gin.Engine {
r := gin.New()
r.ContextWithFallback = fallback
r.Use(deadline(20 * time.Millisecond))
r.GET("/notes/:id", getNote(Store{}))
r.GET("/reports/:id", getNote(Store{hung: true}))
r.GET("/inspect", inspect)
return r
}
func do(r http.Handler, req *http.Request) string {
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Body.Len() == 0 {
return fmt.Sprint(w.Code)
}
return fmt.Sprint(w.Code, " ", w.Body.String())
}
func main() {
gin.SetMode(gin.TestMode)
r := newRouter(false)
fmt.Println("fast dependency:", do(r, httptest.NewRequest("GET", "/notes/7", nil)))
fmt.Println("hung dependency:", do(r, httptest.NewRequest("GET", "/reports/7", nil)))
gone, cancel := context.WithCancel(context.Background())
cancel() // the client disconnected before the handler ran
req := httptest.NewRequest("GET", "/reports/8", nil).WithContext(gone)
fmt.Println("client gone:", do(r, req))
fmt.Println("c as context, fallback off:", do(r, httptest.NewRequest("GET", "/inspect", nil)))
fmt.Println("c as context, fallback on:", do(newRouter(true), httptest.NewRequest("GET", "/inspect", nil)))
}c.Request.WithContext returns a shallow copy of the request, and assigning it to c.Request makes every later c.Request.Context() call see the deadline. defer cancel releases the timer as soon as the chain returns, including on success. getNote maps context.DeadlineExceeded to 504 and context.Canceled to 499, nginx's non-standard code for a client that closed the request, which only labels the log because nobody reads that response. The hung store returns once the 20 ms budget expires. The pre-canceled request shows that a derived context inherits cancellation: the WithTimeout child is already done, and Err reports Canceled, not DeadlineExceeded. In the inspect lines, the default engine reports no deadline and a nil Done channel even though c.Request.Context() has a deadline.
Why passing c as the context is a trap
*gin.Context implements context.Context, so store.Lookup(c, id) compiles. In Gin v1.12.0 its Deadline, Done and Err delegate to c.Request.Context() only when engine.ContextWithFallback is true, and gin.New leaves it false. With the default, Done returns a nil channel, which never becomes ready in a select, and Err always returns nil, so a dependency waiting on c ignores both your deadline and the client's disconnect; against the hung store it would never return. Value splits the same way: string keys are looked up in c.Keys first, and any key not found there reaches the request context only when fallback is on, so trace spans stored by other middleware silently vanish. Pass c.Request.Context() explicitly; it is clear in review and works with any engine. If you also set ContextWithFallback, do it once at startup. Note too that c.Copy keeps the same Request and therefore the same cancellation. That is fine for a short read, but detached work needs its own context; context.WithoutCancel keeps the values and drops the cancellation, as the context-workers lesson discusses.
Never write the response from a second goroutine
A popular timeout middleware runs c.Next in a goroutine, waits on a timer, and writes 504 itself if the timer fires first. Two goroutines now own one response: the handler may still be writing headers or a body while the middleware writes the 504, which is a data race on the ResponseWriter and can send a mixed or duplicated response. Gin makes it worse. As soon as the middleware returns, engine.ServeHTTP puts the *gin.Context back into a sync.Pool, and the next request can receive it while the abandoned handler goroutine is still using it. This is the retention bug from the context-workers lesson, hidden inside middleware. net/http's TimeoutHandler does this safely because it gives the handler a buffered, mutex-protected writer and decides the final response itself. The price is that it buffers the whole body, does not support Flusher, so streaming is impossible, and always answers 503 on timeout. A Gin access log running inside it also records the handler's status, not the 503 the client received. The cooperative design here keeps one writer: the handler notices the deadline and writes the answer.
Choose the status and test the edges
504 Gateway Timeout says a dependency did not answer in time. 503 Service Unavailable, ideally with Retry-After, says the service chose not to do the work, for example because a queue was full or the budget was gone before the work started. Pick one convention and document it for clients. Check ctx.Err() before expensive steps so a request with almost no budget left fails fast, and never start a retry after the deadline has passed. Cancellation reaches only code that looks for it: a database driver can cancel a query only through QueryContext and friends, and a CPU-bound loop must check ctx itself. Test the fast path, a hung dependency, a request canceled before it starts, and a dependency that ignores its context. That last case shows the limit of cooperative cancellation, because the request returns late and the goroutine leaks. Run the suite under the race detector.
TAKE THIS WITH YOU
Derive a per-request deadline in middleware, pass c.Request.Context() to every downstream call, map DeadlineExceeded to 504 and Canceled to a log label, and let only the handler goroutine write the response. Do not use *gin.Context as a context unless ContextWithFallback is on.
Check your understanding
In Gin v1.12.0, with an engine from gin.New(), what does c.Done() return in a handler whose request context has a deadline?
Go to the source
Progress stays in this browser. No account needed.