Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 3 · Lesson 22 · 6 min read

ASP.NET Core Status Codes and Idempotency

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: An Idempotency Filter for POST
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Apply the semantics of GET, POST, PUT, PATCH and DELETE precisely, choose accurate status codes for success and failure, and implement idempotency keys so a client can safely retry a non-idempotent operation after a timeout.

Concept Explanation

HTTP methods carry meaning that intermediaries such as browsers, caches, proxies, and crawlers rely on. Two properties matter most. A safe method does not change server state: GET, HEAD, and OPTIONS are safe. An idempotent method has the same effect whether it is applied once or many times: GET, HEAD, PUT, and DELETE are idempotent, while POST is not, and PATCH is not guaranteed to be. Safety is the reason you must never change data in a GET handler. Browsers prefetch links, search engine crawlers follow them, and antivirus scanners open URLs in emails, and all of that traffic is assumed harmless. A state-changing GET also removes the protection that makes cross-site request forgery harder, because a simple image tag can trigger it.

Idempotency answers a question every distributed system asks: what happens if the client did not receive the response? A mobile user taps Pay, the connection drops, and the app cannot tell whether the charge happened. If the operation is idempotent, the client just retries. PUT to replace a resource, and DELETE, are naturally idempotent. POST creates something new each time, so a naive retry can create a duplicate order or a double charge. This is where the difference between the methods becomes a money problem rather than a style question.

The industry solution is the idempotency key. The client generates a unique value, typically a UUID, and sends it in an Idempotency-Key header with the POST. The server stores the key together with the response of the first successful processing. If the same key arrives again, the server returns the stored response instead of processing again. Several details make this correct: the key must be scoped to the authenticated user so one customer cannot replay or collide with another's, the stored record should include a fingerprint of the request body so reusing a key with different content is rejected with a conflict, concurrent requests with the same key must be handled so only one runs, and keys expire after a retention window such as 24 hours.

Status codes complete the contract. A successful creation returns 201 with a Location header pointing at the new resource. A successful operation with nothing to return is 204. Work accepted for later processing is 202. Common client errors have specific meanings: 400 for a malformed request, 404 for a missing resource, 409 for a conflict with current state, 412 when a precondition such as If-Match fails, 415 for an unsupported media type, and 429 when rate limited. Returning 200 with an error message in the body defeats every generic client, retry policy, and monitoring dashboard, so avoid it.

MethodSafeIdempotentTypical use
GETYesYesRead a resource or collection
POSTNoNo, unless an idempotency key is usedCreate, or trigger an action
PUTNoYesReplace a whole resource at a known URL
PATCHNoNot guaranteedPartially update a resource
DELETENoYesRemove a resource
HEAD and OPTIONSYesYesMetadata and CORS preflight

Worked Example: An Idempotency Filter for POST

The endpoint filter below implements the essentials with a store abstraction. A production version would use Redis or the database with a unique constraint, which Phase 7 revisits; the in-memory version shows the logic.

C#
public sealed record StoredResponse(string BodyHash, int StatusCode, string Body, DateTimeOffset CreatedAt);

public interface IIdempotencyStore
{
    // Returns true if this caller "won" the key and should process the request.
    bool TryBegin(string scopedKey, string bodyHash, out StoredResponse? existing);
    void Complete(string scopedKey, StoredResponse response);
}

public sealed class IdempotencyFilter(IIdempotencyStore store) : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext ctx, EndpointFilterDelegate next)
    {
        var http = ctx.HttpContext;
        var key = http.Request.Headers["Idempotency-Key"].ToString();
        if (string.IsNullOrWhiteSpace(key) || key.Length > 100)
            return Results.Problem("Idempotency-Key header is required (max 100 characters).", statusCode: 400);

        var userId = http.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "anonymous";
        var scopedKey = $"{userId}:{key}";                       // keys are per user, never global

        http.Request.EnableBuffering();
        using var sha = SHA256.Create();
        var hash = Convert.ToHexString(await sha.ComputeHashAsync(http.Request.Body));
        http.Request.Body.Position = 0;

        if (!store.TryBegin(scopedKey, hash, out var existing))
        {
            if (existing is null)
                return Results.Problem("A request with this key is still being processed.", statusCode: 409);
            if (existing.BodyHash != hash)
                return Results.Problem("This key was already used with a different request.", statusCode: 422);
            http.Response.Headers["Idempotent-Replayed"] = "true";
            return Results.Text(existing.Body, "application/json", statusCode: existing.StatusCode);
        }

        var result = await next(ctx);                            // process exactly once
        // ... serialize the produced response and call store.Complete(scopedKey, stored)
        return result;
    }
}

app.MapPost("/api/payments", CreatePayment).AddEndpointFilter<IdempotencyFilter>();
TypeScript
// React client: generate the key once per user intent, reuse it on every retry.
const key = crypto.randomUUID();
async function pay(amount: number) {
  for (let attempt = 0; attempt < 3; attempt++) {
    try {
      return await fetch('/api/payments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
        body: JSON.stringify({ amount }),
      });
    } catch { /* network error: retry with the SAME key */ }
  }
}

The client-side detail matters as much as the server side: the key is generated once when the user confirms, not once per attempt, otherwise every retry looks like a new payment.

The client sends a POST with an Idempotency-Key. The server stores the first result under a per-user key. When the client retries after a timeout, the stored response is replayed instead of charging twice.
The client sends a POST with an Idempotency-Key. The server stores the first result under a per-user key. When the client retries after a timeout, the stored response is replayed instead of charging twice.

Real-World Examples

  • Stripe popularized the Idempotency-Key header for its payments API, storing the result of the first request for a key and returning it on retries, and rejecting a reused key whose parameters differ. The mechanism lets client libraries retry automatically after network failures without risking a double charge, and an IETF working group draft proposes standardizing the header.
  • In 2005, the Google Web Accelerator browser plugin prefetched links on pages, and web applications that used ordinary links to trigger deletions found data disappearing, because the accelerator followed every link automatically. The incident made the rule concrete: GET must be safe, and anything that changes state needs a non-GET method.
Key TakeawaysUse methods according to their semantics: GET is safe and idempotent, PUT and DELETE are idempotent, and POST is not. Protect non-idempotent operations that matter, like payments, with per-user idempotency keys stored server-side, return precise status codes, and never use 200 to report a failure.

Review Questions & Answers

Browsers, crawlers, link previewers, and security scanners issue GET requests automatically and assume they are harmless, so a state-changing GET can be triggered without user intent. It also makes cross-site request forgery trivial, since any page can cause a GET with an image tag. Using POST, PUT, PATCH, or DELETE for changes lets protections like SameSite cookies and CSRF tokens apply.

The client sends a unique key with the first attempt and the same key with every retry. The server records the outcome of the first processing against that key, so a retry returns the stored response instead of charging again. If the first attempt never reached the server, the retry is processed normally, so the client gets exactly one charge in either case.

Scoping prevents one user from colliding with or replaying another user's keys, which could expose someone else's stored response. Comparing the body hash detects a client bug or an attack that reuses a key with different content, which should be rejected instead of silently returning an unrelated earlier result.

Every piece of infrastructure between client and server interprets the status code: retry logic, caches, monitoring, browsers, and API clients all treat 200 as success. Hiding failures in the body breaks alerting, hides error rates from dashboards, and forces every client to write custom parsing. Correct 4xx and 5xx codes with a problem details body keep the whole toolchain accurate.