Outbox, dual writes and the ledger: events that do not get lost, and data you never edit
In an event-driven system one operation changes data in the database and tells other services about it. If it does so with two separate writes, sooner or later one of them fails. This guide uses the code of a delivery platform – microservices in Kotlin and C# on PostgreSQL and Kafka – to show how the outbox works, why a consumer must tolerate duplicates, and why ledger entries are only ever appended while balances are a projection you can rebuild.
As of November 2026. The examples come from the public repository kldev/delivery.platform.app; code fragments are shortened. Each part ends with links to the files and sources.
The problem: the dual write
A driver finishes a delivery. The delivery service stores the DELIVERED status in its database and sends a delivery.completed event to Kafka, which the settlement service is waiting for. These are two different systems with no shared transaction between them. Every order goes wrong somewhere else:
-
Database first, then the broker
The database write succeeded and the send did not: the broker does not answer, the application restarts, time runs out. The delivery is finished, but the driver's settlement is never created and nobody knows.
-
Broker first, then the database
The event went out and the database transaction rolled back, e.g. on a version conflict. Other services settle a delivery that does not exist in the source system.
-
Sending inside the transaction
Sending inside the database transaction changes nothing: the commit can still fail after the send. On top of that the transaction holds its locks for the whole conversation with the broker.
-
A timeout tells you nothing
No acknowledgement does not mean the message did not arrive. A retry may produce a duplicate – so even "retry until it works" does not solve the problem, it only turns a lost event into a double one.
-
The conclusion
The database and the broker cannot be written atomically. What you can do is write everything in one transaction of your own database, send "at least once", and build consumers that a duplicate does not hurt. The next three parts stand on that.
The outbox: the event in the same transaction as the change
Instead of sending the event, the handler stores it as a row of the outbox_messages table – in the same transaction in which it changes the delivery. Either both are stored or neither is. A separate process takes care of sending.
- The handler changes the state and adds the event to the outbox in one transaction (@Transactional in CompleteDeliveryHandler).
- Every second the publisher claims a batch of up to 50 PENDING events that are due. FOR UPDATE SKIP LOCKED keeps several instances of the service from taking the same rows, and locked_until of 60 seconds releases the claim if an instance dies halfway.
- Each event goes to Kafka with the aggregate (delivery) id as the key – events of one delivery land in the same partition and keep their order. The publisher waits for the broker's acknowledgement.
- Once acknowledged, the row becomes PUBLISHED. On failure the attempt counter grows and the next attempt moves out exponentially: 10 s after the first failure, 20 s after the second (the formula is capped at 300 s).
- After three failed attempts the event becomes DEAD and waits for a person. That is not a bin – it is an alert.
// Kotlin, CompleteDeliveryHandler (shortened): state and event in one transaction
@Transactional
fun handle(command: CompleteDeliveryCommand): DeliveryState {
val delivery = deliveryRepository.findById(command.deliveryId) ?: throw NotFoundException(...)
delivery.deliver()
deliveryRepository.update(delivery)
outboxRepository.save(DeliveryCompletedEvent(deliveryId = delivery.id.value, ...))
return DeliveryState.from(delivery)
}
-- The publisher's SQL: claiming a batch of events, safe with several instances
UPDATE outbox_messages
SET locked_until = :lockedUntil
WHERE id IN (
SELECT id FROM outbox_messages
WHERE status = 'PENDING'
AND next_attempt_at <= :now
AND (locked_until IS NULL OR locked_until < :now)
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT :limit
)
RETURNING *;
-
A service that publishes nothing needs no outbox
In the repository the ledger and payment reconciliation had an outbox table and a publisher polling an empty table. Later migrations removed it. The outbox belongs to a service that sends events, not to every service by default.
-
Cleanup and size
PUBLISHED rows can be deleted or archived after a few days. The partial index WHERE status = 'PENDING' keeps the growing history from slowing down the search for events to send.
-
An alternative: reading the WAL (CDC)
Instead of polling the table, Debezium reads the outbox changes from the PostgreSQL WAL and sends them to Kafka. Less delay and fewer queries, but one more component to run and monitor.
At least once: the consumer must tolerate a duplicate
The outbox guarantees the event goes out – but it may go out twice: the publisher sent the message and died before marking it PUBLISHED, or the claim expired halfway. A Kafka consumer also gets messages again, e.g. after partitions are reassigned. That is why every consumer is idempotent.
-- Consumer: store the event id first, in the same transaction as the change
BEGIN;
INSERT INTO processed_events (event_id, event_type, processed_at)
VALUES (:event_id, 'delivery.confirmed', now())
ON CONFLICT (event_id) DO NOTHING;
-- 0 rows inserted = duplicate: COMMIT and stop
-- 1 row = first time: change the data, then COMMIT
-- Ledger: one cause, at most one transaction
ALTER TABLE ledger_transactions
ADD CONSTRAINT uq_ledger_transactions_reference UNIQUE (reference_type, reference_id);
-
The inbox: a table of processed events
processed_events with event_id as the primary key. The consumer stores the event id in the same transaction as its own change. A second attempt at the same event hits the existing row and changes nothing.
-
Insert first, then work
The payment service (C#) starts with INSERT … ON CONFLICT (event_id) DO NOTHING. Zero inserted rows means a duplicate. This is safe even when two copies of the event arrive at the same time – the primary key decides, not an earlier SELECT.
-
Business idempotency
The ledger is idempotent twice: by event id (the inbox) and by cause – the UNIQUE (reference_type, reference_id) constraint in ledger_transactions. One driver settlement gives at most one transaction, even if the same settlement arrives in two different events.
-
An idempotency key for HTTP requests
A client that retries a request after a timeout has the same problem. The delivery service stores the key from the header together with the response in idempotency_records (scope + key as the primary key) – in the same transaction as the change. A repeated request gets the stored response instead of a second delivery.
-
The dead letter queue (DLQ)
An event that cannot be processed (bad format, missing data) goes to a <service>.dlq topic instead of blocking the partition. The DLQ needs monitoring too – these are events the business considers done.
The ledger: entries are only appended
Where money is involved – driver settlements, commissions, customer balances – the source of truth is a ledger, a book of entries. Every operation is a transaction with at least two entries (debit and credit) that add up to zero. Entries are never edited or deleted: the ledger tells you not only how much is on an account, but also where it came from and when.
-- Append-only ledger: the application role without UPDATE and DELETE ...
REVOKE UPDATE, DELETE, TRUNCATE ON ledger_entries, ledger_transactions FROM ledger_app;
-- ... and a trigger that also stops the table owner and migrations
CREATE FUNCTION ledger_append_only() RETURNS trigger LANGUAGE plpgsql AS $f$
BEGIN
RAISE EXCEPTION 'ledger is append-only: % on % is not allowed', TG_OP, TG_TABLE_NAME;
END $f$;
CREATE TRIGGER ledger_entries_append_only
BEFORE UPDATE OR DELETE ON ledger_entries
FOR EACH ROW EXECUTE FUNCTION ledger_append_only();
-- Correcting a mistake: a reversal (same amounts, sides swapped) + a new, correct transaction,
-- both of type ADJUSTMENT, pointing to the corrected transaction in reference_id
-
A transaction must balance
In the repository the LedgerTransaction class itself enforces it: the signed entries sum to zero, at most one entry per account, a settlement amount greater than zero. The database adds its own: CHECK (amount <> 0), only DEBIT and CREDIT types, foreign keys to the transaction and the accounts.
-
Every entry points to its cause
A transaction has reference_type and reference_id – e.g. SETTLEMENT and the settlement id – and two times: occurred_at (when it happened in the business) and created_at (when it was stored). A year later you can still answer "why does this driver have this balance".
-
A mistake is fixed with a new entry
A mistake is corrected with a reversing transaction and a new, correct one – not with an UPDATE. In the repository a bug in the direction of settlement entries was fixed by migration V9 with an UPDATE of existing entries. On demo data that was enough; with real money the same fix should be two ADJUSTMENT transactions, so the history shows what was wrong and when it was fixed.
-
Enforce it in the database, not only in code
A convention in code will not stop a manual UPDATE or a migration. The application role should not have UPDATE and DELETE on ledger_entries, and a trigger should reject them from anyone. This safeguard is not in the repository – it is a proposal for a production system.
-
Not only money
The same pattern fits a warehouse (receipts and issues as entries, stock as their sum), loyalty points, leave allowances or contract hours. Anywhere the question "where does this number come from" matters, not just the number.
Projections: a balance is a result, not a source
An account balance, a "to be paid" list, a monthly report, a view in the panel – these are projections. They are computed from entries or events and can always be deleted and computed again. A projection that cannot be rebuilt has stopped being a projection and become a second source of truth, which will one day drift away from the first.
-- A projection updated in the posting transaction
INSERT INTO ledger_account_balances (account_id, currency, balance, updated_at)
VALUES (:account_id, :currency, :delta, now())
ON CONFLICT (account_id)
DO UPDATE SET balance = ledger_account_balances.balance + EXCLUDED.balance, updated_at = now();
-- Check: the balance must equal the sum of entries
SELECT b.account_id, b.balance,
coalesce(sum(CASE e.type WHEN 'CREDIT' THEN e.amount ELSE -e.amount END), 0) AS from_entries
FROM ledger_account_balances b
LEFT JOIN ledger_entries e ON e.account_id = b.account_id
GROUP BY b.account_id, b.balance
HAVING b.balance <>
coalesce(sum(CASE e.type WHEN 'CREDIT' THEN e.amount ELSE -e.amount END), 0);
-
The balance in the same transaction as the entries
The ledger in the repository adds the balance change in the posting transaction: INSERT … ON CONFLICT DO UPDATE SET balance = balance + change. The balance is never stale. It updates account rows in id order, so two postings to the same accounts cannot deadlock.
-
The price: serialization
The platform account's row serializes concurrent postings in one currency – the cost of an always-correct balance. Under heavy traffic the balance is computed asynchronously, or the account is split into several rows summed on read.
-
A rebuild procedure
rebuild_ledger_account_balances() empties the balance table and computes it again from the SUM of entries. The repository called it once after the entry direction fix and kept it for manual repair. A projection you can delete without fear is a projection done right.
-
Asynchronous projections
Reports and notifications build their own views from Kafka topics. They are up to date "in a moment" (eventual consistency), must be idempotent like any consumer, and must be rebuildable – from the source tables or by reading the events again.
-
A consistency check
A regular query comparing the balance with the sum of entries catches any drift before a customer does. The payment reconciliation service does the same between systems: the expected amount from the settlement against the amount from the payment provider, and a difference ends up as DISCREPANCY.
Where it matters most
The outbox, idempotency and the ledger have a cost: more tables, background processes and thinking. They pay off where a lost or doubled event costs money or a customer's trust.
-
Payments, settlements, commissions
A doubled event is a double payout, a lost one is a driver without money. Here the outbox, idempotent consumers and a ledger are the minimum.
-
Warehouse and stock
Goods reserved in one service and issued in another. Stock as the sum of movements instead of a number overwritten by several processes at once.
-
Integrations with external systems
Sending an invoice, ordering a courier, syncing with an ERP. The external system is sometimes unavailable – an outbox with retries and an idempotency key on its side instead of a call in the middle of a transaction.
-
Notifications
An "order received" e-mail or text sent for an order that was rolled back, or never sent at all. The outbox again – in one transaction with the order.
-
When you do not need it
One service with one database and no broker: a plain transaction is enough. The outbox comes back when the same monolith starts sending e-mails, queue messages or calls to other systems – each such "side effect" is a dual write too.
Documentation
Checklist
Before a new event flow goes to production:
- Every state change other services should learn about stores an event in the outbox in the same transaction. No handler sends to the broker directly.
- An event has its own fixed event_id and a partition key equal to the aggregate id.
- Every consumer stores the event_id in the same transaction as its change, starting with INSERT … ON CONFLICT DO NOTHING.
- Where possible, business idempotency: a unique cause (reference_type, reference_id) rather than the event id alone.
- Monitoring: the number of PENDING events and their age, every DEAD one, every message in a DLQ.
- An append-only ledger – enforced with privileges and a trigger; corrections as a reversal and a new transaction.
- Every projection has a rebuild procedure and a check query comparing it with its source.
- A test that sends the same event twice and checks there is one effect.
Tell us about your process
We reply within one working day. The first conversation about your process is free, and we prepare every quote individually.
Tell us about your process