Ramblings of an aging IT geek
← Ramblings of an aging IT geek
golang

passing context through, and finally understanding why

A short note on why context.Context as the first argument stopped feeling like boilerplate once I had a request that needed cancelling halfway down the stack.

A code editor showing a Go function signature with a context argument

For ages ctx context.Context as the first parameter to every function felt like a tax. You pass it in, you pass it on, you never look at it, and your signatures grow an extra word each. I threaded it through dutifully because the linter and the reviewers wanted it, not because I'd ever felt it earn its place.

Then I had a handler that kicked off three downstream calls, and the client hung up after the first one returned slowly. Without context, those other two calls carried on regardless, talking to a database on behalf of nobody, holding a connection for a response that would never be read. With the request's ctx passed down to each call, the client disconnecting cancelled the context, and every in-flight operation that was watching it unwound itself. The work stopped because the reason for the work had gone away.

That's the whole point I'd been missing. Context isn't a bag for passing values around, although people abuse it for that. It's a cancellation signal that flows down the call tree, so that when the top says "stop", everything underneath hears it. The first argument isn't ceremony. It's the wire that lets a cancelled request actually cancel.

I still don't love how it reads. But I stopped resenting it, which is most of the way to peace.