Appearance
Idempotent act routes
[Idempotent] makes an act route safe to send more than once. The first request runs the operation; any repeat with the same Idempotency-Key gets the stored response instead of running it again. The design, alternatives and decisions are in ADR 0019.
What it guarantees
- One execution per intent. The same key with the same request never runs the act twice.
- Same response on repetition. A repeat returns the stored status, body, content type and
Location, marked withIdempotent-Replayed: true. - Clear refusal on reuse. The same key with a different request is refused with 422
IDEMPOTENCY_KEY_REUSED. - Safe under concurrency. Concurrent repeats wait for the first one instead of running in parallel.
- Atomic with the act. The record commits in the same transaction as the act, so a crash never leaves one without the other.
- Isolated by tenant and user. Another tenant or another user can use the same key without any collision.
- Bounded retention. Records expire after
Retentionand a background purge removes them. - Opt-in per route. Only routes marked
[Idempotent]change behavior. - Cooperates with the unit of work, including acts that call other acts.
- No effect on background jobs. Only HTTP requests to marked routes are affected.
Adoption in three steps
- Map the record in the product's own context and add a migration in the product:
csharp
using Gryd.Infrastructure.Idempotency;
using Microsoft.EntityFrameworkCore;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddGrydIdempotencyRecords("app");
}- Register the support for that context:
csharp
using Gryd.API.Extensions;
services.AddGrydIdempotency<AppDbContext>(o => o.Retention = TimeSpan.FromHours(24));- Mark the routes. New routes require the key; routes already published can accept it as optional, which keeps current clients working:
csharp
using Gryd.API.Idempotency;
using Microsoft.AspNetCore.Mvc;
public sealed record ApproveRequest(Guid RequestId);
[ApiController, Route("api/v1/requests")]
public sealed class RequestsController(AppDbContext db) : ControllerBase
{
[HttpPost("approve"), Idempotent]
public async Task<IActionResult> Approve(ApproveRequest request)
{
// Write through the registered context; the route commits it with the record.
db.Add(new Approval { RequestId = request.RequestId });
await db.SaveChangesAsync();
return Ok();
}
[HttpPost("legacy"), Idempotent(Key = IdempotencyKeyMode.Optional)]
public Task<IActionResult> Legacy() => Task.FromResult<IActionResult>(NoContent());
}[Idempotent] works on a class or a method; the method's attribute wins.
Client contract
- Send the key in the
Idempotency-Keyheader: exactly one value, 1 to 255 characters, all visible ASCII (0x21to0x7E, no space). - Generate one key per intent (per click on "approve", not per HTTP attempt) and resend the same key, with the same method, path, query and body, on every retry.
- A response carrying
Idempotent-Replayed: trueis the stored one; the act did not run again. - On 409
IDEMPOTENCY_REQUEST_IN_PROGRESS, wait theRetry-Afterdelay (1 second) and send the same request again. The 409 is returned only after the server has already waitedLockTimeoutfor the first request. - Only 2xx responses are stored. A 4xx or 5xx outcome rolls the act back and the key stays free to retry. The one exception is a settled refusal, which the route stores and replays.
Errors
| Code | Status | When |
|---|---|---|
IDEMPOTENCY_KEY_REQUIRED | 400 | The route requires the header and the request has none. |
IDEMPOTENCY_KEY_INVALID | 400 | The key is not 1 to 255 visible ASCII characters, or the header is repeated. |
IDEMPOTENCY_KEY_REUSED | 422 | The key was already used with a different request. |
IDEMPOTENCY_REQUEST_IN_PROGRESS | 409 | The first request with this key is still running; carries Retry-After: 1. |
IDEMPOTENCY_RESPONSE_TOO_LARGE | 500 | The response exceeds MaxStoredResponseBytes; the act is not applied. |
Options
| Option | Default | Limits |
|---|---|---|
Retention | 24 hours | 1 minute to 30 days |
LockTimeout | 10 seconds | 100 ms to 60 s |
MaxStoredResponseBytes | 1 048 576 | 1 to 16 777 216 |
MaxRouteStoredResponseBytes | 8 388 608 | 1 to 16 777 216; see Per-route limit |
ReplayedResponseHeaders | empty | Up to 16 names; see Stored headers |
PurgeInterval | 15 minutes | 1 minute to 24 hours |
PurgeBatchSize | 1000 | 1 to 10 000 |
Values outside the limits fail at host start. Calling AddGrydIdempotency again with the same context registers nothing twice but applies the new configure again.
Rules for the handler
- Write through the registered context. The route owns the transaction of that context.
- Do not open or commit a top-level transaction on it. A nested unit of work joins the route's transaction.
- A 4xx result undoes everything the handler saved in that context.
- Do not configure an execution strategy with retry on the context: a replayed delegate would break the single transaction.
- Effects outside the context (e-mail, HTTP calls, another
DbContext) are not undone. Stage them through the transactional outbox instead. - If an exception filter turns an exception into a 2xx response, the act and the record are saved: only 2xx commits.
- Each concurrent arrival holds a database connection from the pool until
LockTimeout. - Columns are PascalCase, like the outbox. A product with a snake_case naming convention must map the record the same way it maps the outbox.
Cleanup
Expired records are removed by a background loop registered with AddGrydBackgroundLoop. It does not run on a host with GrydHostRole.Producer, so the product needs a host with the role All or Executor using the same context to purge. The purge needs ITenantAmbient in the container; without it every cycle logs an error.
Undo without failure
A route sometimes has to answer 2xx and still discard what it wrote: a dry run, or an act that finds nothing to do. IUnitOfWork.ExecuteInTransactionAsync cannot do it, because it joins the route's transaction. Use INestedUnitOfWork.ExecuteNestedAsync: the scope opens a savepoint, and the operation returns NestedOutcome.Keep(...) or NestedOutcome.Discard(...). A discard (or an exception) rolls back to the savepoint, restores the change tracker and leaves the route's transaction alive, so the route still commits the record with a 2xx response.
csharp
using Gryd.Infrastructure.Abstractions;
public sealed record ImportRequest(string FileName, bool DryRun);
public sealed record ImportSummary(int Rows);
[HttpPost("import"), Idempotent]
public async Task<IActionResult> Import(
ImportRequest request, [FromServices] INestedUnitOfWork nested, CancellationToken ct)
{
var summary = await nested.ExecuteNestedAsync(async token =>
{
var rows = await importer.RunAsync(request.FileName, token); // writes through AppDbContext
var result = new ImportSummary(rows);
return request.DryRun ? NestedOutcome.Discard(result) : NestedOutcome.Keep(result);
}, ct);
return Ok(summary); // 2xx: the record is stored; a dry run left nothing behind
}The scope and its costs are described in Nested scope. INestedUnitOfWork is registered by AddGrydAuditablePersistence<TContext>(), which must use the same context as AddGrydIdempotency<TContext>(). Over another context the scope runs in root mode and commits by itself: Keep is not atomic with the idempotency record and Discard undoes nothing of the route's context.
Exempt routes
A route that must not be idempotent says so with [NotIdempotent("reason")]. The reason is mandatory and appears in OpenAPI as x-gryd-idempotency: { "exempt": true, "reason": "..." }. The innermost attribute wins between [Idempotent] and [NotIdempotent] (method over class); both on the same level fail the host start.
To make sure no write route is forgotten, add a test to the product that fails when a POST, PUT, PATCH or DELETE action carries neither mark:
csharp
using Gryd.API.Idempotency;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
[Fact]
public void Every_write_route_is_idempotent_or_exempt()
{
var actions = factory.Services.GetRequiredService<IActionDescriptorCollectionProvider>().ActionDescriptors.Items;
string[] writes = ["POST", "PUT", "PATCH", "DELETE"];
var unmarked = actions
.Where(a => a.ActionConstraints?.OfType<HttpMethodActionConstraint>()
.Any(c => c.HttpMethods.Intersect(writes, StringComparer.OrdinalIgnoreCase).Any()) == true)
.Where(a => !a.FilterDescriptors.Any(f => f.Filter is IdempotentAttribute or NotIdempotentAttribute))
.Select(a => a.DisplayName)
.ToList();
unmarked.Should().BeEmpty();
}Reading FilterDescriptors also sees global filters and [AcceptVerbs].
Per-route limit
[Idempotent(MaxStoredResponseBytes = n)] sets the largest response stored for one route. 0 (default) uses the host limit. The limit applies in every storage mode, including StatusOnly and Encrypted.
The ceiling of a route's value is max(MaxRouteStoredResponseBytes, MaxStoredResponseBytes). A host that already raised MaxStoredResponseBytes above 8 MiB (the limit allows up to 16 MiB) keeps starting: raising the host limit raises the ceiling with it, so nothing breaks on upgrade. A value above the ceiling fails the host start.
Subject of the key
The key belongs to a subject, by default the authenticated user, together with the tenant. A product replaces it with services.AddGrydIdempotencySubjectResolver<TResolver>(), where TResolver implements IIdempotencySubjectResolver (ValueTask<Guid?> ResolveAsync(HttpContext)), for routes reached without a login, such as a link with a credential.
- The resolver runs before the replay and serves every idempotent route of the host, so it must fall back to the authenticated user when the request carries no link credential.
- Return
nullfor a credential that is invalid, expired or revoked. The route then runs without idempotency (outcomeskipped) instead of replaying the response stored for a credential that no longer counts. - Never store the secret.
IdempotencySubjects.Derive(key, scope, value)returns a stableGuid(HMAC-SHA256 ofscope, a zero byte andvalue; first 16 bytes; version 8, RFC 9562 variant). The key must have at least 32 bytes andscopecannot contain a zero character, otherwiseArgumentException. Take thekeyfrom the host's secret store, never from source code or configuration files.
Stored headers
Replay returns the status, body, Content-Type and Location. Other response headers (for example an ETag) come back only when the host lists them:
csharp
services.AddGrydIdempotency<AppDbContext>(o => o.ReplayedResponseHeaders = ["ETag"]);Up to 16 names, first value of each. Set-Cookie, Authorization, Content-Length, Transfer-Encoding, Location and Content-Type cannot be listed (the options fail validation at startup; the last two already have their own column). The feature needs the ResponseHeaders column: see Upgrading. A listed header without the column fails the host start.
Storage modes
[Idempotent(Storage = ...)] chooses what is kept for replay:
| Mode | Stored | Replay |
|---|---|---|
Full (default) | Status, content type, Location and body | The same response |
StatusOnly | Status and Location | Status, Location and the stored headers, no body |
Encrypted | Like Full, body encrypted with ASP.NET Core Data Protection | The same response |
- The mode of the record decides the replay, not the current attribute: a route that changes mode keeps replaying old records as they were stored.
StatusOnlysuits a201withLocationwhose body the client does not need. Prefer it to a200with an empty JSON body, which breaks clients that parse the response.Encryptedneeds the same Data Protection key ring in every instance: persist keys (PersistKeysTo...) and set the sameSetApplicationNameeverywhere. A body that cannot be decrypted replays only status andLocation, marked withIdempotent-Replay-Degraded: true; the stored headers still come back.- Anything but
Fullneeds theStorageModecolumn. OpenAPI shows it asx-gryd-idempotency: { "storage": "StatusOnly" | "Encrypted" }. AddGrydIdempotencycallsAddDataProtection(). A host without Data Protection gains its hosted service and the framework warnings; a host that already configured it keeps its setup. On start, anEncryptedroute logs a warning when the key repository is not persistent. The same check warns about a missing application discriminator, but only on a host without the standard ASP.NET setup: on a regular ASP.NET host the framework fills it from the content root, so the warning stays silent. Do not rely on it; setSetApplicationNameexplicitly on all instances.
Settled refusals
By default a 4xx rolls everything back and the key stays free. Some refusals are business results whose remaining writes are intended, and a retry must get the same refusal without repeating them. Example: capturing a payment that the provider refuses. The charge attempt runs in a nested scope that is discarded; the refused attempt is recorded after the scope; the action answers a stored 422 carrying the provider's code.
csharp
[HttpPost("capture"), Idempotent(Refusals = IdempotentRefusals.Store)]
public async Task<IActionResult> Capture(
CaptureRequest request, [FromServices] INestedUnitOfWork nested, CancellationToken ct)
{
var charge = await nested.ExecuteNestedAsync(async token =>
{
var result = await payments.ChargeAsync(request.PaymentId, token); // writes the charge
return result.Approved ? NestedOutcome.Keep(result) : NestedOutcome.Discard(result);
}, ct);
if (charge.Approved)
{
return Ok();
}
db.Add(new FailedAttempt { PaymentId = request.PaymentId, ProviderCode = charge.Code });
await db.SaveChangesAsync(ct);
return SettledRefusal("The provider refused the payment.", charge.Code); // 422 by default
}The retry with the same key replays the 422 with Idempotent-Replayed: true and does not charge again.
- The error code is the
codeextension of theProblemDetails.SettledRefusal(message, code, statusCode = 422)is a shortcut inGrydBaseController; outside it, returnnew IdempotentRefusalResult(problem). Both accept only 409 or 422 and a non-emptycode, otherwiseArgumentException. - Both sides must opt in: the route (
Refusals = Store) and the response (IdempotentRefusalResult). A signalled refusal on a route without the option, or one whose final status changed, rolls back, is logged as an error and counts asnot_stored. - Never use it for validation or authorization failures. It would commit partial writes and lock the key for the retention. Those helpers keep rolling back.
- Prefer 422. A stored 409 is easily confused with
IDEMPOTENCY_REQUEST_IN_PROGRESS.Retry-Afteris never stored. OpenAPI shows the route asx-gryd-idempotency: { "refusals": "stored" }. - A stored refusal is final for its key during the retention: fixing the cause and retrying needs a new key.
- It needs the
StoredRefusalsfeature, which replaces the status check of the table (see Upgrading). The host fails to start forStorewithout that mapping and forStorecombined withStatusOnly(the replay would lose the code).Encryptedis fine.
Batch acts
An act over many items keeps its idempotency by running one nested scope per item inside the route's transaction, so a crash repeats the whole batch without duplicating anything:
- Cap the number of items. The cost of the tracker snapshot grows with the square of the items.
- Process items in a deterministic order (by id) to avoid deadlocks between concurrent batches.
- Catch the exception of each item and turn it into that item's result; the scope already undid its writes.
- Domain events with effects outside the database and writes through another
DbContextare not undone by the scope. Send them through the outbox orIAfterCommitEffects.
CORS
A browser client only reads Idempotent-Replayed, Retry-After and Idempotent-Replay-Degraded if the CORS policy exposes them. IdempotencyHeaders.ExposedToBrowsers lists the three; add them to the product's own policy:
csharp
policy.WithExposedHeaders([.. IdempotencyHeaders.ExposedToBrowsers, "ETag"]);The GrydAuth CORS policy already exposes them.
Metrics
The meter Gryd.API.Idempotency is exported by default by Gryd.Observability.OpenTelemetry; other hosts register it with AddMeter(IdempotencyMetrics.MeterName).
| Instrument | Type | Unit | Description |
|---|---|---|---|
gryd.idempotency.requests | Counter | {request} | Requests handled by the filter, by final outcome |
gryd.idempotency.claim.duration | Histogram | s | Time spent claiming the key (buckets 0.001 to 30 s) |
Tags: http.route (route template, unknown when absent) and http.request.method; the counter adds gryd.idempotency.outcome. Neither the key, the tenant nor the user is ever a tag.
| Outcome | Meaning |
|---|---|
stored | The act committed with a 2xx and the response was stored |
not_stored | Nothing was stored: 4xx or 5xx, an unhandled exception of the action, a failed commit, or a refusal signal the route could not honour |
response_too_large | The response exceeded the limit; the act was not applied |
replayed | The stored response was returned |
replayed_degraded | The replay came without the body (undecryptable) |
refused | A settled refusal was committed and stored |
key_reused | The key came with a different request (422) |
in_progress | The first request was still running (409) |
skipped | No subject: the route ran without idempotency |
The outcome is recorded right after the commit or rollback, before the body is written. A failure of the infrastructure before the claim (opening the transaction, claiming) is not counted: no outcome exists yet. Effect failures are counted by the other meter, see below.
After-commit effects
An in-process effect tied to the real commit (a cache invalidation, a notification of the same process) is registered with IAfterCommitEffects.Register(name, effect) and runs once, after the database confirmed and before the response is written. It is discarded on rollback and when a nested scope is discarded. See After-commit effects.
Upgrading to 11.9.0
No code change is required. Two behaviors change on upgrade, and the rest is opt-in:
AddDataProtection().AddGrydIdempotencynow registers ASP.NET Core Data Protection. A host that had none gains its hosted service and the framework warnings.- Audit fix. See "Fixed" in the changelog: a transaction that commits after a failed savepoint is treated as aborted, as PostgreSQL does.
- Opt-in columns need a migration in the product. Map the features at the same call and generate a migration (the framework never creates it), as below.
csharp
modelBuilder.AddGrydIdempotencyRecords("app",
IdempotencyRecordFeatures.ResponseHeaders | IdempotencyRecordFeatures.StorageMode | IdempotencyRecordFeatures.StoredRefusals);| Feature | Needed by | Migration |
|---|---|---|
ResponseHeaders | ReplayedResponseHeaders | Adds column ResponseHeaders (jsonb, null) |
StorageMode | Storage = StatusOnly or Encrypted | Adds column ResponseStorage (smallint, null; null means Full) |
StoredRefusals | Refusals = Store | Replaces CK_idempotency_record_StatusCode with "StatusCode" = 0 OR "StatusCode" BETWEEN 200 AND 299 OR "StatusCode" IN (409, 422) |
Turn a feature on only after the migration is applied, and keep the old code compatible with the schema meanwhile. Without the features the model is identical to before and no migration is needed.
- Route ceiling.
MaxStoredResponseBytesbetween 8 and 16 MiB keeps working; see Per-route limit. - The error code of a settled refusal is
code, like every otherProblemDetailsof the framework.
Limits
- One idempotency context per host; a second, different context throws
InvalidOperationException. - Controllers only. The
Idempotency-Keyheader appears in OpenAPI for controller actions; minimal APIs are not supported: there[Idempotent]is silently ignored (the filter factory does not run) and the route has no idempotency. - A request without a subject (no authenticated user and no resolver answer) runs without idempotency.
- The response must fit in the route's limit.
- Locks. An advisory lock (
pg_advisory_xact_lock) taken inside a nested scope that is discarded is released with the savepoint (observed on PostgreSQL). Row locks follow the PostgreSQL rule: they stay until the end of the owner's transaction, except those acquired after a savepoint that is rolled back to. - Aborted transaction. On PostgreSQL, a
COMMITafter a failed command becomes a silentROLLBACK. The audit trail treats the transaction as aborted only after a failed savepoint command, until aROLLBACK TOsucceeds. The after-commit effects are stricter: any server error (PostgresException) or cancelled command with the transaction open marks it aborted, and the queue is discarded with a warning (EventId 21) unless aROLLBACK TOrecovers it. - A failed command of another context that adopted the route's transaction through
UseTransactiondoes not mark the owner as aborted for the effects. - Audit only treats the failure of a savepoint command. An ordinary command that fails, with the error swallowed and a commit after it, still records the trail of a transaction the database undid (a gap that predates this feature).
- After-commit effects do not support
AddDbContextPool.