When a travel platform exports bookings, refreshes reports, or prepares supplier-facing files, the work may continue long after the person who requested it has closed a browser tab. The harder question is what happens when the application stops halfway through. Can the job release resources promptly, preserve completed progress, and return under a new process without duplicate or missing results?
Teams looking to hire dot net developers should ask candidates to demonstrate those behaviors, not merely describe asynchronous programming. This guide focuses on modern .NET hosted services, cancellation propagation, and durable ownership of unfinished jobs. It sets out a practical hiring assessment built around one hypothetical booking export, with clear distinctions between cooperative shutdown, sudden process loss, and recovery.
Why Safe Shutdown Is a Hiring-Level Skill
Background jobs often appear straightforward during a demonstration. A controller accepts a request, a task reads data, and an export eventually appears. Under normal conditions, nearly any implementation may look convincing. The weaknesses emerge during deployment, a container restart, an overloaded dependency, or a worker process that disappears before recording its final status.
A capable developer treats shutdown as part of the workflow rather than an exceptional cleanup event. They can identify which operations are interruptible, which effects have already been committed, and which process is entitled to continue. They know that cancellation is a request for cooperation, not a guarantee that code stops immediately or that remote systems undo completed calls.
Look for an explanation of the business invariant first. For a booking export, an acceptable invariant might be that each committed export part is represented once in a manifest and that an unfinished export is never shown as complete. Whether the worker executes an operation once is a different question from whether the final published result contains duplicate entries. Good design controls the latter even when execution repeats.
Do not turn this interview into a general framework modernization discussion. The hiring problem is narrower: can a candidate implement current .NET background processing so that cancellation, failure, and restart have predictable outcomes?
Choose a Hosting Model That Fits the Job
Know What the Host Actually Manages
ASP.NET Core applications and standalone Worker Service applications can both register hosted services. The IHostedService contract defines StartAsync and StopAsync; BackgroundService adds an ExecuteAsync task representing the long-running service lifetime. Microsoft documents their lifecycle in its .NET 10 guidance for background tasks with hosted services.
The practical interview question is not which base class sounds more advanced. Ask why the candidate chose a hosted service inside the web application or a separately deployed worker. A modest workload may share a process, while long-running or resource-intensive exports may benefit from an independently operated worker. Either model still needs a recovery mechanism if work must survive the process.
Use Dependency Injection Without Lifetime Mistakes
Hosted services are registered as singletons. A per-job database context or other scoped dependency should be resolved inside a created scope, not captured from the root container for the lifetime of the worker. Ask candidates to show where the scope begins and ends, especially around asynchronous operations and job-level exception handling.
Disposal also matters. An active stream, database reader, or temporary export handle should be released when the job ends or is canceled. Cancellation does not replace await using, disposal, or an explicit decision about whether a temporary artifact may be retained for reconciliation.
Explain the Real Shutdown Budget
On graceful host shutdown, the service receives a stopping signal, and the host waits for the background task to finish. Microsoft's hosted-services documentation describes a default graceful-shutdown timeout of 30 seconds for the host configuration it illustrates. That is a budget to respect, not evidence that every unfinished action will complete or that a process manager will allow unlimited extra time.
Ask the developer to distinguish the cancellation token supplied to ExecuteAsync from the token passed into StopAsync. The former signals ongoing work to stop; the latter limits the shutdown operation. Enlarging a timeout may be operationally appropriate, but it cannot make unexpected termination safe. A robust worker remains recoverable even if StopAsync never runs.
Trace Cancellation From Host to Final Side Effect
Make the Token's Journey Visible
In .NET, cancellation is cooperative. A worker must pass its CancellationToken through each relevant asynchronous layer: waiting for a queue item, fetching booking rows, calling an API, writing a stream, and waiting before a retry. Microsoft's cancellation model explains why listeners, not token creators, decide how promptly to stop.
Do not confuse a disconnected HTTP request with host shutdown. Once accepted durably, the export has its own lifecycle; request cancellation should not silently erase its business obligation.
During review, follow a token end to end. A method that accepts a token but calls dependencies without forwarding it provides the appearance of compliance without the behavior. Similarly, an uncancelable delay in a retry loop can consume the shutdown window while accomplishing nothing useful. Look for Task.Delay(delay, token) and token-aware I/O where supported.
Cancellation should be checked before starting another unit of work. Yet checking a token before a remote write does not guarantee that the write will not happen: cancellation can arrive immediately afterward, or the remote system may commit before the caller sees a response. The candidate must recognize that narrow but important uncertainty.
Separate an Interrupted Attempt From a Failed Job
An OperationCanceledException associated with the expected stopping token is ordinarily a shutdown outcome, not a reason to spend retry attempts or mark the business request permanently failed. Other exceptions need classification. A malformed booking record may require review; a temporary network problem may justify another bounded attempt. An ambiguous network timeout may require checking the external result before trying again.
There is also a commit boundary. Cancellation can usually interrupt reading and transformation; it should not interrupt the middle of a small transaction that makes a completed checkpoint visible. The developer should keep such transactions short and finish them consistently, while observing the host's shutdown limits. If a checkpoint cannot be safely committed, recovery must inspect the artifact and prior durable state instead of guessing.
Do not reward use of CancellationToken.None as a general escape hatch. A carefully bounded commit might need a separate short timeout or compensating reconciliation, but bypassing cancellation throughout a job simply transfers unpredictable waiting to deployment and shutdown operations.
Decide Where Jobs Live and Who Owns Them
An In-Memory Queue Is Not a Durable Ledger
A bounded Channel<T> can coordinate work efficiently inside one process. With BoundedChannelFullMode.Wait, producers wait when capacity is exhausted, providing backpressure rather than unbounded memory growth. The .NET channels documentation describes these semantics. They address throughput and memory behavior, not survival across a process crash.
If a request is acknowledged only after adding a delegate to an in-memory channel, the delegate can disappear on restart. A 202 Accepted response does not magically turn volatile work into a persistent obligation. For business-critical exports, store a durable job record before acknowledging acceptance, then use a channel, poller, or notification merely to accelerate discovery of that record.
An external job record may reside in an appropriately configured database or durable work system. Its purpose is to answer what was requested, its present state, which attempt is running, and what progress is committed. Durability depends on the actual persistence and acknowledgment configuration; neither a database name nor a queue product alone is a sufficient guarantee.
Use Conditional Claims Instead of Optimistic Ownership
When multiple worker instances can discover the same job, ownership must be enforced with an atomic claim. A typical record carries a job identifier, state, owner identifier, lease expiry, attempt count, checkpoint, update time, and monotonically increasing ownership generation. A conditional update claims only eligible work and increments the generation as part of that atomic change.
A lease tells other workers when an owner may be presumed unavailable. A heartbeat extends it while work progresses. Neither feature alone prevents an old, slow worker from waking up after its lease expires. Require a fencing check: checkpoint writes and publish decisions must validate the current ownership generation. For externally visible effects, add idempotent artifact naming or an equivalent destination-side guard; a database fence cannot retroactively undo an outside write.
Graceful shutdown may release ownership promptly, but correctness cannot rely on that release. A killed process cannot write a final message. On startup, a reconciliation pass should find expired leases, verify stored checkpoints and artifacts, and make unfinished records eligible for another claim under a new generation.
| Mechanism | Useful responsibility | Limit the candidate must explain |
|---|---|---|
| Hosted service | Runs work under the host lifecycle and receives shutdown notification. | Unexpected process loss may bypass graceful cleanup. |
| Bounded in-memory channel | Buffers local demand and applies producer backpressure. | Queued items do not survive process termination. |
| Durable job record | Tracks requests, state, attempts, and committed checkpoints. | Requires atomic transitions and reliable storage configuration. |
| Lease with fencing | Coordinates ownership across worker instances. | A lease alone cannot prevent stale external side effects. |
| Idempotent publish step | Makes repeated completion attempts converge on one visible result. | Does not imply that underlying execution happened exactly once. |

Worked Hypothetical: A Cancellable Booking Export
Illustrative scenario: A fictional travel agency requests an export of 12,000 booking rows for its internal reconciliation team. The platform creates job EXP-2048, captures the requested date range and tenant, and records status Pending. The intended result is a manifest referencing immutable export parts, not a single mutable file that becomes visible before it is complete. All figures and identifiers here are hypothetical, not a customer implementation or measured performance claim.
Accept, Claim, and Checkpoint Progress
The web endpoint validates authorization, inserts the durable record using a client request key to avoid accidental duplicate submissions, commits it, and responds with a job identifier. A worker queries eligible records and conditionally claims EXP-2048, setting owner worker-A, generation 7, lease expiry, and status Running. The worker opens a fresh dependency-injection scope for its database operations.
For this exercise, the developer chooses batches of 500 rows, ordered by a stable booking key within a fixed export snapshot. The snapshot rule matters: a simple offset over changing data could skip or repeat bookings. Each successful batch becomes an immutable part identified by job, generation-independent batch range, and content checksum. The worker records the part's committed identity and its next cursor in a transaction that verifies generation 7.
After eight batches, the durable checkpoint represents 4,000 rows. The manifest remains unpublished, so a consumer cannot mistake those eight parts for the final export. A progress screen may show 4,000 of 12,000 committed with status Running. It must not equate rows read in memory with rows safely stored.
Interrupt During the Ninth Batch
Now a deployment requests graceful shutdown while the ninth batch is being written. The BackgroundService stopping token becomes canceled. The worker stops acquiring new batches and passes the token to supported reads and writes. Assume the current temporary part is incomplete and has not been committed to the job manifest. The worker disposes the stream and leaves the durable cursor at 4,000 rather than claiming progress that was never finalized.
If time permits, it may record an interruption reason and release its claim using a generation-checked update. If shutdown interrupts that update, the record still has generation 7 and a lease that will eventually expire. This is acceptable because recovery does not depend on a final shutdown callback. A test that only observes a graceful log line would miss this distinction.
Restart, Reconcile, and Complete
After the old lease expires, worker-B claims the job at generation 8. It first checks the eight committed part references, their checksums, the export snapshot, and any orphaned temporary file. It discards or quarantines the incomplete ninth part according to a documented retention rule. It starts again from the last committed cursor, not from a guessed in-memory count.
Suppose the resumed ninth batch encounters a transient storage error. The worker uses a limited retry policy with cancellation-aware delays, then either completes that batch or leaves the job eligible for a later scheduled attempt. It does not immediately retry indefinitely, reset progress to zero, or publish a partial manifest. A permanent validation error instead records a reviewable failure with enough diagnostic context to locate the affected booking.
Once the remaining batches are committed, the current owner conditionally publishes one final manifest and moves the record to Completed. The publication operation checks both the ownership generation and a unique final artifact identity. If a response is lost after publication, reconciliation reads the existing manifest before attempting to publish again. The visible result contains 12,000 eligible booking rows, although a batch might have been attempted more than once.
This exercise tests the limits of the claim. It does not promise exactly-once execution or presume that every remote storage operation is transactional with the job database. The developer must identify which part writes are repeatable, which records prove commitment, and how the system reacts if publication succeeds but its acknowledgment is lost.
Make Retries Finite and Uncertain Outcomes Reconcilable
Retry design should start with an error classification table in the candidate's own reasoning, not a generic statement that transient errors will be retried. Distinguish cancellation, rate limiting, network interruption, invalid data, authorization failures, and a dependency that is unavailable for an extended period. Each class needs a stated response: stop, retry, defer, fail, or flag for operator review.
Set two limits: a short cap for attempts within one ownership period and a durable total-attempt or elapsed-time cap across restarts. Without the latter, an apparently bounded loop can restart forever. Use capped exponential backoff with jitter when appropriate, respect documented server retry hints when available, and persist the next eligible attempt time. Never make that wait ignore host cancellation.
The highest-risk case is an ambiguous outcome. A timeout after an upload may mean nothing was stored, or it may mean storage succeeded and the acknowledgment was lost. Reconciliation should query by a deterministic part identifier and verify metadata or checksum before deciding whether another write is needed. Retrying blindly can create duplicate side effects even when the code uses an apparently safe retry library.
Job state should remain meaningful after attempts are exhausted. A state such as NeedsReview can distinguish a booking data problem from an infrastructure interruption. Store a sanitized error category, attempt history, checkpoint, and safe diagnostic identifiers. Do not persist customer-sensitive payloads in general-purpose logs merely to make troubleshooting convenient.
Operators also need a deliberate re-drive policy. A manual retry should respect the original request key and export snapshot, or create a clearly linked new job if requirements changed. A repair tool should never silently reset committed progress. For a cancellation-aware worker, predictability means being able to explain both when it resumes automatically and when it intentionally stops for a person.
Require Shutdown Evidence, Not Architectural Assurances
Define Tests That Cross the Process Boundary
Ask candidates for a small runnable repository, seed data, and test instructions using dotnet test or an equivalent repeatable command. Unit tests for a cancellation-aware method are useful, but the decisive evidence includes a process-level test that starts the host, submits a job, waits for a committed checkpoint, requests termination, and starts another worker against the same durable state.
One test must initiate a normal host stop while I/O is active. It should show no fresh batch begins after cancellation is observed, the current attempt exits within a declared budget under controlled dependency behavior, and the job is not marked complete. Record the command, process exit, timestamps, checkpoint before and after, and relevant logs. A passing assertion without these observations is weak evidence.
A second test must forcibly terminate the worker without running cleanup, then restart it. The test should deliberately place termination between artifact creation and checkpoint commitment. Expected behavior includes expired-lease recovery, orphan examination, safe replay, and a single final manifest. This catches candidates who put all correctness in StopAsync.
A third test should run two workers against the same pending job and pause one beyond its lease. After another worker acquires a newer generation, the older worker's conditional checkpoint or publish attempt must fail. If an external destination cannot enforce an ownership fence, the candidate must demonstrate the idempotency or reconciliation mechanism that limits stale writes.
Inspect Artifacts and Measurable Assertions
Request a test report with actual exit codes, job-state transitions, lease generations, committed row counts, remaining temporary artifacts, and retry counts. Capture structured events that correlate job identifier, attempt, owner, generation, checkpoint, cancellation reason, and elapsed time. The evidence should be reproducible on a clean checkout with configuration values documented and secrets excluded.
Require failure injection rather than merely a slow computer. A fake repository can pause just before a conditional checkpoint; a controllable storage adapter can acknowledge a write and then simulate a lost response. Tests should verify final content and row uniqueness, not just the number of successful method calls. Observability should help an operator distinguish a healthy drain from a hung shutdown.
Discuss host timeout and deployment termination settings explicitly. The candidate should demonstrate what happens when the configured grace period is shorter than the longest in-flight operation, and how cancellation-aware dependencies respond. A local test cannot prove every production platform's termination behavior; it can prove the application's choices and document the remaining operational assumptions.
Interview Questions That Distinguish Implementation Skill
Give the candidate the hypothetical export and ask for a diagram containing the endpoint, durable job record, claim transaction, worker loop, artifact store, and reconciliation pass. Then interrupt the diagram at three moments: before a claim, after a part upload but before checkpointing, and after final publication but before recording its acknowledgment. In each case, ask what the next owner sees and how it decides what to do.
Strong candidates state assumptions and use precise language. They distinguish a host cancellation signal from a customer-requested cancellation; the latter may need its own durable flag and authorization policy. They ask whether exports can be resumed from a stable snapshot, whether artifacts can be addressed deterministically, and whether more than one worker instance may run. Those questions expose requirements that decide correctness.
Be cautious of responses that use Task.Run from a request handler as the complete solution, store only an in-memory queue, swallow OperationCanceledException as success, or claim a lease makes duplicates impossible. Also examine a candidate who promises exactly-once processing without identifying a shared transaction boundary or showing how ambiguous external outcomes are resolved.
Scoring should consider observable behavior: cancellation reaches dependencies; checkpoints reflect committed work; stale owners cannot advance durable state; retries are finite; restart reconciles uncertain artifacts; and tests genuinely cross shutdown and restart. Code readability and operational documentation matter because the next engineer must diagnose a job started by someone else.
Set a Clear Acceptance Standard Before Hiring
Ask for the architecture sketch, runnable project, automated shutdown tests, and a short operator runbook as one assessment package. The runbook should describe how to find a stuck export, interpret its checkpoint, inspect an expired lease, and re-drive it without silently overwriting a prior result. It should also state the chosen retry limits, shutdown budget, artifact retention rule, and the assumptions behind recovery.
TravelTech365 recommends making those questions central to technical evaluation of background processing work. Developers who can demonstrate safe cancellation and accountable resumption are better positioned to build booking exports and similar operational jobs that remain understandable when real deployment conditions interrupt them.
