A central database sends event tokens through a looping pipeline to cloud services.
Reliable delivery across connected services

Build a Transactional Outbox for Reliable SaaS Events

A transactional outbox saves a business change and its event in one database transaction, then publishes the event asynchronously. This closes the failure gap between saving application data and notifying another system.

For a SaaS application, that means recoverable subscription updates, audit records, and integration jobs. The essential safeguard is durable intent: committed work remains available for delivery after a crash. Start with the database boundary, then make every downstream step safe to retry.

Key Takeaways

  • Commit business data and its outbox event together, within the same database transaction.
  • Expect duplicate delivery, and protect both event processing and business actions with durable uniqueness rules.
  • Track publishing and downstream processing separately, with retries, failure ownership, and controlled replay.

Why Two Successful Writes Aren’t One Transaction

Suppose your application updates a subscription, then publishes an event to a queue. If the database commits but publishing fails, other services never hear about the update.

Reversing the operations creates another problem. The queue can accept the event before the database transaction fails. Consumers then receive an event describing a change that never happened.

Moving publication into a separate service doesn’t make those writes atomic. As AWS’s transactional outbox guidance explains, the solution is to store the business change and event together, then publish committed events separately.

Both database writes must share a transactional boundary. Two independent databases don’t become atomic because application code calls them consecutively.

The outbox guarantees that a successful transaction includes a durable event record. It doesn’t guarantee exactly-once delivery or immediate downstream completion.

Create an Outbox Table With Recovery Fields

For a PostgreSQL-backed application, create an outbox_events table alongside your business tables. Separate immutable event content from mutable delivery metadata.

These fields support a polling implementation:

Field Purpose
event_id UUID primary key, unchanged across retries.
tenant_id Trusted tenant context for routing and isolation.
aggregate_type, aggregate_id Entity category and identifier, such as a subscription.
aggregate_version Entity version for ordering and stale-update detection.
event_type, schema_version Event meaning and payload contract version.
payload, occurred_at JSON event data and occurrence timestamp.
status, next_attempt_at Delivery state and durable retry schedule.
attempts, last_error Attempt count and diagnostic information.
lease_until, claim_token Claim expiration and worker ownership token.
published_at Time the broker acknowledged publication.

The event stays stable while delivery fields change.

Use states such as pending, publishing, published, and dead_letter. Add an index supporting due pending work, typically starting with next_attempt_at. Also support finding expired leases.

Keep payloads small, version their structure, and exclude secrets. Include the facts consumers need rather than requiring them to reconstruct historical state from mutable records.

Treat tenant_id as security context. Derive it from authenticated application context, never an untrusted payload field.

Write Business Data and the Event Together

Put outbox creation inside the application operation that changes the subscription. Every code path producing that change must follow the same rule.

This language-neutral pseudocode shows the transaction:

  1. BEGIN TRANSACTION.
  2. subscription = LOAD subscription FOR UPDATE, scoped to the authenticated tenant.
  3. UPDATE subscription SET plan = requested_plan, version = version + 1.
  4. INSERT outbox_event(event_id, tenant_id, aggregate_id, aggregate_version, event_type, schema_version, payload, status) using the updated subscription, a new UUID, and pending.
  5. COMMIT; return success only after the commit succeeds.

Set next_attempt_at to the database’s current time when inserting the event. Use an event type such as subscription.updated and include the committed plan and version.

If either database write fails, roll back both. Don’t publish to the broker inside this transaction: network calls prolong locks and still don’t join the broker to the database commit.

Also protect repeated API requests. Where requests have operation IDs, store the operation result in this transaction under a uniqueness constraint. Otherwise, a client retry can create a second business operation and another valid event.

Publish Through Polling or Change Data Capture

Keep the local commit and asynchronous publishing as separate stages. AWS’s domain-consistency architecture illustrates this separation around the service’s database transaction.

Start With a Polling Worker

A polling worker reads committed events that are due for delivery. In a short transaction, select a bounded batch with PostgreSQL’s FOR UPDATE SKIP LOCKED, mark the rows publishing, assign claim tokens, set lease expirations, and commit.

SKIP LOCKED lets concurrent workers avoid waiting on already-claimed rows. It doesn’t provide strict event ordering.

Publish outside that transaction. After the broker acknowledges acceptance under its configured durability guarantees, mark the event published, conditional on the current claim token.

Recover abandoned work when leases expire. Conditional updates stop an old worker from overwriting a newer worker’s delivery state, although overlapping publication can still create duplicates.

A broker acknowledgment confirms handoff. It doesn’t prove that a consumer updated an audit trail, provisioned access, or completed another business action.

Choose CDC When Its Operations Fit

Change data capture reads committed changes through database logging rather than repeatedly querying pending rows. Debezium’s Outbox Event Router can transform outbox inserts into Kafka messages and use the aggregate identifier as the message key.

CDC fits teams already operating connectors and Kafka, or workloads where polling latency and database queries become costly. However, it adds connector recovery, offsets, permissions, and database-log retention concerns.

With CDC, connector offsets track publication progress; polling-specific leases and statuses may be unnecessary. Start with polling when operational simplicity matters more than lower delivery latency.

Handle Retries Without Stranding Events

Publication can fail before acceptance, after acceptance, or while the acknowledgment travels back. A timeout alone can’t distinguish those outcomes.

Persist Backoff and Attempt State

For temporary failures, increment the attempt count and persist next_attempt_at using capped exponential backoff with jitter. Randomized delays prevent a recovering broker from receiving synchronized retries.

Set network deadlines so stalled calls don’t occupy workers indefinitely. Don’t rely on sleeping processes to remember scheduled work.

Keep the original event ID throughout recovery. An attempt ID can change for diagnostics, but changing the event ID defeats downstream deduplication.

Isolate Events That Need Intervention

Move invalid payloads and exhausted deliveries to a durable dead-letter state with a reason. Credential failures may need paused delivery until remediation rather than repeated immediate attempts.

Assign failed events an owner and preserve enough context for investigation. After correcting the cause, replay selected events through the same duplicate-safe path.

Limit work per tenant or destination. Otherwise, one unavailable integration can monopolize workers needed by healthy customers.

Make Consumers Idempotent Before Enabling Retries

The unavoidable duplicate window occurs when a broker accepts an event but the publisher crashes before recording success. The replacement worker publishes it again.

Consumers must handle repeated messages safely.

Commit Deduplication With Local Effects

Create a consumer-side processed_events table with a unique key covering the consumer, source, tenant, and event ID.

Within one consumer database transaction, insert the processing record and apply the business change. If the uniqueness constraint reports an existing event, skip its effects. Roll back the processing record if the business change fails.

Acknowledge the message only after this transaction commits. Recording completion before applying the change can permanently skip work after a crash.

Also enforce business-level uniqueness. Two different events may describe the same paid invoice, so granting an entitlement should have its own operation-level constraint.

Protect External Side Effects Separately

A database transaction can’t atomically commit an unrelated payment-provider request or email API call.

For external work, create a durable action record or another outbox entry. Where the destination supports idempotency, derive a stable key from the business operation and downstream action. Preserve that key across attempts.

Carry trusted tenant and connection context into the worker. Customer-specific integrations must use the correct customer’s credentials and authorization rules.

These safeguards reduce duplicate effects; they don’t create a universal exactly-once guarantee across independent systems.

Define Ordering at the Business-Entity Level

Begin by deciding which events actually require ordering. Subscription changes often need per-subscription ordering; unrelated customers usually don’t need a shared sequence.

Generate aggregate_version under a row lock or optimistic concurrency control. Timestamps alone aren’t a reliable ordering mechanism.

Concurrent polling workers can publish later versions first. If strict ordering matters, serialize publication per aggregate and use matching broker partition or message-group keys. Account for retries so a failed earlier event doesn’t get overtaken.

Consumers applying state updates can reject stale versions or retrieve authoritative state. However, don’t discard valid append-only usage or audit facts merely because they arrived late.

Decide what a version gap means. Depending on the event contract, a consumer may need to wait, retry, or reconcile state before proceeding.

Monitor Backlogs, Clean Up, and Test Recovery

Operational visibility needs to follow the event beyond its first successful queue handoff.

Measure Each Processing Boundary

Track pending count, oldest pending age, publication errors, expired leases, and dead-letter age. Then track consumer lag and business-processing failures separately.

Alert when the oldest pending event exceeds your delivery target. Queue depth alone can hide a small number of permanently stuck events.

Include event ID, tenant ID, aggregate ID, and attempt ID in structured logs. Keep sensitive payload data out of routine logs.

Retain Recoverability Without Keeping Everything Forever

Delete or archive confirmed published rows in bounded batches. Never remove pending or unresolved events merely because they’re old.

For CDC, coordinate cleanup with captured progress and recovery requirements. Retain deduplication records across supported automatic-retry and manual-replay windows. Permanent business uniqueness rules provide protection beyond those windows.

Before rollout, crash the publisher after broker acceptance but before marking publication complete. Also test concurrent duplicate consumption and a consumer crash after committing but before acknowledgment.

Exercise expired leases, reordered versions, unavailable destinations, and dead-letter replay. Assert both eventual completion and the absence of repeated business effects.

Build Around Recoverable Completion

A transactional outbox makes event creation atomic with your local business change. Reliable delivery then depends on recoverable publishing, duplicate-safe consumers, and visible failure handling.

Start with one event type and prove the crash boundaries before expanding. Treat business completion as a separate fact from publication, and keep enough durable state to recover when either stage fails.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *