📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you model operations that aren't simple CRUD in a REST API? Compare POST /orders/{id}/cancel, a cancellation sub-resource and PATCH on a status field for state transitions, and show how you implement a long-running operation in ASP.NET Core with 202 Accepted, a status resource, Retry-After and a final result.

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.

Mid-Level Coding Intermediate aspnet-core background-service long-running-operations rest state-transitions web-api

🎯 Key points

  • State transitions with business rules are commands: POST /orders/{id}/cancellation (or /cancel), not PATCH {status}
  • PATCH {status: Cancelled} hides intent, invites invalid transitions and makes per-transition authorisation and validation awkward
  • Each command gets its own authorisation policy (e.g. customer may cancel own pending order, only support may cancel after payment) checked against the resource's current state
  • Invalid transition -> 409 Conflict with ProblemDetails and an error code; stale state -> 412 Precondition Failed with If-Match/rowversion
  • Long-running work: 202 Accepted + Location (or Operation-Location) to a status resource, Retry-After for polling interval
  • Status resource persisted independently of the worker: status (NotStarted/Running/Succeeded/Failed/Canceled), timestamps, error, link to result
  • Do the work out of the request: Channel + BackgroundService locally, Azure Service Bus + worker in production
  • Make the start idempotent (Idempotency-Key or client operation id), offer cancellation, and document commands, 409 codes and terminal states in OpenAPI

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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}/cancellation with an optional reason in the body, though POST /orders/{id}/cancel is common and fine if the team agrees on it. Either way the handler loads the aggregate, calls order.Cancel(reason), and if the transition isn't valid I return 409 Conflict with a ProblemDetails body explaining why. I avoid PATCH {\"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 to Shipped.

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 Location header pointing at /operations/{id} and a Retry-After of a few seconds. The client polls that status resource; it says Running with progress, then Succeeded with a link to the result, or Failed with a ProblemDetails error. In ASP.NET Core I'd use a Channel and a BackgroundService for 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 with Operation-Location.

The mistake I see is fire-and-forget Task.Run inside 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."


Modelling state transitions

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

Long-running operation flow

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

Production example

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%].

🔍 What the interviewer is checking

Checks whether the candidate can model business operations beyond CRUD and implement the asynchronous request-reply pattern correctly in ASP.NET Core.

Green flags

  • Treats transitions as commands and returns 409 for invalid ones
  • Explains why PATCH on status is risky
  • Uses 202 + Location/Operation-Location + Retry-After and a persisted status resource
  • Runs the work outside the request (BackgroundService/Service Bus) and makes the start idempotent

Red flags

  • Holds requests open for minutes or uses fire-and-forget Task.Run
  • Status kept in memory across multiple instances
  • Uses GET /orders/{id}/cancel

📚 Learn in depth

1. Commands vs field updates

PATCH /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.

2. Why not hold the request open?

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.

3. The asynchronous request-reply pattern

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.

4. Where the work runs

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.

5. Idempotent starts and cancellation

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.

6. Push instead of poll

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.

Try it yourself

  1. Implement POST /orders/{id}/cancellation with a domain method and return 409 for shipped orders; write tests for both paths.
  2. Build the report endpoint below, start a job, kill the process mid-run, restart, and see what happens to the operation; then add re-queuing of Running/NotStarted operations at start-up.
  3. Measure how long a synchronous 5-minute request survives behind your gateway (App Service, Front Door, YARP).
  4. Add an Idempotency-Key to the start endpoint and send it twice.

💻 Code

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

⚠ Common mistakes

  • Mistake: Modelling transitions as 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).
  • Mistake: Returning 400 for a valid request that conflicts with current state. Why it is wrong: The request is well-formed; the resource's state is the problem. Instead: 409 Conflict with ProblemDetails explaining the state.
  • Mistake: Holding a request open for minutes. Why it is wrong: Gateways time out (App Service ~230 s), connections drop, and retries restart the work. Instead: 202 Accepted plus a status resource.
  • Mistake: 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.
  • Mistake: Keeping operation status only in memory with multiple instances. Why it is wrong: The poll may hit an instance that doesn't know the operation, returning 404. Instead: Store operations in a shared database or cache.
  • Mistake: No 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.
  • Mistake: Non-idempotent start. Why it is wrong: A retried POST starts the expensive job twice. Instead: Idempotency key or client-supplied operation id.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate uses a BackgroundService for the work Why: Checks hosted service lifecycle and shutdown behaviour
    How to answer

    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.

  2. When: Candidate returns a status URL or allowed actions Why: Checks whether status and allowed actions could be exposed as links
    How to answer

    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.

  3. When: Candidate mentions a client retrying the POST Why: Checks how they make the start request safe to retry
    How to answer

    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.

🛠 Real-world problems: how you handle them

Statement exports failing with 504s behind Azure Front Door
Situation
A [banking portal] let customers export statements as PDFs. Generation took [30-300 s] depending on the date range, and the endpoint ran synchronously on Azure App Service behind Azure Front Door. [~5,000] exports ran per day, peaking at month-end.
Signals
Front Door logs showed 504s on `POST /statements/export` for [~8%] of requests; App Service showed long-running requests and rising CPU at month-end; support tickets said "export spins then fails"; the same customer often appeared several times in a minute.
Investigation
Application Insights `requests` showed durations clustered just under 230 s for failures, matching the App Service front-end timeout. Correlating by user id showed retries starting the same export again. A dotnet-counters session showed many requests in flight during peaks, and the dependency view showed the PDF library dominating time.
Resolution
Immediate: the UI limited date ranges and disabled the button after click. Real fix: `POST /statements/exports` returns 202 with `Location: /operations/{id}` and `Retry-After: 5`; the request is stored in an `Operations` table and queued on Service Bus; a worker on Container Apps (scaled by KEDA on queue length) generates the PDF to Blob Storage and marks the operation `Succeeded` with a short-lived download link. Starts accept an `Idempotency-Key`.
Prevention
An API guideline: anything over 2 s p95 uses the async pattern; alerts on queue age and operation failure rate; load tests at month-end volume; contract tests for the operation status schema.

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].

↩ Usually asked after

More in REST

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me