The Outbox Pattern: Orders That Fell Into the Gap Between the Database and Kafka

In mid-February, the marketing team ran a short flash campaign; the order creation rate jumped to four times normal for 6 minutes. An hour after the campaign, an odd question came in from the data warehouse team: "There are 312 records in the orders table that never show up in the order event stream. What are these?" We checked: the orders were real, the customers had received their food, the money had been collected. But the OrderCreated event for these orders in Kafka had never been born — so the billing service hadn't invoiced them, the data warehouse hadn't counted them, the campaign budget calculation came out wrong, and they were missing from the restaurant reconciliation. The orders had fallen into the invisible gap between the database and Kafka. The textbook name for that gap: the dual write problem.

The Impossibility of Writing to Two Systems at Once

The code looked perfectly innocent: write the order to PostgreSQL inside a transaction, commit, then publish the event to Kafka. It had worked this way for years. So how did 312 orders disappear? During the campaign peak, the Kafka producer's buffer filled up, a few pods were restarted under memory pressure, and every pod that died in that millisecond window between commit and publish left behind orders that had been written to the database but never announced to Kafka. Reversing the order isn't a cure either: if you publish first and commit afterward, this time phantom events from rolled-back transactions leak into the stream. There's no general way to do a single atomic write to two independent systems; XA/two-phase commit exists in theory, but it isn't practical on the Kafka side, and even if it were, you wouldn't want to pay its operational cost. This isn't a glitch you can fix with configuration; it's an architectural hole — and as traffic grows, it hits with statistical certainty.

In the first week, we went through our classic rounds of wrong hypotheses. "Let's add retries to the producer" — retries don't help when a pod dies; if the memory is gone, the queue is gone too. "Let's move the publish inside the transaction" — Kafka can't be part of a PostgreSQL transaction; an event published before the commit can't be recalled on rollback. "Let's extend the graceful shutdown period" — that narrows the window, it doesn't close it; an OOMKill doesn't wait for graceful shutdown. A sentence one of our teammates said in a meeting ended the debate: "We're trying to narrow the gap; we need a design where the gap doesn't exist."

Publishing after commit loses the event when a pod dies; committing after publish leaks the event of a rolled-back order into the stream.
There's no general way to do a single atomic write to two independent systems.

Outbox: Writing the Event With the Same Pen

That design is called the outbox pattern, and the idea is embarrassingly simple: write the event not to Kafka but to an outbox table inside the same database transaction. The order row and its OrderCreated event either exist together or don't exist together in the same commit — atomicity comes from the one place you already have it, the relational database. Then a separate mechanism reads the outbox table and carries the events to Kafka. The gap is closed; in the worst case, an event goes out late, but it is never lost.

The order and its event are written to the outbox table in the same transaction; Debezium reads from the WAL and carries the event to Kafka.
In the worst case the event goes out late, but it is never lost.

The real engineering debate broke out over the "carrier" layer. There were two paths. The first is a polling publisher: a process queries the outbox table several times a second, pushes new rows to Kafka and marks them. Simple, dependency-free, but it brings latency and a constant query load on the database; at our order volume, that query load was measurable. The second is CDC — change data capture: Debezium listens to PostgreSQL's WAL (write-ahead log) via logical replication and streams every row that lands in the outbox table to Kafka within milliseconds. No extra query load on the database, and latency is typically 50-200 milliseconds. We chose Debezium because we already had Kafka Connect infrastructure, and Debezium's outbox event router handled routing the table to topics through configuration.

Debezium's Bill: There's No Free Atomicity

Articles about Debezium usually end here; the most instructive part of our story started after this point. Lesson one: a replication slot is a commitment. PostgreSQL can't delete WAL files as long as the logical slot Debezium reads from isn't advancing. During maintenance in April, the Debezium connector stopped for 14 hours and nobody noticed; the WAL disk grew by 40 GB and the database woke us up at night with a disk alarm. Slot lag is now a first-class metric: we track the restart_lsn gap via pg_replication_slots in Grafana, with a warning at 2 GB and a critical alarm at 10 GB. Lesson two: the CDC pipeline is also at-least-once delivery. When the connector restarts, it resumes from the last offset, and some events land in Kafka twice. This didn't surprise us, because our consumers had already been idempotent since the duplicate-record incident — outbox doesn't eliminate the need for deduplication, it only eliminates loss. Lesson three: the outbox table is a queue, and queues need to be cleaned. Once Debezium has read the rows, they're done; we delete rows older than 48 hours with a daily job, and we partitioned the table so the deletes don't create vacuum pressure. We didn't do this in the first month; by the time the table reached 30 million rows, query plans had started to degrade.

And a fourth lesson nobody thought about up front: schema evolution. The event body in the outbox is JSON, and that JSON is now a contract between two worlds. A developer adding a field to the order event now has to think not just about their own service but about the seven services that consume that event. We solved this with process: event schemas live in a separate repo, versioned, with a backward-compatibility rule checked automatically in CI. If the outbox pattern had remained just a technical patch, this discipline would never have emerged; the pattern elevated events from "by-product" to "product" status.

Four lessons: the replication slot must be monitored, CDC delivers at least once, the outbox table must be cleaned, and the event schema must be versioned.
There's no free atomicity; the cost became visible and manageable.

Ordering guarantees also turned out to be a less-discussed upside of outbox. In the old world, when the OrderCreated and OrderPaid events for the same order were published from two different pods, their arrival order in Kafka wasn't guaranteed, and "payment arrived for an unpaid order" defensive code had piled up in the consumers. With outbox, since events are streamed from a single table using the order ID as the partition key, events for the same order are now ordered on both the producing and consuming sides. Three months after the migration, we deleted some of that defensive code in the consumer services — deleted code is a bigger gift than written code.

How Do We Know the Gap Is Closed?

We didn't do the migration as a big bang. First, we moved only the order service to outbox, and for four weeks we ran the old-style publish and the outbox stream in parallel, comparing the two streams with counters — in shadow mode the difference averaged 30-80 events a day, and all of them were losses on the old path; the outbox side didn't drop a single event. Then the payment, refund and campaign services moved over. Today, an "in the database but not in the stream" check runs as an hourly reconciliation job, and it has reported zero cases in the last four months. During campaign peaks, Debezium lag rises to 1.8 seconds at p99; that's acceptable for our events, because our contract isn't "instantly" but "eventually and completely."

Dual write is the silent tax of microservice architectures: invisible while the system is small, it surfaces in reconciliation meetings once the system grows, and the bill always goes to some other team — in our case, it went to the data warehouse. Outbox + CDC doesn't abolish this tax; it turns it into a visible, manageable infrastructure cost: one table, one connector, three alarms, one cleanup job. If you're seeing "in the database but no event" cases in your own system, or suspect you are but can't measure it, write to me; I'll share our reconciliation query and the critical lines of our Debezium configuration.

The billing fixes for the 312 lost orders ate up four days of three people's time. The monthly cost of the outbox table is a few gigabytes of disk and one connector pod. In this industry, the math rarely comes out this clear: every order that fell into the gap was interest on every sprint that didn't close it.