barista-1 commits a sale to its Postgres database. Before it sends the message that would earn the
customer a stamp, it's killed with exit code 137. barista-db now holds the sale, loyalty-db holds no
stamp, and nothing in the system will ever send that message again.
That's the first scene of the demo in the
companion repo (opens in a new tab), and it's the crash I
asked about in July (opens in a new tab):
the one after the commit and before publishing. If your service publishes from a plain
@TransactionalEventListener(phase = AFTER_COMMIT), it has the same window. I built the same two
Spring Boot 4.2 services four ways and ran every version under the same seeded chaos. A script
counts the damage from the outside, from both databases, the broker and the logs.
Saving first and sending after the commit lost 274 of 1'316 sales. Sending inside the transaction stamped cards for 25 sales that had rolled back. A transactional outbox brought both to zero and stamped 25 sales twice instead. Outbox plus inbox ended at zero lost, zero ghosts and zero double stamps, with 25 duplicates delivered and caught.
Those zeros are about stamps on loyalty cards. Some messages still arrive twice: RabbitMQ delivers at least once, so "once" holds only for what loyalty writes in its own Postgres transaction. It's also one machine, one run per version, and the last version on three seeds. One finding concerns RabbitMQ itself: since 4.3, a message that keeps failing in Spring's default AMQP 1.0 listener never reaches the quorum queue's delivery limit.
The sale commits, the message doesn't
The domain is small on purpose. barista sells coffee and stores each sale in its own Postgres
database. loyalty puts one stamp per cup on a loyalty card, in a second Postgres database. A sale
reaches loyalty as a CoffeeSold message over RabbitMQ, and the card is right when every cup sold
shows up as exactly one stamp.
For one sale, barista has to do two things: commit the row and send the message. No transaction spans Postgres and RabbitMQ, so one of the two happens first, and a crash can happen in between. Each order fails its own way:
- Commit first, crash before sending. The sale exists and loyalty never hears of it. I count that as lost.
- Send first, crash before the commit. Postgres rolls the sale back, but the message is already out. loyalty stamps a card for a sale that never happened, which I count as a ghost.
Even when barista gets both done, loyalty can receive the message twice. RabbitMQ's reliability guide (opens in a new tab) says acknowledgements guarantee at least once delivery, and that consumers "must be prepared to handle deliveries they have seen in the past". After a broker restart, a lost acknowledgement or a producer that sends again after a timeout, loyalty gets the same message again. For a stamp that's the third failure, double-applied: one sale, stamped twice.
The same guide recommends consumers that are idempotent "rather than to explicitly perform
deduplication". That works when the effect is idempotent by nature, like setting an order's status
to PAID. A stamp adds one. Apply it twice and the card is wrong, so this consumer has to
deduplicate explicitly.
Two Spring Boot services and the broker between them
Overview
barista sells coffee, loyalty stamps the customer's card, and RabbitMQ carries one message between them. Each service writes only to its own database.
A sale. A POST /api/sales reaches one of the two barista instances, and barista stores the sale in barista-db.
CoffeeSold goes out. barista publishes CoffeeSold over AMQP 1.0 to the exchange barista, with a message-id and a content-sha256 header.
Routed, then accepted. RabbitMQ routes it into the quorum queue loyalty.coffee-sold and answers barista with accepted.
Checked, stamped, accepted. loyalty checks the hash and the content, writes a stamp to loyalty-db, and accepts only after that.
Parked. A message loyalty refuses for its content (a hash mismatch, invalid content, a reused id) is discarded as rejected and dead-lettered.
Two commits, no shared transaction. barista-db commits the sale, loyalty-db the stamp. The scenarios below change the order of sending, committing and accepting.
All steps
- A sale. A
POST /api/salesreaches one of the two barista instances, and barista stores the sale in barista-db. - CoffeeSold goes out. barista publishes
CoffeeSoldover AMQP 1.0 to the exchangebarista, with amessage-idand acontent-sha256header. - Routed, then accepted. RabbitMQ routes it into the quorum queue
loyalty.coffee-soldand answers barista withaccepted. - Checked, stamped, accepted. loyalty checks the hash and the content, writes a stamp to loyalty-db, and accepts only after that.
- Parked. A message loyalty refuses for its content (a hash mismatch, invalid content, a reused id) is discarded as
rejectedand dead-lettered. - Two commits, no shared transaction. barista-db commits the sale, loyalty-db the stamp. The scenarios below change the order of sending, committing and accepting.
I run two barista instances and two loyalty instances against RabbitMQ 4.4.1 over AMQP 1.0, with
Spring AMQP 4.2's RabbitAmqpTemplate on the way out and its listener container on the way in. The
broker version is pinned: support/compose.yaml and both Testcontainers base classes start the
image rabbitmq:4.4.1-management. That matters for the settling section further down, because what
it shows only happens from RabbitMQ 4.3 on. It's the same client stack as in my
OAuth2 post. Two of each, so a killed instance has a sibling that
keeps going, and a duplicate can go to another JVM than the original did.
Over AMQP 1.0 the broker answers every message barista publishes with an outcome. accepted means
RabbitMQ has taken the message and every queue it routed the message to has it. Nothing is deleted
at that point. The message waits in the queue for loyalty. On the consumer side loyalty answers each
delivery with an outcome as well, and once it answers accepted, RabbitMQ deletes the message from
the queue. The outbox and the inbox don't depend on the protocol: on AMQP 0.9.1 the relay would wait
for a publisher confirm instead of accepted. Only the way loyalty settles its deliveries is
specific to AMQP 1.0.
barista publishes to the exchange barista with the routing key coffee.sold. RabbitMQ routes the
message into the quorum queue loyalty.coffee-sold, which has a delivery limit of 20 and
dead-letters into loyalty.coffee-sold.failed. I call that one the parking queue. Whatever loyalty
refuses ends up there instead of disappearing.
A quorum queue is RabbitMQ's replicated queue type, built on the
Raft consensus algorithm (opens in a new tab): it keeps copies on several nodes, and the
broker answers accepted only once a majority of them has written the message to disk. The demo
runs a single broker node, so there's nothing to replicate to, and the
docs (opens in a new tab) say the guarantees fully hold only from three
nodes. What the demo needs is something classic queues don't have. A quorum queue keeps count of a
message's unsuccessful deliveries and drops or dead-letters one that goes over the delivery limit,
here into the parking queue. The limit has defaulted to 20 since RabbitMQ 4.0, so the broker policy
in the repo's support/rabbitmq/definitions.json only writes the default down.
Every message carries two things loyalty can check:
messageId, a UUID barista assigns when it creates the sale. A message sent again carries the same one.content-sha256, a header with the SHA-256 of the exact bytes Jackson wrote into the body. It lets loyalty tell a redelivery (same id, same bytes) from a producer that reused an id for other content.
Toxiproxy (opens in a new tab) runs between the apps and the broker. That's how
the chaos run drops a broker confirmation or a consumer's settlement without touching either side.
Settlement is AMQP 1.0's word for the ack, and it comes in four outcomes: accepted, released,
rejected and modified.
Outbox on the way out, inbox on the way in
Both halves of the fix have had names for years. microservices.io lists them as Transactional outbox (opens in a new tab) and Idempotent Consumer (opens in a new tab), and Enterprise Integration Patterns calls the second one an Idempotent Receiver (opens in a new tab).
The outbox moves the message into the database. barista writes the sale and an outbox row in one local transaction, so both commit or neither does. A relay picks the row up after the commit, sends it and marks it done once the broker has accepted. If the relay dies first, the row is still there and goes out again. Lost and ghosts drop to zero. Duplicates go up, because going out again is exactly what a duplicate is.
The inbox deals with those duplicates on the other side. loyalty records every message id in a table, in the same transaction as the stamp, and a second delivery finds the id and skips the stamp. Record and effect commit together.
Change data capture reads the outbox from the database log instead of polling it. A Debezium connector reads the log, and Debezium's outbox event router (opens in a new tab) routes each outbox row to its topic. NServiceBus (opens in a new tab) ships both halves as one feature and calls the whole thing the outbox. I took the smallest thing Spring ships for the outbox, Spring Modulith's event publication registry, and wrote the inbox by hand. It's one table and two statements.
The same sale, wired four ways in Spring Boot
The three producers are one switch in SaleService, picked by barista.mode. Everything around
it is the same code in every run. loyalty has two modes, naive and inbox, and the fourth version
is the outbox again with loyalty switched to inbox.
public Receipt sell(String cardId, int cups) {
final var sale = new Sale(cardId, cups);
switch (properties.mode()) {
case AFTER_COMMIT -> {
sales.save(sale); // commits here: save runs in its own transaction
crashPoints.at(CrashPoints.AFTER_COMMIT_BEFORE_SEND, sale.getSaleId());
sender.send(coffeeSold(sale)).join();
}
case IN_TRANSACTION -> transaction.executeWithoutResult(status -> {
// flushed now, so the insert reaches the database before the send
sales.saveAndFlush(sale);
sender.send(coffeeSold(sale)).join();
crashPoints.at(CrashPoints.AFTER_SEND_BEFORE_COMMIT, sale.getSaleId());
});
// Modulith stores the event with the sale; OutboxRelay sends it after the commit
case OUTBOX -> transaction.executeWithoutResult(status -> {
sales.save(sale);
events.publishEvent(coffeeSold(sale));
});
}
return new Receipt(sale.getSaleId(), sale.getMessageId());
}crashPoints.at is a named crash point, a line where the service kills itself on purpose. With a
configured probability it calls Runtime.getRuntime().halt(137): no shutdown hooks, no finally
blocks, the same abrupt end as a kill -9 and the exit code 137 a shell shows for one, but on the
exact line where the window is. A kill -9 from outside stops the process at whatever line it's on.
A named crash point kills it inside the window every time.
Save, then send
If you publish from a plain @TransactionalEventListener(phase = AFTER_COMMIT), this is your
version. sales.save(sale) runs in a transaction of its own and has committed by the time it
returns. Sending comes after, outside any transaction. A kill between the two loses the sale, and so
does a failure to send while RabbitMQ restarts. Nothing retries it.
Overview
barista commits the sale, then sends CoffeeSold. A crash between the two loses the message.
A transaction of its own. sales.save(sale) opens a transaction for the insert alone.
Committed before sending. The transaction commits, and the sale is durable before RabbitMQ has heard of it.
Killed after the commit. barista dies at after-commit-before-send. If sending fails while RabbitMQ restarts, the state is the same.
Lost. Nothing in barista remembers the message, so nobody sends it again. barista-db has the sale, loyalty-db has no stamp.
All steps
- A transaction of its own.
sales.save(sale)opens a transaction for the insert alone. - Committed before sending. The transaction commits, and the sale is durable before RabbitMQ has heard of it.
- Killed after the commit. barista dies at
after-commit-before-send. If sending fails while RabbitMQ restarts, the state is the same. - Lost. Nothing in barista remembers the message, so nobody sends it again. barista-db has the sale, loyalty-db has no stamp.
In the run, 274 of 1'316 committed sales never got a stamp. The crash point fired 5 times. Five of
the lost sales match those kills. The other 269 never needed a crash point: barista committed them
and then failed to send, in the stretch around the broker kill that the chart further down shows.
BrokerRefusesAfterCommitIT (opens in a new tab)
tests that path without any chaos: the broker refuses, the sale stays, and no message exists
anywhere.
Send inside the transaction
Sending inside the transaction gets rid of the lost sales and creates ghosts instead. saveAndFlush
writes the row to the database without committing it, barista sends the message, RabbitMQ accepts
it, and only then does the transaction commit. A crash at that moment rolls the sale back. The
message is already queued.
Overview
barista sends CoffeeSold from inside the open transaction. If that transaction rolls back after sending, loyalty stamps a sale that never happened.
Inserted, not committed. barista opens a transaction and flushes the sale with saveAndFlush. Postgres has the row, and only this transaction can see it.
Sent from inside. With the transaction still open, barista sends CoffeeSold and RabbitMQ accepts it.
Killed before the commit. barista dies at after-send-before-commit, inside the open transaction. If accepted doesn't arrive within 5 s, barista rolls back too.
Rolled back. The connection is gone, so Postgres rolls the open transaction back. The sale never happened.
Stamped anyway. loyalty knows nothing of the rollback. It stamps the message in a transaction of its own, commits, then accepts.
Ghost. loyalty-db holds a stamp for a sale barista-db never committed.
All steps
- Inserted, not committed. barista opens a transaction and flushes the sale with
saveAndFlush. Postgres has the row, and only this transaction can see it. - Sent from inside. With the transaction still open, barista sends
CoffeeSoldand RabbitMQ accepts it. - Killed before the commit. barista dies at
after-send-before-commit, inside the open transaction. Ifaccepteddoesn't arrive within 5 s, barista rolls back too. - Rolled back. The connection is gone, so Postgres rolls the open transaction back. The sale never happened.
- Stamped anyway. loyalty knows nothing of the rollback. It stamps the message in a transaction of its own, commits, then accepts.
- Ghost. loyalty-db holds a stamp for a sale barista-db never committed.
loyalty stamps it, since for loyalty it's a perfectly good message. In the run, loyalty stamped
cards for 25 sales that don't exist.
RollbackInTransactionIT (opens in a new tab)
makes one without any chaos: mark the transaction rollback-only, sell, and the queue holds a message
for a sale that's gone. The transaction also holds a database connection for the whole round trip to
the broker.
The outbox, on Spring Modulith 2.2
Spring Modulith's JDBC event publication registry is an outbox table by another name. Publish an
event inside a transaction and Modulith writes it to event_publication in that same transaction.
That's the OUTBOX case above, and it's the entire atomic part.
The relay is one class, and its listener runs after the commit, like a plain
@TransactionalEventListener(phase = AFTER_COMMIT). The difference from the first version is the
event_publication row that committed with the sale: when sending fails, Modulith still has
something to resubmit. With the registry on the classpath, every AFTER_COMMIT
@TransactionalEventListener gets such a row, so a plain listener becomes an outbox once something
resubmits what failed.
@Component
@RequiredArgsConstructor
class OutboxRelay {
private final CoffeeSoldSender sender;
private final FailedEventPublications failed;
private final CrashPoints crashPoints;
// sending needs no transaction; Spring allows only REQUIRES_NEW or NOT_SUPPORTED here
@ApplicationModuleListener(propagation = Propagation.NOT_SUPPORTED)
CompletableFuture<Void> relay(CoffeeSold coffeeSold) {
return sender.send(coffeeSold)
.thenRun(() -> crashPoints.at(CrashPoints.AFTER_ACCEPT_BEFORE_COMPLETE, coffeeSold.saleId()));
}
// a failed publication stays FAILED until someone resubmits it; so does one left half done by a crash, once it
// is stale (spring.modulith.events.staleness)
@Scheduled(fixedDelayString = "${barista.resubmit-interval}")
void resubmit() {
failed.resubmit(ResubmissionOptions.defaults());
}
}Modulith completes the publication only once the future that relay returns succeeds, and marks it
FAILED when that future fails. The future comes from the sender's send and completes on
RabbitMQ's accepted outcome, nothing else. The stamp helper above it sets the message id and the
hash header:
// runs after Jackson wrote the body, so the hash covers the bytes that go on the wire
private static Message stamp(Message message, CoffeeSold coffeeSold) {
final var properties = message.getMessageProperties();
properties.setMessageId(coffeeSold.messageId().toString());
properties.setHeader(ContentHash.HEADER, ContentHash.of(message.getBody()));
return message;
}
// completes when the broker answers ACCEPTED; a rejected or released message, or no answer in time, fails it
public CompletableFuture<Boolean> send(CoffeeSold coffeeSold) {
return amqp
.convertAndSend(
CoffeeSoldTopology.EXCHANGE,
CoffeeSoldTopology.ROUTING_KEY,
coffeeSold,
message -> stamp(message, coffeeSold)
)
// the template's own publishTimeout doesn't apply to this send
.orTimeout(properties.sendTimeout().toMillis(), TimeUnit.MILLISECONDS);
}A rejected or released outcome fails the future, and so does no answer within 5 s. I put that
orTimeout on it myself. The template passes its publishTimeout to the RabbitMQ client, which
applies it only to a publisher with a fixed address, and there only to how long sending waits for
link credit, the broker's permission to send. The template's publisher has no fixed address, so the
setting limits nothing here, and nothing in the template limits the wait for the outcome.
@ApplicationModuleListener opens a new transaction by default, and sending has nothing to commit,
so NOT_SUPPORTED keeps the listener out of one.
resubmit covers what Modulith doesn't do while the app runs.
spring.modulith.events.republish-outstanding-events-on-restart only helps at the next start, and
it defaults to false. So every 5 s a @Scheduled method resubmits up to 100 FAILED
publications, the default batch, through FailedEventPublications. If a crash leaves a publication
half done, it turns FAILED once it's stale, after 15 s here, and the next pass picks it up.
Overview
The sale and its message commit together, and a relay sends after the commit until RabbitMQ accepts. loyalty has no inbox yet.
Sale and event, one transaction. barista inserts the sale, and Spring Modulith stores CoffeeSold as an event_publication row.
Both or neither. One commit makes both rows durable. A rollback would have taken both.
Sent after the commit. OutboxRelay sends outside any transaction, and RabbitMQ accepts. Modulith writes each status change in a short transaction of its own.
Killed before completion. barista dies at after-accept-before-complete, before the transaction that marks it COMPLETED. The message is in the queue.
Stamped. loyalty stamps the delivery in its own transaction, commits, then accepts.
Stale, then failed. After 15 s in PROCESSING the publication is stale, and a running barista instance marks it FAILED.
Sent again. Every 5 s, resubmit calls the relay again: same message-id, same bytes. Only RabbitMQ's accepted makes it COMPLETED.
Stamped again. loyalty can't tell a message sent again from a new sale. It stamps the second delivery in a second transaction, commits, then accepts.
Double-applied. One sale, stamped twice. The outbox never loses the message, and a consumer without an inbox pays for that by stamping it again.
All steps
- Sale and event, one transaction. barista inserts the sale, and Spring Modulith stores
CoffeeSoldas anevent_publicationrow. - Both or neither. One commit makes both rows durable. A rollback would have taken both.
- Sent after the commit.
OutboxRelaysends outside any transaction, and RabbitMQ accepts. Modulith writes each status change in a short transaction of its own. - Killed before completion. barista dies at
after-accept-before-complete, before the transaction that marks itCOMPLETED. The message is in the queue. - Stamped. loyalty stamps the delivery in its own transaction, commits, then accepts.
- Stale, then failed. After 15 s in
PROCESSINGthe publication is stale, and a running barista instance marks itFAILED. - Sent again. Every 5 s,
resubmitcalls the relay again: samemessage-id, same bytes. Only RabbitMQ'sacceptedmakes itCOMPLETED. - Stamped again. loyalty can't tell a message sent again from a new sale. It stamps the second delivery in a second transaction, commits, then accepts.
- Double-applied. One sale, stamped twice. The outbox never loses the message, and a consumer without an inbox pays for that by stamping it again.
The outbox run lost nothing and invented nothing. It stamped 25 sales twice, because loyalty was
still naive: every message the outbox sent again, and every broker redelivery after a lost
settlement or a loyalty crash, is a second delivery of the same bytes.
BrokerRefusesOutboxIT (opens in a new tab)
shows the outbox sending again on its own: the broker refuses, the publication turns FAILED,
resubmit sends it again, and Postgres' own sha256() over the stored publication matches the
header that went out.
Modulith also ships its own RabbitMQ externalizer. It speaks AMQP 0.9.1 only, hence the hand-written relay. The Modulith docs say this about their own listener-based externalization, which is what this relay does by hand: "While this is a pragmatic, simple solution, it lacks critical features developers might expect from actual outbox pattern implementations." Since 2.1, Modulith can use Namastack Outbox (opens in a new tab) or JobRunr (opens in a new tab) for externalization instead.
The inbox: one insert inside the stamp's transaction
The inbox is one table:
CREATE TABLE inbox
(
consumer text NOT NULL,
message_id uuid NOT NULL,
content_sha256 text NOT NULL,
duplicates int NOT NULL DEFAULT 0,
PRIMARY KEY (consumer, message_id)
);consumer holds the queue name, so the same message id read from two queues counts once per queue.
The service around the table reads top to bottom:
// the inbox row and the stamp commit together, and this returns after the commit, so the listener settles with
// the broker knowing the outcome is durable
@Transactional
public Verdict stamp(CoffeeSold coffeeSold, String body, String sha256) {
if (seenBefore(coffeeSold.messageId(), sha256)) {
return repeatVerdict(coffeeSold.messageId(), sha256);
}
stamps.save(new Stamp(
coffeeSold.messageId(),
coffeeSold.saleId(),
coffeeSold.cardId(),
coffeeSold.cups(),
body,
sha256
));
return Verdict.APPLIED;
}
// the inbox: records the message id, so a second delivery finds it; NAIVE skips it and stamps every delivery
private boolean seenBefore(UUID messageId, String sha256) {
return properties.mode() == LoyaltyProperties.Mode.INBOX
&& inbox.insertIfAbsent(CoffeeSoldTopology.QUEUE, messageId, sha256) == 0;
}
// same id with the same content is a redelivery; same id with other content is a bug at the producer
private Verdict repeatVerdict(UUID messageId, String sha256) {
return inbox.countDuplicate(CoffeeSoldTopology.QUEUE, messageId, sha256) == 1
? Verdict.DUPLICATE
: Verdict.ID_REUSED;
}The two statements behind it:
// 1 the first time a message id is seen, 0 after that; a second instance inserting the same id at the same
// moment waits for the first and gets 0. HQL, because JPQL has no INSERT; Hibernate hands ON CONFLICT DO NOTHING
// to Postgres as written, and duplicates is left out so it takes the column default
@Modifying
@Query("""
INSERT INTO InboxEntry (consumer, messageId, contentSha256) VALUES (:consumer, :messageId, :sha256)
ON CONFLICT DO NOTHING
""")
int insertIfAbsent(
@Param("consumer") String consumer,
@Param("messageId") UUID messageId,
@Param("sha256") String sha256
);
// 1 when the id was seen with the same content, a true duplicate; 0 when the content differs
@Modifying
@Query("""
UPDATE InboxEntry e SET e.duplicates = e.duplicates + 1
WHERE e.consumer = :consumer AND e.messageId = :messageId AND e.contentSha256 = :sha256
""")
int countDuplicate(
@Param("consumer") String consumer,
@Param("messageId") UUID messageId,
@Param("sha256") String sha256
);The insert returns 1 for a new message and 0 for one it has seen. A second loyalty instance that
inserts the same id at the same moment blocks until the first transaction ends. It gets 0 if that
one commits and inserts if it rolls back. Postgres does that on the primary key
(INSERT (opens in a new tab),
index uniqueness checks (opens in a new tab),
transaction isolation (opens in a new tab)), and the app
coordinates nothing. The update counts a duplicate only when the hash matches too. Same id with
different content means the producer reused an id, and loyalty parks that message as ID_REUSED
instead of guessing which version is right.
I wrote the insert as a query on purpose. A JPA save() on an entity with an assigned id selects
first and then merges, so a committed duplicate would be merged over the existing row. A concurrent
one would fail the flush and abort the Postgres transaction, stamp included.
ON CONFLICT DO NOTHING answers with a number and leaves the transaction usable. JPQL has no
INSERT, so the query is HQL, whose
insert statement (opens in a new tab) takes an
ON CONFLICT clause. Hibernate 7.4 sends Postgres the same statement plus a table alias:
insert into inbox as ie1_0(consumer,message_id,content_sha256) values (?,?,?) on conflict do nothing.
Commit first, accept second. stamp returns after the commit, and only then does the listener call
context.accept(). RabbitMQ keeps every delivery until it's settled, so a crash can happen in three
places:
- Before the commit. Inbox row and stamp roll back together, the delivery goes back to the queue, and the next attempt does the whole thing.
- After the commit, before loyalty accepts. Inbox row and stamp are in. The redelivery inserts, gets 0, counts a duplicate and is accepted. Nothing is stamped twice.
- After loyalty accepts. The message is gone and the work is done.
Overview
The sale is committed and CoffeeSold waits in the queue. loyalty writes an inbox row in the stamp's transaction, and accepts only after the commit.
Inbox row, then stamp. loyalty opens a transaction. The inbox insert returns 1, so the id is new, and the stamp goes in beside it.
Killed before the commit. A kill -9 hits loyalty while its transaction is still open.
Rolled back. Postgres rolls back the inbox row and the stamp together, and the unsettled delivery goes back to the queue.
Delivered again, applied. A running loyalty instance finds no inbox row. The insert returns 1, the stamp goes in, and the transaction commits.
Killed before accepting. loyalty dies at after-commit-before-settle. The stamp is committed, but loyalty never accepted, so RabbitMQ delivers again.
Seen, counted, accepted. The insert returns 0 and the hash matches, so loyalty counts a duplicate and writes no stamp. It commits, then accepts.
Stamped once. Three deliveries, stamped once, one duplicate. loyalty commits before it accepts, so a crash either side of the commit leaves loyalty-db right.
All steps
- Inbox row, then stamp. loyalty opens a transaction. The inbox insert returns 1, so the id is new, and the stamp goes in beside it.
- Killed before the commit. A
kill -9hits loyalty while its transaction is still open. - Rolled back. Postgres rolls back the inbox row and the stamp together, and the unsettled delivery goes back to the queue.
- Delivered again, applied. A running loyalty instance finds no inbox row. The insert returns 1, the stamp goes in, and the transaction commits.
- Killed before accepting. loyalty dies at
after-commit-before-settle. The stamp is committed, but loyalty never accepted, so RabbitMQ delivers again. - Seen, counted, accepted. The insert returns 0 and the hash matches, so loyalty counts a duplicate and writes no stamp. It commits, then accepts.
- Stamped once. Three deliveries, stamped once, one duplicate. loyalty commits before it accepts, so a crash either side of the commit leaves loyalty-db right.
So a message counts as processed when its inbox row and its stamp have committed. Every message ends
in one of two states: stamped exactly once, or parked in loyalty.coffee-sold.failed.
The inbox is never purged, and the table has no timestamp to purge by. Whoever adds a cleanup needs
a received_at column and a retention longer than any redelivery can take, which is the same rule
the NServiceBus docs (opens in a new tab) state for their
deduplication data. And "once" covers only what happens inside that transaction. A listener that
sends an email before the commit sends it again on the redelivery. One that sends it after the
commit and crashes never sends it, because the redelivery is a duplicate now. Effects outside the
database need an outbox on the consumer's side too.
Settling by hand on RabbitMQ 4.3
I gave loyalty.coffee-sold a delivery limit of 20, so a message that always fails ends up in the
parking queue. With Spring's default AMQP 1.0 container it never gets there. A listener that throws
gets its delivery released, and since RabbitMQ 4.3 the delivery limit reads delivery-count,
which the quorum queue docs (opens in a new tab) say a released outcome
doesn't raise. The message comes back forever.
ReleasedDoesNotCountIT (opens in a new tab)
shows it against a real broker, the same pinned 4.4.1.
Up to 4.2 the limit counted every return, so a queue that parked poison messages before the upgrade
can stop doing it after. AMQP 0.9.1 has the same split: in the docs' table basic.reject raises the
count and basic.nack doesn't.
So I made loyalty settle every delivery itself:
@RabbitListener(queues = CoffeeSoldTopology.QUEUE, ackMode = "MANUAL")
void onMessage(CoffeeSold coffeeSold, Message message, Consumer.Context context) {
final Verdict verdict;
try {
verdict = verdict(coffeeSold, message);
} catch (RuntimeException e) {
log.warn(
"Message {} failed on delivery {}, requeued: {}",
coffeeSold.messageId(),
message.deliveryCount(),
e.getClass().getSimpleName()
);
// delivery-failed set: unlike a release, this requeue counts toward the delivery limit
context.requeue(Map.of(), true);
return;
}
if (verdict == Verdict.DUPLICATE) {
log.info("Message {} duplicate on delivery {}", coffeeSold.messageId(), message.deliveryCount());
}
if (verdict.accepted()) {
crashPoints.at(CrashPoints.AFTER_COMMIT_BEFORE_SETTLE, coffeeSold.messageId());
context.accept();
} else {
log.warn("Message {} parked: {}", coffeeSold.messageId(), verdict);
// rejected: the broker dead-letters it to the parking queue
context.discard();
}
}An exception requeues with delivery-failed set, the modified outcome that RabbitMQ counts. On
the 21st counted failure, once the count passes 20, the queue dead-letters the message into the
parking queue. A message refused for its content (hash mismatch, invalid fields, a reused id) is
discarded, which is the rejected outcome, and goes to the parking queue at once. The parked
message carries the broker's reason, delivery_limit or rejected, and loyalty's own verdict is in
its log.
ParkingIT (opens in a new tab)
covers each of those paths.
Overview
One message whose listener always throws, in two runs. RabbitMQ checks the queue's delivery limit of 20 against the delivery count shown below it.
Released. The listener throws, and Spring's default AMQP 1.0 container settles the delivery as released.
Not counted. Since RabbitMQ 4.3 the limit reads the delivery count, and a release doesn't raise it. The message comes back forever, the count at 0.
Settled by hand. loyalty calls context.requeue(Map.of(), true), the modified outcome with delivery-failed. RabbitMQ counts it.
Every failure counts. Each redelivery fails the same way and each requeue raises the count by one, until the 21st failure takes it to 21.
Parked past 20. With the count past the limit of 20, RabbitMQ dead-letters the message to the parking queue loyalty.coffee-sold.failed.
All steps
- Released. The listener throws, and Spring's default AMQP 1.0 container settles the delivery as
released. - Not counted. Since RabbitMQ 4.3 the limit reads the delivery count, and a release doesn't raise it. The message comes back forever, the count at 0.
- Settled by hand. loyalty calls
context.requeue(Map.of(), true), themodifiedoutcome withdelivery-failed. RabbitMQ counts it. - Every failure counts. Each redelivery fails the same way and each requeue raises the count by one, until the 21st failure takes it to 21.
- Parked past 20. With the count past the limit of 20, RabbitMQ dead-letters the message to the parking queue
loyalty.coffee-sold.failed.
When a connection dies, RabbitMQ counts an attempt for every delivery still in flight, including the ones the consumer never touched. The more a consumer holds at once, the more attempts one crash uses up. So I gave loyalty one link credit, AMQP 1.0's equivalent of a prefetch of 1:
// one message at a time: a dead connection counts every unsettled delivery toward the delivery limit
@Bean
ContainerCustomizer<RabbitAmqpListenerContainer> oneCredit() {
return container -> container.setInitialCredits(1);
}One credit costs throughput. I didn't measure how much.
A database outage parks messages that would succeed
The counted requeue that parks a poison message redelivers at once, with no pause. If loyalty-db goes down, each loyalty instance keeps retrying the one delivery it holds while the rest wait in the queue. Every attempt waits for a connection, fails and requeues. On the 21st failure the message is parked, although it would have been stamped fine once the database came back, and the next message starts using up its attempts.
Nothing is lost. The parked messages stay in loyalty.coffee-sold.failed, and someone has to move
them back. How long an outage it takes to park one depends mostly on how long each attempt waits for
a connection, which is Hikari's connectionTimeout, 30 s by default. I haven't measured it, because
the chaos run never takes a database down.
RabbitMQ 4.3 has the backoff built in. A quorum queue policy with delayed-retry-type set to
failed holds every counted return back for delayed-retry-min times its delivery count, capped at
delayed-retry-max, with no extra queue
(quorum queue docs (opens in a new tab)). For a database that's down as a
whole, the 4.3 release post (opens in a new tab) advises
pausing the consumer instead of delaying every message. The repo does neither yet. The delivery
limit itself stays right: it's still what parks the message that will never work.
One hash, checked four times
The content-sha256 header comes from the post-processor in CoffeeSoldSender, after Jackson has
written the body. loyalty recomputes it on receipt, before validation and before the stamp, and
parks a mismatch. The chaos script computes it twice more: Postgres' sha256() over the body
loyalty stored, and Python's hashlib over the same text.
All four have to agree for every message, and the hash mismatch column read zero in every run.
Modulith stores the event with the same Boot JsonMapper that the converter uses, which is why a
resubmit produces the same bytes and the same hash as the first attempt.
A hash without a key catches accidents. Anyone who can write to the broker can also recompute it, so an HMAC or a signature would be the next step.
What each version lost under seed 42
I gave each version the same run: seed 42, 2'000 sale requests at a fixed rate, each sent exactly
once, and eight chaos actions at the same seconds. That's three kill -9 on app instances, one
SIGKILL on RabbitMQ, two 6 s windows in which Toxiproxy drops a barista's broker confirmations and
two in which it drops a loyalty instance's settlements. Toxiproxy doesn't delay those bytes. Its
timeout toxic, set to 0, lets no data through and keeps the connection open until the toxic is
removed, so the confirmations and settlements of those 6 s never arrive. On top, each named crash
point kills the JVM on a fixed share of the calls that pass it: 0.25%, and 0.2% for the outbox's
after-accept-before-complete.
Before a run's numbers count, support/chaos.py checks its gates: every crash point fired, every
chaos action ran, and the system drained within 120 s. Each of the three naive runs also has to show
its failure: more than zero lost sales, ghosts or double stamps. The inbox run has to pass three
more. Lost, ghosts, double stamps and hash mismatches are all zero with an empty parking queue, at
least one broker redelivery was caught, and there are as many stamps as cups sold. The script reads
rows, queue depths and log lines, not the apps' metrics. The one figure loyalty writes about itself,
the inbox's duplicate count, gets checked against zero double stamps and the cup total.
| Version | Committed | Lost | Ghosts | Double-applied | Duplicates delivered | Hash mismatch |
|---|---|---|---|---|---|---|
| after-commit, naive | 1'316 | 274 | 0 | 2 | 2 | 0 |
| in-transaction, naive | 1'049 | 0 | 25 | 2 | 2 | 0 |
| outbox, naive | 1'412 | 0 | 0 | 25 | 25 | 0 |
| outbox, inbox | 1'415 | 0 | 0 | 0 | 25 | 0 |
When a request goes to an instance that's down, there's no sale, and the in-transaction version rolls back every sale when sending fails or times out. That's why the committed column differs between rows. The double stamps in the first two rows are broker redeliveries alone: loyalty is naive there too, and the run kills it and drops its settlements.
In the inbox row nothing was lost, invented or stamped twice, and loyalty caught all 25 duplicates. Two of them came back from RabbitMQ with a delivery count above zero, the outbox had sent the rest again. The cups barista sold and the stamps loyalty wrote both come to 2'828. Seeds 43 and 44 ended at zero as well, with 9 and 29 duplicates caught.
The non-zero cells vary a lot between runs. In the two full runs before this one, after-commit lost 115 and 278 sales, depending mostly on how many messages barista tried to send while the broker was down. The zeros in the last row are the result. One run per version on one machine is a demonstration, not a benchmark.
Read it along the chaos markers. In the first row, 269 of the 274 lost sales were committed between
second 16 and second 25, around the SIGKILL on RabbitMQ at 19.8 s. In the in-transaction row, 22 of
the 25 ghosts are at seconds 6 and 17, inside the two windows where Toxiproxy dropped a barista's
broker confirmations. Two of them come from the crash point. In the other 20, the message was
already in the queue while barista still waited for accepted: barista-1's transactions rolled back
when it was killed at second 8, barista-2's when sending timed out after 5 s. In the outbox row,
loyalty wrote 18 of the 25 double stamps at seconds 26 and 27, right after RabbitMQ came back. The
last row has the same gaps in its stamped-sales line and no red at all.
What each version costs to run, from the same repo:
| Version | What it adds | What it costs at runtime | What someone has to watch |
|---|---|---|---|
| after-commit | nothing | nothing | lost messages, which only a comparison of sales and stamps across both databases shows |
| in-transaction | nothing | a database connection held over every broker round trip | ghosts, which look like real events |
| outbox | event_publication, OutboxRelay, a resubmit every 5 s | duplicates, and after a crash the message goes out again only after 15 s of staleness and the next pass | FAILED publications, a growing event_publication |
| inbox | the inbox table, manual settlement, one credit | one insert per message, one message in flight per instance | the parking queue, a growing inbox |
Pick by what a lost message costs
Sending inside the database transaction is the one version I wouldn't use for anything. It loses nothing, but it tells the consumer about rows that rolled back, and on the receiving side a ghost looks exactly like a real event. Between the other three, I'd pick by what one lost or doubled message costs:
- A cache invalidation or a metric can lose one now and then. There I'd save, send after the commit and skip the outbox.
- When a lost message is a lost sale, payment or order, I'd use an outbox. On Spring, Modulith's
registry is the smallest step:
spring-modulith-starter-jdbcand a listener that returns the sender's future, likeOutboxRelay. Create the message id together with the business row, so every message sent again carries the same one. Setspring.modulith.events.completion-modetodeleteorarchive, orevent_publicationkeeps every completed row. If you need more, the Modulith docs point to Namastack Outbox and JobRunr, and Debezium reads the outbox from the database log without polling. - If the consumer's effect adds something, a counter, a balance, a stamp, the inbox goes into the same transaction as the effect, and the delivery is accepted only after that commit. It covers what's stored in that database. An email or an HTTP call needs an outbox on the consumer's side too. Setting a status twice changes nothing, so there I'd follow RabbitMQ's advice and skip the inbox.
- If a producer could ever reuse an id, I'd store a hash next to it. Otherwise the id is enough.
- On a RabbitMQ 4.3 or later quorum queue with Spring's AMQP 1.0 listener, I'd settle manually, or a
listener that throws never reaches the delivery limit. And I'd add the
delayed-retrypolicy, so a database outage doesn't park messages that would succeed.
Where it stops
- A publication that can never be sent is resubmitted every 5 s, forever. Modulith 2.2 can abandon publications, and I didn't configure that.
- Nothing here keeps order. Stamps add up, so order doesn't matter for loyalty. For a state machine it would.
- It's one RabbitMQ node, and neither Postgres database fails during a run.
event_publicationand the inbox both grow without bound.
Run it
You need Docker and mise (opens in a new tab), which installs Java 25, Maven and Python.
git clone https://github.com/lukas-grigis/spring-outbox-inbox
cd spring-outbox-inbox
mise run demomise run demo takes about 6 minutes: the prologue with the killed barista, then all four versions
under the same chaos, then the table. The containers stay up afterwards, and mise run infra:down
removes them. mise run test runs the 20 tests, and the README maps each of the repo's findings to
the test that checks it. If something breaks on your machine, open an issue.
Key takeaways
- Under the same seeded chaos, saving first and sending after the commit lost 274 of 1'316 sales, and sending inside the transaction stamped cards for 25 sales that had rolled back.
- Spring Modulith 2.2's JDBC registry commits the publication with the sale. Modulith completes it only once RabbitMQ has accepted the message, through the future its listener returns. A scheduled FailedEventPublications.resubmit retries what failed, because Modulith doesn't while the app runs.
- One INSERT ... ON CONFLICT DO NOTHING in loyalty's transaction, committed before the delivery is accepted, stamped every sale once: 25 duplicates delivered, none stamped twice.
- Since RabbitMQ 4.3 a released delivery doesn't count toward a quorum queue's delivery limit, and released is what Spring's default AMQP 1.0 listener settles on an exception. Settle manually, or a poison message comes back forever.
Frequently asked questions
- What is the transactional outbox pattern?
- The producer writes its business row and the outgoing message into the same local database transaction, so both commit or neither does. A relay sends the message after the commit and marks it done only once the broker has accepted it. A crash before that leaves the row in place, and the relay sends it again. Nothing is lost, and the consumer has to expect duplicates.
- Is @TransactionalEventListener(AFTER_COMMIT) an outbox?
- Not on its own. In plain Spring the listener runs after the commit and nothing records it, so a crash or a failure to send at that point loses the message, and nothing retries it. The companion repo's save-then-send version has the same shape and lost 274 of 1'316 sales under chaos. Add Spring Modulith's event publication registry and every AFTER_COMMIT @TransactionalEventListener gets a publication row in the business transaction. With a scheduled FailedEventPublications.resubmit, that makes it an outbox.
- Does Spring Modulith implement the transactional outbox?
- Its JDBC event publication registry stores each event in the same transaction as the business data, which is the outbox's atomic half. A listener that returns a CompletableFuture has its publication completed only when the future succeeds. Modulith does not retry failed publications while the app runs, so the app schedules FailedEventPublications.resubmit. The docs call their listener-based externalization a pragmatic, simple solution, and Modulith can use Namastack Outbox or JobRunr for it instead.
- Can RabbitMQ deliver a message exactly once?
- No. RabbitMQ's reliability guide says acknowledgements guarantee at least once delivery. What you can get is an effect that happens once: the consumer records the message id in the same transaction as the effect and skips ids it has seen. Delivered at least once, processed once.
- How do I deduplicate messages in Postgres from Spring Boot?
- Insert the message id with INSERT ... ON CONFLICT DO NOTHING inside the transaction that applies the effect. It returns 1 for a new message and 0 for a duplicate, and a second instance inserting the same id waits for the first transaction. Commit, then acknowledge the delivery.
- Why does my RabbitMQ quorum queue never dead-letter a failing message?
- Since RabbitMQ 4.3 the delivery limit is based on delivery-count, and a released delivery doesn't raise it. Spring's default AMQP 1.0 listener container releases a delivery when the listener throws. Settle manually and requeue with delivery-failed set, or discard to dead-letter at once. On AMQP 0.9.1 the same table applies: basic.reject counts, basic.nack doesn't. Up to 4.2 every return counted.
- When don't I need an inbox?
- When the consumer's effect is idempotent by nature, like setting a status, RabbitMQ's reliability guide recommends an idempotent consumer over explicit deduplication. You need the inbox when the effect adds something: a stamp, a counter, a balance.
Resources
- (opens in a new tab)
Companion repository
Repository · Two Spring Boot 4.2 services, barista and loyalty, wired four ways: save then send, send inside the transaction, a Spring Modulith 2.2 outbox, and the outbox plus a Postgres inbox. RabbitMQ 4.4 over AMQP 1.0, Toxiproxy in between. mise run demo runs all four under the same seeded chaos and counts the damage from both databases. 20 tests check the repo's findings.
- (opens in a new tab)
Pattern: Transactional outbox (microservices.io)
Article · The pattern this post builds on the producer side: write the business row and the message into one local transaction, and let a relay publish it afterwards.
- (opens in a new tab)
Pattern: Idempotent Consumer (microservices.io)
Article · The consumer half: record each message id in the same transaction as its effect, so a redelivery is recognized and skipped.
- (opens in a new tab)
Idempotent Receiver (Enterprise Integration Patterns)
Article · The older name for the same consumer-side idea, from Hohpe and Woolf's pattern catalogue.
- (opens in a new tab)
Working with Application Events (Spring Modulith)
Documentation · The event publication registry this post uses as its outbox, the completion of publications, and the docs' own warning that the listener-based externalization is 'a pragmatic, simple solution' that lacks features of dedicated outbox implementations.
- (opens in a new tab)
Spring Modulith configuration properties
Documentation · Where spring.modulith.events.staleness and republish-outstanding-events-on-restart are defined, and that the latter defaults to false.
- (opens in a new tab)
Reliable Microservices Data Exchange With the Outbox Pattern (Debezium)
Blog · The change-data-capture take on the outbox: read the outbox table from the database log instead of polling it.
- (opens in a new tab)
Outbox Event Router (Debezium documentation)
Documentation · Debezium's ready-made transformation that routes outbox rows read from the database log to their topics, the polling-free alternative to a relay.
- (opens in a new tab)
Outbox (NServiceBus documentation)
Documentation · Both halves shipped as one feature, and the retention rule this post repeats for the inbox: keep deduplication data longer than any message can be retried.
- (opens in a new tab)
Reliability Guide (RabbitMQ)
Documentation · Why duplicates are the normal case: acknowledgements guarantee at least once delivery, consumers must handle deliveries they have seen before, and the guide's advice to prefer idempotent consumers over explicit deduplication.
- (opens in a new tab)
Quorum Queues (RabbitMQ)
Documentation · Poison message handling, delayed retry, and the table of which outcomes raise delivery-count. A released delivery doesn't, and since RabbitMQ 4.3 the delivery limit reads delivery-count.
- (opens in a new tab)
The Raft Consensus Algorithm
Article · The consensus algorithm quorum queues are built on, with the Raft paper. The quorum queue docs link to this page for it.
- (opens in a new tab)
RabbitMQ 4.3 highlights
Blog · What changed in RabbitMQ 4.3: delivery-count rises only on a failed delivery, so a return without a failure no longer counts toward the delivery limit. Quorum queues gained delayed retries, and the post advises pausing a consumer whose database is down.
- (opens in a new tab)
Dead Letter Exchanges (RabbitMQ)
Documentation · How a rejected or over-limit message is dead-lettered into the parking queue.
- (opens in a new tab)
AMQP 1.0 (RabbitMQ)
Documentation · What accepted means on both sides. On a publish, every queue the message was routed to has it. On a delivery, the consumer is done and RabbitMQ can delete the message. And what released, rejected and modified do to a delivery.
- (opens in a new tab)
RabbitMQ AMQP 1.0 Support (Spring AMQP)
Documentation · RabbitAmqpTemplate and the AMQP 1.0 listener container that both services build on.
- (opens in a new tab)
AMQP (Spring Boot reference)
Documentation · Spring Boot 4.2's auto-configuration for the AMQP 1.0 client that both services use.
- (opens in a new tab)
INSERT (PostgreSQL 18)
Documentation · ON CONFLICT DO NOTHING, the single statement that decides whether loyalty has seen a message.
- (opens in a new tab)
Index Uniqueness Checks (PostgreSQL 18)
Documentation · What a second insert of the same key does while the first one's transaction is still open: it waits, conflicts if that transaction commits, and goes through if it rolls back.
- (opens in a new tab)
Transaction Isolation (PostgreSQL 18)
Documentation · How an INSERT with ON CONFLICT DO NOTHING behaves when another transaction inserts the same key at the same time.
OAuth2-secured RabbitMQ over AMQP 1.0
Article · The earlier post on the same client stack: Spring Boot 4.2's AMQP 1.0 auto-configuration, RabbitAmqpTemplate and the native RabbitMQ client.



