Messaging and delivery semantics
What you will learn
Messaging decouples a producer from a consumer using a broker. Delivery guarantees describe what may happen during failures: at-most-once can lose work, at-least-once can repeat delivery, and exactly-once effects require an explicit boundary. Acknowledgment is not the same as completing a business transaction.
- Compare Kafka partitions, consumer groups and RabbitMQ queues.
- Choose acknowledgment timing and bound retries.
- Explain the difference between broker delivery and business effects.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. External cache and broker examples require the companion lab or configured infrastructure. Their predicted results are not execution evidence.
Simulate an acknowledgment failure
public class Main {
public static void main(String[] args) {var delivered=java.util.List.of("e1","e1","e2"); int attempts=0;var unique=new java.util.HashSet<String>(); for(String id:delivered){attempts++;unique.add(id);} System.out.println("deliveries="+attempts);System.out.println("unique="+unique.size()); }}Expected output:
deliveries=3unique=2The repeat models a lost acknowledgment; the set does not model durable broker state.
Kafka versus RabbitMQ
Kafka retains records in partitioned logs; consumer groups assign partitions among members, with one active consumer per assigned partition in an ordinary group. Ordering is per partition, not topic-wide; preserve the aggregate key and consider partition-count changes. Offsets track the next record to consume. Commit only contiguous successfully processed offsets; automatic commit can acknowledge work too early if processing is asynchronous. RabbitMQ routes messages from exchanges to queues; manual acknowledgments release deliveries, publisher confirms report broker acceptance and mandatory returns report unroutable messages. Redelivery and multiple consumers can change observed processing order.
Failure windows and limits
Process then acknowledge gives a replay window if the effect commits but acknowledgment fails. Acknowledge then process creates a loss window. Use bounded prefetch or poll batches, finite retry budgets, delay/backoff and monitored dead-letter handling. A dead-letter queue is not guaranteed durable under every configuration; verify routing and reliability. Jakarta Messaging 3.1 locally transacted sessions acknowledge on commit and recover on rollback; CLIENT_ACKNOWLEDGE can acknowledge all consumed messages in the session. Kafka transactions can coordinate Kafka records and consumed offsets, not arbitrary external databases without cooperation.
Commit only a contiguous prefix
public class Main {
public static void main(String[] args) {long next=10; var completed=new java.util.TreeSet<Long>(java.util.List.of(10L,12L)); while(completed.remove(next))next++; System.out.println(next);completed.add(11L); while(completed.remove(next))next++;System.out.println(next); }}Expected output:
1113Offset 12 cannot be committed past the unfinished 11. This is one partition and a synthetic completion set, not a Kafka client.
Kafka explicit offset commit
Source-reviewed, NOT RUN. File lab-fixtures/cache-messaging-v44/KafkaCommit.java; use the companion lab README.
// Fragment: existing consumer with enable.auto.commit=false, one owning thread.// durableApply must commit the business effect and event marker together.import java.time.Duration;import java.util.Map;import java.util.function.Consumer;import org.apache.kafka.clients.consumer.*;import org.apache.kafka.common.TopicPartition;public class KafkaCommit { public static void consumeOnce(KafkaConsumer<String,String> consumer, Consumer<ConsumerRecord<String,String>> durableApply) { for (var record : consumer.poll(Duration.ofSeconds(1))) { durableApply.accept(record); // throws on failure; stop, do not commit past a gap consumer.commitSync(Map.of(new TopicPartition(record.topic(), record.partition()), new OffsetAndMetadata(record.offset()+1)), Duration.ofSeconds(3)); } }}Predicted behavior: Each successfully applied record commits its next offset; failure stops processing.
Only use on one consumer-owning thread with explicit group and timeout configuration.
RabbitMQ manual acknowledgment
Source-reviewed, NOT RUN. File lab-fixtures/cache-messaging-v44/RabbitDelivery.java; use the companion lab README.
// Fragment: channel has a bounded prefetch; queue and DLX provisioned by lab owner.// Invoke on the channel owner. An exception stops this consumer; close channel to requeue.import com.rabbitmq.client.Channel;import com.rabbitmq.client.Delivery;import java.io.IOException;import java.util.function.Consumer;public class RabbitDelivery { public static void handle(Channel channel, Delivery delivery, Consumer<byte[]> durableApply) throws IOException { byte[] body = delivery.getBody(); if (body.length == 0 || body.length > 4096) { channel.basicReject(delivery.getEnvelope().getDeliveryTag(), false); return; // requires configured dead-letter routing, otherwise discarded } durableApply.accept(body); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); }}Predicted behavior: Valid delivery is acknowledged after durable apply; invalid size is rejected.
DLX configuration is required to route rejected messages; failure closes channel and may redeliver.
Common mistakes
Do not treat publisher confirms as consumer completion, commit the largest seen offset when there is a gap, or retry a poison message forever. Do not assume broker-level exactly-once covers a payment or database effect.
Practice
A partition starts at offset 20. Completed offsets are 20,22,23. Compute the next safe commit; then add 21 and compute it again.
Expected output:
2124Compare with the manual review criteria.
Official reading: Kafka design · Kafka consumer · RabbitMQ · RabbitMQ consumers · RabbitMQ DLX · Jakarta Messaging. Cache and broker execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Messaging and delivery semantics — knowledge check
Cache and messaging reasoning.
Kafka ordering is guaranteed within what boundary?
What does a committed Kafka offset represent?
What does a publisher confirm prove?
What is a risk of acknowledging before processing?
How should a poison message be handled?