Outbox Pattern
The order is in the database, but RabbitMQ goes down before the OrderPlaced event leaves. Subscribers never learn about the order. This is the dual-write problem: the Outbox Pattern solves it by writing the event in the same DB transaction, and the Inbox Pattern guards against duplicates on the subscriber side. In Symfony 8 that means one Doctrine entity manager, one Messenger transport, and roughly 80 lines of code.
In this chapter
The chapters on CQRS, Event Sourcing, and sagas kept relying on the same assumption: when an aggregate publishes an event out of its context after the commit, the event reliably reaches the message broker and, from there, the subscribers. That assumption does not hold. Between the database write and the dispatch to a Messenger transport sit a network hop and two independent systems, each of which can fail on its own. The result is the dual-write problem, one of the most common sources of silent inconsistencies in event-driven architectures.
The Transactional Outbox Pattern is the standard solution to the dual-write problem. Chris Richardson wrote the catalog definition of the pattern; Pat Helland supplies the framework in his paper Life Beyond Distributed Transactions (2007): rejecting distributed transactions and requiring an idempotent receiver. Catalogs call the subscriber-side counterpart Idempotent Consumer, or by its older name Idempotent Receiver; this chapter uses the working name Idempotent Inbox for it, because it stands symmetrically opposite the outbox.
15.01 Dual-write problem#
The simplest publishing implementation looks innocent: after the domain operation, the state
is written to the database and the event goes straight onto the message bus. Code like this passes
code review without comment – until lost events start piling up in production, along with subscriber complaints like “I can see order
12345 in the API, but the OrderPlaced event never reached me.”
Step 1 and step 2 are two independent transactions in two different systems. Any failure between them is enough: a network timeout, a crashed worker, an application restart, a broker outage, an OOM kill of the PHP process. The system then ends up in one of two asymmetric inconsistent states:
- The DB write succeeded, the dispatch to the broker did not. This happens wherever the commit runs
before the dispatch – typically without the
doctrine_transactionmiddleware, whenflush()commits its own transaction. The order exists in the database, but theOrderPlacedevent was never sent. The subscriber contexts (Payment, Warehouse, Notifications) don't know about the order. The customer sees it in the API, but the payment is not charged, the warehouse reserves nothing, and no email arrives. This is the worst scenario: the domain event is lost and leaves no trace in the log. - The dispatch to the broker succeeded, the DB write did not. Under the
doctrine_transactionmiddleware, publishing before the commit is the default order, not the mistake of someone who rearranged the code: the middleware commits only after the handler returns. The commit can then fail after the dispatch, for example because of an optimistic lock. Subscribers receive an event about an order that does not actually exist. The read model adds a row, Payment tries to charge money for a nonexistent order, and Notifications sends an email with a link to a 404. The result is a “phantom event” – an event that did not happen in the source DB.
Both scenarios break the atomicity of writing to two systems, and in event-driven architectures they are not rare. Pat Helland described the problem in his paper Life Beyond Distributed Transactions: An Apostate's Opinion (2007), although he does not use the term dual-write. In his account, a message sent from a transaction that then aborts causes an effect the system has no memory of; transactional enqueuing of messages is therefore a necessity. Once a transaction crosses the boundary of a single store, the database cannot guarantee atomicity, and application logic has to restore it. The word outbox does not appear in the paper either. The table and the relay process were described later by Chris Richardson in Microservices Patterns (2018, chapter 3) and in the microservices.io catalog. His formulation of the solution: the sender first stores the message in the database in the same transaction that changes the domain entities, and only then does a separate process send it to the broker. The catalog lists Event Sourcing as an alternative.
Sources: Helland, P. Life Beyond Distributed Transactions: An Apostate's Opinion, CIDR (2007); Richardson, C. Microservices Patterns, Manning (2018), chapter 3 – Transactional messaging; Microservices.io – Pattern: Transactional Outbox.
15.02 Transactional Outbox – the principle#
Instead of a dispatch to the broker, the event is written to an outbox table in the same database
where the domain state lives, inside the same DB transaction as the aggregate change.
Either both are written (the order and its event), or nothing is (rollback of the whole transaction).
Atomicity is back: both writes sit in a single ACID transaction of one database,
not in two different systems.
A separate process (the relay worker, sometimes called the publisher
or dispatcher) polls the table asynchronously. It selects rows with the status
pending, publishes them to the real message broker, and after a successful publish
marks them as sent. The flow has four phases:
- Phase 1 – the domain transaction. The application handler stores the aggregate and the corresponding outbox rows in one Doctrine transaction.
- Phase 2 – polling the outbox. The relay worker periodically (for example, every
100 ms) selects pending rows from the outbox, ordered by
occurred_at. The result is best-effort FIFO, not guaranteed ordering. The reason is covered in section 15.05. - Phase 3 – publishing to the broker. For each row, the relay publishes the event
to the broker and, after receiving the ACK, marks the row as
sent. The two operations do not run in one transaction. If the relay crashes between them, the row stayspendingand the publish is repeated after the restart. This yields the at-least-once delivery guarantee discussed below. - Phase 4 – consumption by the subscriber. The subscriber receives the message, processes it idempotently (typically through the Inbox Pattern), and acknowledges receipt to the broker (ACK).
15.03 The outbox table schema and Doctrine mapping#
The outbox table has eleven columns. Each solves a specific operational problem that, without the column, surfaces only under production load.
The entity below carries Doctrine attributes and sits in the App\Outbox\Domain namespace. This
is a pragmatic shortcut. The outbox is an infrastructure pattern; teams that keep strict layering
as described in the Architectural Styles chapter
put the table entity in Infrastructure.
What each column is for
| Column | Type | Purpose |
|---|---|---|
id |
UUID v7 (16 B) | Primary key; UUID v7 grows with creation time, but the relay orders by occurred_at. It does not carry deduplication – that is the job of the eventId in the event payload (see Inbox). |
message_type |
VARCHAR(255) | FQCN of the integration event (for example, App\Ordering\Application\IntegrationEvent\OrderPlacedIntegrationEvent). The relay uses it to map the payload back to a PHP class. |
aggregate_type |
VARCHAR(255) | Type of the aggregate that emitted the event (Order, Invoice). Debezium routes to Kafka topics by this column, see 15.05. |
aggregate_id |
VARCHAR(64) | ID of the specific aggregate instance. It serves as the message key: events of one aggregate end up in the same partition, and therefore in the right order. |
payload |
JSON / JSONB | Serialized event state. JSONB in Postgres is preferred – it allows indexing individual fields for debugging. |
status |
VARCHAR(16) | Status enum: pending (waiting for publish), sent (published successfully), failed (given up after N attempts, requires manual handling). |
occurred_at |
DATETIME | Time the event occurred in the domain transaction. Used for ordering in the relay (best-effort FIFO) and for calculating outbox lag. |
attempts |
INT | Number of failed publish attempts. After reaching the threshold (typically 5), the row moves to failed and leaves the hot path. |
sent_at |
DATETIME NULL | Filled in on the transition to sent. Used for compaction (deleting older sent rows). |
last_error |
TEXT NULL | The last publish error – essential for incident analysis. |
available_at |
DATETIME | The time from which the relay may pick the row up again. markFailed() pushes it forward exponentially, so a permanently failing message does not burn attempts in every cycle. |
The migration targets MySQL/MariaDB. A PostgreSQL variant replaces BINARY(16)
with UUID and DATETIME with TIMESTAMP(0) WITHOUT TIME ZONE; the ENGINE
and CHARSET clauses go away. TIMESTAMPTZ and JSONB would require different types in the mapping
(datetimetz_immutable, jsonb), otherwise schema:validate reports a mismatch. On SQLite, BINARY(16) maps to BLOB
and JSON to CLOB. doctrine:migrations:diff does this kind of manual rewriting
more reliably. The example is there to explain the structure, not to be copied across
platforms. Also watch out for SQL comments inside CREATE TABLE: they confuse SQLite
introspection, and the schema then reports as out of sync.
After the migration, run php bin/console doctrine:migrations:migrate and verify
that the index exists:
SHOW INDEXES FROM outbox WHERE Key_name = 'idx_outbox_status_time'
(MySQL) or
SELECT * FROM pg_indexes WHERE indexname = 'idx_outbox_status_time'
(PostgreSQL). The index often gets lost during schema refactoring, so a regression
test in CI that checks for its existence pays off.
15.04 The aggregate publishes, the handler stores to the outbox#
The aggregate knows nothing about infrastructure: it is unaware of RabbitMQ and of the outbox table. It only emits the list of domain events that follow from the operation it has just performed. The application handler takes that list and enqueues it in the outbox table in the same transaction in which it stores the aggregate itself.
$this->em->wrapInTransaction(...) opens a transaction, runs the callback, and at the end
flushes and commits. When an exception escapes the callback, it rolls the transaction back. The Messenger
doctrine_transaction middleware works the same way: it wraps
the whole handler in one transaction. The canonical messenger.yaml from the CQRS chapter
has it on command.bus, so wrapInTransaction in the handler is redundant there. What remains
of it is a nested savepoint and uncertainty about where the commit actually happens.
The example keeps it so that the pattern reads clearly even without knowing the bus
configuration; in your own project, the transaction belongs in one place.
The Doctrine adapter is short, but it has two spots that are often overlooked. store()
must not flush, because the application wrapper holds the transaction. fetchPending()
must also filter by availableAt, otherwise the backoff from markFailed() means nothing.
1<?php2 3declare(strict_types=1);4 5namespace App\Outbox\Infrastructure;6 7use App\Outbox\Application\OutboxRepository;8use App\Outbox\Domain\OutboxMessage;9use Doctrine\ORM\EntityManagerInterface;10use Symfony\Component\Uid\Uuid;11 12final readonly class DoctrineOutboxRepository implements OutboxRepository13{14 public function __construct(private EntityManagerInterface $em) {}15 16 public function store(OutboxMessage $message): void17 {18 // No flush. The message must reach the DB in the same transaction19 // as the aggregate change – the caller takes care of the commit.20 $this->em->persist($message);21 }22 23 public function fetchPending(int $limit = 100): array24 {25 return $this->em->createQuery(26 "SELECT m FROM " . OutboxMessage::class . " m27 WHERE m.status = 'pending' AND m.availableAt <= :now28 ORDER BY m.occurredAt ASC"29 )30 ->setParameter('now', new \DateTimeImmutable())31 ->setMaxResults($limit)32 ->getResult();33 }34 35 public function markSent(Uuid $id): void36 {37 $this->em->find(OutboxMessage::class, $id)?->markSent(new \DateTimeImmutable());38 $this->em->flush();39 }40 41 public function markFailed(Uuid $id, string $error): void42 {43 // Here, by contrast, the flush belongs: the relay runs outside the domain transaction,44 // and the result of the attempt must be visible even if the next message fails.45 $this->em->find(OutboxMessage::class, $id)?->markFailed($error);46 $this->em->flush();47 }48}
15.05 Relay process – two variants#
The outbox table publishes nothing by itself. It needs a relay process that, at some cadence, selects pending rows and sends them to the broker. The microservices.io catalog knows two named patterns for this. Polling Publisher reads the outbox table with a query, and its single but substantial advantage is that it works on top of any SQL database. Transaction Log Tailing reads the database's transaction log instead of querying, that is, the Postgres WAL or the MySQL binlog. The first pattern is implemented as a Symfony Console command, the second as a Debezium connector on top of Kafka.
Variant A: Polling Publisher (Symfony Console command)
The polling worker is an ordinary Symfony Console command that, in an inner loop, calls
fetchPending(), publishes the rows, and marks them as sent.
It is started from supervisord, systemd, or a Kubernetes
Deployment as a permanently running process. The loop has a time limit; when it
expires, the process exits cleanly and the process manager starts it again.
messenger:consume --time-limit uses the same pattern; a periodic restart
keeps the memory of a long-running PHP process under control.
OutboxMessageFactory handles the conversion back. It is not a purely mechanical inverse
of the serializer: denormalization needs to know the target class, so it relies on a whitelist.
The whitelist also serves as a security measure. Without it, the message_type from the database
would decide which class the application instantiates:
1<?php2 3declare(strict_types=1);4 5namespace App\Outbox\Application;6 7use App\Ordering\Application\IntegrationEvent\OrderPlacedIntegrationEvent;8use App\Outbox\Domain\OutboxMessage;9use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;10 11final readonly class OutboxMessageFactory12{13 /**14 * Whitelist of types the relay may instantiate. A new integration event15 * means a new row here – otherwise it ends up in the dead-letter queue, not in the application.16 *17 * @var array<string, class-string>18 */19 private const ALLOWED = [20 OrderPlacedIntegrationEvent::class => OrderPlacedIntegrationEvent::class,21 ];22 23 public function __construct(24 private DenormalizerInterface $denormalizer,25 ) {}26 27 public function reconstitute(OutboxMessage $message): object28 {29 $class = self::ALLOWED[$message->messageType] ?? null;30 31 if ($class === null) {32 throw new \RuntimeException(33 sprintf('Unknown message_type "%s" in outbox.', $message->messageType),34 );35 }36 37 return $this->denormalizer->denormalize($message->payload, $class, 'json');38 }39}
The integration event denormalizes without trouble precisely because it carries nothing but primitives.
A domain event with value objects would end here with the message
“Cannot create an instance of OrderId from serialized data because its constructor
requires the following parameters to be present: $value”. That is another reason the integration shape
is what crosses the boundary.
Variant B: CDC / Debezium
Change Data Capture (CDC) is canonically Transaction Log Tailing: instead of
an application poller, it reads the Postgres WAL (Write-Ahead Log) or the MySQL binlog
and streams every INSERT into the outbox table straight to Kafka. The standard tool
is Debezium, a plugin for Kafka Connect that
acts as a logical replication subscriber of the database.
The application writes a row to outbox, Debezium sees that INSERT
in the transaction log, creates a Kafka record, and sends it to the corresponding topic.
After that, the row no longer changes; the table works as an append-only log.
| Aspect | Polling Publisher (A) | Transaction Log Tailing / Debezium (B) |
|---|---|---|
| Latency | 50–500 ms (polling interval) | single to tens of ms (push from the WAL) |
| Operational complexity | 1× console command + supervisor | Kafka + Kafka Connect + Debezium connector + monitoring of 4 processes |
| Choice of broker | Any (RabbitMQ, SQS, Redis, Doctrine async) | Kafka only (or Pulsar, Kinesis through an adapter) |
| Scale-out | hundreds to low thousands of messages/s per worker, linear with replicas via SKIP LOCKED | set by Kafka, two orders of magnitude higher |
| Ordering guarantee | Best-effort by occurred_at |
Per partition by aggregate_id |
| Operational risk | A stuck worker = growing lag | A stuck connector holds the replication slot, and the WAL piles up on the primary database's disk |
| Recommended for | A typical Symfony project | Multi-tenant SaaS, financial systems, IoT |
The rest of the book works with variant A. It gives a typical Symfony project sufficient reliability without a Kafka stack that would otherwise be added only for the outbox. Debezium pays off only once roughly five Kafka consumers already run in production and outbox lag starts to become a bottleneck.
In terms of configuration, it is a Kafka Connect connector (REST API, or declaratively through
the Strimzi operator). Its core is the Outbox Event Router transformation
(io.debezium.transforms.outbox.EventRouter). It has its own idea
of the table schema, which is worth knowing before the connector is deployed:
- It routes by the
aggregatetypecolumn, not by event type. The default topic isoutbox.event.<aggregatetype value>, so for the valueOrderit isoutbox.event.Order, not a topic named after theOrderPlacedclass. - The Kafka message key is
aggregateid. That is exactly where ordering within a partition comes from. - The
idcolumn travels as a message header, and the documentation offers it directly for deduplication on the consumer side. - The SMT (single message transform) automatically filters out
DELETEoperations on the outbox table. The canonical Debezium model therefore inserts the row and deletes it right away; thestatuscolumn plays no part in it at all.
So the application side does not stay unchanged. The schema from 15.03
has the columns aggregate_type and aggregate_id with an underscore, plus a status model.
Moving to variant B therefore means either renaming the columns to match the SMT's default
expectations or remapping the route.by.field and table.field.event.* options.
The status column also needs a decision: either status stays for the audit trail
and the connector ignores it, or the table moves to the insert-and-delete
model, which needs no compaction.
For Postgres, logical replication comes on top of that. The connector's default plugin.name
is decoderbufs, which requires a server extension; pgoutput has been native in Postgres
since version 10, and is therefore more common in practice. Logical replication requires wal_level = logical
and, for the connector user, the CREATE privilege to create the publication.
Source: Debezium documentation – Outbox Event Router (Red Hat, 2019+).
Doctrine transport as an outbox without a custom table
Symfony Messenger offers a third path, with neither a custom outbox table
nor a relay command. The doctrine://default transport stores messages in the
messenger_messages table in the same database where the domain state lives. Atomicity
is provided by the doctrine_transaction middleware on the command bus: the transaction
the middleware opens around the command handler wraps both the aggregate save
and the event dispatch to the doctrine transport. The precondition is that the transport uses
the same DB connection as the domain state, i.e. the default entity manager. The dual-write
problem disappears: either the order and the message are committed, or nothing is. The
messenger:consume async_events worker then picks the message up and processes it. It does not forward it
to an external broker by itself; that takes a custom handler or the relay from the previous sections.
In this variant, PlaceOrderHandler does not store the integration event in the outbox. It dispatches it
directly, and routing sends it to the doctrine transport:
1// Instead of $this->outbox->store(OutboxMessage::fromIntegrationEvent(...)):2$this->eventBus->dispatch($integrationEvent);
The Symfony documentation never calls this configuration an outbox; the word does not appear in it.
The atomicity is real, though. DoctrineTransactionMiddleware opens a transaction on
the entity manager's connection, runs the handler, then flushes and commits. The doctrine transport's
Connection::send() is a plain INSERT on the same connection and does not open its own isolated
transaction. The message write and the aggregate flush therefore commit together.
The convenience comes at a threefold cost. The format of the stored message is tied to Messenger: the payload
serializes the envelope including stamps, so nobody outside Symfony can reasonably read it.
Auditability and retention are worse than with a custom outbox table: the worker deletes processed
rows, so there is no sent status, no last_error, and no history for
incident analysis. And Messenger determines the table schema; the migration only
adopts it.
For smaller systems, this is still the simplest correct choice: dual write is solved, and the code shrinks to configuration and one worker. A custom outbox table pays off only where you need an audit trail, controlled retention, or publishing to a broker outside Messenger.
Message ordering: best-effort, not a guarantee
ORDER BY occurred_at suggests more than it can deliver. For the Polling Publisher, the microservices.io catalog
lists the drawback “tricky to publish events in order,” and in this
implementation three reasons come together at once. The occurred_at value is created in the PHP process,
so across instances it is subject to clock skew. With equal values, the order is not
defined at all. And with the column's one-second precision (see the comment
in the migration), ties are no exception. Finally, the relay publishes
row by row, so a failure in the middle of a batch lets a later event through before an earlier one.
Reliable ordering can be kept only per aggregate, and only when the message key carries it.
That is why the schema has aggregate_id. In Kafka, it determines the partition, within which
ordering is guaranteed. Global ordering across aggregates does not exist, and domain
logic must not rely on it.
The status = 'pending' filter, on the other hand, is not affected by the gap problem described in the
Event Sourcing chapter. That problem afflicts a relay
that keeps a checkpoint on an auto-increment ID: a transaction with a lower ID can commit
later, and the relay, past its advanced checkpoint, never reads it. An outbox table with a status
column has no checkpoint. A row becomes visible only after the commit and stays pending
until the relay publishes it. A delayed commit shows up in one of the next cycles.
15.06 Idempotent Inbox – the subscriber side#
The outbox provides at-least-once delivery, so the subscriber must expect
to receive the same event more than once. When the handler's side effect is not idempotent (typically
UPDATE counter SET value = value + 1), a duplicate immediately shows up as
a wrong read model state. The customer sees CZK 200 in the account instead of CZK 100, the number
of orders doubles, and the email arrives twice.
The solution has two names in the catalogs. microservices.io lists the pattern as Idempotent
Consumer and recommends a table of processed messages with a composite key
(subscriberId, messageID). Older is the Idempotent Receiver from Enterprise
Integration Patterns (Hohpe & Woolf, 2003): a receiver designed to tolerate the same
message more than once. This chapter sticks with the working name Idempotent Inbox.
The implementation mirrors the outbox: an inbox table in the subscriber's database
with a composite UNIQUE constraint on the pair (event_id, consumer). Before
processing an event, the handler checks whether the pair is already in the inbox. If it is,
the handler acks to the broker and stops. If not, it runs its logic and, in the same transaction,
inserts a new row into the inbox. The UNIQUE constraint serves as a safeguard against
race conditions.
The consumer column is in the inbox table for a reason. The same event_id
is processed by several subscribers (Reporting, Notifications, Search index), and each
needs to keep its own “already processed” state. Without the
consumer column, the second subscriber would hit the first one's UNIQUE constraint and would
never process the event. The UNIQUE is therefore the composite (event_id, consumer),
not event_id alone.
Inbox table retention
The inbox grows just like the outbox; it is only forgotten more often. Every processed message leaves a row in it, and nothing deletes it. After a year in operation, the safeguard against duplicates can become the largest table in the subscriber's database.
The minimum retention is set by how long the broker can still deliver a message: the maximum message TTL plus the longest retry window of the relay process. A row older than that sum has nothing left to deduplicate. The usual choice is 30 days – safely above the common setting of both limits. Deletion uses the same batch cron as the outbox. Choosing a retention shorter than the real retry window opens a hole: a delayed message passes as new.
15.07 Operational aspects#
In a development environment, the outbox works without maintenance. Production brings four operational questions: how to measure lag, how to keep the table small, what to do with permanently failing rows, and how to monitor that nothing has been forgotten.
Outbox lag
Outbox lag is the time an event spends in the pending state before the relay
sends it to the broker. The age of the oldest pending row serves as the alerting metric.
Export these metrics to Prometheus (outbox_pending_seconds,
outbox_pending_count) and build an alert on them in Grafana. The critical
threshold is usually 30 seconds. When lag exceeds it, something is stuck:
the relay worker crashed, the broker is unavailable, or the DB is at 100% CPU. In normal operation,
the median lag is under 1 second.
Outbox table compaction
The outbox table grows linearly with the number of published events. Without compaction, after a year
of operation it contains millions of historical rows. They slow down even indexed queries
and take up disk space for nothing. The standard strategy deletes rows in the sent state
older than N days, where N is usually 7 to 30, depending on compliance requirements.
LIMIT 10000 is deliberate here: deletion goes in batches, not as a single DELETE FROM outbox. A large delete runs as one long transaction, holds locks on a huge
number of rows, and can block production INSERTs from handlers. Cron runs it every
5 minutes, and 10,000 rows per run is enough for a typical load (roughly 3 million events per day).
The tempting form DELETE … WHERE sent_at < NOW() - INTERVAL 30 DAY LIMIT 10000
is shorter, but it works only in MySQL and MariaDB. Postgres and SQLite reject it,
and because cron runs silently, the error shows up only as a growing table. The threshold
is therefore computed in PHP, and the batch is bounded by a subquery on id.
Dead-letter queue for permanent failures
Some events never get published. The integration event class changed and the old
payload can no longer be denormalized, the message_type is missing from the
OutboxMessageFactory whitelist, or the payload is corrupted. After N attempts (typically 5),
OutboxMessage::markFailed() switches them to the failed state. Such rows are
handled as follows:
- Move them off the hot path – the relay no longer tries to publish them.
- Alert loudly – the alert
outbox_failed_total > 0. - Have a CLI tool for them –
app:outbox:retry-failed, or a manual SQL update of the status back topendingafter fixing the cause. - Never delete them automatically. A row in the
failedstate documents an undelivered event and should stay on record even after weeks.
Vacuum and index bloat (PostgreSQL)
The outbox has a specific I/O profile: a high INSERT rate, a short lifecycle (a row is created →
within seconds an UPDATE to sent → after N days a DELETE), and the history is never read.
The default autovacuum settings in PostgreSQL are not sized for such a profile,
and after a few days of operation, index bloat appears:
- The status UPDATE creates a new row version, and the old one remains as a dead tuple (MVCC).
The indexed
statuscolumn changes, so a HOT update is out of the question, and the new version also gets new entries in the indexes. - DELETE during compaction adds more dead tuples.
- The default autovacuum threshold (
autovacuum_vacuum_scale_factor = 0.2) waits until 20% dead tuples accumulate. At thousands of writes per second, that takes minutes. - Meanwhile, the
(status, occurred_at)index swells to multiples of its original size, selects slow down, and lag rises.
The standard measure: per-table vacuum tuning.
Partitioning at high volume (PostgreSQL)
At a sustained high volume, on the order of thousands of events per second, a single-table
outbox becomes an operational bottleneck. PostgreSQL declarative partitioning by
occurred_at brings:
- Fast deletion of old data through
DETACH PARTITIONandDROP TABLEinstead ofDELETE. The long delete transaction goes away, and the duration does not depend on the number of rows (O(1) instead of O(n)). A regularDETACHneeds an exclusive lock on the parent table;DETACH PARTITION … CONCURRENTLY(since PostgreSQL 14) makes do with a weaker one. - Targeted vacuum – autovacuum works per partition, so old partitions that are no longer written to hardly keep it busy.
- Index locality – the active partition contains only events from the last few hours, so the index is small and fits in RAM.
Operational automation: the pg_partman extension
manages both the creation of new partitions and the removal of old ones via cron. MySQL has
native PARTITION BY RANGE with the same effect, but with no counterpart to pg_partman –
management is manual.
Distributed relay – multi-instance
A singleton polling worker (replicas: 1 in Kubernetes) is the simplest
configuration. It has two weaknesses, though. The first is a single point of failure: the worker
crashes or freezes, and lag grows until Kubernetes restarts it. The second is
limited throughput, because one PHP process handles on the order of hundreds to low
thousands of messages per second.
At higher volume or with a stricter availability requirement, two paths are available:
Path 1 – leader election through Redis/etcd. Several workers run, but only one, the “leader,” publishes. When the leader crashes, another takes over its role at the latest when the lease expires (10 s in the example). The result is HA without a double publish, but throughput does not increase – still only one worker dispatches.
The worker calls acquireOrRenew() every 3 seconds (a 10 s TTL leaves headroom for network
delay). As long as the method returns false, the worker stands still. As soon as it
returns true on some tick, the worker has become the leader and starts dispatching. Watch out: processing a batch must
finish before the lease expires, or the worker must keep renewing the lease during
the batch. Otherwise a new leader takes over the lease, starts dispatching rows the old
worker is still publishing, and a double publish occurs.
Path 2 – SELECT … FOR UPDATE SKIP LOCKED. Several workers run in parallel, and each
reserves its own batch of rows. There is no leader here and no single point of failure.
Throughput then grows roughly linearly with the number of workers, and the at-least-once guarantee
is preserved. SKIP LOCKED is supported by PostgreSQL since version 9.5 and by MySQL 8.
The price is ordering: events of the same aggregate can come out of order when
different workers process them in different batches. If ordering matters to a subscriber,
the outbox is split by aggregate_id (for example, hash modulo the number of workers),
and each worker processes only its own share.
Backpressure – what if the broker cannot keep up
When Kafka or RabbitMQ cannot keep up with incoming messages (a network error, a full broker disk, a partition
leader election), the relay gets a timeout or an error on publish. Outbox rows
stay pending and pile up. Production INSERTs are not throttled in the meantime: whoever starts
blocking the application layer spreads the broker outage into the core domain.
A broker outage is a different kind of failure than an unpublishable message from the section
on the dead-letter queue. During a half-hour outage, markFailed() from 15.03 would
use up five attempts in roughly half a minute and move even healthy rows to failed.
The relay therefore does not count a broker connection error (TransportException)
toward attempts: it abandons the
cycle and waits with a backoff at the level of the whole worker.
The standard pattern has four components. After a failed publish, the worker switches to
exponential backoff and waits 1 s, 2 s, 4 s, up to a maximum of 30 s. Meanwhile, it logs
outbox_publish_errors_total. An alert watches the growth rate of pending rows:
delta(outbox_pending_count[5m]) > 10000 signals that writes exceed
consumption and the broker cannot keep up. In terms of capacity, the database must absorb 30 minutes
of broker outage; at 1,000 events per second, that is 1.8 million extra rows,
which means a budget for disk and vacuum. For low-priority events (audit, metrics)
that can tolerate loss, controlled sampling can be considered under prolonged backpressure.
Integration events carrying a business fact (OrderPlacedIntegrationEvent), however, cannot be dropped.
15.08 Anti-patterns#
The outbox has a simple schema, yet the same mistakes keep recurring in code review. They cancel its guarantees and return the system to the dual-write problem.
15.09 Migrating an existing project – step by step#
An eighteen-month-old Symfony project with a hundred handlers and publishing after flush is not moved to the outbox with a big-bang refactoring. The outbox arrives handler by handler, next to the existing behavior, and the old code disappears only once the new one demonstrably works.
Step 1: Add the outbox table and entity
Create a migration following section 15.03, run
doctrine:migrations:migrate, and deploy to production. Nobody uses the table
yet, so the regression risk is zero. Verify that the migration really
created the composite index idx_outbox_status_time, not just a single-column one.
Step 2: Refactor one handler
Choose one main handler – typically PlaceOrderHandler, or whatever handler
hurts most from dual write. Add wrapInTransaction to it, and next to
$bus->dispatch() call $outbox->store(OutboxMessage::fromIntegrationEvent(...))
with the integration shape of the event (see 15.04).
Do not delete the old $bus->dispatch() yet – legacy subscribers would stop working.
Send the same integration event instance through it, though, that the handler stores in the
outbox. The Inbox in step 4 needs both copies to have the same eventId. Subscribers that
have so far listened to the domain event therefore have to be switched
to the integration shape in the same step.
Step 3: Add an inbox to subscribers one at a time
For each subscriber context, create an inbox table and refactor the handler
following section 15.06. This is the longest step of the migration (typically weeks),
but it can be parallelized across teams – each context adds its Inbox independently.
The Inbox must be in place before the relay. Otherwise, between the deployment of the relay
and of their own Inbox, subscribers would receive every event twice and process it twice.
Step 4: Deploy the relay command
Once all subscribers of events from the refactored handler have an Inbox,
implement OutboxDispatchCommand from section 15.05 and deploy it
under supervisor. While the legacy publish is also active, subscribers receive both versions
of every event, and the Inbox discards the second copy. The precondition is that the legacy dispatch
from step 2 sends the integration event with the same eventId as the row in the outbox.
The domain event has no eventId, and the Inbox would not pair the two copies.
Step 5: Turn off the legacy publish
Once the relay runs stably, delete the original $bus->dispatch() in the handler;
event delivery then rests on the outbox alone. This is a risky step – during
the first days, watch the outbox lag and the number of duplicates caught by the inbox. If something fails,
reverting the pull request undoes the change within five minutes.
Step 6: Measure and tune
After a month of operation, go through the metrics: the median lag, how fast the table grows,
how many rows ended up in failed, and how many duplicates the Inbox caught. These
numbers guide the tuning of the relay process's polling interval, the batch limit, the cleanup retention,
and the alert thresholds. The outbox is not “set-and-forget” – it needs occasional operational maintenance.
15.10 Summary#
The Outbox Pattern costs one extra table, one Symfony command, and a change to one application handler. In exchange, it eliminates a whole class of bugs (lost events, phantom events) that would otherwise be traced through logs only after an incident. The resulting guarantee is at-least-once delivery of events through any message broker, without XA/2PC and without a special cloud service.
The Idempotent Inbox is the necessary counterpart on the subscriber side. Without it, duplication from the outbox leaks into read models and side effects, and the gain from the outbox is lost. The outbox together with the inbox gives an exactly-once effect: every event shows up in the read model exactly once, even when the broker delivers the message several times.
Comparison with alternatives
The outbox is not the only answer to dual write. The other paths have a narrower scope or a higher cost.
| Solution | How it handles dual write | When it fits |
|---|---|---|
| Transactional Outbox | The event is written in the same DB transaction, a relay publishes it | The default choice wherever the aggregate lives in an ACID database |
| Event Sourcing | The event is the state, there is no second write | When the rest of the model pays off for the domain too, not just for delivery |
| Listen-to-yourself | The application publishes first, and the DB is written only by the consumer of its own message | When the broker is more reliable than your own DB and reads may lag |
| Synchronous calls | No dual write arises, the contexts call each other directly | A small system without asynchronous integration; the price is the autonomy of contexts |
| 2PC / XA | A distributed transaction over the DB and the broker | Practically never – see 15.01 |
The options are not mutually exclusive. An event-sourced context does not need an outbox table, because the event store does its job, but it still needs an Inbox on the consumer side.
The main points for practice:
- The outbox is a table in the same DB as the domain state – otherwise it loses its purpose.
- The Doctrine entity needs
#[ORM\Index(columns: ['status', 'occurred_at'])]; without it, the relay does a full table scan on every poll. - The atomicity of the order and the outbox rows is guaranteed by one transaction: the
doctrine_transactionmiddleware, or$em->wrapInTransaction(...)in the handler. - A Polling Publisher under supervisor is enough for almost every Symfony project; Transaction Log Tailing through Debezium only for Kafka-native systems with high volume, and even there at the cost of a different table schema.
- The inbox table has UNIQUE
(event_id, consumer)– the consumer column is the key to multi-subscriber scenarios. - Monitoring outbox lag, the number of sent and failed messages, and inbox duplicates is essential.
- Migrating an existing project is incremental – handler by handler, context by context, never big-bang.
The Outbox Pattern builds on the patterns from the previous chapters. In CQRS, it ensures reliable delivery of events from the command side to the read side. In Event Sourcing, the event store takes over the role of the outbox, and the projections that read it replace the relay. In sagas, it guarantees delivery of events and commands between contexts, so a saga never gets “stuck” because of a lost message.
Recommended further reading: Helland, P. – Life Beyond Distributed Transactions, CIDR (2007); Richardson, C. – Microservices Patterns, Manning (2018), chapters 3 and 4; Kleppmann, M. – Designing Data-Intensive Applications, O'Reilly (2017), chapter 11 (Stream Processing); microservices.io – Pattern: Transactional Outbox.
Frequently asked questions
Outbox vs. CDC / Debezium – which one when?
For a typical Symfony project, a Polling Publisher (variant A) is enough. The operational overhead is minimal (one Symfony command under supervisor), and latency under 1 second is enough for typical business scenarios (orders, payments, notifications). Debezium / CDC pays off only where (a) Kafka infrastructure is already deployed, (b) the latency requirement is under 50 ms, (c) the volume exceeds 10,000 events/s, and (d) the team has experience with Kafka Connect. Otherwise you pay for several times the operational complexity with little benefit. Details in the Relay process – two variants section.
What if we use a NoSQL database (MongoDB, Cassandra, DynamoDB)?
If the aggregate lives in a NoSQL store without multi-document ACID transactions (Cassandra, early versions of MongoDB), the classic Outbox Pattern does not work: the atomicity of writing the order and the event to two collections is not guaranteed. Options: (1) MongoDB has had multi-document transactions since version 4.0, so an outbox is possible; (2) DynamoDB offers TransactWriteItems – the same; (3) Cassandra has no ACID transactions (a logged batch only guarantees that all writes are eventually applied, without isolation) – Change Data Capture is used instead, or Event Sourcing with the events stored directly in the aggregate document. The choice of store for the domain state decides whether an outbox can be implemented at all.
How large should a relay batch be?
By default, 100 rows per polling cycle. The 100 ms interval applies only to an empty outbox: as long as there are pending rows, the relay runs without pausing, and throughput is set by the latency of the broker and the database. If lag rises above 5 seconds and the broker CPU has headroom, raise the limit to 500. Above a batch of 1,000, you run into DB serialization of the updates – instead of one large batch, split the work across several workers with SELECT ... FOR UPDATE SKIP LOCKED. The main rule: measure first, then tune, not “by feel.”
Is an outbox worth it in a monolith?
Yes. The dual-write problem does not arise only between microservices, but between any two transactional systems. A monolith publishing events to RabbitMQ or Redis Streams has exactly the same problem as a microservice: the database transaction is separate from the broker acknowledgment. If the monolith has event-driven contexts (Symfony Messenger with an async transport, Spatie Laravel events, and the like), an outbox pays off in it just as in microservices. Only a strictly synchronous monolith, where publishing does not exist and everything flows in one HTTP transaction, does not need one.
What to do during a prolonged broker outage?
The outbox as a whole is self-healing: when the broker is down for 30 minutes, the relay worker gets timeouts or connection refused errors, the rows stay pending, and their number and the lag grow – but the application handlers keep writing events (only to the DB). Once the broker recovers, the relay sends the backlog within a few minutes, the lag returns to normal, and the subscribers catch up. What you need: (a) an alert on lag > 30 s, so the team knows about the outage; (b) enough space in the DB for the accumulated pending rows (typically not a problem, the rows are small); (c) compaction that never deletes pending rows, only sent rows older than N days; (d) a relay that does not count a broker connection error toward the row attempts – otherwise the outage would move healthy messages to failed (see Backpressure – what if the broker cannot keep up).
Do I have to use UUID/ULID, or is AUTO_INCREMENT enough?
The default choice is UUID v7 (or, as an alternative, ULID), not AUTO_INCREMENT. Reasons: (1) UUID v7 is globally unique across DB instances – there is no risk of collisions during replication, restore from backup, or migration. (2) It carries a time component, so the ID correlates with creation order – useful for debugging and for index scans. (3) The client can generate it in advance and send it, for example, as the value of the Idempotency-Key header. (4) AUTO_INCREMENT complicates sharding and multi-region setups. The Symfony Uid component is enough for this: Uuid::v7() in the entity.