Skip to content

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 with Idempotent-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 Retention and 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 ​

  1. 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");
}
  1. Register the support for that context:
csharp
using Gryd.API.Extensions;

services.AddGrydIdempotency<AppDbContext>(o => o.Retention = TimeSpan.FromHours(24));
  1. 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-Key header: exactly one value, 1 to 255 characters, all visible ASCII (0x21 to 0x7E, 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: true is the stored one; the act did not run again.
  • On 409 IDEMPOTENCY_REQUEST_IN_PROGRESS, wait the Retry-After delay (1 second) and send the same request again. The 409 is returned only after the server has already waited LockTimeout for 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 ​

CodeStatusWhen
IDEMPOTENCY_KEY_REQUIRED400The route requires the header and the request has none.
IDEMPOTENCY_KEY_INVALID400The key is not 1 to 255 visible ASCII characters, or the header is repeated.
IDEMPOTENCY_KEY_REUSED422The key was already used with a different request.
IDEMPOTENCY_REQUEST_IN_PROGRESS409The first request with this key is still running; carries Retry-After: 1.
IDEMPOTENCY_RESPONSE_TOO_LARGE500The response exceeds MaxStoredResponseBytes; the act is not applied.

Options ​

OptionDefaultLimits
Retention24 hours1 minute to 30 days
LockTimeout10 seconds100 ms to 60 s
MaxStoredResponseBytes1 048 5761 to 16 777 216
MaxRouteStoredResponseBytes8 388 6081 to 16 777 216; see Per-route limit
ReplayedResponseHeadersemptyUp to 16 names; see Stored headers
PurgeInterval15 minutes1 minute to 24 hours
PurgeBatchSize10001 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 null for a credential that is invalid, expired or revoked. The route then runs without idempotency (outcome skipped) instead of replaying the response stored for a credential that no longer counts.
  • Never store the secret. IdempotencySubjects.Derive(key, scope, value) returns a stable Guid (HMAC-SHA256 of scope, a zero byte and value; first 16 bytes; version 8, RFC 9562 variant). The key must have at least 32 bytes and scope cannot contain a zero character, otherwise ArgumentException. Take the key from 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:

ModeStoredReplay
Full (default)Status, content type, Location and bodyThe same response
StatusOnlyStatus and LocationStatus, Location and the stored headers, no body
EncryptedLike Full, body encrypted with ASP.NET Core Data ProtectionThe 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.
  • StatusOnly suits a 201 with Location whose body the client does not need. Prefer it to a 200 with an empty JSON body, which breaks clients that parse the response.
  • Encrypted needs the same Data Protection key ring in every instance: persist keys (PersistKeysTo...) and set the same SetApplicationName everywhere. A body that cannot be decrypted replays only status and Location, marked with Idempotent-Replay-Degraded: true; the stored headers still come back.
  • Anything but Full needs the StorageMode column. OpenAPI shows it as x-gryd-idempotency: { "storage": "StatusOnly" | "Encrypted" }.
  • AddGrydIdempotency calls AddDataProtection(). A host without Data Protection gains its hosted service and the framework warnings; a host that already configured it keeps its setup. On start, an Encrypted route 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; set SetApplicationName explicitly 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 code extension of the ProblemDetails. SettledRefusal(message, code, statusCode = 422) is a shortcut in GrydBaseController; outside it, return new IdempotentRefusalResult(problem). Both accept only 409 or 422 and a non-empty code, otherwise ArgumentException.
  • 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 as not_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-After is never stored. OpenAPI shows the route as x-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 StoredRefusals feature, which replaces the status check of the table (see Upgrading). The host fails to start for Store without that mapping and for Store combined with StatusOnly (the replay would lose the code). Encrypted is 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 DbContext are not undone by the scope. Send them through the outbox or IAfterCommitEffects.

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).

InstrumentTypeUnitDescription
gryd.idempotency.requestsCounter{request}Requests handled by the filter, by final outcome
gryd.idempotency.claim.durationHistogramsTime 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.

OutcomeMeaning
storedThe act committed with a 2xx and the response was stored
not_storedNothing 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_largeThe response exceeded the limit; the act was not applied
replayedThe stored response was returned
replayed_degradedThe replay came without the body (undecryptable)
refusedA settled refusal was committed and stored
key_reusedThe key came with a different request (422)
in_progressThe first request was still running (409)
skippedNo 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(). AddGrydIdempotency now 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);
FeatureNeeded byMigration
ResponseHeadersReplayedResponseHeadersAdds column ResponseHeaders (jsonb, null)
StorageModeStorage = StatusOnly or EncryptedAdds column ResponseStorage (smallint, null; null means Full)
StoredRefusalsRefusals = StoreReplaces 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. MaxStoredResponseBytes between 8 and 16 MiB keeps working; see Per-route limit.
  • The error code of a settled refusal is code, like every other ProblemDetails of the framework.

Limits ​

  • One idempotency context per host; a second, different context throws InvalidOperationException.
  • Controllers only. The Idempotency-Key header 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 COMMIT after a failed command becomes a silent ROLLBACK. The audit trail treats the transaction as aborted only after a failed savepoint command, until a ROLLBACK TO succeeds. 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 a ROLLBACK TO recovers it.
  • A failed command of another context that adopted the route's transaction through UseTransaction does 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.

See ADR 0019 and ADR 0020.

Released under the MIT License.