Modelling non-CRUD operations: state transitions as action endpoints, sub-resources or PATCH, and the asynchronous request-reply pattern (202 Accepted, Location/Operation-Location, status resource, Retry-After, result link) implemented in ASP.NET Core 10 with a background worker.
Treat state transitions with business rules as commands: POST /orders/{id}/cancellation (a sub-resource, or /cancel if you prefer verbs for actions) makes intent explicit, lets you validate and authorise that transition, and returns 409 Conflict when it isn't allowed. PATCH {"status":"Cancelled"} looks RESTful but hides intent and invites invalid transitions.
For long-running work, use the asynchronous request-reply pattern: return 202 Accepted with a Location (or Operation-Location) pointing at a status resource and a Retry-After header; a background worker does the job and updates the status (Running, Succeeded, Failed), and the finished status links to the result. The trade-off is extra state and polling versus holding HTTP requests open and hitting gateway timeouts.
"Not everything is create, read, update, delete. Cancelling an order, approving a claim or refunding a payment are state transitions with rules: you can only cancel before shipping, only a manager can approve, refunds must not exceed the charge. I model those as commands. My preference is a noun sub-resource,
POST /orders/{id}/cancellationwith an optional reason in the body, thoughPOST /orders/{id}/cancelis common and fine if the team agrees on it. Either way the handler loads the aggregate, callsorder.Cancel(reason), and if the transition isn't valid I return 409 Conflict with a ProblemDetails body explaining why. I avoidPATCH {\"status\": \"Cancelled\"}, because it turns a business operation into a field edit: the endpoint has to work out which transition was requested, every transition shares one authorisation policy, and clients can try to jump straight toShipped.Long-running operations need a different shape. If generating a report or importing a file takes minutes, I can't hold the request open: Azure Front Door and App Service gateways time out at around four minutes, and clients give up sooner. So the API accepts the request, stores an operation record, queues the work, and returns 202 Accepted with a
Locationheader pointing at/operations/{id}and aRetry-Afterof a few seconds. The client polls that status resource; it saysRunningwith progress, thenSucceededwith a link to the result, orFailedwith a ProblemDetails error. In ASP.NET Core I'd use aChanneland aBackgroundServicefor a simple service, and Azure Service Bus with a separate worker when I need durability and scale. Azure's own APIs use the same pattern withOperation-Location.The mistake I see is fire-and-forget
Task.Runinside the controller with no status at all, so when the pod restarts the work silently disappears. The operation has to be a persisted resource, and starting it should be idempotent so a retried POST doesn't start the job twice."
| Option | Example | Pros | Cons |
|---|---|---|---|
| Action sub-resource (noun) | POST /orders/42/cancellation |
Explicit intent, own validation and auth, can be a resource you GET later | More endpoints |
| Action endpoint (verb) | POST /orders/42/cancel |
Very clear, common in practice (Stripe, GitHub) | Purists object to verbs |
| PATCH status | PATCH /orders/42 {"status":"Cancelled"} |
Fewer endpoints | Hides intent, invalid transitions, one auth policy for all |
| PUT whole resource | PUT /orders/42 {...status...} |
Simple CRUD | Worst: every transition is a full replace |
| Step | Request | Response |
|---|---|---|
| Start | POST /reports |
202 Accepted, Location: /operations/7f3, Retry-After: 5 |
| Poll | GET /operations/7f3 |
200 {"status":"Running","percentComplete":40}, Retry-After: 5 |
| Done | GET /operations/7f3 |
200 {"status":"Succeeded","resourceLocation":"/reports/91"} |
| Failed | GET /operations/7f3 |
200 {"status":"Failed","error":{...ProblemDetails...}} |
| Cancel | POST /operations/7f3/cancel |
202 or 409 if already finished |
A [statement export] endpoint generated PDFs synchronously and took [30-300 s]. Behind Azure Front Door, [~8%] of large exports failed with 504s, and users retried, multiplying load. Moving to 202 + an operation resource with a Service Bus-backed worker removed the 504s, and deduplicating starts with an idempotency key cut export volume by [~20%].
Checks whether the candidate can model business operations beyond CRUD and implement the asynchronous request-reply pattern correctly in ASP.NET Core.
Green flags
Red flags
Task.RunGET /orders/{id}/cancelPATCH /orders/42 {"status":"Cancelled"}
handler must infer: which transition? from which state? who may do it?
POST /orders/42/cancellation {"reason":"customer request"}
handler knows: Cancel transition -> policy "CanCancelOrder" -> order.Cancel(reason)
In a rich domain model each transition is a method that enforces its invariants (Cancel throws or returns a failure if Status == Shipped). The endpoint maps a domain failure to 409 Conflict. Concurrency is handled with a rowversion and If-Match (412) or by retrying the command against fresh state.
Client --> Front Door (240 s origin timeout) --> App Service (230 s front-end timeout) --> API
Every hop has a timeout, mobile networks drop connections, and a request thread or connection held for minutes reduces capacity. A dropped connection also loses the result and invites a retry that starts the work again.
POST /reports ----------------> API: insert Operation(NotStarted), enqueue job
<---- 202, Location: /operations/7f3, Retry-After: 5
Worker: dequeue -> Running -> ... -> Succeeded(resource /reports/91)
GET /operations/7f3 ----------> 200 {status: Running}
GET /operations/7f3 ----------> 200 {status: Succeeded, resourceLocation: /reports/91}
GET /reports/91 --------------> 200 report
The Azure REST API guidelines use Operation-Location for the status monitor and a terminal set of statuses (Succeeded, Failed, Canceled). Some APIs return 303 See Other from the status resource once complete; returning 200 with a resourceLocation field is simpler for clients and proxies.
| Option | Durability | Scale | Use when |
|---|---|---|---|
Channel<T> + BackgroundService |
Lost on restart unless persisted and re-queued at start-up | One instance | Small services, tolerable re-run |
| Azure Service Bus queue + worker | Durable, retries, DLQ | Scale out (KEDA on queue length) | Production default |
| Durable Functions | Durable orchestration, built-in status endpoint | Serverless | Multi-step workflows |
Persist the operation record in the database either way, so status survives restarts and any instance can answer the poll.
Accept an Idempotency-Key (or a client-supplied operation id with PUT /operations/{id}) so a retried start returns the existing operation. For cancellation, the worker observes a CancellationToken linked to a cancel flag on the operation.
Polling is simple and works everywhere. For better UX, add a webhook callback or SignalR notification on completion, but keep the status resource as the source of truth.
POST /orders/{id}/cancellation with a domain method and return 409 for shipped orders; write tests for both paths.Running/NotStarted operations at start-up.Idempotency-Key to the start endpoint and send it twice.A state transition as a command, and a long-running operation with 202 Accepted, a status resource and a BackgroundService reading from a Channel.
// Program.cs (.NET 10)
using System.Collections.Concurrent;
using System.Threading.Channels;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<OperationStore>();
builder.Services.AddSingleton(Channel.CreateBounded<Guid>(new BoundedChannelOptions(100) { FullMode = BoundedChannelFullMode.Wait }));
builder.Services.AddHostedService<ReportWorker>();
var app = builder.Build();
// 1. State transition as a command with its own rules.
var orders = new ConcurrentDictionary<int, Order>(new Dictionary<int, Order> { [42] = new(42, "Pending") });
app.MapPost("/orders/{id:int}/cancellation", (int id, CancelOrder body) =>
{
if (!orders.TryGetValue(id, out var order)) return Results.NotFound();
if (order.Status is "Shipped" or "Cancelled")
return Results.Problem(statusCode: StatusCodes.Status409Conflict,
title: "Order cannot be cancelled", detail: $"Order is {order.Status}.");
orders[id] = order with { Status = "Cancelled" };
return Results.Ok(orders[id]);
});
// 2. Long-running operation: accept, persist, queue, return 202 + status location.
app.MapPost("/reports", async (ReportRequest req, OperationStore store, Channel<Guid> queue, HttpResponse res, CancellationToken ct) =>
{
var op = store.Create(req);
await queue.Writer.WriteAsync(op.Id, ct); // bounded: applies back-pressure instead of unbounded memory
res.Headers.RetryAfter = "5";
return Results.Accepted($"/operations/{op.Id}", op);
});
app.MapGet("/operations/{id:guid}", (Guid id, OperationStore store, HttpResponse res) =>
{
if (store.Get(id) is not { } op) return Results.NotFound();
if (op.Status is OperationStatus.NotStarted or OperationStatus.Running) res.Headers.RetryAfter = "5";
return Results.Ok(op);
});
app.Run();
public sealed record Order(int Id, string Status);
public sealed record CancelOrder(string? Reason);
public sealed record ReportRequest(DateOnly From, DateOnly To);
public enum OperationStatus { NotStarted, Running, Succeeded, Failed, Canceled }
public sealed record Operation(Guid Id, OperationStatus Status, int PercentComplete, string? ResourceLocation, string? Error);
// In production this is a table, so status survives restarts and any instance can answer the poll.
public sealed class OperationStore
{
private readonly ConcurrentDictionary<Guid, Operation> _ops = new();
public Operation Create(ReportRequest _) { var op = new Operation(Guid.CreateVersion7(), OperationStatus.NotStarted, 0, null, null); _ops[op.Id] = op; return op; }
public Operation? Get(Guid id) => _ops.GetValueOrDefault(id);
public void Update(Operation op) => _ops[op.Id] = op;
}
public sealed class ReportWorker(Channel<Guid> queue, OperationStore store, ILogger<ReportWorker> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var id in queue.Reader.ReadAllAsync(stoppingToken))
{
var op = store.Get(id)!;
try
{
for (var pct = 0; pct <= 100; pct += 25)
{
store.Update(op = op with { Status = OperationStatus.Running, PercentComplete = pct });
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken); // stand-in for real work
}
store.Update(op with { Status = OperationStatus.Succeeded, ResourceLocation = $"/reports/{id}" });
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
log.LogError(ex, "Report {OperationId} failed", id);
store.Update(op with { Status = OperationStatus.Failed, Error = "Report generation failed." });
}
}
}
}
curl -i -X POST localhost:5000/reports -H 'Content-Type: application/json' -d '{"from":"2026-10-01","to":"2026-10-31"}'
# HTTP/1.1 202 Accepted
# Location: /operations/0193...
# Retry-After: 5
PATCH {"status": ...}. Why it is wrong: The server must infer the transition, invalid jumps are easy, and every transition shares one authorisation rule. Instead: A command endpoint per transition (POST /orders/{id}/cancellation).Task.Run fire-and-forget in the endpoint. Why it is wrong: Work is lost on restart or scale-in, exceptions vanish, and scoped services (DbContext) are disposed under it. Instead: Queue to a BackgroundService or Service Bus worker and persist the operation.Retry-After on 202 or running status. Why it is wrong: Clients poll in tight loops and add load. Instead: Send Retry-After and document the polling contract.The key judgement is recognising business commands disguised as field updates. If a change has rules, side effects or its own permissions, it deserves its own endpoint; generic PATCH is for plain data. Separate commands also make security reviewable: each one maps to an authorisation policy that can look at the resource's state (a resource-based IAuthorizationService.AuthorizeAsync(user, order, "CancelOrder") check), so "customers can cancel their own pending orders, support staff can cancel paid ones" is explicit and testable instead of buried in a PATCH handler's branching. Pragmatically, I care less about noun-vs-verb purity (/cancellation vs /cancel) than about consistency across the API and documenting each command's 409 error codes and required permissions in the OpenAPI document.
For long-running work, the operation resource is a contract: terminal states, polling interval, retention period of results, and cancellation semantics should all be documented. Its state lives in shared storage owned by the API, not inside the worker process, so workers can crash, scale or be replaced without losing track of operations. I measure queue depth and age, operation duration percentiles, failure rates and how many polls each operation receives (a high number means Retry-After is too short or ignored).
| Approach | When it fits | Cost | When not |
|---|---|---|---|
| Synchronous 200 | Work under ~1-2 s | Simple | Variable or long work |
| 202 + status resource (polling) | Minutes-long jobs, any client | Operation store, polling load | Real-time UX needs push |
| 202 + webhook / SignalR callback | Partners or UIs wanting push | Callback security, retries | Clients behind firewalls |
| Durable Functions orchestration | Multi-step workflows with waits | Platform lock-in, learning curve | Simple single-step jobs |
A hosted service is a class the .NET Generic Host starts and stops with the application. IHostedService gives you StartAsync and StopAsync. BackgroundService is the base class most people use: you override one method, ExecuteAsync(CancellationToken stoppingToken), and loop until the token is cancelled at shutdown. You register it with AddHostedService<T>(), as a singleton, so you use IServiceScopeFactory to get scoped services like a DbContext. In .NET 10 the whole of ExecuteAsync runs on a background task, so it doesn't delay start-up. On shutdown the host cancels the token and waits up to HostOptions.ShutdownTimeout (30 seconds by default). The Worker Service template is the same host without a web server, for queue consumers and scheduled jobs.
The trade-off: running inside your API is simple, but a separate worker scales and fails independently.
The Richardson maturity model grades HTTP APIs: level 0 is one endpoint doing RPC (everything POSTed to /api), level 1 adds resources (/orders/42), level 2 uses HTTP methods and status codes properly, and level 3 adds hypermedia controls (HATEOAS): responses include links describing what the client can do next.
Hypermedia lets the server drive workflows (no cancel link once an order ships) and move URLs without breaking clients. In practice most production APIs are level 2 plus OpenAPI, with targeted hypermedia where it clearly removes client logic: next links for paging, Location for created resources and status URLs for long-running operations. Full HATEOAS costs richer media types and smarter clients, which few teams get a return on.
A safe method (GET, HEAD, OPTIONS) asks for no state change; an idempotent one has the same effect on server state however many times it's repeated (safe methods plus PUT and DELETE). They matter because a timeout is ambiguous: the server may have done the work. Resilience handlers, gateways, service meshes and browsers retry on that basis, so only idempotent requests can be retried blindly.
When a write must be retryable but isn't naturally idempotent (creating an order, taking a payment), you design idempotency in: PUT to a client-generated id, conditional requests with If-Match, an Idempotency-Key header that replays the stored result, or a unique constraint on a natural key. The trade-off is extra storage and complexity versus duplicate orders and double charges.
How to tell it (STAR)
**S:** At [company], statement exports ran synchronously and took up to five minutes, so about [8%] failed with 504s at month-end and customers retried, adding even more load. **T:** I was asked to make exports reliable before the next month-end. **A:** I confirmed in Application Insights that failures clustered at the App Service 230-second timeout and that retries restarted the same work. I redesigned the endpoint to return 202 with an operation resource, moved generation to a Service Bus-backed worker scaled with KEDA, stored results in Blob Storage, and made starts idempotent with a key from the UI. **R:** 504s on exports went to [zero], duplicate exports fell by [~20%], and month-end CPU on the web tier dropped by [about half].
Last updated 23 Nov 2026.