Skip to content

Transactional outbox ​

The outbox persists delivery intent with its business fact. ADR 0012 defines the design, alternatives and acceptance ledger.

Capability boundary ​

TransactionalOutbox stages intent. OutboxProcessor.ProcessOneAsync processes one eligible message per call; local effects and receipts commit in the destination PostgreSQL transaction, possibly in another database. AddOutboxMessaging starts no hosted service; AddOutboxWorker opts into pumps. External adapters and an operations UI remain pending. This change adds platform-owned local messages only through explicit host composition and platform execution scope. This API ships in v10.2.0, and a host opts in explicitly. Auth dispatch and Notifications' specialized processor remain distinct: Event Dispatching.

Producer model ​

Each producer maps OutboxMessage and immutable OutboxPayload in its schema; processing also maps OutboxDeliveryState. Mutable delivery data remains separate from the payload. Explicit mapping preserves Notifications' table contract and specialized payloads. No context discovery or startup migration occurs.

InputContract
Message IDGenerate once; preserve on command reconstruction/retry.
Scope / tenant IDTenant is the compatibility default and requires a nonempty owner. Platform is an explicit scope with TenantId = Guid.Empty; empty does not infer platform.
Aggregate ID / sequenceStream key and positive position protected by producer concurrency.
Kind / versionContract name and positive version, e.g. requisition.approved / 1; no CLR names or required version suffix.
Payload / hashImmediate serialized snapshot; digest checks consistency, not authenticity. No entity/service/deferred serialization.
Occurred / availableUTC occurrence and earliest eligibility; availability promises no execution time.
Correlation / causationOptional opaque CorrelationId and nonempty GUID CausationId.
AuthorOptional opaque CausedBy; never identity, permission or authentication.

(Scope, TenantId, AggregateId, Sequence) is unique across kinds. Reserve one aggregate ID per stream; unprotected MAX + 1 is unsafe. The library neither detects nor repairs sequence gaps.

Producer API ​

OutboxEnvelope<TPayload> is the input; TransactionalOutbox<TContext> binds the trusted context and ITenantSession. The host authorizes the operation, supplies PostgreSQL options/tenant services, maps filters/write guards and applies migrations. The writer neither accepts an untrusted context selection nor resolves Auth.

csharp
var outbox = new TransactionalOutbox<PurchasingDbContext>(context, tenantSession);
outbox.Enqueue(envelope);
await context.SaveChangesAsync(cancellationToken);

The complete insert-only example includes the business row, tenant guard and transaction; identity/concurrency remain product duties. Auth's membership producer uses typed Stage; it configures neither delivery nor command retry.

Serialization uses default System.Text.Json. Kind is literal/nonblank, at most 100 characters; version/sequence are positive. CorrelationId/CausedBy are optional nonblank strings up to 200; CausationId is an optional nonempty GUID. Timestamps must be nondefault UTC. Tenant messages must match any session tenant; group reads are rejected. Platform messages require services.AddPlatformTransactionalOutbox<TContext>() and PlatformTransactionalOutbox<TContext>, Scope = Platform, empty TenantId, and an explicit TenantSnapshot.ForPlatformExecution() frame. The frame is not host authorization: composition and caller authorization remain host duties. Tenant writer rejects platform messages; platform writer rejects tenant messages. Neither creates ambient identity or authorizes HTTP input. A trusted tenant producer without a session may still supply the tenant it owns explicitly; do not pass an untrusted request’s tenant to that writer.

Transaction ownership ​

Enqueue only stages: no save, commit, publish or network I/O. Unmapped or known nonrelational contexts are rejected. Save writes business state and intent atomically; an explicit outer transaction owns commit. Its successful Save is insufficient for publication: rollback removes both, and consumers use another context after commit. Processor factories require no tracked entities (even Unchanged), current transaction or automatic EF retries. Legacy PostgresOutbox.ClaimAsync owns a short claim transaction and clears its tracker.

Failure and retry ​

Never publish an in-memory fallback. After rollback, reconstruct the whole command in a fresh context with the same ID/body. For execution-strategy retries, capture ID, sequence proposal, occurrence and payload before the delegate; rebuild business state and intent together, checking aggregate concurrency. Never retry only enqueue or reuse a saved context.

After uncertain commit, verify the operation in a new context before replay; a unique conflict alone proves neither the business fact nor its body. Command idempotency/result verification belong to the application. The writer never silently acknowledges duplicates and does not clear DomainEvents; a future collector must preserve a recoverable snapshot and prove retry after collection.

Explicit local consumption ​

The source maps all three types above. The destination maps InboxReceipt.Configure(modelBuilder.Entity<InboxReceipt>(), "accounting") with tenant filters/write guards. A platform route uses AllowPlatformMessages(producerId) plus AddPlatformLocalConsumer and a separately mapped PlatformInboxReceipt, configured with its context so its query filter permits reads only in IsPlatformExecution. Both receipt types can be mapped in one destination. Each context owns its migrations; apply scope and receipt migrations before enabling processing.

The complete context/consumer example implements ILocalOutboxConsumer<AccountingDbContext, RequisitionApproved>:

csharp
services.AddOutboxMessaging(builder =>
{
    builder.AddProducer<PurchasingDbContext>("purchasing", sp =>
        new PurchasingDbContext(sourceOptions, sp.GetRequiredService<ITenantSession>()));
    builder.AddLocalConsumer<AccountingDbContext, RequisitionApproved, ReserveBudgetConsumer>(
        "purchasing", "accounting.reserve-budget", "requisition.approved", 1,
        sp => new AccountingDbContext(destinationOptions, sp.GetRequiredService<ITenantSession>()));
});

This insert-only illustration is not a budget domain model. The host supplies options, tenant services and migrations. IDs are ordinal/nonblank, up to 100 characters, without peripheral whitespace; kinds are literal ordinal/nonblank strings up to 100, without trimming. Registration rejects duplicate IDs, unknown producers, invalid options and conflicting payload types per route. Consumer IDs are unique across a producer's routes. A producer must call AllowPlatformMessages(producerId) before registering a platform route; plans include only routes for the message scope, including when tenant and platform routes share kind/version. LeaseDuration/MaxFailures must be positive; RetryDelay may be zero.

Handlers default to scoped; existing host lifetime/factory survives. DI owns async disposal; handlers do not dispose themselves. Factories receive scoped providers and return fresh PostgreSQL contexts, without tracked entities/current transactions/automatic EF retries. The processor owns context disposal. Same CLR type may address distinct databases. One physical outbox has ONE stable ProducerId; replicas keep IDs/plans compatible. Moving a destination requires preserving receipts. A drain may map only source tables without retry; Auth's normal context is not a valid drain.

Call await processor.ProcessOneAsync("purchasing", cancellationToken) after resolving OutboxProcessor. Status is NoMessage, Completed, RetryScheduled, DeadLettered, LeaseLost or Deferred, with optional MessageId/FailureCode; confirmed Deferred has separate metadata. Manual processing does not poll: another call is needed when eligible. AvailableAt prevents early claims. GetFailuresAsync(producerId, tenantId, 0, 50, cancellationToken) caps results at 200; the unified query below spans producers. The host authorizes both; neither exposes an HTTP endpoint.

Plan, inbox and failure boundaries ​

Before delivery, the source freezes ordered ConsumerIds and a fingerprint of ProducerId, event data and plan. Restarts reuse it; new consumers do not join old plans. Missing consumers, empty plans, unknown kind/version, invalid metadata/payload/hash fail visibly. Hash validation precedes typed deserialization. Messages cannot select CLR types/deserializers.

An eligible message with no matching registered route is prepared with an immutable empty plan, then ends DeadLettered with OUTBOX_NO_CONSUMERS and FailureCount unchanged at zero. The message has no handler failure to count. Adding a route later does not change that persisted plan. The only way back is the authorized OutboxAdministration.RecoverEmptyPlanAsync (see Operator actions): it accepts only a dead-lettered NoConsumers row with a verified [] plan and intact payload, and routes registered afterwards count only once that recovery has run. Replay of other dead letters stays out of scope. A message that has never been prepared has no plan yet; if processing is enabled after a compatible route is registered, its first preparation can include that route. Keep the worker off while a producer has no complete route coverage. Such rows remain Pending without a plan, but still consume database storage, indexes, backup and operational capacity.

Receipt key is (ProducerId, MessageId, ConsumerId). A destination ReadCommitted transaction reserves it before the handler, waiting on concurrent reservations. A matching completed receipt skips execution; committed incomplete or tenant/fingerprint conflict stops replay. Effect and receipt commit in the same context and transaction. If A committed and B failed, retry skips A; only all completed receipts allow source Completed. There is no distributed rollback or cross-database FK.

Trusted handlers may Save but must not manage/dispose the supplied transaction, write through another context or perform external I/O. Ownership checks cannot undo an early commit or sandbox code; an incomplete durable receipt exposes the violation. Known rolled-back handler failures spend MaxFailures; claims, cancellation, crashes, lost acks and uncertain commits do not. Uncertainty requires a fresh receipt check. Cleanup cannot replace an established outcome. Logs/failures contain codes and technical metadata, never payloads/exception messages/credentials. Unfinished/stopped stream messages block successors; other streams progress. External reconciliation and authorized replay/discard remain separate work.

Lease and execution identity ​

PostgreSQL time governs leases. Source ack/retry/fencing locks before checking expiry, including after lock waits; no source transaction spans handler execution. Recheck after the blocking inbox reservation and before each new handler. An effect started under valid lease may commit late in another DB; receipts prevent duplication. Expired workers start no next handler and cannot ack/retry. Lease validity and destination commit are not atomic across DBs.

ProcessOneAsync suppresses inherited ExecutionContext before task/scope/factory/handler creation, then restores flow before awaiting. HTTP identity/ambient request transactions do not enter. Tenant consumption applies the message tenant via ITenantAmbient, filters enabled, no group/bypass, optional CurrentTenantOnly visibility. Platform consumption uses the explicit platform execution frame (filters remain enabled; optional-tenant visibility is GlobalOnly), then restores scope. Platform receipt rows remain hidden from tenant route reads. CausedBy grants no identity or permissions.

Declared waiting ​

A handler may throw OutboxDeferredException("FILES_OWNER_NOT_READY", TimeSpan.FromSeconds(5)). Code must match [A-Z][A-Z0-9_]{0,99}; delay is 1 ms–24 hours per request. Use application constants, never payload/person/exception text. After confirmed destination rollback (including Save/receipt), the source records Pending, reason and AvailableAt under its lease fence. Confirmed Deferred returns DeferralCode/DeferredConsumerId/DeferredAt/DeferredUntil and null FailureCode; uncertain rollback remains a technical retry requiring fresh receipt verification.

Waiting neither spends nor resets FailureCount. It replaces current failure diagnosis; another confirmed outcome clears deferral metadata. Query age remains original, with earliest retry time. Completed consumers skip, successors block, and other streams remain eligible. Migrate the three nullable companion fields before deployment. See the full contract.

Continuous worker and observation ​

After composing routes, opt in on the selected drain host:

csharp
services.AddOutboxWorker(options =>
{
    options.PollInterval = TimeSpan.FromSeconds(1);
    options.ErrorBackoff = TimeSpan.FromSeconds(5);
});
services.ConfigureOutboxOperations(options => options.SourceTimeout = TimeSpan.FromSeconds(5));

One pump per producer/process isolates unavailable sources and blocked handlers. Idle pumps poll; source errors back off locally. Normal IHost stop cancels/awaits cooperative cleanup; it cannot forcibly interrupt arbitrary code.

csharp
var backlog = await provider.GetRequiredService<OutboxOperationsQuery>()
    .QueryAsync(tenantId, kind: null, limit: 50, cancellationToken: cancellationToken);
var localWorker = provider.GetRequiredService<IOutboxWorkerDiagnostics>().GetSnapshot();

Tenant observation requires an explicit nonempty tenant; kind is an optional literal filter. For explicit platform observations, register AddPlatformOutboxOperations() and call QueryPlatformAsync with the composed PlatformOutboxOperationsCapability; this capability does not authorize HTTP access. Detail limit is 1–200; counts cover all matching active work; Completed and Discarded are terminal and excluded. Partial marks unavailable sources/unknown counts; Truncated means more details on available sources. Snapshots are consistent per producer, not across DBs. Authorization is the host's responsibility. Exclusive buckets separate waiting/failed/stopped/running; eligibility and expired leases are flags. Age uses original OccurredAt and source DB time, not AvailableAt; missing payloads have unknown age. Local diagnostics report enabled/lifecycle/pump progress, not remote liveness or DB readiness; no worker means Enabled=false. Safe cleanup/logging failures cannot overturn confirmed delivery. ADR 0012 specifies buckets, scheduling limits, shutdown and operational gaps.

Auth migration boundary ​

AuthorizationAffectingEventHandler keeps TokenVersion inside Auth's transaction. Classify invariants versus durable reactions and retain revocation/rollback/consumer-failure tests before migration. Neither this foundation nor async conversion satisfies the global precommit-publication guard; moving generation after commit is unacceptable.

Migrated-path gate (CA-04) ​

OutboxMigratedPathsArchitectureTests (in GrydAuth.API.Tests) reads build/outbox-migrated-paths.json and fails when a listed type calls IPublisher.Publish, IMediator.Publish or IDomainEventDispatcher, or implements INotificationHandler<T>; when an entry no longer resolves to a type; when the list is unsorted; or when it has fewer entries than minimumEntries.

  • Add a path: once a type stages its durable reaction through the outbox, add { "type": <full name>, "reason": <why> } in ordinal order and raise minimumEntries to the new count.
  • Remove a path: lower minimumEntries in the same diff so the shrink is reviewed.
  • Justify an exception: a handler that must stay in process goes in exceptions with type, event and reason. Today only AuthorizationAffectingEventHandler for IAuthorizationAffectingEvent qualifies: TokenVersion is a transactional invariant (ADR 0012, section 1). The gate checks that the exception exists and that something raises its event.

Handlers still in process and not listed are not rejected.

Acceptance boundary ​

Stages 2b/2c add worker, observation and waiting mechanisms, not full Auth/Files adoption, real-host composition or CA27/P1 acceptance. Attach PostgreSQL proof to each PR; tenant/permission/order tests must execute the relevant guards/handlers. The ledger separates storage, processing, hosting and product evidence.

Database ownership and migration ​

Producer migrations own source tables/schema; consumer databases may differ. Scope migrations add Scope with a Tenant default, enforce the Tenant/Platform and TenantId pairing, and partition stream uniqueness by scope. Existing generic rows remain Tenant; only the Notifications migration backfills its documented legacy TenantId = Guid.Empty global rows to Platform. Before that Notifications migration, stop and drain every legacy writer that can insert global rows with an empty tenant; deploy the scope-aware writer only after the migration succeeds, then resume producers and workers. This avoids old binaries inserting rows that the new constraint must reject. Apply each producer and destination receipt migration before enabling its new platform writer or route. The scope-aware package rollout still requires an explicit host adoption and deployment plan; schema support alone does not enable platform processing. Unexplained empty-tenant rows in other outboxes fail the constraint visibly. Every intent-writing DB needs a drain. The scope-aware packages ship in v10.2.0; migrations and API availability do not by themselves authorize a rollout. Coordinate writer shutdown, migration, package deployment, and worker enablement as one reviewed release sequence. ADR0011 removed speculative per-tenant/module routing; this guide does not restore it or validate Nexio scale. CA25 needs a topology decision and actual delivery in both DBs. Core has no product browser flow: use transactional DB evidence, adding browser checks for an operational UI or adopted application flow.

Operator actions and payload retention ​

Hosts that need a strict route inventory can call RequireRouteAdmission(producerId) and declare each supported (scope, kind, version, consumer ids) with AdmitRoute. The worker claims only admitted routes; unknown kinds and versions remain pending until a host explicitly admits them. Existing registrations retain their prior dynamic matching unless they opt into this requirement.

In a gradual rollout an old replica does not drain a kind it does not know yet: the message stays pending instead of dying as NoConsumers, and a replica that knows the route drains it later. Register the route before turning the worker on, so no message is prepared with an empty plan.

A kind that has no consumer on purpose is declared with DeclareRouteWithoutConsumers(producerId, scope, kind, version, reason); reason is required, has no peripheral whitespace and at most 200 characters. Its messages end Completed with plan [], no receipt and no failure code, so retention and the operations backlog treat them as done and their stream is released. The declaration counts as an admitted route but does not turn on RequireRouteAdmission. It does not reach a consumer added later: completed messages are not redelivered and there is no replay. A route that is not admitted blocks the next messages of the same stream, never other streams. Composition fails when the key also has a consumer or an AdmitRoute, when it is declared twice, or when the producer is unknown.

Retry, empty-plan recovery, and discard are explicit host operations. Register AddOutboxAdministration<TAuthorizer>() only with a host authorizer that derives actor attribution from trusted execution context and rejects unauthorized requests. Each request needs a stable request id and a reason; the producer transaction journals that decision with the state change. Retry preserves message id, frozen plan, fingerprint, and receipts. Empty-plan recovery accepts only a dead-lettered NoConsumers row with a verified [] plan and intact payload. Discard becomes Discarded, not Completed, and unblocks only its stream successor. The operation result and producer action journal preserve its terminal disposition; active backlog counts exclude it. Messages with external or uncertain effects cannot use these operations.

Payload cleanup is opt-in at the host composition and scheduling boundaries. Register AddOutboxPayloadRetention() only in a trusted maintenance host that authorizes who can resolve and invoke the service, then call OutboxPayloadRetention.PurgeCompletedPayloadsAsync with an explicit minimum age and bounded batch size. Eligibility is based on the database-recorded CompletedAt cut, never the older business OccurredAt; cleanup removes serialized payload only and retains the message sequence stub, delivery state, administrative journal, and destination receipts. Migrations should stamp pre-existing Completed rows at migration time so their retention age starts conservatively.

The migrations in this change are 20261026172019_OutboxOperations (Auth), 20261026172030_OutboxOperations (Files), and 20261026172039_OutboxOperations (Notifications). They add the database completion cut; Auth and Files also add the producer-owned action journal. Apply the matching producer migration before enabling retention or administration. Stop older writers before the migration and deploy the completion-aware writer before resuming them: old binaries can mark rows Completed without setting CompletedAt, which safely prevents cleanup but never ages out.

For a restore or coordinated cutover, stop producers and workers first. Preserve backups of each producer's message stubs, payloads, delivery state and operator journal, along with destination inbox receipts and effects. Restore producer and destination databases to a coordinated point while workers remain stopped. A mismatched restore can leave a destination effect with no receipt, or a receipt confirming an effect that the restore removed; neither state can be made safe by retrying the source blindly. Reconcile every affected message against destination receipts and durable effects before restarting workers. Never delete receipts or force a fingerprint to make a replay pass. Discarded messages remain terminal and visible in the operator journal; retry is limited to a confirmed rolled-back HandlerFailed outcome. An unadmitted route remains Pending and blocks later messages in its aggregate stream; admitting a route does not expand a previously frozen plan. After an operator action or any Discarded transition, rolling back the Auth or Files Operations migration is refused while the journal or discarded row exists. Reconcile and archive that evidence through an explicitly reviewed procedure before rollback; the migration does not erase it, and an older worker must never be allowed to reinterpret a discarded message as unfinished work.

Replay to a new consumer is not implemented. It requires a separate consumer identity, replay origin/id, explicit authorization and a bounded time window; it must not reuse retry or invent a new business stream sequence. Define and review that contract before adding a replay API.

Validation evidence and remaining boundary ​

The current implementation was verified with the Core Infrastructure suite (467 tests), Notifications Infrastructure suite (301 tests), Auth migration/operations tests (6 tests), and Files migration tests (11 tests). These include PostgreSQL checks for action-journal idempotency, denied authorization, transaction rollback and uncertain commit confirmation, preserved receipts, route admission and query eligibility, payload-hash rejection, retention cut, and guarded migration rollback. The Notifications suite also verifies that cancellation records CompletedAt from the database clock. Repository format and analyzer gates passed with the pinned .NET SDK; the analyzer gate reports only the existing informational diagnostics.

This evidence covers infrastructure mechanics and migration behavior. It does not establish product authorization policy, real-host adoption, replay to a new consumer, or a coordinated production restore. Those remain explicit rollout and design work; no UI or external-effect reconciliation was simulated by these tests.

Released under the MIT License.