An ASP.NET Core photo site queues thumbnail jobs in an in-memory Channel; why are jobs lost on deploys and crashes, and how do you drain them or make them durable?
answer
- the buffer lives in process memory
- at-most-once across restarts
- server stops before your services
- Writer.TryComplete(), then drain
- persist intent first, re-enqueue on start
basics
~20 sQueued jobs exist only in process memory, so the queue is at-most-once: a crash, kill or overrun shutdown loses them. Drain on graceful stop by completing the writer and reading until empty; when loss is unacceptable, record each job durably first.
solid answer
~50 sA `Channel<T>` is a buffer in the process's memory, so every restart drops what is queued: a crash or `OutOfMemoryException` loses everything, and a graceful stop loses whatever the consumer abandons when `stoppingToken` cancels `ReadAllAsync`. Graceful deploys can be fixed: the web server stops first (hosted services stop in reverse registration order and the server is registered last), so the consumer's `StopAsync` override calls `Writer.TryComplete()` and then `base.StopAsync`, while `ExecuteAsync` reads with `ReadAllAsync()` without the stopping token and drains until the channel reports completion, bounded by `HostOptions.ShutdownTimeout`. Crashes cannot be fixed in memory. Persist the intent first: save the photo with a `ThumbnailsPending` status, treat the channel as a wake-up, re-enqueue pending rows at start-up, and make rendering idempotent. When jobs need retries, visibility or sharing across replicas, move to a durable job store or message broker.
code
csharp · 17 linespublic sealed class ThumbnailWorker(Channel<ThumbnailJob> channel, ThumbnailRenderer renderer) : BackgroundService
{
public override async Task StopAsync(CancellationToken cancellationToken)
{
channel.Writer.TryComplete(); // refuse new jobs
await base.StopAsync(cancellationToken); // waits for the drain, up to the shutdown timeout
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// No stopping token here: keep reading until the channel is completed and empty.
await foreach (var job in channel.Reader.ReadAllAsync())
{
await renderer.RenderAsync(job.PhotoId, CancellationToken.None);
}
}
}go deeper
Recall that a Channel lives in memory, so queued jobs disappear whenever the process restarts.
Explain the shutdown order, why ReadAllAsync(stoppingToken) abandons the buffer, and how TryComplete plus a tokenless read drains it.
Design for crashes as well as deploys: persist intent before responding, sweep pending work at start-up, keep rendering idempotent, and size capacity to the shutdown window.
Decide when the cost of a durable store or broker is justified by the cost of lost or delayed work, and document the delivery guarantee the team is accepting.
## Why the queue is at-most-once A `Channel<T>` holds its items in an in-memory buffer inside one process. Nothing writes them to disk. Each queued thumbnail job is therefore delivered **at most once**: if the process ends before the consumer reads it, it is gone, and nothing records that it ever existed. The process ends more often than people assume: - every deployment replaces the process; - an orchestrator kills it when a health probe fails or a node is drained; - an unhandled exception in any `BackgroundService` stops the host by default; - out-of-memory, a crash, or a forced kill after the grace period. The last group gives no chance to clean up. The first group is a **graceful** shutdown, and there the loss is a design choice. ## What a naive consumer does at shutdown With `await foreach (var job in reader.ReadAllAsync(stoppingToken))`, shutdown cancels `stoppingToken`, `ReadAllAsync` throws `OperationCanceledException`, and the loop exits with items still buffered. Clean for the host; lost for the users. ## Draining on a graceful stop The stop order makes draining possible. `WebApplicationBuilder.Build()` registers the web server's hosted service after yours, and the host stops hosted services in reverse order, so: 1. the server stops accepting requests first, and no new jobs arrive; 2. your consumer's `StopAsync` runs next and calls `channel.Writer.TryComplete()`; any late write now gets `false` from `TryWrite` or a `ChannelClosedException` from `WriteAsync`; 3. `base.StopAsync` cancels `stoppingToken` and waits for `ExecuteAsync`; 4. `ExecuteAsync` reads with `ReadAllAsync()` **without** the stopping token, so it keeps going until the buffer is empty and the channel reports completion, then returns. The whole drain must fit in `HostOptions.ShutdownTimeout` (30 seconds by default, shared with every other service) and in the orchestrator's grace period. A queue of 500 jobs at two seconds each will not fit: capacity also bounds how much a deploy can lose. ## Surviving crashes: persist the intent Memory cannot survive a crash, so the durable fact must be written before the response: - in the upload request's own transaction, save the photo row with `ThumbnailStatus = Pending`; - write the job to the channel as a **hint** to start now; - when rendering succeeds, set the status to `Done`; - at start-up, and periodically, query rows still `Pending` beyond a grace period and re-enqueue them. This turns at-most-once into **at-least-once**: a job can now run twice, for example when the process dies after rendering but before saving `Done`. So rendering must be **idempotent**: write thumbnails to deterministic blob names that a second run overwrites. ## Checklist for a channel you keep - Bounded capacity sized so a full drain fits the shutdown window. - `TryComplete` in the consumer's `StopAsync`, tokenless `ReadAllAsync` in `ExecuteAsync`. - A durable status written in the request's transaction, and a start-up sweep for stale pending rows. - Idempotent processing, and logs or metrics for jobs re-enqueued by the sweep. ## When to leave the channel behind | Need | In-memory channel | Durable store or broker | |---|---|---| | survive a crash | no | yes | | share work across replicas | no, each process has its own | yes | | retries with back-off, dead-lettering | hand-written | built in | | visibility into pending and failed jobs | hand-written | dashboards, queue metrics | | zero infrastructure | yes | no | A persistent job library or a message broker earns its keep once two or three of the right-hand needs are real. Until then, a channel plus a status column is a sound, cheap design.
- What happens to an upload request that writes to the channel after TryComplete has been called?`TryWrite` returns `false` and `WriteAsync` fails with `ChannelClosedException`. In practice it is rare, because the web server's hosted service stops before yours and stops accepting requests first. Still, an endpoint should handle the failure, and with the status-column design the photo row is already `Pending`, so the start-up sweep renders it later.
- Why does persisting a Pending status turn the queue into at-least-once, and what does that demand from the renderer?A pending row survives any crash, and the sweep re-enqueues it, so no job is forgotten. But the process can die after rendering and before marking `Done`, so the same job may run again. The renderer must therefore be idempotent, for example writing thumbnails to deterministic names that a repeat simply overwrites.
- Channel<T> flushes its buffer to disk when the host stops
- Pass stoppingToken to ReadAllAsync and every queued job still gets processed
- Writer.TryComplete() discards the items already in the buffer
- A graceful drain also protects against crashes and forced kills
- With a Pending status column, each job runs exactly once