ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 3 · Jakarta EE & Enterprise Java
  4. Volume V
  5. Delivery
Book 3 · Volume V — Messaging, JSON, Security & Validation · Topic 2.1

Delivery

At-most-once, At-least-once, Exactly-once concepts

9 min readStage 1 · Foundations8 interview questions
On this page
  1. 1. · Concept & Definition
  2. 2. · Why It Matters
  3. 3. · How It Works
  4. 4. · Java / Jakarta EE Code Examples
  5. Deep Dive — Choosing a Deduplication Key
  6. Deep Dive — Where Messages Actually Get Lost
  7. 5. · Configuration, Defaults & Diagnostics
  8. 6. · Production Usage Patterns
  9. 7. · Common Pitfalls & Misconceptions
  10. 8. · Best Practices
  11. 9. · Architect's Perspective & Trade-offs
  12. 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.

Three levels, and what the consumer must tolerate
Figure 2.1.1 — Three levels, and what the consumer must tolerate

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 duplicationWhen it happens
Consumer crash after processing, before acknowledgementProcess or pod restart
Transaction rollback after partial side effectsException in a later step
Lost acknowledgementNetwork interruption at the wrong moment
Broker failoverIn-flight messages redelivered by the new node
Producer retry after an uncertain sendTimeout 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.

At-least-once delivery plus a deduplication store
Figure 2.1.2 — At-least-once delivery plus a deduplication store
ApproachMechanismCostCaveat
XA transactionBroker and database in one 2PCHigh; needs XA supportPoor cloud support, blocking
Deduplication tableMessage id + work in one local transactionOne table and an indexRetention must cover the redelivery window
Natural idempotencyThe operation is repeatable by natureNoneOnly some operations qualify
Broker-side dedupProducer id plus sequence numberConfigurationCovers the broker hop only
Conditional writeUPDATE … WHERE status = 'PENDING'NoneWorks when state guards the change

4· Java / Jakarta EE Code Examples

JAVAWhen losing a message is acceptable
// 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));
JAVAThe default guarantee in Jakarta EE
// 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);
        }
    }
}
JAVAThe pattern that works with any broker
// 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);
}
JAVAA conditional write that tolerates duplicates
// 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();
}
JAVARedelivery headers
// 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

KeyStabilityNotes
JMSMessageIDBroker-assigned, unique per messageChanges 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-sendsThe recommended key; generate once, at the source
Natural key (orderId + eventType + version)Stable and meaningfulWorks when one event per key is expected
Payload hashStable for identical payloadsFails 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 questionAnswer
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

GapLoss scenarioRemedy
Business write → sendState committed, send fails or the process diesTransactional outbox
Send → broker diskNon-persistent message, broker restartsPERSISTENT delivery mode
Broker node lossSingle node, no replicationClustered broker with replication or shared store
Delivery → processingAcknowledged before the work is durableAcknowledge after processing (transacted or container-managed)
Processing → downstreamSide effect fails after acknowledgementKeep side effects inside the transaction, or record intent first
ExpiryTTL shorter than the outageSize 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

SettingEffect on the guarantee
DeliveryMode.PERSISTENTMessage survives a broker restart
Transacted or container-managed sessionAcknowledgement after processing → at-least-once
AUTO_ACKNOWLEDGE with async listenersAcknowledgement on return — loss window during processing
Redelivery delay and max attemptsHow persistent the retry is before dead-lettering
Time to liveMessages silently disappear after expiry
Broker replication modeWhether an acknowledged send survives node loss
MetricWhat it tells you
Redelivery count distributionHow often duplicates actually occur
Duplicate hits in the dedup storeProof the mechanism is working
Expired message countMessages lost to TTL — often unnoticed
Dead-letter depthMessages that exhausted retries
Outbox backlogSends 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 JMSMessageID when 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

GuaranteeMechanismConsumer mustFits
At-most-onceNon-persistent, ack firstTolerate gapsTelemetry, hints, presence
At-least-oncePersistent, ack after workBe idempotentAlmost all business messaging
Effective exactly-onceAt-least-once + dedup storeOwn a dedup tablePayments, stock, billing
True exactly-onceXA or shared transaction logNothing extraRare; high cost

10· Interview Q&A

Q1L1 · BasicConcept

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.

Q2L1 · BasicConcept

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.

Q3L2 · IntermediateInternals

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.

Q4L2 · IntermediateConcept

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.

Q5L3 · Senior EngineerDesign

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.

Q6L3 · Senior EngineerScenario

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.

Q7L4 · Technical ArchitectTrade-off

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.

Q8L5 · Solution ArchitectScenario

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.