Introduction
In a distributed system, a client may send a request that is successfully processed by the server while the response is lost because the connection fails. The client may then assume that the operation failed and retry the request. For critical POST operations such as creating an order, starting a payment, or making a reservation, this can create duplicate records and duplicate business actions.
This lesson addresses two related reliability problems. First, we will use idempotency to make a critical POST operation safe to retry. Then we will use optimistic concurrency to prevent one client from silently overwriting changes made by another client.
HTTP defines some methods, including GET, PUT, and DELETE, as idempotent. POST is not idempotent by default. However, an application can define an Idempotency-Key contract and make a particular POST operation resistant to retries.
1. Idempotency and the retry problem
An operation is idempotent when sending the same logical request one or more times produces the same intended server-side result. If the same order-creation command is retried, the server should create one order, not two.
The server cannot reliably identify a retry by inspecting only the request body. Two legitimate orders may contain the same customer, product, and quantity. The client should therefore generate a unique key for each logical operation.
POST /api/orders HTTP/1.1 Content-Type: application/json Idempotency-Key: 7f9d7b7e-0d8d-4c82-bc30-9f5f4d0c52ab { "customerId": 42, "items": [ { "productId": 10, "quantity": 2 } ] }
The server stores the key together with a scope such as the user and operation. If the same key is received again, the server returns the result of the original operation instead of creating another order.
2. The idempotency record and uniqueness guarantee
Idempotency should not depend only on an in-memory dictionary. In a multi-instance deployment, each API instance would have a different dictionary, and all records would disappear after a restart. The key and the result should be persisted in a shared database or another durable store.
public sealed class IdempotencyRecord { public Guid Id { get; set; } public string Scope { get; set; } = null!; public string Key { get; set; } = null!; public int StatusCode { get; set; } public string ResponseBody { get; set; } = null!; public string ResponseContentType { get; set; } = "application/json"; public DateTimeOffset CreatedAt { get; set; } }public sealed class AppDbContext : DbContext { public DbSet<Order> Orders => Set<Order>(); public DbSet<IdempotencyRecord> IdempotencyRecords => Set<IdempotencyRecord>(); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<IdempotencyRecord>() .HasIndex(x => new { x.Scope, x.Key }) .IsUnique(); } }
A scope such as orders:create:user-42 prevents accidental collisions between users or operations. The unique database index is essential. Two concurrent requests can both observe that an application-level lookup found no record, but the database uniqueness constraint prevents both requests from successfully claiming the same key.
3. Implementing the order-creation flow
At the controller or endpoint boundary, validate that the key exists and has an acceptable format. Requiring a key for critical POST operations is usually safer than silently accepting requests without one.
[HttpPost] public async Task<IActionResult> CreateOrder( CreateOrderRequest request, CancellationToken cancellationToken) { if (!Request.Headers.TryGetValue("Idempotency-Key", out var values) || !Guid.TryParse(values.ToString(), out var key)) { return BadRequest(new ProblemDetails { Title = "Idempotency-Key is required", Detail = "Send a valid GUID in the Idempotency-Key header.", Status = StatusCodes.Status400BadRequest }); } var scope = $"orders:create:user-{User.GetUserId()}"; var existing = await db.IdempotencyRecords .SingleOrDefaultAsync(x => x.Scope == scope && x.Key == key.ToString(), cancellationToken); if (existing is not null) { return new ContentResult { StatusCode = existing.StatusCode, ContentType = existing.ResponseContentType, Content = existing.ResponseBody }; } var order = await orderService.CreateAsync(request, cancellationToken); var responseBody = JsonSerializer.Serialize(order); db.IdempotencyRecords.Add(new IdempotencyRecord { Id = Guid.NewGuid(), Scope = scope, Key = key.ToString(), StatusCode = StatusCodes.Status201Created, ResponseBody = responseBody, CreatedAt = DateTimeOffset.UtcNow }); await db.SaveChangesAsync(cancellationToken); return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order); }
In production, the order and the idempotency record should be written in the same transaction. You must also handle the unique-index violation that can occur when two requests with the same key arrive at nearly the same time. A robust design creates the business record and the idempotency record atomically, handles the uniqueness race, and stores a processing state when the operation may take a long time.
Matching the key to the request body
If an existing key is reused with a different request body, returning the original result without explanation can hide a client error. Store a normalized request summary or hash with the idempotency record. If the key exists but the request hash differs, return 409 Conflict.
public sealed class IdempotencyRecord { public string RequestHash { get; set; } = null!; // other properties... }
4. Optimistic concurrency and rowversion
Idempotency controls repeated delivery of the same command. Concurrency controls different commands that update the same resource. For example, one operator may change an order to “Preparing” while another user changes it to “Cancelled.” The second update must not silently overwrite the first update without detecting the conflict.
SQL Server's rowversion column automatically changes whenever the row is updated. It is an opaque value that the application should not interpret. EF Core can use it as a concurrency token and include the original value in the update condition.
public sealed class Order { public int Id { get; set; } public int CustomerId { get; set; } public OrderStatus Status { get; set; } public decimal Total { get; set; } [Timestamp] public byte[] RowVersion { get; set; } = Array.Empty<byte>(); }protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>() .Property(x => x.RowVersion) .IsRowVersion(); }
During an update, EF Core produces a condition conceptually similar to WHERE Id = @id AND RowVersion = @originalVersion. If another transaction has changed the row, no row matches and EF Core raises DbUpdateConcurrencyException.
5. ETag and If-Match for client-side validation
Expose the concurrency value through an ETag rather than exposing an implementation-specific database detail. A GET response may include:
ETag: "AAAAAAAAB9E="
When updating the resource, the client sends that value in the If-Match header:
PUT /api/orders/42 HTTP/1.1 If-Match: "AAAAAAAAB9E=" Content-Type: application/json
The server compares the supplied ETag with the current representation. If it no longer matches, the update should not be applied and the server should return 412 Precondition Failed.
[HttpPut("{id:int}")] public async Task<IActionResult> UpdateOrder( int id, UpdateOrderRequest request, CancellationToken cancellationToken) { var order = await db.Orders.SingleOrDefaultAsync(x => x.Id == id, cancellationToken); if (order is null) return NotFound(); if (!Request.Headers.TryGetValue("If-Match", out var ifMatch)) return StatusCode(StatusCodes.Status428PreconditionRequired); var currentTag = $"\"{Convert.ToBase64String(order.RowVersion)}\""; if (!StringValues.Equals(ifMatch, currentTag, StringComparison.Ordinal)) { return Problem( statusCode: StatusCodes.Status412PreconditionFailed, title: "The order has changed", detail: "Retrieve the latest representation and retry with its ETag.", type: "https://api.example.com/problems/concurrency-conflict"); } order.Status = request.Status; try { await db.SaveChangesAsync(cancellationToken); } catch (DbUpdateConcurrencyException) { return Problem( statusCode: StatusCodes.Status409Conflict, title: "Concurrency conflict", detail: "The order was modified by another request.", type: "https://api.example.com/problems/concurrency-conflict"); } return NoContent(); }
412 means that a client-supplied precondition is no longer true. 409 can be used when the requested operation conflicts with the current state of the resource. Define this distinction in the API contract and return a consistent ProblemDetails document in both cases.
6. The ProblemDetails contract
Enable centralized ProblemDetails support in the application:
builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
Do not expose SQL statements, provider-specific messages, or stack traces in concurrency responses. Return information that helps the client recover: the error type, status, a short explanation, a trace identifier, and a recommendation to retrieve the latest representation.
{ "type": "https://api.example.com/problems/concurrency-conflict", "title": "Concurrency conflict", "status": 409, "detail": "The order was modified by another request.", "instance": "/api/orders/42", "traceId": "00-7c2f..." }
Common mistakes
- Keeping idempotency records only in a memory cache and ignoring multiple API instances.
- Treating an idempotency key as globally unique without including the user or operation scope.
- Returning the old result when the same key is reused with a different request body.
- Writing the business operation and the idempotency record in separate transactions.
- Allowing clients to modify the rowversion property as if it were an ordinary DTO field.
- Returning 500 for every concurrency conflict or exposing database details to the client.
- Sending an ETag in GET responses but failing to validate it with If-Match during updates.
Short practice exercise
- Add a SQL Server rowversion column to the Orders table and configure it with IsRowVersion().
- Create an IdempotencyRecords table and add a unique index on Scope + Key.
- Require the Idempotency-Key header on POST /api/orders.
- Send the same POST request twice with the same key and verify that only one order is created and the same result is returned.
- Read the same order from two clients. After the first client updates it, verify that the second client's update with the old ETag is rejected with 412 or 409.
- Confirm that the error response uses application/problem+json and does not reveal internal database details.
Conclusion
Reliable command operations require more than simply enabling retries. Idempotency-Key, durable records, a unique database constraint, and a transaction work together to make critical POST operations safe under network failures and client retries. Optimistic concurrency and rowversion prevent silent data loss when different clients update the same resource.
These mechanisms should become part of the API contract, OpenAPI documentation, observability data, and client retry policy. When designed together, the API remains predictable not only during successful requests, but also under ambiguous network outcomes and simultaneous changes.