The Chenile story · Data and workflows · 4 of 4

The durable outbox: a state change and its consequences, committed together

When a state change must cause something elsewhere, such as starting a worker, signalling a parent or raising an event, Chenile writes the consequence as a row in an outbox table in the same local transaction as the change. Dispatchers carry the rows out afterwards with leases, claim tokens, retries and receipts. Nothing is lost in a crash, nothing is counted twice, and no distributed transaction is needed.

The problem: two systems, one decision

A state change rarely ends at the database. A process entering EXECUTING must start a worker; a child finishing must tell its parent; a finished process must announce it; an accepted trigger must eventually raise its event. The state lives in the database. The consequence lives somewhere else: a message broker, another service, another row that only some other code should write.

There are two obvious orders, and both are wrong:

  • Save, then act. If the service crashes after the commit but before the publish, the process waits forever for a worker nobody started.
  • Act, then save. If the transaction then rolls back, a worker runs for a state change that never happened.

The textbook way to make both happen or neither is a distributed transaction, XA, with two-phase commit across the database and the broker. It is heavy to operate, not every broker supports it, it slows every state change down, and it makes each change depend on the broker being up at that moment. Chenile does not use it.

The How it works tab animates the alternative.

The idea: write the consequence down

Instead of acting, the code that changes state records what must happen, as a row in an outbox table in the same database, in the same transaction:

BEGIN
  UPDATE process_table           SET state = 'EXECUTING' …
  INSERT INTO chenile_process_outbox (… 'START_WORKER', 'P-1:EXECUTOR' …)
COMMIT

One local transaction now covers both. If it commits, the state and the instruction to act on it exist together; if it rolls back, neither does. Afterwards a dispatcher reads the outbox and carries each row out. The consequence is delayed by a moment, never lost.

Chenile’s outbox, the chenile-outbox module, is a core component rather than a detail of one feature. Process management records every consequence of every process transition in it, and the trigger service records every accepted trigger in it. Anything that needs “this state change must cause that, reliably” can add its own commands.

Commands own their consequences

An outbox row is a command: a type, an idempotency key and a JSON payload the command defines. Each kind of command is one class implementing OutboxCommandLifecycle:

String type();                                    // "START_WORKER"
boolean shouldEnqueue(C context);                 // does this change need me? (no writes)
void enqueue(C context);                          // write my row
Map<String, String> executionHeaders(OutboxCommand command);
void dispatch(OutboxCommand command);             // carry it out
void onDead(OutboxCommand command);               // after the last failed attempt

Two parts keep this extensible:

  • A producer decides what to write. After a state change, the producer asks each command registered for that kind of change whether it applies, then lets it write its row. Process transitions have four commands: CREATE_SUBPROCESS, SIGNAL_PARENT, EMIT_COMPLETED and START_WORKER. Triggers have one, DISPATCH_TRIGGER.
  • A registry decides how to run a stored row. It maps the row’s type to its command. Adding a command is adding a bean: no enum, no central switch, no new column. Two commands claiming the same type fail at startup; a stored type nobody handles fails, retries and ends dead instead of being silently acknowledged.

Carrying the rows out

Dispatchers run in every replica, polling the outbox every second by default. Correctness rests on a few database primitives, each used deliberately.

One owner per attempt. A replica claims the next due row with SELECT … FOR UPDATE SKIP LOCKED, so concurrent replicas each get a different row and never wait on one another. The claim marks the row RUNNING, increments its attempt and gives it a fresh claim token and a lease (300 seconds by default).

Fenced writes. Every later write to the row is a single UPDATE … WHERE id = ? AND claim_token = ?, and the affected-row count is the check. A replica that paused, lost its lease and came back finds that its update matches no row, so its transaction rolls back and nothing it did is kept.

Leases instead of crash detection. If a replica dies mid-dispatch, nobody needs to notice. Its lease runs out and any replica may claim the row again, with a new token.

Effect and acknowledgement together. The handler runs in its own transaction, after re-checking the claim under a row lock. Its local changes, its receipt and the row’s DONE acknowledgement commit together, or not at all.

The original context. The row stores its tenant and, if the command wants them, the headers of the request that created it. The dispatcher installs them before running the command, so the work runs as that request did, even from a background thread.

Exactly once where it can be, at least once where it cannot

Delivery from an outbox is at least once: a command can run again after a crash or a lost lease. Three separate guards turn that into exactly-once effects wherever the effect is in the database:

  • No duplicate rows. The idempotency key is unique, and the row is inserted with ON CONFLICT DO NOTHING, so recording the same consequence twice writes one row. Plain “insert and catch the error” would not do: in PostgreSQL a constraint violation aborts the whole business transaction it shares.
  • No duplicate claims. The claim token and lease make exactly one replica the owner of each attempt.
  • No duplicate effects. A command checks a receipt, keyed by business identity, in the same transaction as its effect: a child counts towards its parent once, a successor starts once, a worker start is recorded once.

An effect outside the database, such as a message to a broker, cannot be rolled back with the transaction, so it stays at least once. The receiver deduplicates, on the dispatchId every worker message carries.

When a command keeps failing

A failed command goes back to PENDING, hidden until its backoff has passed: 1 second, then 2, 4, 8, up to a minute between attempts. After the fifth failure it is DEAD, and the dispatcher logs the dead count every cycle until someone acts. Nothing loops forever.

A dead command’s onDead hook runs once. Most commands leave recovery to an operator: fix the cause, then replayDead(id) puts the same row back in the queue, keeping its identity and its receipts, so anything that already happened does not happen again. START_WORKER compensates on its own: it ends its process with errors, so the tree unwinds instead of waiting for a worker that will never run.

The same visible_after column that drives the backoff makes the outbox a durable timer: a row can be written to become due later.

Why JDBC, not JPA

The outbox repository is hand-written SQL on purpose. The table is a concurrent work queue, and its correctness depends on statements an ORM cannot express safely: FOR UPDATE SKIP LOCKED, compare-and-set updates whose row count is the fence, and ON CONFLICT DO NOTHING inside a transaction it must not abort. The business entities stay in JPA. Both use the same DataSource and transaction manager, which the outbox checks at runtime, so its rows and receipts commit with the business change. PostgreSQL is the reference database.

One outbox per tenant database

When each tenant has its own database, each has its own outbox table, and a row is written to the table of the request’s tenant. The background poller has no tenant of its own, so it visits the tenants one after another, pinning each tenant’s database while it drains that tenant’s rows. A failure in one tenant does not stop the others.

Where to go next