How to Implement Idempotency Keys in ASP.NET Core 10 Web API Using C# and SQL Server – Prevent Duplicate API Requests (2026)
How to Implement Idempotency Keys in ASP.NET Core 10 Web API Using C# and SQL Server – Prevent Duplicate API Requests (2026)
A customer clicks Place order, your API saves the order, and the response disappears before the browser receives it. The browser retries. Without a shared record of that operation, the second POST can create a second order even though both requests came from one checkout attempt.
This guide implements idempotency keys in ASP.NET Core 10 Web API using C# and SQL Server. The goal is specific: repeated requests with the same authenticated owner, operation and key should replay one committed order response during a documented retention window. Concurrent requests must not both pass a check-then-insert race.
How do you prevent duplicate POST requests in ASP.NET Core?
Require a client-generated Idempotency-Key, scope it to the authenticated caller and operation, fingerprint the validated request, and coordinate processing in shared durable storage. Commit the business change and replay response in one database transaction. A matching retry reuses that response; a live-key payload mismatch is rejected. A dictionary lookup or cache check followed by an independent insert is insufficient under concurrency.
1. API idempotency, HTTP methods and ordinary caching
An operation is idempotent when repeating it has the same intended server-side effect as performing it once. It does not require every response to have identical text or status. Deleting an already-deleted resource may return a different status while still leaving the resource deleted. Logging or metering each attempt does not by itself change the intended resource effect.
| Method or operation | HTTP semantics | Application consequence |
|---|---|---|
| GET, HEAD, OPTIONS, TRACE | Safe methods are idempotent | Do not implement order creation in a GET endpoint |
| PUT and DELETE | Idempotent by defined semantics | Implement the intended replacement/deletion consistently |
| POST | Not inherently idempotent | Creation needs an explicit retry contract when duplicates matter |
| PATCH | Not inherently idempotent | A particular patch can be designed to be idempotent; do not assume it |
See RFC 9110, section 9.2.2 for the definition. A method’s name alone does not repair an implementation that performs an unintended additional business action on each retry.
Duplicate requests arise from double-clicks, mobile network changes, client timeouts, proxy retries, job restarts and uncertain acknowledgements. Disabling a button reduces accidental clicks but cannot coordinate two servers or recover a response lost after commit. The client must generate one key per logical action and persist it until that action is resolved.
Idempotency is also different from an HTTP response cache. A cache usually avoids repeated reads and tolerates eviction according to its policy. An idempotency record associates a write attempt with its outcome and must remain available for the promised retry horizon. If it disappears too early, the business operation may run again.
| Ordinary caching | Idempotency for this order API |
|---|---|
| Usually keyed by resource/query | Keyed by owner + operation + client key |
| Often acceptable to recompute after eviction | Recomputation can create another order |
| Focuses on retrieval efficiency | Focuses on write correctness and response recovery |
| May share public representations | Requires authorization before every lookup or replay |
A natural business uniqueness rule remains useful. For example, a merchant checkout reference can have a permanent unique constraint. Two different idempotency keys intentionally represent two different operations in this sample; they can create two identical-looking orders. Do not confuse duplicate-request prevention with detecting every possible duplicate business purchase.
2. Idempotency-Key: current specification status and explicit API policy
As of 4 November 2026, draft-ietf-httpapi-idempotency-key-header-08 is an active Internet-Draft, published 22 October 2026. It is work in progress, not a published RFC. The draft uses a Structured Field string, and recommends documenting key and expiry policies. It describes 400 for a required missing key, 422 for a different payload under a reused key, and 409 for an outstanding concurrent request. Check its status again when implementing.
Our API accepts a deliberately narrow subset: exactly one quoted, non-empty UUID in D format, without parameters. It is not a general-purpose Structured Fields parser. The quote characters are part of the header value:
The implementation normalizes UUID text and SKU case, so equivalent inputs map consistently. It rejects multiple header values and unsupported fields. The server hashes the normalized key for storage; a hash is an identifier, not proof of identity or permission.
| Situation | This API’s documented behavior |
|---|---|
| Missing/invalid key or invalid order | 400; no idempotency record is written |
| First valid request | Create order and completed replay record; return 201 |
| Same owner, operation and key; same fingerprint | Replay stored 201 body and Location |
| Same live key; different normalized request | 422; no new order |
| Another transaction holds that scoped key | 409 with Retry-After: 1; retry unchanged |
| Database failure or uncertain outcome | Safe failure; resolve by retrying the original key |
| Key reaches its 24-hour expiry | Treated as a new operation; duplicate prevention no longer applies |
The 24-hour period is a teaching policy, not an IETF-mandated duration. A client must not keep retrying an old checkout indefinitely. Choose a production retention period from the real retry and reconciliation horizon, and consider a permanent business reference when duplicates remain unacceptable after that window.
Payment providers illustrate why contracts matter. Stripe’s official documentation distinguishes API v1 response replay from API v2 retry behavior. Our sample does not implement either provider’s full contract, process a payment, or copy a provider’s error-retention policy. It records only a successfully committed local order result.
3. Database-backed idempotency architecture and limits
The request filter performs input checks and creates a fingerprint. The order service begins a SQL transaction and acquires a transaction-owned application lock scoped to the owner, operation and key. It reads the retained record only after acquiring that lock. A live matching record is replayed. Otherwise, the service writes an order and its response record before committing.
A unique composite index on OwnerId, Operation, KeyHash provides an additional invariant: the table cannot contain two records for the same protected scope. The lock coordinates compliant writers before they do business work; the unique index protects the stored identity. Neither is a reason to allow unrelated code paths to bypass the service.
This design suits short operations whose durable side effects are in the same SQL Server database. It intentionally avoids a separately committed Processing row that could be abandoned by a crashed worker. Processing exists as an open transaction and lock; only Completed rows are durably visible.
| Approach | Useful property | Critical limitation |
|---|---|---|
| SQL record plus local SQL business transaction | Both outcomes can commit together | Database load and transaction duration must be controlled |
| Redis or distributed-cache coordination | Fast shared admission and TTL support | A cache write and separate SQL commit are not one atomic transaction |
| In-memory dictionary or SemaphoreSlim | Simple within one process | Does not coordinate separate instances or survive restarts |
| Durable workflow / queue | Useful for long-running asynchronous work | Needs leases, recovery states and an explicit 202/status contract |
A Redis SET-if-absent can help coordinate work, but it does not close the crash gap between an SQL order commit and a Redis replay record. Redis persistence, eviction, lease expiry and ownership-safe lock release all need separate consideration. A distributed lock alone is not a complete idempotency implementation.
The guarantee is bounded: one local committed creation per retained scope through this service. It is not an exactly-once guarantee for payment gateways, emails, brokers, all future retries or other database writers.
4. Prerequisites, .NET 10 project setup and secure secrets
Install a current serviced .NET 10 SDK, SQL Server Developer/Express or Windows LocalDB for local practice, an editor supporting .NET 10, and Postman or curl. Use a dedicated development database. The test fixture later creates and removes a randomly named test database on an isolated SQL Server instance.
The researched SQL Server provider listing shows EF Core 10.0.14 targeting .NET 10. This example aligns the provider, Design package and EF tool to 10.0.14. Pin compatible stable versions; do not select EF Core 11 preview merely because a package page offers it.
Replace the generated project file with the one above, create the C# files shown below, and keep all application types in IdempotencyDemo.Api. The UserSecretsId deliberately remains in the project file; removing it would disconnect your local configuration. No third-party idempotency library is required.
TrustServerCertificate=true is for this local development example. In production, use a trusted SQL certificate, encryption with certificate validation, a restricted database identity and your controlled secret mechanism. Environment variable ConnectionStrings__Orders can supply the connection string; credentials must not be committed to source control or logged.
The demo keys must be distinct, random and 32–256 characters. They are not an idempotency key and must not appear in browser-distributed JavaScript. Microsoft’s Secret Manager guidance explains that user secrets are a development convenience, not an encrypted production vault. Set AllowedHosts to your real hostname when deploying.
If you need the EF and SQL basics first, the related ASP.NET Core 10 CRUD and SQL Server tutorial covers that foundation. This article adds a distinct transactional retry contract.
5. DTOs, entity models and the EF Core DbContext
The request contains a SKU and quantity. The server determines the authenticated owner and the unit price. The client cannot supply a customer ID or payment amount that silently changes the protected operation. The response contains the created order fields; its serialized JSON is saved for replay.
The record stores the request fingerprint, original status, body, content type and relative Location. It does not save arbitrary response headers, cookies or bearer tokens. This example only commits a Completed record with status 201. It is not a generic cache for every possible endpoint result.
EF creates the unique index from IsUnique(). Microsoft’s index documentation covers composite unique indexes; SQL Server unique constraints also enforce uniqueness and create a corresponding unique index. Here we deliberately use a named unique index rather than a separate alternate-key constraint.
Do not run that statement after migrations have already created the index. An ordinary non-unique index is insufficient. Including only the raw client key would also be incorrect for this contract because two authenticated customers are allowed to use the same UUID independently.
An optimistic row-version token solves a different problem: detecting competing updates to an existing row. It does not reserve a nonexistent idempotency record. EF’s concurrency guide notes that duplicate inserts generally raise a provider-specific unique-constraint failure rather than DbUpdateConcurrencyException.
6. Endpoint filter: key validation and request fingerprinting
An endpoint filter can inspect bound arguments before the handler runs. This is a better fit here than generic middleware that copies response streams: it can validate the typed order and prepare a domain-specific fingerprint. The service still owns the database transaction, so the filter cannot accidentally save the replay record in an unrelated transaction.
See Microsoft’s Minimal API filter documentation. The filter below is attached only to the POST handler whose first argument is CreateOrderRequest. Reusing it on a different argument order requires changing that binding.
The fingerprint hashes a fixed JSON shape after explicit normalization. SKU values such as kb-01 and KB-01 are equivalent. JSON whitespace and property order do not affect the hash because the server serializes the validated representation itself. Quantity 2 and quantity 3 are different operations under a live key.
This is a documented semantic policy, not a general JSON canonicalization library. If you add an address, currency, discount code or other operation-affecting field, include its normalized value in the fingerprint. Version the fingerprint/operation contract when semantics change, and plan old-key behavior across deployments. Do not silently change the operation scope during a retry window.
SHA-256 does not encrypt payloads. A fingerprint can still reveal equality or permit guessing of low-entropy inputs. The sample does not persist request bodies, but the response record is still sensitive application data. Bound key length and request size before doing database work.
7. Coordinate concurrent requests with a SQL transaction-owned lock
Two API instances share SQL Server but do not share a process-local semaphore. They must agree on one lock resource for the same owner, operation and key. The resource below uses a hash of that scope, and the SQL command passes it as a parameter rather than concatenating it into executable SQL.
sys.sp_getapplock supports transaction ownership and a zero lock timeout. In this implementation, a nonnegative return code means success; -1 means the resource was not immediately available and maps to 409. Cancellation and deadlock return codes need separate handling. Locks owned by a transaction release when it commits or rolls back.
All cooperating instances must use the same database, database principal and resource format. This sample uses public as the application-lock principal; review permissions with the DBA rather than granting the application db_owner. A lock in one database does not coordinate an independent database shard.
The contender returns before reading the other transaction’s record. Consequently, a changed payload may first receive 409 while the original is active, then 422 after a completed record becomes visible. The service does not use NOLOCK to read uncommitted responses.
An alternative is inserting a unique reservation row and handling the duplicate-key race. That can work, but a durable Processing reservation also needs a recovery/lease design. This short local transaction avoids that separate state while still enforcing uniqueness at the database level.
8. Implement atomic order creation and response replay
The two SaveChangesAsync calls are inside the same explicit transaction. Saving the order does not commit that transaction by itself. If writing the response record fails, disposing the uncommitted transaction rolls the order back. The response is not sent until CommitAsync succeeds. Microsoft’s EF Core transaction guidance explains the atomic boundary.
On replay, the service reads the saved JSON string and returns the original status, content type and Location. It does not regenerate a new ID, timestamp or body from the current order. A later GET may show a changed resource; replay answers what the original creation request produced.
Idempotency-Replayed is a diagnostic header defined by this sample, not a standard field. First creation returns false and replay returns true. Date, tracing and other transport headers can differ; the code does not promise a byte-for-byte copy of the entire HTTP message.
Validation failures, lock contention and transient failures do not create replay records here. After rollback, the same key can be attempted again. If your business needs to persist deterministic declines or failed outcomes, design and test those states explicitly instead of caching every 500 response or treating all failures as safely retryable.
9. Authentication, safe error handling and Program.cs
The local handler maps two private demo keys to fixed owner IDs. It does not trust an OwnerId supplied in JSON or a caller-controlled customer header. Every replay is behind authentication, just like a new order request.
Replace this demo authentication with a trusted identity provider for production. Validate token issuer, audience, expiry and permissions, and include tenant scope when identities are not globally unique. See the related JWT authentication in ASP.NET Core 10 guide. An idempotency key is never an authentication credential.
The handler returns safe ProblemDetails and logs a type, status and trace ID. It does not expose SQL messages, connection strings, raw request headers or response bodies. The Retry-After value is a small backoff hint, not a promise that the operation will be complete after one second. Rate-limit, authentication and body-binding errors may use their own framework response shapes.
The ASP.NET Core error-handling documentation describes IExceptionHandler. The explicit logging also avoids assuming that .NET 10 middleware diagnostics will log every handled exception. For more detail, see the related global exception-handling tutorial.
The app rejects unknown JSON fields, limits request bodies to 16 KB, requires authentication and disables response caching with no-store. The GET endpoint filters by owner and returns 404 for a missing or inaccessible order. There is no public order enumeration endpoint.
No OpenAPI UI package is needed for this example; the instructions use Postman and curl. If you add OpenAPI documentation, explicitly describe the quoted key and authentication header. Do not expose a production testing UI with embedded credentials.
10. Create the SQL Server schema with EF Core migrations
With the files saved and development secrets configured, restore, generate the initial migration and apply it to your local development database:
Review the generated migration for the Orders and IdempotencyRecords tables, the composite unique index, the expiry index and the completed-result check constraint. Commit the migration, model snapshot, local tool manifest and resolved dependency lock file. The official migration guide explains generated migrations and deployment options.
The generated migration source is not reproduced as fabricated output here. Generate it from this model, inspect the actual SQL and apply a reviewed script or migration bundle during deployment. Do not run EnsureCreated against a production database managed by migrations, and do not grant the runtime application schema-management permissions just to simplify deployment.
11. Test the idempotent POST endpoint with Postman or curl
For a repeatable check, run the ASP.NET Core idempotency smoke test on GitHub against the local demo. It checks missing keys, order creation, exact response replay, and reuse of a key with a different quantity.
These steps were not executed while writing the article. Start the API locally, trust its development certificate, and use the actual listening URL:
In Postman, create private local variables baseUrl=https://localhost:7045, demoKey with Alice’s configured key, and requestKey with one generated UUID. Keep the same requestKey for every retry of this logical operation. Keep secrets out of shared environment exports.
First order request
Send POST {{baseUrl}}/api/orders with these headers:
Expected status: 201 Created. The response contains Location, Cache-Control: no-store and Idempotency-Replayed: false. The following shape is illustrative; the ID, date and formatting come from your actual run:
Replay, payload mismatch and owner isolation
- Repeat the identical request with the same key and identity. Expect 201, the same saved body and Location, and Idempotency-Replayed: true.
- Change quantity to 3 while retaining the live key. Expect 422 and no additional order.
- Remove the key, omit its quotes or send an empty UUID. Expect 400.
- Use a new UUID. Expect a new order: a different key is a different operation.
- Use Bob’s key with Alice’s UUID. Expect an independent order for Bob, not Alice’s replay.
- Request Alice’s returned Location using Bob’s credentials. Expect 404.
- Send concurrent same-key requests. Depending on timing, a contender sees 409 or replays after the first transaction completes.
A fingerprint mismatch response should have status 422 and a safe detail similar to the following, with an actual trace ID assigned by the server:
curl example
This Bash example expects DEMO_KEY to be set privately. The single-quoted header preserves the double quotes in the HTTP key value. Reuse the exact same key string for retries; do not regenerate it in a retry loop.
The single-quoted Bash header above preserves the double quotes directly. Trust the local certificate in your client rather than turning off certificate validation globally. Do not use this synthetic order endpoint to test real payment credentials.
Use a clean development scenario when interpreting counts: creating a fresh key or testing Bob intentionally adds orders. Do not copy response data from a real customer database into a public debugging report.
Seven real-SQL integration tests
The tests exercise the order service against SQL Server, not EF’s in-memory provider. They cover response replay, changed payloads, owner separation, deterministic lock contention, eight concurrent callers, expiry and failure after the order write. A fake or SQLite substitute cannot validate sp_getapplock behavior; see Microsoft’s database testing guidance.
Use the current xunit.v3 package shown in the test project below. Its fixture lifecycle methods return ValueTask. The package supports a stand-alone test executable, so the command uses dotnet run rather than assuming a particular dotnet test runner configuration. See the official xUnit v3 guide. Use a dedicated test instance and an account permitted to create/drop only disposable test databases. The fixture overrides Initial Catalog with a random IdemIntegration_ name, creates it, then removes that test database on teardown.
The test-only interceptor throws after SaveChanges has written the order but before the service commits. The test checks that rollback leaves no order and that the same key can execute afterward. EF’s interceptor documentation explains registration. This is a controlled injected failure, not proof of every possible network or database outage.
The tests are supplied, not reported as passing. Also add HTTP integration tests for authentication, duplicate header rejection, unknown JSON fields, status and replay headers. Exercise real connection loss around commit in an isolated fault-injection environment; the supplied interceptor test does not simulate an ambiguous COMMIT acknowledgment.
12. Server failures, commit uncertainty and retries
| Failure point | Database outcome | Client recovery |
|---|---|---|
| Before SQL transaction / validation failure | No new order or replay record | Correct input; reuse policy depends on whether this is still the same logical operation |
| After order SaveChanges but before commit | Uncommitted work rolls back | Retry same key after rollback resolves |
| Commit succeeded but HTTP response was lost | Order and replay record both exist | Same-key retry returns stored result |
| Connection lost during CommitAsync | Client cannot safely assume success or rollback | Retry same key; SQL outcome determines replay versus execution |
| Client disconnects during processing | Cancellation may race with database completion | Do not assume cancellation means no order; resolve using same key |
Microsoft’s connection-resiliency guidance discusses commit uncertainty and execution strategies. This sample does not enable EF automatic transaction retries. If you add them, replay the entire transaction with fresh state and an explicit success-verification strategy; do not merely add EnableRetryOnFailure around manually managed transactions.
The client should use bounded exponential backoff with jitter for retryable failures, honor the API’s hints, and retain the original key and normalized parameters. A new key after a timeout defeats deduplication. A 422 requires fixing key/payload usage, not a blind retry. A 409 may resolve once the active transaction finishes. A 503 can also indicate a persistent configuration fault, so retries must be bounded and observable.
Expiry and cleanup
A completed record is retained for 24 hours in this example. On a request after expiry, the service deletes that expired record inside its scoped transaction and processes a new operation. The old order remains. The expiry test deliberately expects two orders after 25 hours, making the boundary visible.
Unused expired keys also need scheduled cleanup. Run a small-batch job under a dedicated maintenance identity, monitor its progress, and choose a schedule compatible with your retention policy:
Do not delete Orders as part of this cleanup. Do not shorten retention merely to reduce table size. The sample uses the application TimeProvider for expiry; synchronize instance clocks or adopt a consistent database-time policy before a distributed deployment. SQL cleanup and requests can contend, so keep batches small and handle transient deadlocks without weakening correctness.
EF’s ExecuteDelete documentation explains that it executes immediately rather than waiting for SaveChanges. The service’s per-key expired-row deletion is safe within its already-open transaction. A bare ExecuteDelete elsewhere does not automatically join an unrelated business transaction.
13. Security, production performance and external side effects
Protect the scope and replay data
- Authenticate and authorize before lookup and replay; never let a key authorize access.
- Include tenant and caller/client identity in the scope where applicable. Do not accept owner scope directly from the request body.
- Use high-entropy keys without personal data. Keep keys, payloads and stored response bodies out of routine logs.
- Encrypt and restrict database access according to your data classification. Hashing a key does not encrypt the saved response.
- Bound request size, response size, active key creation and per-caller rates. Otherwise, a caller can create unbounded records using fresh UUIDs.
- Preserve authorization behavior after account suspension or permission changes; replay is not an authentication bypass.
- Store only permitted headers. Never replay Set-Cookie, bearer tokens or a user-specific cross-request security header indiscriminately.
The example validates one small order shape and produces a bounded response. It does not include a production distributed rate limiter, quotas, authorization roles or a full identity provider. Those are required deployment decisions, not guarantees supplied by an idempotency key.
Keep the transaction short and observable
Use indexed scope lookups, async I/O and cancellation tokens. Do not share a DbContext across parallel requests. Monitor transaction duration, application-lock contention, replay rate, payload mismatches, SQL failures and expiry cleanup backlog. Alert on unique-index violations: a recurring violation can indicate a writer bypassing the lock protocol or a scope mismatch, not merely harmless load.
A zero lock timeout avoids waiting on the application lock, but SQL queries, commits and cleanup can still wait on other database resources. Configure database/HTTP timeouts coherently and load-test representative traffic. No throughput or latency benchmark is claimed here.
For IIS deployment, install the appropriate Hosting Bundle, use HTTPS, configure a restricted identity and secure connection configuration, and test retries across application-pool restarts. See the related ASP.NET Core 10 IIS deployment guide. Durable SQL state survives an API process restart; a process-local dictionary would not.
Payments, emails and brokers are outside this transaction
Do not hold this SQL transaction open while charging a card or sending email and assume the two systems committed together. The remote service may succeed while the local transaction rolls back, or vice versa. Pass a stable provider-supported idempotency reference, reconcile uncertain outcomes and use an appropriate durable workflow or transactional outbox boundary.
For payment processing, also validate webhook signatures, deduplicate incoming events and enforce valid state transitions. Request idempotency, webhook deduplication and business uniqueness are separate protections. This tutorial creates an order only; it deliberately makes no exactly-once claim about an external payment provider.
14. Common mistakes and troubleshooting
| Symptom or mistake | Why it matters | Corrective check |
|---|---|---|
| Two orders despite checking the record first | Both requests can observe no row | Acquire shared coordination before checking; preserve the unique index |
| Works on one server but duplicates after scaling | An in-memory lock is per process | Use the same database lock scope across instances |
| Key reused with changed quantity | The client changed the logical operation | Expect 422 while the record is live; use a new key for a deliberate new order |
| Unquoted UUID returns 400 | This endpoint documents a quoted-string subset | Include literal double quotes in the header |
| Missing migrations or duplicate index name | Schema is absent or manual SQL was run twice | Inspect generated migrations and sys.indexes |
| Application lock reports an error | Missing transaction, permissions or inconsistent scope | Check return codes and transaction ownership; do not grant broad roles blindly |
| Unique violation is caught as concurrency-token failure | Insert uniqueness is not optimistic row-version handling | Inspect provider-specific errors in restricted diagnostics |
| Transaction error after enabling retries | Automatic execution strategy conflicts with ad hoc transaction management | Use an explicit verified transaction retry design |
| Same body but fingerprint differs after deployment | Normalization or operation schema changed | Preserve retry compatibility and version the contract deliberately |
| Order committed but client saw 503 or disconnect | Commit acknowledgment or HTTP response was lost | Retry same key; do not assume no order exists |
| Old key creates another order | The retention window has ended | Use a longer documented horizon or permanent business uniqueness |
| Cleanup causes blocking or deadlocks | Large deletes contend with live traffic | Use expiry index, short batches, monitoring and bounded recovery |
| Tests pass with EF InMemory but production duplicates | The substitute does not reproduce SQL locking | Run the supplied real-SQL tests and fault scenarios |
| LocalDB connection fails | Wrong instance, unsupported platform or missing installation | Use Windows LocalDB or configure a reachable SQL Server instance |
Useful developer questions are often about the race, not about generating a UUID. The Stack Overflow race-condition discussion illustrates that concern. EF’s historical commit-failure discussion reinforces the need to distinguish retry policy from outcome verification. These are research context, not normative API contracts or proof of a current EF defect.
When diagnosing a failure, establish whether the request reached SQL, whether its transaction committed, whether a live scoped record exists, and whether the retry used the original key and parameters. Avoid deleting records to “unstick” a request before understanding the committed business outcome.
15. Frequently asked questions
Is POST idempotent in ASP.NET Core 10 by default?
No. ASP.NET Core does not infer an order-creation retry contract from POST. The application must define the key scope, payload consistency, concurrency and replay behavior.
Should the client or server generate the idempotency key?
The client initiating the logical operation should generate and retain it before the first attempt. If the key is delivered only in the server’s response, a lost first response leaves the client unable to reuse it.
Can two users use the same key?
Yes under this sample’s policy, because owner identity is part of the protected scope. Their records and orders remain separate. A production multi-tenant system may need tenant, client and user components rather than one owner ID.
Why return 201 again on a replay?
The stored result represents the original creation response. This sample reuses its status, body and Location while marking the replay with an application-specific header. An alternative contract can differ, but clients must know what to expect.
Why does the same key with a different body return 422?
A live key identifies one operation. Reusing it with a different normalized request is rejected instead of silently returning an unrelated order. If the first request is still active, the contender may see 409 before the service can inspect the completed record.
Do JSON whitespace and property order change the fingerprint?
No in this implementation. It fingerprints the validated server-generated representation. Adding or changing a meaningful field requires updating that representation and planning compatibility.
Should I store failed responses too?
That is a contract decision. This implementation saves only completed order creation. Validation, contention and uncommitted failures leave no record. A payment API may need durable declines or in-doubt states with different retry semantics.
Is a Redis lock enough?
It can coordinate admission, but it does not atomically commit a separate SQL order and replay record. Consider lease loss, eviction, crashes and recovery. Keep the authoritative correctness boundary explicit.
What happens after expiry?
The sample treats an expired key as a new operation and may create another order. The old order is not removed. Clients must not rely on replay beyond the advertised window.
Does this guarantee exactly-once payment processing?
No. It protects one local SQL order operation during retention. External payments, webhooks and messages need their own stable references, deduplication and reconciliation policies.
Can I use this for a ten-minute background job?
Do not keep a SQL transaction and application lock open for that duration. Use a durable asynchronous workflow with an explicit reservation state, lease, recovery policy and status endpoint.
Were these code examples tested?
They were reviewed against documentation but were not compiled or executed here. Run the build and seven supplied SQL integration tests locally, then test the HTTP contract and commit-uncertainty scenarios in staging. No test screenshot or benchmark is fabricated.
16. Conclusion and useful follow-up topics
A dependable idempotent POST endpoint needs more than a key in a header. The key must have an authenticated scope, the payload needs a documented equivalence policy, concurrent requests need shared coordination, and the business change and replay result need one durable commit boundary.
The sample keeps that boundary visible: validate first, acquire a SQL transaction-owned lock, check the retained fingerprint, then either replay or commit an order and its response. Retention and external systems remain explicit limits. Run and extend the tests before production rather than treating a successful manual request as evidence that retries are safe.
Suggested supporting articles — not created here
- Designing idempotency-key compatibility across rolling API deployments and schema changes.
- Building a reconciliation workflow for ambiguous SQL COMMIT outcomes.
- Coordinating checkout references across tenants and database shards.
These are focused future directions. No additional article or published post is created as part of this draft.
17. References and further reading
Primary implementation references checked on 4 November 2026:
- HTTP semantics and idempotent methods
- Current Idempotency-Key document status
- Idempotency-Key draft-08 text (work in progress)
- Stripe idempotency contracts
- EF Core SQL Server provider
- SQL Server provider package
- EF Core Design 10.0.14
- EF Core transactions
- Composite and unique indexes
- SQL Server unique constraints
- SQL Server application locks
- EF Core connection resiliency and commit uncertainty
- EF Core concurrency conflicts
- EF Core migrations
- Minimal API endpoint filters
- Development secret storage
- ASP.NET Core error handling
- ExecuteDelete behavior
- Choosing a database testing strategy
- EF Core interceptors
- xUnit v3 project and execution guide
- xunit.v3 package
Research scope and search intent
The research reviewed HTTP specifications, Microsoft documentation, package pages, provider documentation and developer discussions. Competing tutorials covered payment state machines and generic middleware/storage providers. This guide focuses on a visible local SQL transaction boundary, explicit fingerprint semantics, a documented retention limit and executable real-SQL test examples. It does not claim that every competing article omits those subjects.
The primary query is idempotency keys in ASP.NET Core. Related intent includes preventing duplicate POST requests, SQL Server idempotency, EF Core transactions, concurrent request handling, request fingerprints, response replay and the Idempotency-Key header. No reliable keyword-volume or competition dataset was available, so no volume, CPC, ranking or earnings figures are invented. The direct answers, comparison tables and original diagrams serve developer comprehension rather than promise search outcomes.
Comments
Post a Comment