Search Sreeni's Insights

Filter by content type
technical October 13, 2016 7 min read

Idempotency in REST APIs - why DELETE twice is still gone

REST API idempotency explained through safe DELETE retries, idempotency keys, action filters, atomic response storage and reliable client retry behaviour.

Share:

Idempotency in REST APIs - why DELETE twice is still gone

Networks are failing in an uncomfortable way: the client can lose the response even when the server has completed the operation. A retry is therefore not always a new request. In the previous article, we discussed chatty APIs and the cost of network calls. In this article, we are going to see idempotency, why DELETE can safely be repeated and how an idempotency key can make a payment-like POST safe to retry.

TL;DR Summary

  • An idempotent operation has the same intended result when it is repeated.
  • GET is safe and idempotent when it has no side effect.
  • PUT and DELETE are intended to be idempotent, but the implementation must preserve that meaning.
  • POST is not automatically idempotent and may need an idempotency key.
  • The key and stored response need a scope, retention policy and concurrency rule.
  • A retry must be bounded and observable.
  • Idempotency is protecting a business effect, not only an HTTP status code.

Challenges

The response is lost after a successful write

A client submits a purchase of units, and the connection drops before the 201 response arrives. The client cannot know whether the server processed the order. If the endpoint creates another order on every retry, a network problem becomes a financial problem.

HTTP vocabulary is misunderstood

DELETE is not meaning that the server must remove the row twice. The first call can mark a document as deleted, and the second call can return the already-gone result. Idempotence is about the intended state, not about pretending that the second request never happened.

Keys are stored without a policy

An idempotency key must be scoped to the operation and retained long enough to cover realistic retries. Storing every key forever is expensive, while expiring it too quickly can allow a duplicate. The response, status and relevant result must be stored together.

What is idempotency?

An idempotent API operation can be repeated without creating an additional unintended effect after the first successful application of the operation.

In simple terms, when we delete a resource, it is gone. If we DELETE it again, it is still gone. For a non-idempotent creation or payment action, an idempotency key is making repeated requests refer to the same attempt.

An everyday analogy is mathematics. 10 - 10 is zero, and subtracting the same already-removed item again does not make the result more removed. A purchase is different: pressing the payment button twice must not buy twice merely because the first response was delayed.

Why idempotency is important?

Retries are normal in distributed systems. Idempotency lets clients recover from a timeout without asking an operator to guess whether a business action happened. The implementation must also consider concurrency, because two requests with the same key can arrive at the same time.

The following table summarises common HTTP semantics:

VerbIs Safe?Is Idempotent?Typical use
GETYesYesRead a fund
POSTNoNo by defaultCreate an order
PUTNoYesReplace Fund 123 profile
PATCHNoNot necessarilyChange selected fields
DELETENoYesRemove a document

Safe means the request is not changing the resource. Idempotent does not mean the response body or status must be identical on every repetition. DELETE can return 204 the first time and 404 or 410 the second time while preserving the same intended state.

Idempotency key flow

The following diagram depicts a client POST with an Idempotency-Key:

Idempotency key retry flow
Idempotency key retry flow

The API checks whether the key has been seen. The purple path is the retry path: the stored response is returned without processing the payment again. For a new key, the service processes the payment, stores the key and response, and returns 201.

Implementing the key in Web API 2

In ASP.NET Web API 2, an action filter can check the header before the controller action:

public class IdempotencyFilter : ActionFilterAttribute
{
    public override async Task OnActionExecutingAsync(
        HttpActionContext actionContext,
        CancellationToken cancellationToken)
    {
        IEnumerable<string> values;
        if (!actionContext.Request.Headers.TryGetValues(
            "Idempotency-Key", out values))
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest,
                "Idempotency-Key is required.");
            return;
        }

        var key = values.Single();
        var store = (IIdempotencyStore)actionContext.Request
            .GetDependencyScope()
            .GetService(typeof(IIdempotencyStore));
        var response = await store.GetAsync(key);
        if (response != null)
        {
            actionContext.Response = response.ToHttpResponse(
                actionContext.Request);
        }
    }
}

The filter is only the first part. The store must atomically reserve the key, record the request hash and persist the response with the business record. A second request using the same key but a different request body should return 409 Conflict, because one key is representing one operation.

[IdempotencyFilter]
public async Task<IHttpActionResult> CreateOrder(
    CreateOrderRequest request)
{
    var order = await orderService.CreateOnceAsync(request);
    return Created("/orders/" + order.Id, order);
}

CreateOnceAsync is using a unique key constraint or an equivalent atomic operation. The service is not checking and then inserting in two unrelated calls, because two concurrent requests can both pass the check.

DELETE twice

For a document endpoint:

DELETE /funds/123/documents/factsheet HTTP/1.1

The first request can mark the document deleted and return 204. The second request can return 404 or 410. The important part is that the document is not being restored or deleted as a second business effect. Audit logging can still record both requests.

Concurrency and retention

The idempotency store is part of the business write, not an optional cache. A request with key order-123-attempt-1 first reserves that key with a pending state. A second request arriving at the same time waits for the first result or receives a clear conflict, rather than processing independently.

The stored record contains the key, operation name, request hash, status code, response body and expiry time:

CREATE TABLE IdempotencyRecords
(
    IdempotencyKey nvarchar(100) NOT NULL,
    Operation nvarchar(100) NOT NULL,
    RequestHash varbinary(32) NOT NULL,
    StatusCode int NULL,
    ResponseBody nvarchar(max) NULL,
    State nvarchar(20) NOT NULL,
    ExpiresAtUtc datetime2 NOT NULL,
    CONSTRAINT PK_IdempotencyRecords
        PRIMARY KEY (IdempotencyKey, Operation)
);

The key is scoped to the authenticated client or account where required. A key sent by one client should not replay a response to another client. The retention period depends on the expected retry window and business settlement process. An order which can be retried for one day needs a different retention decision from a read request which is retried for seconds.

When the operation fails before the business record is committed, the pending key is marked failed or released according to the policy. A permanent validation error is returned for the same key, while a transient database error can be retried safely. This keeps the retry story explicit instead of leaving a half-created order.

The key is included in the audit record, so support can answer whether an order was retried and which stored response was returned. The hash and operation name are normally enough for correlation; logging the complete request can expose personal data. For a payment-like action, the external provider must offer its own idempotency mechanism or the local order must use a durable state machine, otherwise a crash between provider success and local storage creates a reconciliation problem.

The API is documenting the retry response so client developers are not inventing their own policy. A repeated key returns the original status and body, while a changed payload returns a conflict. This is giving the consumer a deterministic result when the network is not.

The client is also recording the key before sending the request, so a browser retry uses the same operation identity. A new key is generated only for a genuinely new order.

Must Do and Don’ts

  • Must Do: Require an idempotency key for payment-like or order-creating POSTs, otherwise a lost response can create a duplicate.
  • Must Do: Store the request hash with the key, because reusing a key for a different payload is an error.
  • Must Do: Reserve the key atomically, so concurrent requests cannot both process the same operation.
  • Must Do: Expire keys according to the business retry window and monitor conflicts.
  • Don’t: retry every POST automatically, because the server may already have completed the side effect.
  • Don’t: assume a 404 on the second DELETE means the API is not idempotent; the resource can remain deleted.

Wrap up

In this article, we have looked at safe and idempotent HTTP verbs, DELETE repetition, idempotency keys, Web API 2 action filters and atomic response storage. Idempotency is giving the client a reliable retry story across an unreliable network. I hope this article provided you some insights into making REST APIs safer. In the next article, I will walk you through the Twelve-Factor App and what it means for .NET teams.

Related Posts