ASP.NET Core Web API Idempotency Key Implementation

Leave a Comment

Duplicate HTTP requests are a common occurrence for modern online applications. An API gateway could resubmit a request if it did not obtain a response in time, a user might click the Submit button again, or a mobile application might try again following a network timeout.

Duplicate requests can cause major issues for processes like order creation, payment processing, ticket booking, and money transfers. It is possible for two orders to be made, inventory to be deducted more than once, or the same payment to be completed twice.

 

One way to prevent these problems is to implement idempotency keys in an ASP.NET Core Web API.

An idempotency key is a unique value sent by a client with a request. The server uses that value to identify repeated attempts to perform the same logical operation. When the same request arrives again with the same key, the API can return the previously stored result instead of executing the operation again.

This approach is especially useful for POST and PATCH endpoints that perform operations with side effects. It also works well with mobile applications, payment integrations, distributed systems, and APIs that use retry policies.

This article explains how idempotency keys work, how to implement them in ASP.NET Core, how to store request and response information, and how to handle concurrent requests safely in production.

What Is an Idempotency Key?

An idempotency key is a client-generated identifier that represents one logical operation.

For example, suppose a mobile application sends a payment request to an ASP.NET Core API. The server processes the payment, but the network connection fails before the response reaches the application.

The client cannot determine whether the payment succeeded. It may send the request again.

Without idempotency protection, the server may process the payment a second time. With an idempotency key, the client sends the same key with both attempts. The server recognizes the repeated operation and returns the result recorded for the original request.

A typical HTTP request looks like this:

POST /api/payments HTTP/1.1
Content-Type: application/json
Idempotency-Key: 8f4c2d10-6b12-4e92-a61c-1e6f20a53d89

{
  "customerId": 1025,
  "amount": 2500,
  "currency": "INR"
}

The client must reuse this key when retrying the same logical payment.

The key should not be generated again for every HTTP attempt. If the client creates a new key for each retry, the server will treat every request as a new operation.

Idempotency and HTTP methods

HTTP defines idempotency as a property of an operation: performing the same request multiple times has the same intended effect as performing it once.

HTTP method

Naturally idempotent?

Typical behavior

GET

Yes

Reads a resource without changing its state

HEAD

Yes

Returns response headers without changing state

PUT

Yes, when implemented correctly

Replaces a resource with the supplied representation

DELETE

Yes, in intended effect

Removes a resource; repeated deletion does not remove additional resources

POST

Not necessarily

Often creates a new resource or triggers an operation

PATCH

Not necessarily

Depends on the requested modification

For example, setting an order's status to Shipped can be idempotent if repeating the operation does not create additional effects. Incrementing a counter by one is not idempotent because repeating the request changes the value again.

An idempotency key is particularly useful when an operation is not naturally idempotent but clients still need safe retry behavior.

How Idempotency Keys Work

A typical idempotency implementation maintains a persistent record for each logical request.

The record usually contains:

  • Idempotency key.

  • Client or tenant identifier.

  • Request fingerprint.

  • Processing status.

  • HTTP response status code.

  • Response body.

  • Relevant response headers.

  • Creation and expiration timestamps.

The request fingerprint helps the server determine whether the same key is being reused with a different request.

Request processing flow

The general workflow looks like this:

  1. The client generates an idempotency key before starting an operation.

  2. The client sends the key in the Idempotency-Key header.

  3. The API validates the key and identifies the authenticated caller.

  4. The server checks whether a record already exists for that caller and key.

  5. If no record exists, the server attempts to claim the key atomically.

  6. The server validates and executes the operation.

  7. The server stores the result and marks the operation as completed.

  8. If the same request arrives again, the server returns the stored result instead of executing the operation again.

The key must be claimed atomically. Otherwise, two requests arriving at almost the same time can both check the database, find no existing record, and execute the same operation.

Different request scenarios

Scenario

Recommended behavior

New key and valid request

Execute the operation and store its result

Same key and same completed request

Replay the stored response

Same key and different request body

Reject the request with a conflict response

Same key while the first request is processing

Return a documented in-progress response or wait for completion

Request fails before the operation is committed

Allow a safe retry according to the failure policy

Stored result has expired

Treat the key according to the documented retention policy

The exact HTTP status codes can vary by API contract. The important requirement is that clients can distinguish a successful replay, a conflicting request, and an operation that is still in progress.

Design the Idempotency Storage

A reliable implementation needs persistent storage. An in-memory dictionary can demonstrate the concept, but it is not sufficient for a production API running across multiple application instances.

For example, if an API runs on three servers behind a load balancer, each server has its own memory. A retry might reach a different server that has no knowledge of the original request.

A shared database or distributed store is therefore required.

Create an idempotency table

The following SQL Server table stores the information needed to identify and replay a request.

CREATE TABLE dbo.IdempotencyRecords
(
    Id BIGINT IDENTITY(1,1) PRIMARY KEY,

    ClientId NVARCHAR(100) NOT NULL,
    IdempotencyKey NVARCHAR(128) NOT NULL,

    RequestHash VARBINARY(32) NOT NULL,

    Status NVARCHAR(20) NOT NULL,

    ResponseStatusCode INT NULL,
    ResponseBody NVARCHAR(MAX) NULL,

    CreatedAtUtc DATETIME2 NOT NULL
        DEFAULT SYSUTCDATETIME(),

    ExpiresAtUtc DATETIME2 NOT NULL,

    CONSTRAINT UQ_Idempotency_Client_Key
        UNIQUE (ClientId, IdempotencyKey)
);

The unique constraint is particularly important. It ensures that one client cannot create multiple records for the same key, even when requests arrive concurrently at different application instances.

The ClientId column identifies the authenticated API consumer, tenant, or user. This prevents two unrelated clients from accidentally sharing the same idempotency-key namespace.

The RequestHash column stores a SHA-256 fingerprint of the request. The Status column can contain values such as Processing and Completed.

For a production implementation, consider storing response headers as well as the response body. If the API returns a Location header or another important response header, a replay should preserve the relevant parts of the original response.

The response body may contain sensitive information. Apply appropriate database permissions, encryption, retention, and access policies.

Generate a request fingerprint

A key should identify one logical request, not become a way to replay an unrelated response.

For example, the following two requests must not be treated as equivalent:

{
  "customerId": 1025,
  "amount": 2500,
  "currency": "INR"
}
{
  "customerId": 1025,
  "amount": 5000,
  "currency": "INR"
}

If both requests use the same key, the API should reject the second request rather than return the first payment's result.

A simple fingerprint can be generated using SHA-256:

using System.Security.Cryptography;
using System.Text;

public static class RequestFingerprint
{
    public static byte[] Create(string requestBody)
    {
        var bytes = Encoding.UTF8.GetBytes(requestBody);

        return SHA256.HashData(bytes);
    }
}

This example hashes the raw request body. A production implementation should also consider the HTTP method, route, relevant query parameters, content type, and authenticated caller scope.

If JSON property ordering or insignificant formatting can vary between retries, raw-body hashing may treat semantically equivalent JSON as different requests. One solution is to serialize a validated request model into a consistent representation before hashing.

Do not include volatile values such as trace IDs, timestamps generated separately for every attempt, or authentication tokens in the fingerprint.

Implement Idempotency Key Validation

Before checking storage, validate the incoming key.

The API should reject missing, empty, or excessively long keys when the endpoint requires idempotency protection.

A simple helper can read the header:

public static class IdempotencyKeyValidator
{
    public static bool TryGetKey(
        HttpRequest request,
        out string key)
    {
        key = string.Empty;

        if (!request.Headers.TryGetValue(
            "Idempotency-Key",
            out var values))
        {
            return false;
        }

        if (values.Count != 1)
        {
            return false;
        }

        var value = values[0];

        if (string.IsNullOrWhiteSpace(value))
        {
            return false;
        }

        if (value.Length > 128)
        {
            return false;
        }

        key = value.Trim();

        return true;
    }
}

This validates the presence and basic format of the header. A production API should also define which characters it accepts and document the maximum key length.

Do not trust the key as an authentication mechanism. The key identifies an operation; authentication and authorization must still be performed for every request.

Implement an Idempotency Service

The application should keep idempotency storage operations separate from the controller or endpoint logic.

A useful design is to introduce an interface that manages the lifecycle of a request:

public interface IIdempotencyService
{
    Task<IdempotencyResult> BeginAsync(
        string clientId,
        string key,
        byte[] requestHash,
        CancellationToken cancellationToken);

    Task CompleteAsync(
        string clientId,
        string key,
        int statusCode,
        string responseBody,
        CancellationToken cancellationToken);
}

The result can describe whether the request is new, already completed, currently processing, or using a different payload.

public enum IdempotencyState
{
    New,
    Completed,
    Processing,
    Conflict
}

public sealed record IdempotencyResult(
    IdempotencyState State,
    int? StatusCode = null,
    string? ResponseBody = null);

The storage implementation should use the database's unique constraint to claim a key atomically.

The important operation is not simply checking whether a record exists. It is attempting to insert a new Processing record and allowing the unique constraint to decide which concurrent request wins.

A simplified SQL Server claim operation is:

INSERT INTO dbo.IdempotencyRecords
(
    ClientId,
    IdempotencyKey,
    RequestHash,
    Status,
    ExpiresAtUtc
)
VALUES
(
    @ClientId,
    @IdempotencyKey,
    @RequestHash,
    'Processing',
    DATEADD(HOUR, 24, SYSUTCDATETIME())
);

If another request has already inserted the same client and key combination, SQL Server rejects the insert because of the unique constraint.

The application can then read the existing record and compare its fingerprint and status.

Handle only the expected duplicate-key errors, such as SQL Server error numbers 2601 and 2627, as a concurrent claim. Other database errors must be treated as actual failures rather than silently interpreted as duplicates.

The claim and completion operations should also use appropriate ownership or state checks. A request that did not acquire the key must never be allowed to overwrite the result created by the request that owns it.

Handle Duplicate and Concurrent Requests

After attempting to claim a key, the API needs to decide what to do with the result.

A completed request with the same fingerprint should return the stored response. A different fingerprint should be rejected. A request that is still processing requires an explicit policy.

For example, an API might use the following responses:

Condition

Example response

First successful request

201 Created

Same key and same completed request

Replay original 201 Created response

Same key with a different payload

409 Conflict

Same key while the original request is processing

409 Conflict with a retry instruction

Missing required key

400 Bad Request

Some APIs choose to wait for the original request to finish instead of returning a conflict. That approach requires bounded waiting, cancellation handling, and a way to observe completion safely.

Returning 409 Conflict for an in-progress request is often simpler. The client can retry after a short delay using the same key.

The response contract should be documented so that mobile applications and other API consumers know how to handle each condition.

Build a Minimal API Endpoint

The following example illustrates how an ASP.NET Core Minimal API can use an idempotency service.

The storage implementation is injected rather than placing database logic directly inside the endpoint.

app.MapPost(
    "/api/payments",
    async (
        HttpContext context,
        PaymentRequest payment,
        IIdempotencyService idempotency,
        IPaymentService paymentService,
        CancellationToken cancellationToken) =>
    {
        if (!IdempotencyKeyValidator.TryGetKey(
            context.Request,
            out var key))
        {
            return Results.BadRequest(
                "A valid Idempotency-Key header is required.");
        }

        var clientId =
            context.User.FindFirst("client_id")?.Value;

        if (string.IsNullOrWhiteSpace(clientId))
        {
            return Results.Unauthorized();
        }

        var requestJson =
            System.Text.Json.JsonSerializer.Serialize(payment);

        var requestHash =
            RequestFingerprint.Create(requestJson);

        var result = await idempotency.BeginAsync(
            clientId,
            key,
            requestHash,
            cancellationToken);

        if (result.State == IdempotencyState.Conflict)
        {
            return Results.Conflict(
                "The idempotency key was used with a different request.");
        }

        if (result.State == IdempotencyState.Processing)
        {
            return Results.Conflict(
                "The original request is still being processed.");
        }

        if (result.State == IdempotencyState.Completed)
        {
            context.Response.Headers["Idempotency-Replayed"] =
                "true";

            return Results.Content(
                result.ResponseBody ?? string.Empty,
                "application/json",
                statusCode: result.StatusCode ?? 200);
        }

        var paymentResult =
            await paymentService.ProcessAsync(
                payment,
                key,
                cancellationToken);

        var responseBody =
            System.Text.Json.JsonSerializer.Serialize(
                paymentResult);

        await idempotency.CompleteAsync(
            clientId,
            key,
            StatusCodes.Status201Created,
            responseBody,
            cancellationToken);

        return Results.Content(
            responseBody,
            "application/json",
            statusCode: StatusCodes.Status201Created);
    });

This endpoint demonstrates the main integration points: validate the key, identify the caller, calculate a fingerprint, claim the operation, replay a completed result, and execute a new operation.

It is an architectural example, not a complete production implementation. The service must implement atomic claiming, ownership checks, expiration, response persistence, and failure recovery. The endpoint should also preserve relevant response headers, such as Location, when storing and replaying the response.

The payment service receives the same key so it can use the key when calling an external payment provider that supports idempotency.

Handle Failures Between Processing and Response Storage

A common implementation mistake is to assume that storing a Processing record and later updating it to Completed is enough to guarantee exactly-once execution.

Consider this sequence:

  1. The API claims the idempotency key.

  2. The payment provider successfully processes the payment.

  3. The API process crashes before saving the response.

  4. The client retries the same request.

  5. The database still contains a Processing record.

The API cannot safely assume that the payment failed. Re-executing the operation might create a duplicate payment.

This is a distributed systems problem: the database and external payment provider do not share one atomic transaction.

There are several ways to address it.

Use downstream idempotency support

If the payment provider supports idempotency keys, forward a stable key to the provider.

The same logical payment should use the same downstream key on every retry. This allows the provider to recognize repeated requests even when the application cannot determine whether an earlier attempt succeeded.

Do not assume every external API supports this feature. Review the provider's documentation and key-retention rules.

Use a database transaction for local operations

When the business operation and idempotency record are stored in the same database, a database transaction can help make the changes atomic.

For example, creating an order and marking its idempotency record as completed can be committed together.

If the transaction rolls back, neither change is committed.

This is different from calling an external payment provider, because a database transaction cannot automatically roll back an operation already completed by another service.

Use an outbox or reconciliation workflow

For operations involving multiple systems, consider the transactional outbox pattern.

The application commits the business operation and an outbox message in the same database transaction. A background worker publishes the message to the external system.

The consumer should also handle duplicate messages safely.

For payment operations, reconciliation may be required when the external provider's result is uncertain. A durable operation state machine is often more reliable than simply expiring a Processing record and allowing another request to execute.

Store and Expire Idempotency Records

Idempotency records should not remain in the database forever. A retention policy controls how long the API remembers completed operations.

For example, a payment API may retain keys for 24 hours or longer, depending on the provider contract and business requirements.

The correct duration depends on how long clients may retry, how long requests can remain in progress, and the consequences of processing the same logical operation again.

A SQL Server cleanup operation might look like this:

DELETE TOP (1000)
FROM dbo.IdempotencyRecords
WHERE Status = 'Completed'
  AND ExpiresAtUtc < SYSUTCDATETIME();

Run cleanup periodically through a background service or scheduled job. Use batches so a large cleanup operation does not create unnecessary database pressure.

Do not delete an active Processing record merely because its original expiration time has passed. First determine whether the operation is still running, completed externally, or needs reconciliation.

The API must also define what happens after a key expires. Once the record is deleted, a request using that key may be treated as new. Therefore, clients should not assume that an idempotency key protects an operation indefinitely.

Secure Idempotency Key Storage

Idempotency keys are not authentication credentials, but they still need careful handling.

A few security practices are important:

  • Scope keys to an authenticated user, tenant, or API client.

  • Do not use a globally shared key namespace for unrelated callers.

  • Validate key length and accepted characters.

  • Avoid logging full request bodies or sensitive payment details.

  • Restrict access to stored response data.

  • Consider storing a hash of the client-provided key rather than the raw value.

  • Use TLS for all API requests.

  • Apply retention and cleanup policies to stored records.

The scope should represent the caller that owns the logical operation. For example, a multi-tenant API should normally keep each tenant's keys separate.

Authorization must still run before replaying a stored response. A caller should not receive a previous response simply because they know another user's idempotency key.

Test Idempotency in ASP.NET Core

Idempotency should be tested under normal, repeated, and concurrent request conditions.

A basic test should send the same request twice using the same key and verify that the business operation executes only once.

For example, an integration test can use HttpClient:

[Fact]
public async Task RepeatedRequest_ReturnsSameResult()
{
    var key = Guid.NewGuid().ToString();

    var firstRequest = new HttpRequestMessage(
        HttpMethod.Post,
        "/api/payments");

    firstRequest.Headers.Add(
        "Idempotency-Key",
        key);

    firstRequest.Content = JsonContent.Create(
        new PaymentRequest(1025, 2500, "INR"));

    var firstResponse =
        await _client.SendAsync(firstRequest);

    var secondRequest = new HttpRequestMessage(
        HttpMethod.Post,
        "/api/payments");

    secondRequest.Headers.Add(
        "Idempotency-Key",
        key);

    secondRequest.Content = JsonContent.Create(
        new PaymentRequest(1025, 2500, "INR"));

    var secondResponse =
        await _client.SendAsync(secondRequest);

    Assert.Equal(
        firstResponse.StatusCode,
        secondResponse.StatusCode);

    Assert.Equal(
        "true",
        secondResponse.Headers
            .GetValues("Idempotency-Replayed")
            .Single());

    Assert.Equal(
        1,
        _paymentService.ProcessCount);
}

This example assumes the test application exposes the replay header and uses a test payment service that tracks how many times the operation executes.

A complete test suite should also cover:

Test case

Expected result

Missing key

Request rejected when a key is required

Empty key

Request rejected

Same key and same payload

Original result replayed

Same key and different payload

Conflict response

Two simultaneous requests with the same key

Only one request claims and executes the operation

Different clients using the same key

Requests remain isolated by client scope

First operation fails

Behavior follows the documented failure policy

Application restarts

Completed records remain available in persistent storage

Expired key

Behavior follows the documented retention policy

External service succeeds but API crashes

Retry does not duplicate the external operation

Concurrent tests are especially important. A test that sends two requests sequentially does not prove that the storage implementation handles race conditions.

Run concurrency tests against the same type of database or distributed store used in production. An in-memory test store may not reproduce database locking and uniqueness behavior.

Common Mistakes to Avoid

Mistake

Why it is a problem

Better approach

Generating a new key for every retry

The API treats every attempt as a new operation

Reuse one key for the logical operation

Using only an in-memory dictionary

Multiple instances cannot share state

Use persistent shared storage

Checking for a key before inserting

Concurrent requests can both pass the check

Use an atomic insert and unique constraint

Ignoring request fingerprints

A key can be reused with different data

Compare a stable request fingerprint

Returning cached responses before authorization

Stored data may be exposed to another caller

Authenticate and authorize before replay

Deleting processing records immediately

An external operation may already have succeeded

Use recovery and reconciliation

Assuming a database transaction covers an external API

The external operation cannot be rolled back with the database

Use downstream idempotency and outbox patterns

Keeping records forever

Storage grows unnecessarily

Apply a documented retention policy

Assuming exactly-once execution

Failures across system boundaries make this difficult

Design for deduplication and recovery

Best Practices for Production APIs

  1. Generate one idempotency key for each logical operation.

  2. Reuse the same key for network retries and repeated client submissions.

  3. Scope keys to the authenticated user, tenant, or API consumer.

  4. Enforce uniqueness in persistent storage.

  5. Calculate a fingerprint to detect reuse with a different request.

  6. Store the original response status, body, and relevant headers.

  7. Define explicit behavior for requests that are still processing.

  8. Use downstream idempotency support for payment and other external operations.

  9. Use database transactions when the business operation and idempotency record share the same database.

  10. Apply a retention policy that matches client retry behavior and business requirements.

  11. Test concurrent requests and application restarts.

  12. Monitor duplicate requests, fingerprint conflicts, processing timeouts, and replay counts.

Idempotency should be part of the API contract, not just an internal implementation detail. Document the required header, key scope, retention period, replay behavior, and error responses so every client follows the same rules.

Advantages and Disadvantages

Advantages

Disadvantages

Prevents duplicate processing from repeated requests

Requires persistent storage

Makes client retries safer

Adds database operations to request processing

Useful for payment and order APIs

Requires careful concurrent request handling

Supports distributed API deployments

Requires a shared storage mechanism

Can replay the original response

Response storage increases data-retention requirements

Helps recover from uncertain network outcomes

Does not automatically guarantee exactly-once execution across external systems

Conclusion

Idempotency keys are an important reliability feature for ASP.NET Core APIs that perform operations with side effects. They help prevent duplicate payments, orders, bookings, and other operations when clients retry requests after timeouts or network failures.

A reliable implementation needs more than checking whether a key exists. It requires atomic key claiming, request fingerprinting, persistent storage, response replay, authorization, expiration, and a clear policy for concurrent requests.

For operations that involve external services, combine API-level idempotency with downstream idempotency support, database transactions where appropriate, and reconciliation workflows for uncertain outcomes.

Start with a shared database and a unique constraint, then test repeated and concurrent requests before deploying the implementation. This makes API retries safer and gives clients a predictable way to recover from network failures.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Previous PostOlder Post Home

0 comments:

Post a Comment