The interviewer adds one sentence to your otherwise reasonable design: “The client disconnected, but CPU usage kept climbing.” A timeout exists. Every function accepts a context. Yet the service continues doing work that nobody will receive.
This is a useful senior or staff engineer practice problem because it connects API contracts to task ownership. A convincing answer explains who can request cancellation, where execution observes it, who waits for completion, and what happens to side effects already in progress. This guide uses Go examples, with lessons that transfer to other concurrency models. The scenario, timing budgets, and rehearsal rubric are illustrative preparation tools, not a company's hiring criteria.
1. Separate cancellation from completion
Start with three events on the whiteboard: the caller loses interest, the worker receives a stop request, and the worker actually exits. These events need separate evidence. Go's CancelFunc documentation explicitly says that cancellation does not wait for work to stop. Derived contexts carry the signal; they do not establish that every operation has released its resources.
For the practice scenario, design a report endpoint that fetches an account, reads transactions, and produces a summary. Give the handler ownership of the tasks needed for that response. Give a separate service supervisor ownership of any durable export job. Write the success condition before choosing a concurrency primitive: either the handler produces the required report, or its owned tasks finish their cancellation path and release their resources.
The follow-up to anticipate is a worker inside a library that never checks the stop request. Your design needs an actual boundary for that work: a cancellable API, a documented I/O deadline, bounded computation, or a separately supervised process. Merely passing a context through the function signature does not demonstrate that the boundary exists.
2. Spend one remaining deadline budget
The gRPC deadline guide distinguishes a deadline from a timeout duration, warns that clients have no deadline by default, and describes propagation to downstream calls. Support depends on language and configuration. Explain how your chosen stack passes the remaining allowance instead of restarting the full timeout at every service.
Illustrative calculation: suppose the endpoint has a 900 millisecond response budget. Admission and parsing consume 120 milliseconds. Reserve another 80 for assembling and sending the response. Downstream work then has at most 700 milliseconds. If a required lookup takes 250 milliseconds, a subsequent lookup has at most 450 from that allocation. These are invented practice numbers; real settings need measurements under load.
Parallel calls share elapsed time, so do not add their individual allowances as if they ran sequentially. Queue waiting also consumes the caller's budget. In your explanation, describe what happens when a task reaches the front of the queue with too little time left to be useful. Rejecting or degrading that request can be a deliberate admission policy. Starting a fresh full-duration timer would silently change the promise you just made.
3. Give concurrent tasks an owner and a join
Go's errgroup package combines task synchronization and error propagation. WithContext cancels its derived context on the first task error or when Wait returns. Wait still waits for all registered functions. Therefore, one sibling that ignores cancellation can hold the entire join open. Also avoid using the group's derived context for a later operation after Wait has completed successfully: it has been canceled then, too.
For the report endpoint, decide which dependencies are required. An account lookup failure may invalidate the report, while an optional explanatory annotation may be safely omitted. If you place both in one fail-fast group without handling the optional failure, you have accidentally made the annotation mandatory. State the desired product behavior, then encode the error policy.
Bound admission as well as active work
SetLimit bounds active goroutines in an errgroup, and a Go call blocks while waiting for room. Its limit must not change while tasks are active. That is not automatically a cancellation-aware queue. A useful design review asks where the submitter waits, how that wait ends, and whether pending work can accumulate elsewhere. For this scenario, propose a bounded worker queue with explicit overload behavior, or admission that can abandon its wait when the caller leaves.
4. Audit every blocking edge
The Go team's pipelines and cancellation article shows a classic leak: a consumer stops reading, leaving an upstream sender blocked. Increasing a channel buffer only moves the failure if its size depends on how many results the consumer will ignore. Cancellation must reach the operation that is actually waiting.
Trace the report through queue submission, channel sends, dependency calls, and result collection. For a channel send, a select can offer both the send and the cancellation path. That gives the worker an escape when the receiver disappears. It does not grant cancellation priority when multiple cases are ready. If the product needs a strict “no more output after this point” guarantee, define additional synchronization and the exact point where that guarantee takes effect.
The Go database cancellation guide passes a derived timeout context into QueryContext, defers the cancel function, and closes returned rows. Apply that pattern at the database boundary, then verify the behavior of your actual driver and database. Draw resource ownership beside the call: the code that receives rows must close them, including when result processing ends early.
5. Propagate the signal without inventing rollback
The gRPC cancellation guide explains that the library generally cannot interrupt an application handler. Long-running processing must cooperate, and outgoing RPC cancellation behavior differs across languages. In an interview, name the propagation mechanism instead of assuming that closing the client connection stops the whole dependency tree.
Now change the scenario: the report endpoint also records that a paid report was purchased. Cancellation no longer answers the business question. The gRPC status-code reference notes that DEADLINE_EXCEEDED can occur even when a state-changing operation completed successfully, because the response arrived too late.
Your proposed contract should let the caller recover the result using a stable operation identity. Explain how the service records the purchase outcome and how a retry retrieves or reconciles it. Treat cancellation as a request to stop unnecessary execution. Treat business reversal as a separate operation with its own rules. This distinction lets you answer “what if the commit happened just before the deadline?” without promising that a timeout erased durable state.
6. Make cleanup bounded and explicitly owned
In the practice design, normal request work follows the request lifetime. A required cleanup action may need a short opportunity to finish after that request is canceled. Specify exactly which action qualifies, its maximum duration, and who observes its completion. Avoid turning every canceled request into an untracked background task.
A cleanup context derived directly from an already canceled parent starts canceled. If you intentionally establish a separate cleanup lifetime, also establish its own deadline and supervisor. Retain only the metadata the cleanup needs. A business action that must survive process loss belongs in a durable workflow with recovery, rather than relying on a goroutine to outlive an HTTP response.
For example, closing local rows and releasing a memory buffer belong to the task's ordinary exit path. Publishing a purchased report after the response disappears may be durable job work. Ask the interviewer which promise the product makes. That answer determines whether you should stop the operation, finish a bounded local cleanup, or recover an accepted job after restart.
7. Design shutdown as a sequence with a final budget
A process shutdown adds another lifetime. Go's signal.NotifyContext can translate selected operating-system signals into context cancellation. Its stop function unregisters the notification behavior and releases associated resources. The application still needs to decide what that signal means for admission, current requests, and background workers.
For this service, propose a sequence: stop admitting new report work, let accepted requests drain within a budget, then cancel remaining service-owned work and wait within the remaining allowance. Keep the drain context separate from the signal context that already fired. If every active request inherits immediate signal cancellation, your claimed drain period will not give those requests a chance to finish normally.
Go's HTTP server Shutdown documentation describes closing listeners and idle connections, then waiting for active connections to become idle. A context bounds that wait. Shutdown does not close or wait for hijacked connections such as WebSockets. It also makes serving functions return ErrServerClosed, so main must remain alive until the shutdown coordination finishes.
Explain your fallback if the drain budget expires: record the unfinished work, apply the appropriate connection or task stop mechanism, and preserve recovery information for accepted durable jobs. The outer platform can impose a harder limit. Kubernetes documents Pod termination as graceful stopping followed by forced termination of remaining processes when the grace period expires. Fit your application budget inside that boundary; do not make cleanup depend on having unlimited time.
8. Test the lifecycle, then rehearse the explanation
Use controlled synchronization in practice tests. Start a worker, observe that it reached the intended blocking point, cancel its owner, and require an explicit completion signal within the test's bound. Repeat with a consumer that exits early, a dependency that ignores cancellation, a full admission queue, and shutdown during an active report. These tests should expose which guarantee depends on cooperation.
For diagnosis, the Go diagnostics guide describes goroutine profiles as stack traces of current goroutines and block profiles as evidence of synchronization waits. Use those tools to locate stuck workers. A total goroutine count can suggest a trend, but it does not identify the owner or prove every canceled request released its work.
Illustrative practice rubric: give yourself one point for stating the caller's deadline, one for assigning each task an owner, one for identifying every blocking escape path, one for joining owned work, and one for distinguishing cancellation from a committed outcome. Use the five points to find gaps in your next rehearsal, not to predict an employer's decision.
Finish your mock answer by following one request from admission to completion, then replaying it with a disconnect halfway through. Introduce process termination only after the request story is clear. This keeps the discussion concrete: each context has a purpose, each task has someone responsible for it, and each claim of completion has observable evidence.
Practice explaining concurrent systems
Use Interview Copilot to prepare for senior and staff engineer interviews, rehearse failure scenarios, and refine how you explain engineering decisions.
Start practicingSources & References
- Go context: cancellation contracts
- gRPC: Deadlines and propagation
- Go errgroup: task groups, waiting, and concurrency limits
- Go blog: Pipelines and cancellation
- Go: Canceling in-progress database operations
- gRPC: Cooperative cancellation
- gRPC: Status codes and ambiguous deadline outcomes
- Go os/signal: NotifyContext lifecycle
- Go net/http: Graceful shutdown and connection boundaries
- Kubernetes: Termination of Pods
- Go language specification: Select statements
- Go: Diagnostics and concurrency profiles