Video in progress
How do you test the transactional outbox pattern, so that no message is lost and sending one twice does no harm?
I check four things separately: that the business record and the outbox row are saved in one transaction or roll back together; that the relay doesn't lose rows if the broker goes down; that two relay instances don't pick up the same row twice; and that the consumer tolerates duplicates. All of it with a real database and broker, in tests without @Transactional.
📖 Answer
The whole point of an outbox is "all or nothing" and "at least once". Both are verified only with a real transaction and a real failure; mocks give almost nothing here.
- Atomicity. Let an error occur after the order is saved but before the commit:
@Test
void outboxRowIsRolledBackWithOrder() {
// auditSpy is a @MockitoSpyBean; it's called inside place() after the outbox row is written
doThrow(new IllegalStateException("boom")).when(auditSpy).record(any());
assertThatThrownBy(() -> orderService.place(newOrder()));
assertThat(orderRepo.count()).isZero();
assertThat(outboxRepo.count()).isZero();
}
In the success case, both exist. If the test is @Transactional, this difference isn't visible at all.
-
No broker. I cut the Kafka connection with Toxiproxy, and
place()must still succeed, with the outbox row staying in theNEWstate. After the connection comes back, I use Awaitility to wait until the message lands in the topic and the row becomesSENT. -
"Sent it, but couldn't mark it". If the relay crashes after sending the message but before writing
SENT, the message goes out again on the next run. That's normal, which makes this a consumer test: send a message twice with the sameeventIdand the result must be one. -
Parallel relays. Two pods read the outbox at the same time. Even if
SELECT ... FOR UPDATE SKIP LOCKEDis used, I pin it down with a test: run the relay on two threads at once and count that every row reached the broker exactly once.
One more subtle point is ordering. The Created and Paid events of one order must go out with the same key, otherwise they can land on different partitions and be read in reverse order. The test checks the key in the outbox.
If the relay is done with CDC like Debezium, points 2 and 4 become the infrastructure's job, but points 1 and 3 are still your code.
Sign up to mark studied questions and save your progress.