On this page
- 1. · Concept & Definition
- 2. · Why It Matters
- 3. · How It Works
- 4. · Java / Jakarta EE Code Examples
- Deep Dive — Choosing a Deduplication Key
- Deep Dive — Where Messages Actually Get Lost
- 5. · Configuration, Defaults & Diagnostics
- 6. · Production Usage Patterns
- 7. · Common Pitfalls & Misconceptions
- 8. · Best Practices
- 9. · Architect's Perspective & Trade-offs
- 10. · Interview Q&A
1· Concept & Definition
A delivery guarantee states what can happen to a message between production and successful processing. At-most-once means it may be lost but never duplicated. At-least-once means it is never lost but may arrive more than once. Exactly-once means neither — which no broker can provide end to end on its own, because the consumer's side effects are outside the broker's control.

2· Why It Matters
- The guarantee decides how the consumer must be written; it cannot be retrofitted cheaply.
- Duplicates are not rare edge cases: they occur on every redelivery, failover and consumer restart.
- Choosing at-most-once for business data is a decision to lose some of it, and should be explicit.
- "Exactly-once" in vendor documentation usually means within that product's boundary, not across your side effects.
- The cost difference between the levels is real: persistence, acknowledgement round trips and a deduplication store.
3· How It Works
At-most-once
The message is acknowledged before it is processed, or sent non-persistently. If the consumer crashes mid-processing, or the broker restarts before the message reaches disk, the message is gone and nothing will retry it. This is acceptable — even correct — for data that is periodic and self-correcting: telemetry, cache invalidation hints, presence updates, progress indicators.
At-least-once
The message is acknowledged only after processing succeeds. If anything fails in between, the broker redelivers. Nothing is lost, but the consumer will occasionally see the same message twice: after a consumer crash, after a rollback, after a failover, or when an acknowledgement is lost on the network. This is the default in Jakarta Messaging with transacted or container-managed sessions.
| Cause of duplication | When it happens |
|---|---|
| Consumer crash after processing, before acknowledgement | Process or pod restart |
| Transaction rollback after partial side effects | Exception in a later step |
| Lost acknowledgement | Network interruption at the wrong moment |
| Broker failover | In-flight messages redelivered by the new node |
| Producer retry after an uncertain send | Timeout where the send may have succeeded |
Exactly-once concepts
End-to-end exactly-once requires the message acknowledgement and the consumer's side effects to commit atomically. That is possible only when both sit in one transactional boundary — an XA transaction across broker and database (Volume IV Chapter 6), or a broker and store that share a transaction log. In every other case, the achievable and much cheaper goal is effective exactly-once: at-least-once delivery plus deduplication in the consumer.

| Approach | Mechanism | Cost | Caveat |
|---|---|---|---|
| XA transaction | Broker and database in one 2PC | High; needs XA support | Poor cloud support, blocking |
| Deduplication table | Message id + work in one local transaction | One table and an index | Retention must cover the redelivery window |
| Natural idempotency | The operation is repeatable by nature | None | Only some operations qualify |
| Broker-side dedup | Producer id plus sequence number | Configuration | Covers the broker hop only |
| Conditional write | UPDATE … WHERE status = 'PENDING' | None | Works when state guards the change |
4· Java / Jakarta EE Code Examples
// At-most-once: fast, lossy, deliberate
context.createProducer()
.setDeliveryMode(DeliveryMode.NON_PERSISTENT) // not written to disk
// stale telemetry is worthless
.setTimeToLive(5_000)
.send(metricsTopic, jsonb.toJson(sample));// At-least-once: container-managed transaction, redelivery on failure
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationLookup",
propertyValue = "java:/jms/queue/payments"),
@ActivationConfigProperty(propertyName = "destinationType",
propertyValue = "jakarta.jms.Queue")})
public class PaymentListener implements MessageListener {
@Inject PaymentService payments;
@Override
public void onMessage(Message message) {
try {
// throws → rollback → redelivery
payments.capture(message.getBody(String.class));
} catch (JMSException e) {
throw new EJBException(e);
}
}
}// Effective exactly-once: deduplication in the consumer's own database
@Entity
public class ProcessedMessage {
@Id private String messageId; // JMSMessageID or a business event id
private Instant processedAt;
}
@Transactional
public void handle(String messageId, PaymentCommand command) {
if (em.find(ProcessedMessage.class, messageId) != null) return; // duplicate
// same transaction
em.persist(new ProcessedMessage(messageId, Instant.now()));
// same transaction
payments.capture(command);
}// Natural idempotency: no dedup store needed
@Transactional
public void markShipped(long orderId, Instant shippedAt) {
em.createQuery("""
UPDATE Order o SET o.status = :shipped, o.shippedAt = :at
// guard makes it repeatable
WHERE o.id = :id AND o.status = :packed""")
.setParameter("shipped", SHIPPED).setParameter("at", shippedAt)
.setParameter("id", orderId).setParameter("packed", PACKED)
.executeUpdate();
}// Detecting a redelivery in the consumer
boolean redelivered = message.getJMSRedelivered();
int attempts = message.getIntProperty("JMSXDeliveryCount"); // 1 on first delivery
if (attempts > 5) {
deadLetter.send(message, "too many attempts"); // Chapter 3
return;
}Deep Dive — Choosing a Deduplication Key
| Key | Stability | Notes |
|---|---|---|
JMSMessageID | Broker-assigned, unique per message | Changes if the producer re-sends after a failure — duplicates from the producer are not caught |
| Business event id (UUID from the producer) | Stable across re-sends | The recommended key; generate once, at the source |
| Natural key (orderId + eventType + version) | Stable and meaningful | Works when one event per key is expected |
| Payload hash | Stable for identical payloads | Fails when a legitimate repeat has identical content |
The distinction matters: a producer that retries an uncertain send creates a new JMSMessageID for the same business fact, so deduplicating on the broker's id will not stop it. The event id must be generated with the event — ideally in the same local transaction that produced it (the outbox pattern, Volume IV Chapter 6).
| Retention question | Answer |
|---|---|
| How long to keep processed ids? | Longer than the maximum possible redelivery window — typically days, not hours |
| Where to store them? | In the consumer's own database, in the same transaction as the work |
| How to purge? | A scheduled delete by age, with an index on the timestamp |
| What about volume? | One narrow row per message; partition or use a TTL store when volume is very high |
Deep Dive — Where Messages Actually Get Lost
| Gap | Loss scenario | Remedy |
|---|---|---|
| Business write → send | State committed, send fails or the process dies | Transactional outbox |
| Send → broker disk | Non-persistent message, broker restarts | PERSISTENT delivery mode |
| Broker node loss | Single node, no replication | Clustered broker with replication or shared store |
| Delivery → processing | Acknowledged before the work is durable | Acknowledge after processing (transacted or container-managed) |
| Processing → downstream | Side effect fails after acknowledgement | Keep side effects inside the transaction, or record intent first |
| Expiry | TTL shorter than the outage | Size TTL against realistic recovery times |
This table is worth walking through for each critical flow in a system: the guarantee is only as strong as its weakest gap, and most designs that claim at-least-once are in fact at-most-once at the very first gap, because the send is not tied to the business transaction.
5· Configuration, Defaults & Diagnostics
| Setting | Effect on the guarantee |
|---|---|
DeliveryMode.PERSISTENT | Message survives a broker restart |
| Transacted or container-managed session | Acknowledgement after processing → at-least-once |
AUTO_ACKNOWLEDGE with async listeners | Acknowledgement on return — loss window during processing |
| Redelivery delay and max attempts | How persistent the retry is before dead-lettering |
| Time to live | Messages silently disappear after expiry |
| Broker replication mode | Whether an acknowledged send survives node loss |
| Metric | What it tells you |
|---|---|
| Redelivery count distribution | How often duplicates actually occur |
| Duplicate hits in the dedup store | Proof the mechanism is working |
| Expired message count | Messages lost to TTL — often unnoticed |
| Dead-letter depth | Messages that exhausted retries |
| Outbox backlog | Sends that have not reached the broker |
6· Production Usage Patterns
- At-least-once everywhere business data is involved, with idempotent consumers as a standard.
- Event ids generated at the source and carried in the payload, used as the deduplication key.
- Non-persistent, short-TTL messages reserved for telemetry and hints.
- An outbox for any message that must accompany a database change.
- Duplicate and expiry metrics on dashboards, not just queue depth.
7· Common Pitfalls & Misconceptions
- Assuming exactly-once because the broker's marketing says so.
- Deduplicating on
JMSMessageIDwhen producers can re-send. - Acknowledging before processing in a hand-written listener.
- Side effects outside the transaction — emails sent twice on redelivery.
- TTL shorter than a realistic outage, silently discarding work.
- No dedup retention policy, so the table either grows forever or purges too early.
8· Best Practices
- Decide the guarantee per flow and write it into the design documentation.
- Make every consumer idempotent, whatever the broker promises.
- Tie the send to the business transaction with an outbox.
- Measure duplicates and expiries; they are the evidence that the design works.
9· Architect's Perspective & Trade-offs
| Guarantee | Mechanism | Consumer must | Fits |
|---|---|---|---|
| At-most-once | Non-persistent, ack first | Tolerate gaps | Telemetry, hints, presence |
| At-least-once | Persistent, ack after work | Be idempotent | Almost all business messaging |
| Effective exactly-once | At-least-once + dedup store | Own a dedup table | Payments, stock, billing |
| True exactly-once | XA or shared transaction log | Nothing extra | Rare; high cost |
10· Interview Q&A
What is at-least-once delivery?
At-least-once delivery guarantees that a message is never lost, at the price that it may be processed more than once. The broker stores the message persistently and the consumer acknowledges it only after processing succeeds; if the consumer crashes, rolls back or the acknowledgement is lost, the broker delivers it again. In Jakarta Messaging this is what a message-driven bean with container-managed transactions, or a transacted session, gives you by default. Duplicates are therefore part of normal operation, appearing after restarts, failovers and rollbacks rather than only in rare corner cases. The consequence is a design rule: every at-least-once consumer must be idempotent, through deduplication or naturally repeatable operations.
What is at-most-once delivery?
At-most-once delivery guarantees that a message is never processed twice, at the price that it may be lost. It arises when the consumer acknowledges before the work is durable, for example a listener that hands the message to another thread and returns, or when the producer sends with DeliveryMode.NON_PERSISTENT, so a broker restart discards it. Nothing retries a lost message. That is acceptable for data that is periodic and self-correcting, such as metrics samples, presence updates or cache-invalidation hints, where the next message supersedes the last and a short TTL avoids acting on stale values. Choosing it for orders, payments or stock is a decision to lose business data.
Why is true exactly-once delivery so hard?
Because the broker's acknowledgement and the consumer's side effects live in different systems, and no ordering of two independent commits survives every crash. If the consumer commits its database work first and dies before acknowledging, the broker redelivers and the work is repeated. If it acknowledges first and dies before committing, the message is gone. Closing that window needs both outcomes in one atomic commit, which means an XA transaction coordinated across broker and database, or a store that shares the broker's transaction log. XA is costly, blocking during coordinator failures and poorly supported by managed cloud services. Kafka's exactly-once, similarly, covers reads and writes inside Kafka, not your database or an email.
What is effective exactly-once?
Effective exactly-once means the business outcome happens once even though the message may be delivered several times. Delivery stays at-least-once, and the consumer makes processing idempotent: it records the message's event id in a deduplication table in the same local transaction as the work, so a redelivered message finds its id already present and is skipped, while a failure rolls back the work and the record together. Where the operation is naturally repeatable, a conditional update guarded by the current status does the same job without any table. It is far cheaper than XA, works with any broker, and is the standard approach for payments, stock and billing.
Which deduplication key would you choose, and why?
A business event id generated once at the source, usually a UUID created in the same transaction as the state change and carried in the payload or a message property. It is stable across every retry, so it catches producer and broker duplicates alike. JMSMessageID is assigned by the provider on each send, so when a producer times out on an uncertain send and retries, the same fact arrives with a new message id and slips past deduplication. A natural key such as order id plus event type and version also works when exactly one event per key is expected. A payload hash is the weakest choice, because two legitimate identical events would be discarded.
Where do messages actually get lost in practice?
Most often in the gap between the business write and the send: the database commit succeeds, then the send fails or the process dies, and nothing records that a message was owed. That is why the transactional outbox, writing the message to a table in the same transaction and publishing it afterwards, is the first fix. The next gaps are NON_PERSISTENT delivery lost on a broker restart, unreplicated brokers losing acknowledged messages, consumers acknowledging before the work is durable, side effects that fail after acknowledgement, and TTLs shorter than a realistic outage. I walk every critical flow through those gaps, because its guarantee is only as strong as the weakest one.
How do you decide the delivery guarantee for a flow?
By comparing the business cost of losing a message with the cost of processing it twice, flow by flow. Telemetry, presence and cache hints are superseded by the next message, so at-most-once with non-persistent delivery and a short TTL is cheapest and correct. Business facts such as orders or customer changes must not be lost, so they get persistent at-least-once delivery, an outbox on the producer side and idempotent consumers. Money-moving or stock-changing operations, where a duplicate is as harmful as a loss, add a deduplication store or conditional writes. XA is reserved for rare cases where neither works. The chosen guarantee is documented, with duplicate and expiry metrics to prove it.
How would you explain the duplicate risk to a business stakeholder?
In business terms, as two kinds of failure and what each would cost. Without protection, any messaging system will occasionally either drop an instruction, such as a payment never collected, or repeat one, such as a customer charged twice. We deliberately choose never to drop instructions, which means repeats will occur during restarts and failovers, so we add a safeguard that recognises an instruction already carried out and ignores it. I would then quantify it, for example a few hundred redeliveries a day at current volume, none visible to customers, for one small table and modest engineering effort. The stakeholder is approving a known, bounded cost rather than trusting a technical promise.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.