Modern applications frequently communicate with APIs through mobile apps, web applications, and third-party services. During these interactions, network failures and request timeouts are common. A client may send a request successfully, but the response may never reach the client. When this happens, the client may send the same request again because it cannot determine whether the original operation was completed.
This situation can create serious problems when an API performs operations that should happen only once. For example, a payment endpoint may charge a customer twice, an order endpoint may create duplicate orders, or a wallet API may deduct the same amount more than once.
A common solution is idempotency. An idempotent API operation produces the same intended result when the same request is submitted multiple times. ASP.NET Core developers can implement this behavior using idempotency keys, request validation, and persistent storage.
This article explains why duplicate requests occur, how idempotency keys work, how to implement them in ASP.NET Core, and how to handle concurrent requests, failed operations, and repeated client submissions.
Understanding the Duplicate Request Problem
Consider an application where a customer places an order through a mobile application. The application sends a POST request to the server, and the server successfully creates the order. However, before the response reaches the mobile device, the network connection is interrupted.
The mobile application sees a timeout and cannot determine whether the order was created. It may retry the request.
If the API processes every request independently, the server creates another order. The customer now has two orders even though they intended to place only one.
The same problem can happen with payment processing. Suppose a payment request reaches the server, the payment provider processes the transaction, and the server loses the connection before returning the response. If the client retries without any duplicate protection, the payment might be processed again.
This problem is not necessarily caused by a bug in the client or server. Distributed systems cannot always guarantee that a client receives the response to an operation that has already completed.
The server therefore needs a way to recognize that a new request is a retry of an earlier operation.
What Is Idempotency?
Idempotency means that repeating the same operation with the same input does not create additional unintended effects.
For example, consider an API that sets a user's notification preference to enabled. Sending the same request several times still leaves the preference enabled. This operation is naturally idempotent when implemented as an update to a specific value.
However, consider an API that adds 500 points to a user's reward balance. If the request is submitted three times, the balance may increase by 1,500 points. This operation is not naturally idempotent.
The distinction is important because HTTP methods alone do not guarantee that application code behaves idempotently.
GET, PUT, and DELETE are generally defined as idempotent HTTP methods, while POST is not inherently idempotent. However, the actual behavior depends on how the application implements each endpoint.
An API that creates orders or processes payments through POST requests often needs additional protection against duplicate submissions.
What Is an Idempotency Key?
An idempotency key is a unique identifier generated by the client for a particular operation. The client sends this identifier with the request, and the server stores the result associated with it.
If the client retries the same operation, it sends the same key. The server checks whether that key has already been processed.
If the key is new, the server processes the request and stores the result. If the key already exists, the server returns the previously stored result instead of performing the operation again.
For example, a mobile application might generate a unique key when the user confirms an order.
var idempotencyKey = Guid.NewGuid().ToString();
The application sends the key through an HTTP header:
POST /api/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: 2a8d6a42-4f35-4d81-9a92-1c72b3f9c840
{
"productId": 101,
"quantity": 2
}
If the request times out, the client retries using the same Idempotency-Key value.
The server recognizes that the request belongs to an operation it has already processed. Instead of creating another order, it returns the stored response.
The client must generate a new key for a genuinely new operation. Reusing an old key for a different purchase can cause the server to return the previous operation's result.
Designing the Idempotency Storage
An idempotency implementation needs persistent storage because the server must remember previously processed keys.
Storing keys only in application memory is not reliable for production applications. The application may restart, requests may reach different server instances, or multiple containers may process requests simultaneously.
A database table is a common solution.
For example, an IdempotencyRecords table can contain the following columns:
Column | Purpose |
|---|
Id | Unique record identifier |
Key | Client-generated idempotency key |
RequestHash | Hash of the original request |
Status | Processing, Completed, or Failed |
ResponseBody | Stored response content |
ResponseStatusCode | Original HTTP status code |
CreatedAt | Record creation time |
UpdatedAt | Last update time |
The Key column should have a unique constraint within the appropriate scope.
The scope is important. Two different users should not accidentally share the same idempotency record simply because they generated identical key strings. A practical uniqueness rule is often based on the authenticated user or tenant, the endpoint or operation type, and the idempotency key.
For example, a database constraint might enforce uniqueness across UserId, OperationName, and Key.
The RequestHash column helps detect when a client reuses an existing key with a different request body. The server should not silently return the result of an unrelated operation.
The stored response allows the server to return a consistent result when the same operation is submitted again.
Creating the Idempotency Entity
The first implementation step is to create an entity representing an idempotency record.
public class IdempotencyRecord
{
public long Id { get; set; }
public string UserId { get; set; } = string.Empty;
public string OperationName { get; set; } = string.Empty;
public string Key { get; set; } = string.Empty;
public string RequestHash { get; set; } = string.Empty;
public string Status { get; set; } = "Processing";
public int? ResponseStatusCode { get; set; }
public string? ResponseBody { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
The entity stores the key, the operation identity, and the request hash. It also stores the response status and body after the operation completes.
The UserId property identifies the owner of the operation. For a multi-tenant application, the tenant identifier may also need to be included in the uniqueness scope.
The Status property indicates whether the request is currently being processed or has completed. A production implementation should use clearly defined status values rather than allowing arbitrary strings.
The database configuration should enforce the uniqueness rule:
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdempotencyRecord>()
.HasIndex(x => new
{
x.UserId,
x.OperationName,
x.Key
})
.IsUnique();
modelBuilder.Entity<IdempotencyRecord>()
.Property(x => x.Key)
.HasMaxLength(100);
modelBuilder.Entity<IdempotencyRecord>()
.Property(x => x.OperationName)
.HasMaxLength(150);
}
The unique index is essential because two requests can arrive at almost the same time. Both requests might check the database and discover that the key does not exist. Without a database constraint, both could insert a record and execute the operation.
Application-level checks alone cannot reliably prevent this race condition. The database must enforce uniqueness.
Generating a Request Hash
An idempotency key identifies an operation, but the server should also verify that the request body remains the same when the key is reused.
Suppose the client first sends an order request for two products and later sends a request using the same key but with a quantity of ten. Returning the original response without detecting the changed request can hide a client-side error.
A request hash helps detect this situation.
using System.Security.Cryptography;
using System.Text;
public static class RequestHashHelper
{
public static string Generate(string requestBody)
{
var bytes = Encoding.UTF8.GetBytes(requestBody);
var hash = SHA256.HashData(bytes);
return Convert.ToHexString(hash);
}
}
This method converts the request body into bytes and generates a SHA-256 hash. The resulting value can be stored with the idempotency record.
When the same key is received again, the application generates a new hash and compares it with the stored value.
If the hashes are different, the server should reject the request because the client is attempting to reuse the key for different content.
For JSON requests, consider whether property ordering, whitespace, and serialization differences should be treated as meaningful changes. If the client and server may serialize equivalent JSON differently, hashing the raw body can produce different hashes for logically equivalent requests.
A more advanced implementation can deserialize the request into a known model and create a consistent representation before hashing it. The exact approach should match the API's request validation and serialization rules.
Implementing an Idempotency Service
The next step is to create a service that checks for existing records, reserves a new key, and stores the result.
The service should be responsible for the idempotency lifecycle rather than duplicating database logic inside every controller.
A simplified result model can look like this:
public class IdempotencyResult
{
public bool IsDuplicate { get; set; }
public bool IsConflict { get; set; }
public int? StatusCode { get; set; }
public string? ResponseBody { get; set; }
}
The service needs methods for retrieving existing records, creating a new processing record, and completing the record with the final response.
public interface IIdempotencyService
{
Task<IdempotencyRecord?> GetAsync(
string userId,
string operationName,
string key,
CancellationToken cancellationToken);
Task<bool> TryCreateAsync(
IdempotencyRecord record,
CancellationToken cancellationToken);
Task CompleteAsync(
IdempotencyRecord record,
int statusCode,
string responseBody,
CancellationToken cancellationToken);
}
The TryCreateAsync method should rely on the database's unique constraint. If another request has already inserted the same scoped key, the database rejects the duplicate insertion.
The service can catch the specific database uniqueness violation and return false to indicate that another request has reserved the key.
The exact exception type and error code depend on the database provider. For example, SQL Server and PostgreSQL report unique constraint violations differently. Do not treat every database exception as a duplicate-key condition.
The CompleteAsync method updates the record after the business operation finishes. It stores the response status code and body so that later requests can receive the same result.
The record should not be marked completed until the business operation has reached the state that the application considers successful or safely repeatable.
Using Idempotency in an Order Endpoint
Consider an order API that creates an order and returns its identifier.
The endpoint receives an Idempotency-Key header and uses the idempotency service to determine whether the operation has already been processed.
A simplified controller flow looks like this:
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService;
private readonly IIdempotencyService _idempotencyService;
public OrdersController(
IOrderService orderService,
IIdempotencyService idempotencyService)
{
_orderService = orderService;
_idempotencyService = idempotencyService;
}
[HttpPost]
public async Task<IActionResult> CreateOrder(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
if (!Request.Headers.TryGetValue(
"Idempotency-Key",
out var keyValue))
{
return BadRequest(
"Idempotency-Key header is required.");
}
var key = keyValue.ToString();
if (string.IsNullOrWhiteSpace(key))
{
return BadRequest(
"Idempotency-Key cannot be empty.");
}
var userId = User.Identity?.Name ?? "anonymous";
const string operationName = "CreateOrder";
var existing = await _idempotencyService.GetAsync(
userId,
operationName,
key,
cancellationToken);
if (existing != null)
{
return HandleExistingRecord(existing);
}
var requestJson =
System.Text.Json.JsonSerializer.Serialize(request);
var requestHash =
RequestHashHelper.Generate(requestJson);
var record = new IdempotencyRecord
{
UserId = userId,
OperationName = operationName,
Key = key,
RequestHash = requestHash,
Status = "Processing",
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
var created = await _idempotencyService.TryCreateAsync(
record,
cancellationToken);
if (!created)
{
return Conflict(
"This request is already being processed.");
}
var order = await _orderService.CreateAsync(
request,
cancellationToken);
var responseBody =
System.Text.Json.JsonSerializer.Serialize(order);
await _idempotencyService.CompleteAsync(
record,
StatusCodes.Status201Created,
responseBody,
cancellationToken);
return StatusCode(
StatusCodes.Status201Created,
order);
}
private IActionResult HandleExistingRecord(
IdempotencyRecord record)
{
if (record.Status == "Completed")
{
return StatusCode(
record.ResponseStatusCode ?? 200,
record.ResponseBody);
}
return Conflict(
"This request is already being processed.");
}
}
This example demonstrates the general flow, but it is intentionally simplified. A production implementation must compare the request hash before returning an existing result, handle failed operations, and ensure that the business operation and idempotency record are coordinated safely.
There is also a response-format detail to consider. Returning a stored JSON string directly as an object result may cause ASP.NET Core to serialize it as a JSON string rather than return the original JSON document. A production implementation should store and replay the response with the correct content type and response body handling.
The important idea is that the idempotency record is reserved before the business operation begins. This prevents another request from independently creating the same operation.
Handling Concurrent Requests
Duplicate requests do not always arrive one after another. A mobile application may retry quickly, a browser may submit a form twice, or multiple application instances may receive the same request at nearly the same time.
This creates a race condition.
Consider the following sequence:
Request A checks whether an idempotency key exists.
Request B checks the same key before Request A inserts its record.
Both requests discover that the key is not present.
Both attempt to create the record.
Both try to execute the business operation.
A unique database constraint prevents both requests from successfully reserving the same key. Only one insertion can succeed.
The second request should then check the existing record and determine whether the first request is still processing or has completed.
For an operation that is still processing, the API can return HTTP 409 Conflict, HTTP 202 Accepted with a status resource, or another documented response depending on the API contract.
For an operation that has completed, the API should return the stored response.
The exact response policy should be consistent so that clients know whether they should retry, wait, or retrieve the existing operation.
Handling Failed Operations and Application Crashes
An idempotency implementation must also consider what happens when an operation fails.
Suppose the application creates a processing record and then crashes before completing the order. The record remains in the Processing state.
If the client retries, the API may continue returning a conflict response even though the original operation will never finish.
A production system needs a recovery strategy for incomplete records.
One approach is to store processing timestamps and define an expiration or recovery policy. A background worker can inspect old processing records and determine whether they should be retried, marked as failed, or reconciled with the business system.
However, simply deleting old processing records is dangerous. The original business operation may have succeeded even though the application failed before updating the idempotency record.
For example, an external payment provider might have completed a charge, but the application could crash before saving the payment result. Reprocessing the request without checking the provider may charge the customer again.
For operations involving external systems, use the provider's own idempotency support whenever available. Also consider durable transaction records, reconciliation processes, and the transactional outbox pattern.
An idempotency key protects the API boundary, but it does not automatically create a distributed transaction across the application database and external services.
Choosing the Right HTTP Response
The API should return consistent responses for repeated requests.
Situation | Possible response |
|---|
Missing idempotency key | 400 Bad Request |
New request successfully processed | 201 Created |
Same key and same request already completed | Return the original result |
Same key is currently processing | 409 Conflict or 202 Accepted |
Same key used with a different request | 409 Conflict |
Temporary processing failure | Documented retryable error |
The exact response codes depend on the API design, but the behavior should be documented.
For example, a mobile application should know whether a 409 response means it should wait and retry, or whether it should stop because the key was reused with different content.
Do not return a generic success response for every duplicate request. Returning the original result provides clients with the information they need to continue safely.
Testing Idempotency in ASP.NET Core
Idempotency should be tested with more than a single repeated request.
The test suite should verify that the same key does not create multiple business records.
For example:
[Fact]
public async Task CreateOrder_ShouldNotCreateDuplicateOrders()
{
var key = Guid.NewGuid().ToString();
var request = new CreateOrderRequest
{
ProductId = 101,
Quantity = 2
};
var firstRequest = new HttpRequestMessage(
HttpMethod.Post,
"/api/orders");
firstRequest.Headers.Add(
"Idempotency-Key",
key);
firstRequest.Content = JsonContent.Create(request);
var firstResponse =
await _client.SendAsync(firstRequest);
var secondRequest = new HttpRequestMessage(
HttpMethod.Post,
"/api/orders");
secondRequest.Headers.Add(
"Idempotency-Key",
key);
secondRequest.Content = JsonContent.Create(request);
var secondResponse =
await _client.SendAsync(secondRequest);
Assert.Equal(
HttpStatusCode.Created,
firstResponse.StatusCode);
Assert.Equal(
firstResponse.StatusCode,
secondResponse.StatusCode);
}
This test verifies that the same key and same request can be submitted twice without receiving two different creation results. A more complete test should also inspect the database or a test repository to confirm that only one order was created.
Additional tests should cover:
Submitting the same request with the same key.
Reusing the same key with a different request body.
Submitting two requests with the same key concurrently.
Retrying while the first request is still processing.
Retrying after a completed operation.
Handling incomplete records after simulated failures.
Ensuring different users can use identical key values within their separate scopes.
Concurrency tests are particularly important. Send two requests simultaneously using the same key and verify that the business operation executes only once. The test should use synchronization primitives when necessary so that both requests reach the reservation logic at nearly the same time.
Best Practices for Idempotency Keys
Generate a unique key for each new business operation. Reuse the same key only when retrying that operation.
Require authentication for operations where the idempotency record must be associated with a specific user or tenant.
Use a database unique constraint to prevent concurrent requests from reserving the same key.
Store a request hash and reject reuse of a key with different request content.
Store the original response status and body when the API contract requires replaying the completed result.
Define how the application handles records that remain in the Processing state after a crash.
Use provider-supported idempotency mechanisms for external payments and other operations with side effects.
Define a retention policy for completed idempotency records. Removing records too early can allow an old client retry to execute the operation again.
Avoid storing sensitive response information unnecessarily. Apply appropriate access controls and data-retention rules.
Test duplicate requests under concurrent execution, not only sequential execution.
Conclusion
Duplicate requests are a normal possibility in distributed applications. A client may retry because of a timeout or network failure even when the server has already completed the original operation.
Idempotency keys provide a reliable way to recognize repeated requests and prevent unintended duplicate operations. ASP.NET Core applications can implement this behavior using request headers, persistent idempotency records, request hashing, and database uniqueness constraints.
For production systems, the implementation must also handle concurrent requests, incomplete processing records, application crashes, and external service failures. Simply checking whether a key exists is not enough because multiple requests can arrive simultaneously.
A well-designed idempotency strategy makes APIs safer for mobile applications, payment systems, order processing, and other operations where repeating the same request should not create additional side effects.
Join the conversation! Your thoughts help the community grow.