Skip to content

ADR 0019 — Idempotent act routes: the record lives in the context that owns the act ​

  • Status: Accepted
  • Date: 2026-11-14
  • Baseline inspected: develop, 63638c74
  • Related: ADR 0012, ADR 0011, ADR 0015
  • Request answered: Nexio, "idempotência nas rotas de ato" (REQ-01..REQ-10)
  • Backlog: backlog/idempotency/backlog-idempotency.md
  • Amended by: ADR 0020
  • Guide: Idempotent act routes

Context ​

The Nexio runs on Gryd.IO and exposes dozens of routes that execute business acts: approve, reject, publish, delegate, apply, import. The same request reaches the server more than once (double click, automatic resend by the browser or a proxy, a client retry after a timeout whose response was lost). Without protection the act runs twice, or the retry gets a conflict error although the first attempt succeeded.

The platform offers nothing for HTTP today. The only idempotency that exists is the outbox consumer's InboxReceipt (ADR 0012), which this decision does not touch. The request asks for ten guarantees (REQ-01..REQ-10): one execution per intent, the same response on repetition, a clear refusal when a key is reused for a different request, safety under concurrent arrival, atomicity between the act and its record, isolation by tenant and user, bounded retention with automatic cleanup, opt-in adoption per route, cooperation with the unit of work including nested acts, and no effect on background jobs.

The principle is the one of ADR 0012, section "Storage belongs to the context that owns the fact": each participating product maps the record into its own EF Core context and schema, so the fact and its record share one transaction.

Options considered ​

OptionEvaluationVerdict
Central idempotency store in its own contextLoses atomicity between the act and its record without a distributed transaction (same reason as ADR 0012).Rejected
MediatR behavior that stores the command responseDepends on TResponse surviving a JSON round trip and does not repeat the exact HTTP response.Rejected
Redis/in-memory lock + response cacheNot atomic with the act; a crash between the commit and the cache write loses the record.Rejected
MVC resource filter that owns the transaction of the producer's contextRecord and act commit together; replays the exact HTTP response; handlers do not change.Chosen

Decision ​

D1. Opt-in per action or controller. [Idempotent] marks a route; [Idempotent(Key = IdempotencyKeyMode.Optional)] adopts it on already published routes without breaking clients. Without the attribute the header is ignored. The layer is HTTP, per route; Roger's decision: "HTTP, por rota" (the filter sits on the action, stores status and body and replays the same HTTP response; handlers do not change).

D2. Key in the Idempotency-Key header. A valid key has 1 to 255 characters, all between 0x21 and 0x7E (visible ASCII, no space), and the header carries exactly one value. A missing key on a Required route returns 400 IDEMPOTENCY_KEY_REQUIRED; an invalid one returns 400 IDEMPOTENCY_KEY_INVALID.

D3. IdempotencyRecord mapped by the product in its own DbContext (AddGrydIdempotencyRecords(schema)), table idempotency_record. The primary key is (TenantId, SubjectId, Key). TenantId is ITenantSession.TenantId ?? Guid.Empty and SubjectId is ICurrentUserService.UserId. The product generates the migration.

D4. The filter owns the transaction. It opens a ReadCommitted transaction on the registered context, claims the record before the action with INSERT ... ON CONFLICT DO UPDATE ... WHERE r."ExpiresAt" <= clock_timestamp(), which atomically takes either a new key or an expired one, runs the action with the response in a buffer and, only on a 2xx status, stores the response in the record and commits. Any other status or an exception rolls back: nothing of the act and nothing of the record. The client receives bytes only after the commit.

D5. Repetition. The same request fingerprint (RequestFingerprint: SHA-256, lowercase hex, of "v1\n" + METHOD + "\n" + PATH + "\n" + QUERY + "\n" in UTF-8 followed by the raw body bytes) returns the same status, Content-Type, Location and body, plus Idempotent-Replayed: true. A different fingerprint returns 422 IDEMPOTENCY_KEY_REUSED.

D6. Concurrency. The primary key makes the second arrival wait for the first. The wait is capped by a transaction-local lock_timeout (default 10 s), restored right after the insert. If it expires the response is 409 IDEMPOTENCY_REQUEST_IN_PROGRESS with Retry-After: 1. Roger's decision: "Espera e repete".

D7. Nested acts. EfUnitOfWork and handlers join the filter's transaction; a handler must not open or commit its own top-level transaction. A context whose execution strategy retries is refused with InvalidOperationException.

D8. Retention. ExpiresAt is the database clock plus Retention (default 24 h; Roger's decision: "24 horas"). An expired record is ignored and replaced. A BackgroundService purges in batches every PurgeInterval.

D9. Boundaries. Outside HTTP (jobs, outbox, Hangfire) nothing changes: the mechanism is an MVC filter. One context per host (D-01). Without an authenticated user the route runs without idempotency and logs a warning (D-02). A response above MaxStoredResponseBytes returns 500 IDEMPOTENCY_RESPONSE_TOO_LARGE and rolls back.

Consequences ​

  • The stored response has the same sensitivity as the act's data and stays in the product's database for the retention period.
  • Routes that adopt the filter now undo writes made before a 4xx.
  • The product needs a migration.
  • Only writes through the registered context roll back. Another DbContext, e-mail, HTTP calls or an in-process reaction outside the transaction do not; external effects go through the outbox (ADR 0012).
  • IdempotencyRecord carries TenantId without a tenancy marker by design (access only by SQL with the tenant in the primary key), so the scope review does not flag it.
  • The second arrival holds a pool connection for up to LockTimeout.

Out of scope ​

  • Queue and outbox consumers.
  • Minimal APIs.
  • Several contexts per host.
  • Adoption in the Gryd.IO modules' own routes.

Updated at:

Released under the MIT License.