Resilience and observability
Background work and queues
Moving work that should not keep the user waiting out of the request path.
Understand the concept
Some work should not fit into the time a user waits for a response: sending e-mail, resizing images, generating reports, posting to social media. Doing it inside the request slows the response, and a failing external service fails the user’s action too. The answer is for the request to merely ‘record the work’ while the real work happens in the background.
In ASP.NET Core a BackgroundService is a long-lived loop that starts with the app. With a simple queue (Channel) the request enqueues work and the background service picks it up. An in-memory queue, however, loses its contents if the app restarts. Work that must not be lost is written somewhere durable: an ‘outbox’ table in the database or a message queue (RabbitMQ, Azure Service Bus).
The outbox pattern solves an important problem: the database change and the ‘send e-mail’ job are written to the outbox table in the same transaction. The change can never succeed while the e-mail job is lost, or the other way round. The background job reads the outbox, sends and marks successes. This project’s publishing automation and social sharing logs follow similar logic, keeping failures retryable.
Slow or unreliable work must not harm user experience or data consistency.
Starting fire-and-forget work with Task.Run from a request; the scope and DbContext vanish when the request ends and errors are lost.
One topic. Three levels of depth.
// İstek: yalnız kaydet ve hemen yanıt ver
await db.Messages.AddAsync(message, ct);
await db.SaveChangesAsync(ct);
return Accepted(); // 202: kabul edildi, işlem sürüyor202 Accepted says the work was received but is not finished yet.
This page connects to no real server or database. Code samples are illustrative for .NET 8, Next.js and SQL Server; timings are example values in the simulation, not measurements. Try samples only in your own development environment; never share real connection strings, tokens or passwords.
Try it yourself first.
When the contact form is sent, the message is saved and an e-mail is sent to you. When the SMTP server stalls for 10 seconds the user sees ‘error’ although the message was saved. How do you redesign it?
Show the solution and explanation
1) İstek: mesajı + 'bildirim gönder' işini aynı transaction’da yaz (outbox), hemen 201/202 dön.
2) Arka plan işi: outbox’tan alıp e-postayı gönderir; hata olursa artan aralıklarla tekrar dener.
3) Kullanıcı yalnız kendi işleminin (mesajın kaydı) sonucunu görür.Separating the user’s action from side effects stops an external failure from surfacing as a false error.