ADR-0018: Transactional outbox for domain events + command idempotency
- Status: accepted — supersedes the in-transaction domain-event dispatch of ADR-0006; processor semantics (lease claim, per-handler checkpoints, back-off, dead-letter window) refined by ADR-0023
- Amended: 2026-10-08 — idempotency v2: the reservation rides the command's unit of work and the stored response is replayed (see Amendment below)
- Amended: 2026-10-11 — declared unique constraints: every registered constraint becomes its
Result, any unregistered constraint still throws (see Amendment (2026-10-11) below) - Amended: 2026-10-11 — one
Idempotency-Keyvalue per request, a key an endpoint may require, and one owner for everyIdempotency.*code (see Second amendment (2026-10-11) below) - Amended: 2026-11-09 — a concurrent first that fails on the winner's data is answered from the store, not with the feature's own error (see Amendment (2026-11-09) below)
- Date: 2026-07-16
Context
Section titled “Context”Domain events were dispatched inside SaveChanges (ADR-0006's original interceptor), so a side-effecting handler (SendReceiptOnInvoicePaid sends an email) ran before the transaction committed. With EF retry owned by the DbContext (EnableRetryOnFailure), a transient Postgres blip could re-run the save and re-send the email; a rolled-back transaction could send an email for a payment that never happened. Separately, POST commands weren't idempotent — a client retry created duplicate invoices/payments.
Decision
Section titled “Decision”Transactional outbox. OutboxWriteInterceptor serializes each pending domain event into an OutboxMessage row in the same transaction as the aggregate change (no handlers run during SaveChanges). OutboxProcessor (a BackgroundService in the long-running API host, not the one-shot MigrationService) polls unprocessed messages, deserializes, and dispatches them after commit, marking each processed (with bounded retries). Side effects therefore run at-least-once, only after the data is durably committed.
- Domain events crossing the outbox use primitive/simple types (e.g.
InvoicePaidDomainEventcarries astringemail, not theEmailAddressvalue object) so they JSON round-trip. Strongly-typed IDs round-trip via the SharedKernel JSON converter.
Command idempotency. An opt-in IdempotencyFilter endpoint filter reserves an Idempotency-Key header value (IIdempotencyStore → IdempotencyKeys table, PK-enforced) before the handler runs; a duplicate key short-circuits with 409. If the handler throws, the key is released so a genuinely-failed request can be retried. Applied to the invoice command endpoints. (Superseded by the 2026-10-08 amendment below: the reservation is no longer written before the handler runs, and a retry is answered with the stored response rather than refused.)
Consequences
Section titled “Consequences”- Closes the concurrency/idempotency/outbox/retry interaction: retried transactions no longer re-fire side effects (outbox), duplicate requests can't double-apply (idempotency), and lost updates are caught (the
xminconcurrency token). - Eventual delivery of side effects (post-commit) instead of synchronous — the correct trade-off for external effects.
- Two new tables (
OutboxMessages,IdempotencyKeys). Response replay for idempotency (returning the original response) was named here as the documented evolution; the amendment below delivers it.
Amendment (2026-10-08): idempotency v2 — reserve inside the unit of work, replay the stored response
Section titled “Amendment (2026-10-08): idempotency v2 — reserve inside the unit of work, replay the stored response”The original filter left two holes exactly where the header exists to help. It committed the key in its own SaveChanges before the handler ran, so a process kill between the reservation and the command's commit blocked the client's retry for Retention:IdempotencyKeyAge (2 days) for an operation that never happened. And a retry of an operation that did happen — a client re-sending after a lost response — was answered "already processed" with no id and no Location, so the client could not finish what it started.
Decision
Section titled “Decision”- The reservation rides the command's unit of work.
IIdempotencyStorebecomesFindAsync(key)→None | InFlight(reservedAtUtc) | Completed(requestFingerprint, StoredResponse),Reserve(key, fingerprint)— which only tracks the row on the request's scopedAppDbContext— andCompleteAsync(key, StoredResponse). The UnitOfWork decorator's commit therefore writes the reservation, the aggregate and the outbox rows in one transaction.TryReserveAsync/ReleaseAsyncare gone: nothing is written before the commit, so there is nothing to release. A command that fails before its commit (validation, not found, concurrency conflict, exception) leaves no reservation and its key may be retried as is. - The commit race is decided by the primary key. Two first requests both pass the lookup, both reserve, both run; the loser's
SaveChangeshitsPK_IdempotencyKeysand its whole unit of work rolls back.AppDbContext.CommitAsyncmaps that one unique violation toIdempotencyErrors.Duplicate(409 through the Result seam, ADR-0004 amendment) — which is why theIdempotencyErrorscatalogue lives inApplication.Abstractions, where Persistence can reach it. Any other unique violation still throws. (Refined by the 2026-10-11 amendment below: any unregistered constraint still throws; a registered one becomes itsResult.) - Scope and fingerprint. The stored key is
SHA-256(user:METHOD:path:client key)— the method joins the composite. The fingerprint isSHA-256(method, path + query, SHA-256 of the body)where the body is the one the endpoint bound, re-serialised with the host's JSON options: the filter runs after binding, when the request stream is spent, and the canonical form is the better definition anyway (whitespace or member order is not a different request; a changed value is). - The row (
IdempotencyKeys) gainsRequestFingerprint,StatusCode,ContentType,Body,LocationandCompletedAtUtc; a row without aStatusCodeis in flight.InitialCreatewas regenerated (pre-release convention; the template repository's all-options CI leg regenerates it again with the tenant columns). - What a retry gets. Completed with the same fingerprint and a stored body: the response, byte for byte, with
Idempotency-Replayed: true;Locationis the only header replayed. Completed with the same fingerprint but no stored body: 409Idempotency.Duplicate— the command applied once, read the resource. Completed with a different fingerprint: 422Idempotency.FingerprintMismatch— the key was reused for another request, a client bug rather than a retry. In flight: 409Idempotency.InFlightwithRetry-After: 1. A blank key is still a 400Idempotency.InvalidKey. The 422 is written fromIdempotencyProblems.FingerprintMismatch(aProblemDescriptornext to the filter) because a 422 has noErrorType; every other outcome goes throughCustomResults. - The replay cap. The body is stored up to 64 KB (
IdempotencyFilter.DefaultMaxReplayBodyBytes), per endpoint viaRequireIdempotency(maxReplayBodyBytes:). A larger response is served unchanged and completed without a body, so its retry is the 409 above. It is a property of an endpoint's response shape rather than a deployment knob, which is why it is not configuration. - Completion is one small write after the response went out, never with the request's token. A fault after the commit (post-commit work must use
CancellationToken.None,.claude/rules/api.md) ends the request with a 500 but completes the reservation without a body: the retry is a 409, never a second apply. - Retention is unchanged: the janitor sweeps
IdempotencyKeysbyCreatedAtUtcwhatever the state.
Known residue
Section titled “Known residue”A crash between the commit and CompleteAsync leaves a committed command with no stored response: the row reads in flight (409 Idempotency.InFlight) until retention sweeps it (default 2 days). The same window opens if storing the outcome fails (logged at Warning). It cannot be closed without serialising the HTTP response inside the command's transaction, which would break the pipeline's commit boundary; the client's remedy is to read the resource.
Consequences
Section titled “Consequences”- Clients may retry a keyed POST safely and receive the original answer; the UI's typed client can opt back in to automatic POST retries for the calls it keys (follow-up in UI.Common).
- One extra
SELECTper keyed request (the lookup) and oneUPDATEper successful one (the completion). - Fitness:
IdempotencyReplayTests(replayed 201 and 204, the 422, a commit race held at a barrier, an in-flight duplicate held at a gate, a failed command, the cap),IdempotencyStoreTests(the three states against Postgres, nothing written before the commit, the PK race, retention),IdempotencyPostCommitTests,MigrationDriftTests.
Amendment (2026-10-11): declared unique constraints
Section titled “Amendment (2026-10-11): declared unique constraints”The 2026-10-08 amendment mapped exactly one unique violation, PK_IdempotencyKeys, and said any other
still throws. Registration showed the cost: two registrations of one e-mail both pass the account
lookup and Identity's own uniqueness check, the second INSERT loses at Identity's unique UserNameIndex
(the user name is the e-mail), and the caller got a 500 for what a sequential duplicate answers as 409.
Decision
Section titled “Decision”- One map, by constraint name.
UniqueConstraintErrors(internal to Persistence) maps a pinned constraint name to theErrorits violation stands for:PK_IdempotencyKeys→Idempotency.Duplicate,UserNameIndex→Auth.EmailAlreadyInUse. Each name is pinned by its configuration (IdempotencyKeyConfiguration.PrimaryKeyName,ApplicationUserConfiguration.UserNameIndexName), not inherited silently from a library default. - Both commit points consult it.
AppDbContext.CommitAsync(the unit of work) andIdentityService.RegisterAsync(whose Identity writes commit in their own transaction) catch aDbUpdateExceptiononly when the map knows its constraint, clear the change tracker and return the mappedResult. - Any unregistered constraint still throws. A violation nobody declared is a model the code did not foresee: a 500 with an Error log, never a guessed 409. There is deliberately no blanket "unique violation → Conflict". Registering a constraint means pinning its name, adding a row to the map and racing it in a test.
- One code, one type. Identity's reported rejections no longer share
Auth.RegistrationFailedwith the role-assignment rollback: a duplicate Identity reports itself isAuth.EmailAlreadyInUse(409), anything else is 400Auth.RegistrationRejectedwhose description is a fixed sentence perIdentityError.Code(Identity's own descriptions echo the e-mail into the response and the outcome log);Auth.RegistrationFailedstays the 500 for the rollback.
Consequences
Section titled “Consequences”- A lost registration race answers exactly what a sequential duplicate answers, and exactly one account
exists (
RegistrationRaceTests, which holds both registrations past Identity's checks before either inserts).RegistrationRejectionTestspins the codes and the PII-free descriptions.
Second amendment (2026-10-11): one key per request; a key an endpoint may require
Section titled “Second amendment (2026-10-11): one key per request; a key an endpoint may require”The 2026-10-08 amendment defined what a key buys and what a blank key costs, and said nothing about two
keys or none. The filter read the header as one string, and a repeated header's values come out of
StringValues joined with a comma, so a and b became the key a,b, one the caller never sent (a
single value holding a list was taken whole the same way), and a retry that sent them in the other order
was a different request. And a missing header always meant "no
idempotency": right for a write to an addressed resource, wrong for a create, where an accidental repeat
cannot be told from a second intent and a client that forgot the header learns it from a duplicate.
Decision
Section titled “Decision”- One value. The filter accepts exactly one
Idempotency-Keyvalue. Two headers, or a value with a comma in it, are a 400Idempotency.InvalidKey: never joined, never split, never the first one taken. The code is the one the blank and the too-long key already answer with, because the remedy is the same (send one usable key, or omit the header); the description says which rule the key broke. - A required key is an endpoint's opt-in.
RequireIdempotency(keyRequired: true)answers a request without the header with a 400Idempotency.KeyRequired, and the OpenAPI document marks the header required on that operation. The default stays optional, so an endpoint keeps the behaviour above unless it asks. The reference slice opts in onPOST /invoices; the writes to an existing invoice act on an addressed resource and keep the key optional. - One owner per code. Every
Idempotency.*outcome that is anErrorlives in Application'sIdempotencyErrors, the header outcomes only the filter produces (MultipleKeys,KeyRequired) as much as theDuplicatethe unit of work returns.Idempotency.InvalidKeyis declared once (IdempotencyErrors.InvalidKeyCode) and shared by the blank, too-long and multi-value errors. TheIdempotencyHeaderErrorsclass that ADR-0024's second amendment places beside the filter was folded into it; nothing on the wire changed. The fingerprint mismatch stays aProblemDescriptor: a 422 has noErrorType(the 2026-10-08 amendment).
ADR-0024's second amendment records the wire contract of both outcomes (status, code, the
ProblemDetailsContractTests rows); this amendment records the filter's rules behind it.
Consequences
Section titled “Consequences”- A client that sends a key gets the guarantee for exactly the key it sent, or a 400 that says why not.
- An endpoint author decides per endpoint whether a missing key is acceptable; the document tells the client which.
- Fitness:
EndpointContractTests(a repeated header and a list are each a 400Idempotency.InvalidKeywith the multi-value description;POST /invoiceswithout a key is a 400Idempotency.KeyRequiredwhile a write to an existing invoice still runs without one),ProblemDetailsContractTests(theIdempotency.KeyRequiredrow), the OpenAPI snapshot (the header is required on the create only),ErrorCodeVocabularyTests(one meaning per code).
Amendment (2026-11-09): the store re-check for a loser that fails first
Section titled “Amendment (2026-11-09): the store re-check for a loser that fails first”The 2026-10-08 amendment says two concurrent firsts resolve at the primary key. That holds while both
reach their commit, which the reference slice guarantees only because Invoice has no unique business
key; the add-feature skill tells every feature with one to add a registered unique index. With one,
the loser can fail on the winner's data before its reservation ever meets PK_IdempotencyKeys: the
feature's own uniqueness lookup finds the row the winner just committed, or the business index fires
before the primary key inside the same commit. Either way the loser answers the feature's 409 (an
e-mail already in use) for a create that succeeded, and a client that retried after a lost response
learns that its own request is a conflict.
Decision
Section titled “Decision”- A failed keyed request asks the store again. When the endpoint returns a 4xx for a request that
carried a key,
IdempotencyFilterrepeats the lookup it made before reserving. The winner's reservation committed in the same transaction as the row the loser failed on, so the untracked re-read sees it: in flight (409Idempotency.InFlightwithRetry-After), completed with a replayable body (the replay), completed without one (409Idempotency.Duplicate), or completed for another body (422Idempotency.FingerprintMismatch, the key reused). Nothing found means no same-key request committed, and the 4xx is the request's own answer. A 4xx can be answered from the store because, on an endpoint that declaresRequireIdempotency, nothing commits the request'sAppDbContextexcept the unit-of-work decorator (UnitOfWorkDecorators), which commits only on a successResult, and the endpoint maps that success to a 2xx; so the re-read never finds the request's own reservation. A handler that saves through Identity'sUserManagerbefore it fails breaks that condition: sign-in's lockout count (AccessFailedAsync, then a 401) saves the same context, reservation included. Keyed, such an endpoint would find its own key in flight, answer 409 and leave the keyInFlight. - The primary key's verdict stands. A loser whose commit did reach the primary key already answers
Idempotency.Duplicate, so the filter does not ask again; the 2026-10-08 race is unchanged. - Only failures pay for it. One extra
SELECT, on a keyed request that failed with a 4xx; a success and a request without a key cost nothing new. A 5xx is not re-checked: it is a fault, not a lost race.
Consequences
Section titled “Consequences”- A feature with a unique business key needs nothing of its own for its idempotent create: the loser of
a same-key race hears an
Idempotency.*answer or the replay, never its feature's conflict code. - A same-key request that fails for a reason of its own while another one commits hears the store's answer instead of its own 4xx; with the same body that answer is the truth about the key, and with a different body it is the 422 the reused key earns anyway.
- Fitness:
IdempotencyReplayTests.A_concurrent_first_that_fails_on_the_winners_data_is_answered_from_the_store_not_with_its_own_409(a derived host whose create handler fails the second of two same-key requests with a conflict once the first committed; the loser answersIdempotency.InFlight,Idempotency.Duplicateor the replayed 201), beside the primary-key race the 2026-10-08 amendment already lists.
The documentation of Trellis.Templates 0.2.0 · release notes