Skip to content

ADR 0020 — Idempotent acts: nested scopes, after-commit effects and route options ​

  • Status: Accepted
  • Date: 2026-11-16
  • Baseline inspected: develop, 660c5aa3
  • Related: ADR 0019, ADR 0012, ADR 0015
  • Request answered: Nexio, "lacunas na adoção de [Idempotent]" (P-01..P-12)
  • Backlog: backlog/idempotency-gaps/backlog-idempotency-gaps.md

Context ​

ADR 0019 delivered the [Idempotent] filter. The Nexio adopted it on every act route and found gaps that affect any product. The triage, done against the code, confirmed the readings of the request:

ItemWhat the code shows
P-03Under an open transaction, ExecuteInTransactionAsync only runs and saves; there is no savepoint and no way to undo only the act's part. The filter commits on any 2xx.
P-03 (trail)OutboxAuditTrail.Stage only queues an entity in the tracker; the audit interceptor holds events until TransactionCommitted, ignores savepoints and drops everything on any TransactionFailed.
P-06One idempotency context per host; the Auth context uses EnableRetryOnFailure and two flows use ExecuteInOwnedTransactionAsync.
P-08Upload confirmation in Files commits in its own context.
P-09No Meter in the idempotency filter.
P-01The Auth CORS exposed-header list is fixed.
P-04The response-size limit is per host only.
P-10No exemption attribute; the "innermost wins" rule is duplicated between filter and Swagger.
P-02No in-process effect tied to the real commit.
P-11Replay returns only status, Content-Type, Location and body.
P-12The body is stored raw in bytea.
P-05Without an authenticated user the filter skips idempotency.

Decision ​

D1. Nested unit of work. INestedUnitOfWork.ExecuteNestedAsync opens a savepoint inside an open transaction; with no open transaction it opens its own. The operation returns NestedOutcome.Keep(...) or NestedOutcome.Discard(...) (default is Discard). Discard or an exception runs ROLLBACK TO SAVEPOINT followed by RELEASE SAVEPOINT.

D2. Change tracker. Before the savepoint the scope saves the owner's pending changes and snapshots the tracker. On undo it detaches what entered after the snapshot and restores values (including concurrency tokens), navigations and domain events. It never calls ChangeTracker.Clear().

D3. Transaction-bound work. Work tied to the transaction (audit, effects) lives in a single structure, TransactionBoundBuffer<T>: what was born after the mark disappears on ROLLBACK TO SAVEPOINT and moves up a level on RELEASE. The stack stays correct only because every CREATE has its RELEASE. A savepoint failure discards nothing immediately; a later commit of the aborted transaction does, and only a failed Commit or Rollback does it at once.

D4. After-commit effects. IAfterCommitEffects registers an in-process effect on the context's transaction. It runs once, after the database confirmed, with CancellationToken.None, before the HTTP response is written. A failure is logged and counted and never reaches the caller of CommitAsync. The effect is discarded on rollback and when a savepoint is undone. Registering without a transaction, or during the drain, throws InvalidOperationException. The effect must not use the same DbContext.

D5. Exemption. [NotIdempotent("reason")] is filter metadata: the "innermost wins" rule decides between it and [Idempotent]; both at the same level fail at startup. OpenAPI documents it as x-gryd-idempotency. One rule (the route resolver) serves the filter, Swagger and the startup validation.

D6. Per-route limit. [Idempotent(MaxStoredResponseBytes = n)] up to max(MaxRouteStoredResponseBytes, MaxStoredResponseBytes) (MaxRouteStoredResponseBytes defaults to 8 MiB). An invalid attribute fails at startup.

D7. Pluggable subject. IIdempotencySubjectResolver is replaceable per host; the default is the authenticated user. A subject derived from a secret uses IdempotencySubjects.Derive (HMAC, version 8 Guid). An invalid or revoked token yields null before the replay.

D8. Stored headers. A host-provided list of response headers is stored in an opt-in column (IdempotencyRecordFeatures.ResponseHeaders).

D9. Storage mode per route. Full, StatusOnly or Encrypted (Data Protection), recorded on the row in an opt-in column; the replay follows what was recorded. A body that cannot be decrypted replays only status and Location with Idempotent-Replay-Degraded.

D10. Metrics. The Gryd.API.Idempotency meter has an outcome counter and a claim-wait histogram, exported by default.

D11. Browser-exposed headers. IdempotencyHeaders.ExposedToBrowsers lists the headers; the GrydAuth CORS policy exposes them.

D12. Settled refusals. A route opts in with [Idempotent(Refusals = IdempotentRefusals.Store)], and each response opts in too: only a 409 or 422 built with IdempotentRefusalResult (SettledRefusal in GrydBaseController) is committed and stored, with its writes (for example the record of the refusal, written after an act undone in a discarded nested scope). Anything else, including a signalled refusal whose final status changed, rolls back as before; a signal the route cannot honour is logged as an error and counted as not_stored. The status set is {409, 422}, and the CK_idempotency_record_StatusCode check accepts it only for contexts mapped with IdempotencyRecordFeatures.StoredRefusals. The route validator fails the start for Store without that mapping and for Store with StatusOnly, because the replay would lose the error code. This amends, only in this mode, the consequence of ADR 0019 that routes adopting the filter undo writes made before a 4xx. Rejected alternative: leaving the transaction to the action, for the reason of the owned transaction in the filter (D-19).

Consequences ​

  • No behavior changes unless the new API is used, except AddDataProtection() and the audit fix below.
  • The scope costs a tracker snapshot proportional to the tracked entities.
  • The new columns require a migration only for products that turn them on.
  • Encryption requires persisted Data Protection keys and the same ApplicationName across instances.
  • Raw SQL SAVEPOINT or a direct ROLLBACK TO on an outer savepoint breaks the stack.
  • Locks acquired after the savepoint follow PostgreSQL semantics (documented in the guide).
  • A stored refusal is final for its key during retention; retrying after fixing the cause needs a new key.
  • On PostgreSQL a COMMIT after a failed savepoint command becomes a silent ROLLBACK while EF still raises TransactionCommitted. The audit trail treats the transaction as aborted only after a failed savepoint command, until a ROLLBACK TO succeeds. The effects are stricter: any server error (PostgresException) or cancelled command with the transaction open marks it aborted, and the discarded queue is logged as a warning. Both discard what they hold when the transaction commits aborted.
  • Known limits: a failed command of another context that adopted the transaction through UseTransaction does not mark the owner (effects); audit only handles the failure of a savepoint command.
  • AddGrydIdempotency calls AddDataProtection(); the application-discriminator warning only fires on a host without the standard ASP.NET setup.
  • The settled-refusal code travels in the code extension of the ProblemDetails.
  • Behavior fix in audit: a savepoint failure used to skip the trail of a transaction that then committed.

Out of scope ​

  • P-06 (idempotency on module routes): one context per host in ADR 0019, EnableRetryOnFailure in the Auth context and two Auth flows using ExecuteInOwnedTransactionAsync. The request classes it as a blocker; it proceeds as its own epic.
  • P-08 (Files in the consumer's transaction): new design in GrydFiles; it will be the third user of TransactionBoundBuffer<T>.
  • Nested scope in the GrydAuth UnitOfWork; minimal APIs.

Updated at:

Released under the MIT License.