Pub/Sub and Delivery Semantics: Kafka Partitions, Consumer Groups, and What Exactly-Once Really Guarantees
System Design series · Part 5 Service communication (3 of 5)
- REST, gRPC, and GraphQL: Choosing an API Style by Caller
- Message Queues: Decoupling, Peak Shaving, Retries, and Why Messages Will Be Duplicated
- Pub/Sub and Delivery Semantics: Kafka Partitions, Consumer Groups, and What Exactly-Once Really Guarantees
- Idempotency and Idempotency Keys: Making Retries Safe
- Real-Time Updates: Choosing Between Polling, Long Polling, SSE, and WebSocket, and Pushing from Many Servers
System Design series Part 5-3 | Previous: Message Queues | Next: Idempotency and Idempotency Keys | Series map
Read first: Part 4-3 Consistent Hashing, Part 4-5 CAP and PACELC, Part 5-2 Message Queues.
Scenario and problem
The queue in the previous post had only one kind of consumer: sending confirmation emails. But more and more services care that “someone signed up”:
- The mail service sends a confirmation email
- The speaker dashboard updates the sign-up count
- The recommendation system records the user’s interests
- The data warehouse builds daily reports
- The audit system keeps every change to sign-ups
And new requirements keep coming: the recommendation team is launching a new model and wants to retrain it on the last three months of sign-up records.
- Only one consumer at firstThe queue in the previous post had only one kind of consumer: sending confirmation emails.
- More and more services careThe speaker dashboard has to update the sign-up count, the recommendation system has to record interests, the data warehouse has to build daily reports, and the audit system has to keep every change to sign-ups. And new requirements keep coming.
- Replay the last three monthsThe recommendation team is launching a new model and wants to retrain it on the last three months of sign-up records. Messages cannot vanish once they are consumed.
The sign-up service should not know which consumers exist, and it should not change its code for every new consumer. It only has to announce “this happened”, and whoever is interested subscribes. That is publish/subscribe.
The simplest approach and its limits
- The sign-up service calls each service in turn: every new consumer means changing the sign-up service, and any one consumer failing affects sign-ups
- Send a separate message to each consumer’s own queue: the sign-up service still has to know which consumers exist
- RabbitMQ’s fanout exchange: the sign-up service sends to just one exchange, each consumer binds its own queue, and the broker does the copying. This solves the decoupling, but a message is deleted once it is consumed, so new consumers cannot see past messages, and the three months of history the recommendation team wants is nowhere to be found
Core mechanism
Two Pub/Sub models
flowchart LR
subgraph R["RabbitMQ: one copy per subscriber"]
P1[Sign-up service] --> X[fanout exchange]
X --> Q1[Mail queue] --> C1[Mail service]
X --> Q2[Speaker queue] --> C2[Speaker dashboard]
end
subgraph K["Kafka: every subscriber reads the same log"]
P2[Sign-up service] --> T[(registration-events<br/>kept for 90 days)]
T -->|each tracks how far it has read| G1[Mail service]
T --> G2[Speaker dashboard]
T --> G3["Recommender: reads from the start"]
end
| RabbitMQ exchange | Kafka topic | |
|---|---|---|
| Message lifetime | One copy per queue, deleted once acknowledged | One log, deleted by retention time or size, whether or not anyone has read it |
| Read position | The broker tracks the state of each message | Each consumer records which offset it has read up to |
| New subscribers | See only messages sent after they subscribe | Can start reading from any position within the retention period |
| Replay | Not possible | Move the offset back and process again |
| Handling a single message | Acknowledged individually, redelivered individually | A consumer group advances in offset order, and one stuck message blocks the ones behind it (share groups are the exception, see below) |
| Routing | Exchanges and routing keys, very flexible | By topic and partition, simpler |
Kafka treats messages as a historical record of events, not as jobs to be done. That makes it a good fit for many subscribers and for cases that need replay. The price is losing flexible routing, and classic consumer groups have no per-message acknowledgment either.
Partitions and ordering
A topic is split into several partitions. Each partition is an append-only log with strict ordering inside it, and there is no ordering across partitions.
When a producer sends a message, it can give it a key, and the same key always hashes to the same partition. So:
- Use the same key for events that need ordering: for “sign up → pay → cancel” on the same sign-up, use the sign-up ID as the key, which guarantees they are processed in order
- The choice of key decides how load is spread: with the talk ID as the key, every event for a popular talk crowds into one partition. That partition’s consumer cannot keep up, while the other partitions sit idle (the same hot spot problem as in Sharding)
- Adding partitions changes which partition a key maps to: the hash is taken modulo the number of partitions, so going from 12 partitions to 16 moves most keys to a different partition (the modulo problem from Consistent Hashing). During the transition, old and new events for the same key are spread across two partitions, and ordering is no longer guaranteed. Leave room in the partition count from the start
Consumer groups
Consumers in the same consumer group split the work on a topic: at any one time, each partition is assigned to only one consumer in the group. Different groups are independent of each other, and each records its own offsets.
- The mail service, the speaker dashboard, and the recommendation system are three different groups, and each group receives every event
- Running 4 instances of the mail service means 4 consumers in the same group, sharing the 12 partitions
- Parallelism is capped by the number of partitions: with 12 partitions, at most 12 consumers have work to do, and a 13th sits idle
Since Kafka 4.2, share groups (KIP-932) can be used in production: several consumers can work on the same partition together, each message is acknowledged individually, and delivery attempts are counted, which works much like the work queue from the previous post. The price is that ordering is not guaranteed, so share groups suit jobs that are processed one by one and independently, not event streams that must be processed in order.
When a consumer joins, leaves, or crashes, the group reassigns partitions (a rebalance). A consumer that spends so long processing that it does not call poll again within max.poll.interval.ms is also considered failed, which triggers a rebalance. The revoked partitions go to other consumers, which continue from the last committed offset, so messages that were processed but not yet committed are processed again.
When the offset is committed decides the delivery semantics
Processing a message and committing its offset are two separate steps, and their order decides what happens on a crash:
| Order | On a crash | Semantics |
|---|---|---|
| Commit the offset, then process | This message is skipped | at-most-once |
| Process, then commit the offset | This message is processed again | at-least-once |
By default the Kafka client commits offsets automatically at regular intervals. When it commits has nothing to do with whether processing has finished, so it can commit messages that have not been fully processed. Since 2.3, Spring for Apache Kafka turns auto-commit off by default; instead, the listener container commits only after it has processed a batch of messages (AckMode.BATCH), which is at-least-once.
What exactly-once really guarantees
“Exactly-once” is often misread as “every message is processed only once”. In practice it has to be looked at in parts:
- The producer does not write duplicates: a producer that does not receive an acknowledgment resends, which can write two records to the log. With an idempotent producer, the broker gives each producer an ID and uses sequence numbers to drop duplicate writes
- “Read → process → write back” inside Kafka: a transaction can tie “writing to the output topic” and “committing the input offset” together, so either all of it succeeds or none of it counts. Downstream consumers that set
isolation.level=read_committedsee only committed transactions - External side effects are not covered: sending email, calling an HTTP API, and writing to another database are out of reach of Kafka transactions. If the email has been sent and the consumer crashes before committing the offset, the email is sent again
So “exactly-once” in practice means at-least-once delivery + idempotent processing. Retrying an API call follows the same idea, covered in detail in the next post. A message may be processed twice, but the second time has no extra effect. There are two ways to do this:
- A deduplication table: in one database transaction, record “this consumer has processed this event ID” and run the business logic. If the event ID already exists, skip it
- Store the offset with the result: the consumer writes the processing result and the offset in the same database transaction, and on restart reads the offset from the database instead of from Kafka
Durability
| Setting | Level | Effect |
|---|---|---|
replication.factor=3 |
topic | Each partition has 3 replicas |
min.insync.replicas=2 |
topic or broker | Accept acks=all writes only while at least 2 in-sync replicas exist |
acks=all |
producer | Report success only after every in-sync replica has written |
unclean.leader.election.enable=false |
topic or broker | Never let a lagging replica become leader; pause rather than lose data |
The default for min.insync.replicas is 1. If you set only acks=all without raising it, then when the in-sync replicas shrink to just the leader, “every in-sync replica” means the leader alone, writes still succeed, and the data is lost as soon as the leader fails. This is the CAP trade-off again: min.insync.replicas=2 rejects writes when there are not enough replicas, choosing consistency and giving up availability.
Retries: blocking and non-blocking
A Kafka consumer advances by offset. When processing a message fails:
- Blocking retries: retry in place a few times, while every message behind it in this partition waits. Ordering is preserved, but one bad message stalls the whole partition
- Non-blocking retries: send the failed message to a retry topic, so the original partition keeps moving, and the retry topic’s consumer processes it later. The partition never gets stuck, but the order of messages with the same key is broken
- Final failure: send it to a dead letter topic (DLT) for someone to deal with
Events that need ordering (state changes of the same sign-up) use blocking retries with a limited number of attempts; events where order does not matter (writes to the data warehouse) can use non-blocking retries.
Comparing options
| Option | Model | Replay | Good for |
|---|---|---|---|
| RabbitMQ fanout / topic exchange | One queue per subscriber | No | A fixed set of subscribers, per-message retries and flexible routing needed |
| Kafka | Retained partitioned log, each consumer group reads on its own | Yes | Event streams, many subscribers, replay needed, high throughput |
| Cloud Pub/Sub services (such as SNS with SQS) | A topic fans out to each subscriber’s queue | Depends on the service | You do not want to run a broker |
| Redis Pub/Sub | Live broadcast, nothing stored | No; a subscriber that is offline misses messages | Real-time notifications that can be lost |
The talk platform’s choice: “sign-up events” have several subscribers and the recommendation system needs replay, so use Kafka. For job-style tasks such as sending confirmation emails, use the work queue from the previous post, or have the mail service subscribe to the Kafka events and put them into its own work queue.
In Java
1. Producer: set durability explicitly, with the sign-up ID as the key
spring:
kafka:
producer:
properties:
"[acks]": "all"
"[enable.idempotence]": "true"Defaults differ between versions of the Kafka client, so write the durability settings out explicitly instead of relying on defaults. The topic itself is created with replication.factor=3 and min.insync.replicas=2.
@Component
public class RegistrationEventPublisher {
private static final String TOPIC = "registration-events";
private final KafkaTemplate<String, RegistrationEvent> kafkaTemplate;
public RegistrationEventPublisher(KafkaTemplate<String, RegistrationEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public CompletableFuture<SendResult<String, RegistrationEvent>> publish(RegistrationEvent event) {
// Events for the same sign-up go to the same partition and are processed in order
return kafkaTemplate.send(TOPIC, String.valueOf(event.registrationId()), event);
}
}send is asynchronous, so check whether the returned future failed. As in the previous post, the dual-write problem between “committing to the database” and “sending the event” is solved with an outbox (Sagas and the Outbox Pattern, Outbox Pattern).
2. Error handling: a limited number of blocking retries, then the DLT
@Configuration
public class KafkaErrorHandlingConfig {
@Bean
public DefaultErrorHandler kafkaErrorHandler(KafkaTemplate<Object, Object> template) {
// By default it sends to the same partition of <original topic>-dlt, so the DLT needs at least as many partitions as the original topic
DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(template);
DefaultErrorHandler handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1_000L, 3L));
handler.addNotRetryableExceptions(InvalidEventException.class); // malformed events are not retried
return handler;
}
}- Spring Boot automatically applies a
CommonErrorHandlerbean to the default listener container factory FixedBackOff(1_000L, 3L): 3 retries 1 second apart, 4 attempts in total; after that the record goes to the DLT, the offset is committed, and the partition moves onDefaultErrorHandlerdoes not retry exceptions such as deserialization failures and type conversion failures by default. For a message that fails to deserialize to reach the error handler at all, the consumer has to be configured withErrorHandlingDeserializer; otherwise the consumer keeps failing on the same offset
3. An idempotent consumer
The speaker dashboard’s group keeps a sign-up count for each speaker. Events may arrive more than once, so a deduplication table makes sure each event is counted only once:
CREATE TABLE processed_event (
consumer VARCHAR(64) NOT NULL,
event_id CHAR(36) NOT NULL,
PRIMARY KEY (consumer, event_id)
);@Component
public class SpeakerStatsListener {
private static final String CONSUMER = "speaker-stats";
private final JdbcClient jdbc;
private final TransactionTemplate transactions;
public SpeakerStatsListener(JdbcClient jdbc, TransactionTemplate transactions) {
this.jdbc = jdbc;
this.transactions = transactions;
}
@KafkaListener(topics = "registration-events", groupId = CONSUMER)
public void onEvent(RegistrationEvent event) {
transactions.executeWithoutResult(status -> {
try {
jdbc.sql("INSERT INTO processed_event (consumer, event_id) VALUES (:consumer, :eventId)")
.param("consumer", CONSUMER)
.param("eventId", event.eventId())
.update();
} catch (DuplicateKeyException alreadyProcessed) {
return; // duplicate event: already counted before
}
jdbc.sql("UPDATE speaker_stats SET registrations = registrations + :delta WHERE speaker_id = :speakerId")
.param("delta", event.type() == RegistrationEvent.Type.CANCELLED ? -1 : 1)
.param("speakerId", event.speakerId())
.update();
});
}
}- The deduplication record and the business update are in the same transaction: when the update fails, both roll back, and the event is processed again when it is redelivered; when it succeeds, both commit, and later duplicates are stopped by the primary key
- The event ID is generated by the producer when the event happens (a UUID, for example), not taken from the Kafka offset. When a producer sends the same event twice, the offsets differ but the event ID is the same
- The deduplication table keeps growing; clean it up periodically, based on the longest period over which an event can be redelivered
The code above follows the official documentation for Spring for Apache Kafka 4.1, Spring Boot 4.1, and Apache Kafka 4.3; it has not been compiled or run.
Pitfalls and gotchas
- Assuming exactly-once covers every side effect: Kafka transactions cover only what happens inside Kafka. Sending email, calling APIs, and writing to other databases all have to be made idempotent by you
- Processing so long that it triggers a rebalance: when the messages from one poll take longer than
max.poll.interval.msto process, the consumer is kicked out of the group, its partitions go to another consumer, the same batch is processed twice, and this can repeat in an endless loop. Fetch fewer records per poll, or hand the slow work to another thread pool and control its progress - Adding partitions breaks ordering: the same key moves to a different partition. Give topics that need ordering enough partitions from the start
- Hot partitions: keys are spread unevenly, and the lag of one partition drags down the whole. Watch the lag of each partition, not just the total
- Non-blocking retries break ordering: the “cancel” for a sign-up may finish processing before its “sign up”. Do not use retry topics for events that need ordering
- Leaving
min.insync.replicasat the default of 1: the guarantee ofacks=allquietly weakens when replicas drop out - A DLT with fewer partitions than the original topic: the default recoverer sends to the partition with the same number, and the send fails when that partition does not exist
- Where a new consumer group starts reading: this is decided by
auto.offset.reset. Set it explicitly, depending on whether a new group should process the history from the start or only events from now on - Evolving the event format: Kafka events are retained and replayed, so a consumer may read an old format from months ago. Make only compatible changes (add optional fields), and manage the format with a schema registry or an explicit version field
Security
- ACLs for topics and consumer groups: only the sign-up service may write to
registration-events. If other services can write to it, they can forge sign-up events and feed fake data to the speaker dashboard, the recommendation system, and the audit system alike. Reading takes two permissions, on the topic and on the group, and these need limits too; otherwise another service can join the group with the same group ID and take over partitions that belong to the mail service - Disable automatic topic creation: when the broker creates topics automatically, any client with permission that mistypes a topic name, or maliciously sends to a new one, creates a new topic. Turn it off in production and create every topic through an administrative process
- Personal data and retention: keeping events for 90 days with replay means email addresses and names are also kept for 90 days, and a single record cannot be deleted. For users who ask to have their personal data deleted, you can have events carry only IDs and keep the personal data in a database where it can be deleted, or encrypt the personal data fields with a separate key for each user, so that deleting the key makes those fields impossible to decrypt
- Replay is an attack surface too: anyone who can reset a consumer group’s offsets can make the system process past events again, for example sending refund notifications a second time. Control who can reset offsets, and keep the consumers themselves idempotent
- Encryption and authentication on connections: use TLS between clients and brokers and between brokers, and authenticate with SASL or mTLS; only then do ACLs mean anything
- Data in the DLT: the DLT holds the raw events that failed processing, which may include malformed malicious content and personal data. Tools for viewing and redelivering DLT messages need access control, and must not show the content on a web page without escaping it
When to use it, and when not to
- Use a log-based Pub/Sub such as Kafka: many subscribers, replay or going back in time needed, high event volume, per-key ordering needed
- Use a broker such as RabbitMQ: job-style tasks, per-message acknowledgment and retries needed, flexible routing needed, a fixed set of subscribers
- Don’t use it: simple background jobs with only one consumer (the work queue or database queue from the previous post is enough), requests that need a synchronous response, or a team that cannot yet run a Kafka cluster (consider a managed cloud service)
References
- Apache Kafka Documentation — Design (Message Delivery Semantics, Replication): https://kafka.apache.org/documentation/#design
- Apache Kafka Documentation — Security (Authorization and ACLs): https://kafka.apache.org/documentation/#security_authz
- Spring for Apache Kafka Reference — Committing Offsets: https://docs.spring.io/spring-kafka/reference/kafka/receiving-messages/message-listener-container.html
- Spring for Apache Kafka Reference — Handling Exceptions (DefaultErrorHandler, Dead-Letter Publishing Recoverer): https://docs.spring.io/spring-kafka/reference/kafka/annotation-error-handling.html
- Spring for Apache Kafka Reference — Non-Blocking Retries: https://docs.spring.io/spring-kafka/reference/retrytopic.html
- Spring Boot Reference — Apache Kafka Support: https://docs.spring.io/spring-boot/reference/messaging/kafka.html
- Jay Kreps, “The Log: What every software engineer should know about real-time data’s unifying abstraction”, 2013: https://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying
- Martin Kleppmann, Designing Data-Intensive Applications, O’Reilly, 2017, Chapter 11
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments