The transactional outbox: never lose a notification
The contact form on this site does two things: it stores the message, and it notifies me on Telegram. The obvious code is two lines.
repository.save(message);
telegram.send(message); // what if this throws, or the process dies right here?
These lines have a gap between them. If Telegram is down, the visitor gets an error for a message that was in fact saved, or the message is saved and I never hear about it. Swapping the order just changes the failure: I get notified about a message that was never stored.
You can't fix this with a database transaction, because Telegram isn't part of it. The transactional outbox pattern removes the gap by not having a second operation in the request at all.
Write the intent with the data
The request does one atomic write, which contains both the message and the fact that it still has to be delivered. A separate job does the delivery later.
On this site, messages are MongoDB documents, so the outbox can be fields in the same document. A single-document write in MongoDB is atomic, which means there's no multi-document transaction to manage:
public record Delivery(DeliveryStatus status, int attempts, String lastError,
Instant nextAttemptAt, Instant sentAt) {
public static Delivery pending(Instant now) {
return new Delivery(DeliveryStatus.PENDING, 0, null, now, null);
}
}
With a relational database, you'd insert a row in an outbox table in the same transaction as the business row. The idea is identical: the data and the promise to act on it succeed or fail together.
The request is now done as soon as the write succeeds, and it doesn't depend on Telegram at all. An outage there no longer affects the person filling in the form.
The delivery job
A scheduled job runs every five seconds, finds messages that are due, and tries to send each one:
@Scheduled(fixedDelayString = "${contact.telegram.poll-interval:PT5S}", initialDelayString = "PT5S")
public void deliverPending() {
if (!telegram.isConfigured()) {
return;
}
List<ContactMessage> due = repository.findDueForDelivery(clock.instant(), Limit.of(BATCH_SIZE));
for (ContactMessage message : due) {
deliver(message);
}
}
Each outcome is recorded on the document:
- Sent: the status becomes
SENT, with a timestamp. - Failed: the attempt count goes up, the error is stored, and the next attempt is set for one minute later.
- Failed ten times: the status becomes
FAILED, an error is logged, and the job stops trying.
That last state matters. Without a limit, one message that can never be delivered gets retried forever. With it, the failure stays in the database, with its error, where I can look at it.
The query needs an index on the fields it filters by, otherwise this polling job scans the collection every five seconds for the life of the application.
What you get, and what you don't
The outbox guarantees at least once, not exactly once. Consider this order of events:
- Telegram accepts the message.
- The process dies before the job records
SENT. - On restart, the job sends it again.
I'd get the same message twice. For a personal notification, that's plainly fine, and much better than losing one. Where a duplicate would actually hurt, the consumer has to be idempotent, usually by checking an identifier it has already processed. Payment APIs that accept an idempotency key exist for this reason.
No arrangement of code removes this trade-off. When a call crosses a network and you don't get the answer, you can't know whether it took effect. You can only choose between possibly sending twice and possibly never sending.
Running more than one instance
This job has one simplification, and the code comment says so: it runs on a single application instance, so a message can't be picked up twice at the same time. With several instances, two of them would read the same pending message and both send it.
To scale out, each worker has to claim work atomically. In MongoDB, that's findAndModify, which sets a claim and returns the document in one step. In PostgreSQL:
UPDATE outbox
SET claimed_at = now()
WHERE id IN (
SELECT id FROM outbox
WHERE status = 'PENDING' AND next_attempt_at <= now()
ORDER BY next_attempt_at
LIMIT 20
FOR UPDATE SKIP LOCKED
)
RETURNING id, payload;
SKIP LOCKED lets workers take different rows without waiting for each other. You also need a way to recover claims from a worker that crashed, typically a timeout after which a claim expires.
For high volumes, polling can be replaced by reading the database's change stream, with Debezium for example. I wouldn't start there. A loop running every few seconds is easy to understand, easy to test with a fake clock, and more than enough for most systems.
The whole pattern comes down to one habit: when two things must both happen and only one of them is under your transaction, write down the intention to do the other and let something retry it.