Video in progress

Senior 🧪 Testing

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.

  1. 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.

  1. No broker. I cut the Kafka connection with Toxiproxy, and place() must still succeed, with the outbox row staying in the NEW state. After the connection comes back, I use Awaitility to wait until the message lands in the topic and the row becomes SENT.

  2. "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 same eventId and the result must be one.

  3. Parallel relays. Two pods read the outbox at the same time. Even if SELECT ... FOR UPDATE SKIP LOCKED is 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.