
A Go engineer traced a timeout bug to a repository using context.Background() instead of the request's deadline context. The fix and how to catch it in code review.
A Go engineer ran into a timeout bug that didn't show up in unit tests. The handler set a 5-second deadline on the context, passed it to the service, and expected an error if the database call exceeded that window.
Under production load, the database kept processing long after the handler had already returned a timeout to the client. The leak: the repository layer had replaced the incoming context with context.Background(). That new context carries no deadline. The database call ran to completion, consuming a goroutine before it finished or the server ran out of memory.
The fix is simple: propagate the parent context through every layer. If the repository needs extra values or a tighter deadline, derive from the parent with context.WithTimeout or context.WithValue. Never from context.Background() inside a function that already receives a context parameter.
A code-review grep for context.Background() inside any function that also takes a context.Context argument catches this pattern. The only legitimate uses are in main(), test helpers, or situations where no parent context exists – none of which apply inside a repository.
The bug slipped past unit tests because those tests run in isolation and finish quickly. Under real traffic, a 10-second query triggers the leak. One developer traced the fix to a single line change.
Drafted by a large language model from the source reporting linked above, then screened by automated publishing checks. It is not read by a journalist before publication. Some articles cite our Alpha Score. Verify prices and figures against the original source. Educational coverage, not personalized advice.