Go Developer interview question

How do you use context in Go services?

context.Context carries deadlines, cancellation, and request-scoped values across API boundaries. It should be the first parameter, propagated rather than stored in a struct, and never replaced with context.Background inside request work.

Direct answer

What a strong answer covers

How it works

A context travels with a request: it carries the deadline, the cancellation signal, and a few request-scoped values such as a trace ID. Each layer derives a child context with a tighter deadline or a cancel function it owns and defers. Storing a context in a struct or passing context.Background from deep inside a handler breaks the chain, so a client disconnect or a timeout no longer stops the work it started.

Example

When an HTTP request is cancelled, passing r.Context() to the database call lets the query stop as well. A downstream call that must finish even if the client leaves, such as writing an audit record, gets context.WithoutCancel or a fresh context with its own short timeout.

Common mistakes

  • Putting business data into context values instead of function parameters.
  • Forgetting to call the cancel function returned by WithTimeout, which leaks the timer until it fires.
  • Using one context for the whole batch job so a single slow item cancels every sibling.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
Go Developer interview questions