Kest

Search

Search the documentation

Reliability

Transactional outbox

Never lose an event, never announce something that rolled back.

The problem

You save an order and then tell the rest of the world:

orders.save(order)                                  // 1. database
kafka.emit("order.created", order)                  // 2. message broker

If the process dies between 1 and 2, the order exists and nobody was told. If you swap them and the database save fails, you told everybody about an order that does not exist. Two systems (the database and the broker) cannot share one transaction, so one of the two is always at risk.

The fix

Write the message into the same database, in the same transaction, as the order. A separate relay reads the table and delivers the messages. Now either both the order and its message exist, or neither does:

BEGIN
  INSERT order
  INSERT outbox message ("order.created")      <- same transaction
COMMIT
        ...later, a background relay: SELECT pending messages -> send to Kafka -> mark done

Use it

// startup: where do messages go?
Kest.run<AppModule> {
    import(OutboxModule.forRoot {
        store = SqlOutboxStore(datastore)                       // PostgreSQL or MySQL; creates its table (kest_outbox)
        on("order.created") { m -> kafka.emit("orders", m.payload) }
        on("email.welcome") { m -> mailer.send(Json.parseObject(m.payload)) }
    })
}
 
// in a service: the message and the data commit together
@Injectable
class OrderService(private val orders: OrderRepository, private val outbox: OutboxService) {
    @Transactional
    fun place(cmd: PlaceOrder): Order {
        val order = orders.save(Order.from(cmd))
        outbox.publish("order.created", mapOf("id" to order.id, "total" to order.total))      // part of the transaction
        return order
    }
}

If place throws, the transaction rolls back and no message is recorded.

How delivery works

  • At least once. The relay may deliver a message twice (it crashed after sending but before marking it done). Receivers must tolerate duplicates: use m.id as an idempotency key (Idempotency keys).
  • Ordered by creation within one relay.
  • Retries with exponential backoff (500 ms, 1 s, 2 s... up to 5 minutes). After maxAttempts (8) a message is parked as DEAD instead of being retried forever.
  • Several instances can run relays at the same time: a message is claimed with a conditional UPDATE and a lease, so only one instance gets it. If an instance dies holding a claim, the lease (30 s) expires and another takes over.
OutboxModule.forRoot {
    store = SqlOutboxStore(datastore)
    pollMillis = 200          // how often the relay looks
    batchSize = 50
    maxAttempts = 8
    leaseMillis = 30_000
    relay = false             // do not run a relay in THIS process (an API node that only writes; a worker node does the delivering)
}

Look after the dead letters

outbox.pending()              // how many are waiting
outbox.deadCount()            // how many gave up
outbox.deadLetters()          // the messages and the last error of each
outbox.revive(id)             // after you fixed the cause, put one back in the queue

Export pending() and deadCount() as metrics and alert when the dead count is above zero or the pending count keeps growing: that means the relay or the receiver is stuck.

Delayed messages

outbox.publish("cart.reminder", mapOf("cart" to id), delayMillis = Duration.ofHours(1).toMillis())

Testing

InMemoryOutboxStore (the default) needs no database. Call outbox.drain() in a test to run the relay once, synchronously, and assert what your handler received.

Only the SQL store gives the "same transaction" guarantee, and only when publish runs inside the transaction of the same datastore as your data.

Read more