Events and the Outbox: Why Saving a Record and Publishing a Message Can Go Half Wrong, and the Table That Fixes It
A support app saves ticket T-101 and publishes 'ticket created'. Crash between the two and the event is lost; publish first and a failed commit sends an email about a ticket that doesn't exist. The outbox writes the event as a row in the same transaction, a relay publishes it, and an idempotent consumer handles the relay's duplicates.
What you will learn
- Tell a task (do this) from an event (this happened)
- Explain the dual write problem and why neither order of save and publish is safe
- Write the event to an outbox table in the same transaction, and let a relay publish it
- Make consumers safe to receive the same event twice
Before you start
- Celery and Redis for background tasks
- What a database transaction is
There's a bug that hides between your database and your message broker. You save a record, you send a message, and sometimes only one of them happens. Here are both ways it goes wrong, how the outbox fixes it, and what it still doesn't fix. The example is a simple support ticket app.
Do this vs this happened
A task is an instruction: do this. Send this reply email, and one worker does it. An event is news: this happened. A ticket was created, and email, search and reports can all react to it, and the app doesn't even know who's listening. A task has one worker; an event can have many listeners. Either way, it leaves through a message broker, the post box between services.
The waiter's pad
A waiter takes an order and keeps it in his head. On the way to the kitchen he drops a tray, and the order is gone. Nobody's getting that tea. Now the same waiter writes the order on his pad first. He drops the tray again, but the order is safe on the pad, and when things calm down he takes it to the kitchen. Write it down first, deliver it afterwards.
Two writes, no shared commit
A customer opens a ticket, and there are two things to do: save the ticket in the database, and publish an event to the broker. These are two separate systems, each with its own commit, and no commit covers both. The app can die between them, or one write can fail while the other succeeds. That's the dual write problem. There's a heavy tool called two-phase commit, but not every database and broker supports it.
Order 1: save, then publish
The app saves ticket T-101 and the commit works. Just before the publish, the app crashes (a deploy, a dead machine). The broker gets no event, and email and search never hear about it. The ticket is saved and the event is lost. "Just add a retry"? That retry lived inside the process that died.
Order 2: publish, then commit
The app saves ticket T-102, not committed yet, then publishes the event, and the email service sends the customer "we got your ticket". Now the commit fails and the database rolls the ticket back. The customer has an email about a ticket that doesn't exist, and you can't unsend an email. Swapping the order only swaps the failure.
The outbox table
The fix is to stop writing to two systems. Begin one transaction in your own database, save the ticket, and in the same transaction save the event as a row in a table called the outbox. That's the waiter's pad. Commit, and both rows land together: both, or neither. In outline (pseudocode, not from a project file):
# pseudocode
with db.transaction():
db.insert("tickets", ticket)
db.insert("outbox", {"event_id": new_id(), "type": "ticket.created",
"payload": ticket, "sent": False})
# the relay, a separate background process
for row in db.select("outbox", sent=False):
broker.publish(row)
db.update("outbox", row.id, sent=True)
A small background process, the relay, reads the rows that haven't been sent, publishes each one, then marks it sent. If the broker is down, the rows just wait, and saving tickets keeps working.
Both gaps closed
- The app crashes right after the commit: the outbox row was committed with the ticket, so it's still there, and the relay sends it.
- The commit fails: the rollback takes both rows away, so the relay finds nothing. No event, no false email.
The event goes out if the ticket was saved, and only then.
The relay can publish twice
The outbox doesn't fix everything. The relay reads a row and publishes event E-104, then crashes just before marking it sent. On restart the row still says unsent, so it publishes E-104 again. The outbox gives you at least once, not exactly once: nothing is lost, but an event can arrive twice.
Consumers: safe to run twice
Every event carries a unique ID, and the reports service keeps the IDs it has seen. E-104 arrives, the ID is new, so it does the work (the open tickets count goes to 1) and saves the ID. The same event arrives again; the ID is already there, so it skips it, and the count stays at 1. Save the ID and the work in one transaction. You need this anyway, because brokers can deliver the same message twice on their own. The same guard for Celery tasks is in safe to run twice, and for a document queue in a message queue for document ingestion.
Common mistakes
- Publishing inside the database transaction and hoping the commit works.
- A retry in the same process as the crash.
- Expecting the outbox to give exactly once.
- Saving the seen event ID in a different transaction from the work.
Quick recap
| Approach | What goes wrong |
|---|---|
| Save, then publish | Crash in between: ticket saved, event lost |
| Publish, then commit | Commit fails: email about a ticket that doesn't exist |
| Outbox + relay | Relay crash: event sent twice, so consumers dedupe by ID |
Write it on the pad first, deliver it after, and don't panic if it's delivered twice.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
