Spring Consumers: @KafkaListener, Group, Offset Commit, Rebalance
Nov 2026 · 12 min read
The Spring consumer reads OrderCreated events with KafkaListener and stores them in memory so it can be tested via REST. The reader proves that two instances in one group split the partitions, that offsets only advance after acknowledge, and that pausing raises the lag, which is delivered again on resume.
Full code: https://github.com/Sch39/java-spring-boot
Problem
order-service already publishes OrderCreated, but nothing reads it correctly yet. One consumer is not enough when traffic rises, and committing offsets too early makes messages get lost when processing fails.
Offsets advance before the message finishes processing: with auto commit, the offset can be committed before the listener finishes, so failed messages are never read again.
It is unclear what a new instance gets: without seeing the assignment and lag, it is hard to confirm that two instances really split the partitions.
Outcome
The reader can:
Set up
notification-servicewith@KafkaListener, a JSON deserializer, andack-mode=manual.Prove that offsets are committed only after
acknowledge()by comparing the consumed offset with the committed offset.Read the assignment and lag per partition from two instances, then see pause raise the lag and resume deliver it.
Implementation
Folder Structure
notification-service/
├── build.gradle
└── src/
├── main/
│ ├── java/dev/sch39/notificationservice/
│ │ ├── OrderCreated.java
│ │ ├── Notification.java
│ │ ├── NotificationStore.java
│ │ ├── OrderListener.java
│ │ ├── NotificationController.java
│ │ └── ConsumerController.java
│ └── resources/application.yml
└── test/java/dev/sch39/notificationservice/
├── KafkaTestSupport.java
├── NotificationConsumerTest.java
└── NotificationNoAckTest.javaSetup
This is a second project, so it is created with its own spring init (run from the / folder). The local Kafka broker must be running at localhost:9092; official guide: https://kafka.apache.org/quickstart. The order-service from the previous article is used as the producer in the E2E.
mkdir -p notification-service
cd notification-service
spring init --type=gradle-project --java-version=21 --boot-version=4.1.2 --dependencies=web,kafka --group-id=dev.sch39 --artifact-id=notification-service --package-name=dev.sch39.notificationservice --extract . \
&& rm src/main/resources/application.properties \
&& printf 'spring:\n application:\n name: notification-service\n' > src/main/resources/application.yml
rm src/test/java/dev/sch39/notificationservice/NotificationServiceApplicationTests.javanotification-service/src/main/resources/application.yml
spring:
application:
name: notification-service
server:
port: 8081Code Blocks
Block 1: The consumer's version of the event
notification-service/src/main/java/dev/sch39/notificationservice/OrderCreated.java:
package dev.sch39.notificationservice;
public record OrderCreated(String orderId, String customerId, long amount) {
}Purpose: Define the consumer's own copy of the event contract, separate from the class in order-service.
Block 2: The stored notification
notification-service/src/main/java/dev/sch39/notificationservice/Notification.java:
package dev.sch39.notificationservice;
public record Notification(String orderId, String customerId, long amount,
String key, int partition, long offset, int port) {
}Purpose: Store the partition, offset, key, and instance port alongside the event contents so the origin of each message is visible.
Block 3: In-memory storage
notification-service/src/main/java/dev/sch39/notificationservice/NotificationStore.java:
package dev.sch39.notificationservice;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.stereotype.Component;
@Component
class NotificationStore {
private final List<Notification> items = new CopyOnWriteArrayList<>();
void add(Notification notification) {
items.add(notification);
}
List<Notification> all() {
return List.copyOf(items);
}
}Purpose: Hold the notifications received by the listener without a database.
Block 4: Deserializer, manual ack, and group
notification-service/src/main/resources/application.yml:
spring.application.name=notification-service
server.port=8081
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JacksonJsonDeserializer
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.enable-auto-commit=false
spring.kafka.consumer.properties.spring.json.use.type.headers=false
spring.kafka.consumer.properties.spring.json.value.default.type=dev.sch39.notificationservice.OrderCreated
spring.kafka.listener.ack-mode=manual
app.topic.orders=orders
app.listener.id=notification
app.ack-enabled=truePurpose: Set the JSON deserializer with a default type and no type headers, manual commit, and the group name via app.listener.id.
Block 5: Listener with acknowledge
notification-service/src/main/java/dev/sch39/notificationservice/OrderListener.java:
package dev.sch39.notificationservice;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;
@Component
class OrderListener {
private final NotificationStore store;
private final int port;
private final boolean ackEnabled;
OrderListener(NotificationStore store,
@Value("${server.port}") int port,
@Value("${app.ack-enabled}") boolean ackEnabled) {
this.store = store;
this.port = port;
this.ackEnabled = ackEnabled;
}
@KafkaListener(id = "${app.listener.id}", topics = "${app.topic.orders}")
void onOrder(ConsumerRecord<String, OrderCreated> record, Acknowledgment ack) {
OrderCreated event = record.value();
store.add(new Notification(event.orderId(), event.customerId(), event.amount(),
record.key(), record.partition(), record.offset(), port));
if (ackEnabled) {
ack.acknowledge();
}
}
}Purpose: Store each event and then commit the offset via acknowledge(), with an app.ack-enabled switch so the no-ack case can be tested.
Block 6: GET /notifications endpoint
notification-service/src/main/java/dev/sch39/notificationservice/NotificationController.java:
package dev.sch39.notificationservice;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class NotificationController {
private final NotificationStore store;
NotificationController(NotificationStore store) {
this.store = store;
}
@GetMapping("/notifications")
List<Notification> notifications() {
return store.all();
}
}Purpose: Show the notifications received by this instance along with partition, offset, key, and port.
Block 7: Assignment and lag per partition
notification-service/src/main/java/dev/sch39/notificationservice/ConsumerController.java:
package dev.sch39.notificationservice;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.ListOffsetsResult.ListOffsetsResultInfo;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/consumer")
class ConsumerController {
record PartitionLag(int partition, long committed, long end, long lag) {
}
record Assignment(int port, boolean paused, List<PartitionLag> partitions) {
}
private final KafkaListenerEndpointRegistry registry;
private final KafkaAdmin kafkaAdmin;
private final String listenerId;
private final int port;
ConsumerController(KafkaListenerEndpointRegistry registry, KafkaAdmin kafkaAdmin,
@Value("${app.listener.id}") String listenerId,
@Value("${server.port}") int port) {
this.registry = registry;
this.kafkaAdmin = kafkaAdmin;
this.listenerId = listenerId;
this.port = port;
}
@GetMapping("/assignment")
Assignment assignment() throws Exception {
MessageListenerContainer container = registry.getListenerContainer(listenerId);
List<TopicPartition> assigned = container.getAssignedPartitions().stream()
.sorted(Comparator.comparingInt(TopicPartition::partition))
.toList();
return new Assignment(port, container.isContainerPaused(), lag(assigned));
}
private List<PartitionLag> lag(List<TopicPartition> assigned) throws Exception {
if (assigned.isEmpty()) {
return List.of();
}
try (Admin admin = Admin.create(kafkaAdmin.getConfigurationProperties())) {
Map<TopicPartition, OffsetAndMetadata> committed = admin.listConsumerGroupOffsets(listenerId)
.partitionsToOffsetAndMetadata().get();
Map<TopicPartition, ListOffsetsResultInfo> end = admin.listOffsets(
assigned.stream().collect(Collectors.toMap(Function.identity(), tp -> OffsetSpec.latest())))
.all().get();
return assigned.stream().map(tp -> {
OffsetAndMetadata c = committed.get(tp);
long committedOffset = c == null ? 0 : c.offset();
long endOffset = end.get(tp).offset();
return new PartitionLag(tp.partition(), committedOffset, endOffset, endOffset - committedOffset);
}).toList();
}
}
}Purpose: Show the partitions held by this instance along with the committed offset, end offset, and lag.
Block 8: Pause and resume
notification-service/src/main/java/dev/sch39/notificationservice/ConsumerController.java:
@PostMapping("/pause")
void pause() {
registry.getListenerContainer(listenerId).pause();
}
@PostMapping("/resume")
void resume() {
registry.getListenerContainer(listenerId).resume();
}Purpose: Stop and restart the container's record fetching without shutting down the service.
Test Blocks
Test 1: Helper and partition per key
notification-service/src/test/java/dev/sch39/notificationservice/KafkaTestSupport.java:
package dev.sch39.notificationservice;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.function.BooleanSupplier;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
final class KafkaTestSupport {
private static final Map<String, Object> CONFIG = Map.of("bootstrap.servers", "localhost:9092");
private KafkaTestSupport() {
}
static void createTopic(String topic, int partitions) throws Exception {
try (Admin admin = Admin.create(CONFIG)) {
admin.createTopics(List.of(new NewTopic(topic, partitions, (short) 1))).all().get();
}
}
static void deleteTopic(String topic) throws Exception {
try (Admin admin = Admin.create(CONFIG)) {
admin.deleteTopics(List.of(topic)).all().get();
}
}
static long committedTotal(String group) throws Exception {
try (Admin admin = Admin.create(CONFIG)) {
return admin.listConsumerGroupOffsets(group).partitionsToOffsetAndMetadata().get()
.values().stream().mapToLong(OffsetAndMetadata::offset).sum();
}
}
static boolean await(BooleanSupplier condition, Duration timeout) throws InterruptedException {
long end = System.currentTimeMillis() + timeout.toMillis();
while (System.currentTimeMillis() < end) {
if (condition.getAsBoolean()) {
return true;
}
Thread.sleep(200);
}
return condition.getAsBoolean();
}
static String json(String orderId, String customerId, long amount) {
return "{\"orderId\":\"" + orderId + "\",\"customerId\":\"" + customerId + "\",\"amount\":" + amount + "}";
}
}notification-service/src/test/java/dev/sch39/notificationservice/NotificationConsumerTest.java:
package dev.sch39.notificationservice;
import static dev.sch39.notificationservice.KafkaTestSupport.await;
import static dev.sch39.notificationservice.KafkaTestSupport.committedTotal;
import static dev.sch39.notificationservice.KafkaTestSupport.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import com.jayway.jsonpath.JsonPath;
@SpringBootTest
@AutoConfigureMockMvc
class NotificationConsumerTest {
static final String TOPIC = "orders-test-" + UUID.randomUUID();
static final String GROUP = "notif-" + UUID.randomUUID();
@DynamicPropertySource
static void props(DynamicPropertyRegistry registry) {
registry.add("app.topic.orders", () -> TOPIC);
registry.add("app.listener.id", () -> GROUP);
}
@BeforeAll
static void createTopic() throws Exception {
KafkaTestSupport.createTopic(TOPIC, 2);
}
@AfterAll
static void deleteTopic() throws Exception {
KafkaTestSupport.deleteTopic(TOPIC);
}
@Autowired
NotificationStore store;
@Autowired
KafkaTemplate<String, String> template;
@Autowired
MockMvc mvc;
private long lagTotal() throws Exception {
String body = mvc.perform(get("/consumer/assignment")).andReturn().getResponse().getContentAsString();
List<Number> lags = JsonPath.read(body, "$.partitions[*].lag");
return lags.stream().mapToLong(Number::longValue).sum();
}
private boolean paused() throws Exception {
String body = mvc.perform(get("/consumer/assignment")).andReturn().getResponse().getContentAsString();
return JsonPath.read(body, "$.paused");
}
@Test
void listenerReceivesPartitionAndOffset() throws Exception {
for (String customer : List.of("c1", "c2", "c3", "c1")) {
template.send(TOPIC, customer, json(UUID.randomUUID().toString(), customer, 100)).get();
}
assertTrue(await(() -> store.all().size() >= 4, Duration.ofSeconds(20)),
"notifications: got " + store.all().size() + ", want >= 4");
String body = mvc.perform(get("/notifications")).andReturn().getResponse().getContentAsString();
List<Map<String, Object>> items = JsonPath.read(body, "$[?(@.key == 'c1')]");
items.forEach(n -> System.out.println(
"key=" + n.get("key") + " partition=" + n.get("partition") + " offset=" + n.get("offset")
+ " port=" + n.get("port")));
Set<Object> c1Partitions = items.stream().map(n -> n.get("partition")).collect(Collectors.toSet());
assertEquals(2, items.size(), "records for key c1: got " + items.size() + ", want 2");
assertEquals(1, c1Partitions.size(), "partitions for key c1: got " + c1Partitions + ", want 1");
}Purpose: Prove that the listener receives events through the JSON deserializer and that two events keyed c1 land on one partition.
Test 2: Offset is committed after ack
notification-service/src/test/java/dev/sch39/notificationservice/NotificationConsumerTest.java:
@Test
void offsetIsCommittedAfterAck() throws Exception {
int before = store.all().size();
template.send(TOPIC, "c-ack", json(UUID.randomUUID().toString(), "c-ack", 1)).get();
assertTrue(await(() -> store.all().size() > before, Duration.ofSeconds(20)), "record not consumed");
long expected = store.all().size();
assertTrue(await(() -> {
try {
return committedTotal(GROUP) == expected;
} catch (Exception e) {
return false;
}
}, Duration.ofSeconds(20)), "committed: got " + committedTotal(GROUP) + ", want " + expected);
System.out.println("consumed=" + expected + " committed=" + committedTotal(GROUP));
}Purpose: Prove that after acknowledge() the number of committed offsets equals the number of consumed records.
Test 3: Pause raises lag, resume delivers it
notification-service/src/test/java/dev/sch39/notificationservice/NotificationConsumerTest.java:
@Test
void pauseBuildsLagAndResumeDrainsIt() throws Exception {
assertTrue(await(() -> {
try {
return lagTotal() == 0;
} catch (Exception e) {
return false;
}
}, Duration.ofSeconds(20)), "lag not zero before pause");
mvc.perform(post("/consumer/pause"));
assertTrue(await(() -> {
try {
return paused();
} catch (Exception e) {
return false;
}
}, Duration.ofSeconds(20)), "container not paused");
int before = store.all().size();
for (int i = 0; i < 3; i++) {
template.send(TOPIC, "c-pause", json(UUID.randomUUID().toString(), "c-pause", i)).get();
}
Thread.sleep(3000);
long lagWhilePaused = lagTotal();
int consumedWhilePaused = store.all().size() - before;
System.out.println("paused lag=" + lagWhilePaused + " consumed=" + consumedWhilePaused);
assertEquals(3, lagWhilePaused, "lag while paused: got " + lagWhilePaused + ", want 3");
assertEquals(0, consumedWhilePaused, "consumed while paused: got " + consumedWhilePaused + ", want 0");
mvc.perform(post("/consumer/resume"));
assertTrue(await(() -> {
try {
return lagTotal() == 0 && store.all().size() == before + 3;
} catch (Exception e) {
return false;
}
}, Duration.ofSeconds(20)), "lag after resume: got " + lagTotal() + ", want 0");
System.out.println("resumed lag=" + lagTotal() + " consumed=" + (store.all().size() - before));
}
}Purpose: Prove that while paused, three records wait as lag without being consumed, then resume delivers all three and the lag returns to zero.
Test 4: Without ack, the offset does not advance
notification-service/src/test/java/dev/sch39/notificationservice/NotificationNoAckTest.java:
package dev.sch39.notificationservice;
import static dev.sch39.notificationservice.KafkaTestSupport.await;
import static dev.sch39.notificationservice.KafkaTestSupport.committedTotal;
import static dev.sch39.notificationservice.KafkaTestSupport.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.util.UUID;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@SpringBootTest(properties = "app.ack-enabled=false")
class NotificationNoAckTest {
static final String TOPIC = "orders-noack-" + UUID.randomUUID();
static final String GROUP = "notif-noack-" + UUID.randomUUID();
@DynamicPropertySource
static void props(DynamicPropertyRegistry registry) {
registry.add("app.topic.orders", () -> TOPIC);
registry.add("app.listener.id", () -> GROUP);
}
@BeforeAll
static void createTopic() throws Exception {
KafkaTestSupport.createTopic(TOPIC, 2);
}
@AfterAll
static void deleteTopic() throws Exception {
KafkaTestSupport.deleteTopic(TOPIC);
}
@Autowired
NotificationStore store;
@Autowired
KafkaTemplate<String, String> template;
@Test
void offsetStaysUncommittedWithoutAck() throws Exception {
for (int i = 0; i < 3; i++) {
template.send(TOPIC, "c-noack", json(UUID.randomUUID().toString(), "c-noack", i)).get();
}
assertTrue(await(() -> store.all().size() == 3, Duration.ofSeconds(20)),
"consumed: got " + store.all().size() + ", want 3");
Thread.sleep(3000);
long committed = committedTotal(GROUP);
System.out.println("consumed=" + store.all().size() + " committed=" + committed);
assertEquals(0, committed, "committed without ack: got " + committed + ", want 0");
}
}Purpose: Prove that a listener that does not call acknowledge() consumes three records but no offsets are committed.
Run Test
Run from the notification-service/ folder:
./gradlew test --rerun-tasks -iOutput:
...
NotificationConsumerTest > listenerReceivesPartitionAndOffset() STANDARD_OUT
key=c1 partition=1 offset=0 port=8081
key=c1 partition=1 offset=3 port=8081
NotificationConsumerTest > offsetIsCommittedAfterAck() STANDARD_OUT
consumed=5 committed=5
NotificationConsumerTest > pauseBuildsLagAndResumeDrainsIt() STANDARD_OUT
paused lag=3 consumed=0
resumed lag=0 consumed=3
NotificationNoAckTest > offsetStaysUncommittedWithoutAck() STANDARD_OUT
consumed=3 committed=0
...
BUILD SUCCESSFUL in 25sManual E2E
Run order-service on port 8080 (from the previous article), then two notification-service instances in two terminals from the notification-service/ folder (the local broker at localhost:9092 must be running). Wait about one minute for both instances to get partitions, and leave a few seconds between curl commands.
SERVER_PORT=8081 ./gradlew bootRunSERVER_PORT=8082 ./gradlew bootRuncurl -s -X POST -w "\n" "localhost:8080/orders/bulk?customerId=c1&count=3" "localhost:8080/orders/bulk?customerId=c2&count=3"
curl -s -w "\n" localhost:8081/notifications localhost:8082/notifications localhost:8081/consumer/assignment localhost:8082/consumer/assignment
curl -s -X POST -w "%{http_code}\n" localhost:8081/consumer/pause "localhost:8080/orders/bulk?customerId=c1&count=3"
curl -s -w "\n" localhost:8081/consumer/assignment --next -s -X POST -w "%{http_code}\n" localhost:8081/consumer/resume
curl -s -w "\n" localhost:8081/consumer/assignmentOutput:
[{"topic":"orders","partition":2,"offset":39},{"topic":"orders","partition":2,"offset":40},{"topic":"orders","partition":2,"offset":41}]
[{"topic":"orders","partition":1,"offset":25},{"topic":"orders","partition":1,"offset":26},{"topic":"orders","partition":1,"offset":27}]
[{"orderId":"9380f8c1-cf30-464f-975f-538598c4bcb1","customerId":"c1","amount":100,"key":"c1","partition":2,"offset":39,"port":8081},{"orderId":"2c770cce-78eb-4a2a-9078-7e75b7bd8b1d","customerId":"c1","amount":101,"key":"c1","partition":2,"offset":40,"port":8081},{"orderId":"f7a81e06-7c03-439a-b17c-b1e267311dae","customerId":"c1","amount":102,"key":"c1","partition":2,"offset":41,"port":8081}]
[{"orderId":"b4faa465-ac15-4aa5-b0e6-baa4fc6c0360","customerId":"c2","amount":100,"key":"c2","partition":1,"offset":25,"port":8082},{"orderId":"302ace31-6fac-408e-951f-3acfe7026ad9","customerId":"c2","amount":101,"key":"c2","partition":1,"offset":26,"port":8082},{"orderId":"58e67cc3-c275-43cb-8ea9-5be55cc99620","customerId":"c2","amount":102,"key":"c2","partition":1,"offset":27,"port":8082}]
{"port":8081,"paused":false,"partitions":[{"partition":2,"committed":42,"end":42,"lag":0}]}
{"port":8082,"paused":false,"partitions":[{"partition":0,"committed":0,"end":0,"lag":0},{"partition":1,"committed":28,"end":28,"lag":0}]}
200
[{"topic":"orders","partition":2,"offset":42},{"topic":"orders","partition":2,"offset":43},{"topic":"orders","partition":2,"offset":44}]200
{"port":8081,"paused":true,"partitions":[{"partition":2,"committed":42,"end":45,"lag":3}]}
200
{"port":8081,"paused":false,"partitions":[{"partition":2,"committed":45,"end":45,"lag":0}]}Purpose: Prove that two instances in one group split the partitions, and that pausing on instance 8081 holds three records as lag that are delivered again after resume.
Why It Works
Group and assignment: @KafkaListener(id = ...) is used as the group.id, overriding the value in the consumer factory. Two instances with the same id are in one group, so the broker splits the three partitions between them: in this run 8081 holds partition 2 and 8082 holds partitions 0 and 1. Key c1 always goes to partition 2, so only the instance holding it receives c1 messages.
Manual ack and offset commit: With ack-mode=manual, the container does not commit on its own. After acknowledge() is called, the semantics are the same as BATCH mode, that is, offsets are committed after all records from that poll() have finished processing. That is why committed=0 when the listener does not call acknowledge(), even though three records have entered the store.
Pause without rebalance: pause() takes effect right before the next poll(). The container still calls poll() but does not fetch records, so the consumer is not considered dead and does not trigger a rebalance, while the end offset keeps rising and the lag grows. resume() resumes fetching records and the lag drops to zero.
Deserializer without trusted packages: With spring.json.use.type.headers=false and spring.json.value.default.type, the deserializer ignores the type header from the producer and always uses the consumer's own class. OrderCreated in order-service and in notification-service may live in different packages, and the trusted packages error from the previous article does not appear.
Edge Cases
Rebalance when an instance joins or leaves: When the second instance joins, the first instance's log shows partitions revoked: [orders-0, orders-1, orders-2] followed by partitions assigned: [orders-0, orders-1]. When another instance dies, its partitions return to the remaining instances.
Process killed forcefully: In this run, fifteen seconds after instance 8082 was stopped with SIGKILL, 8081 had not yet taken over its partitions. Only after waiting about another minute did 8081 hold all three partitions, because the broker waits for session.timeout.ms before considering that member gone.
More instances than partitions: Within one group, a partition is read by only one consumer. The 4th instance on a 3-partition topic gets no partition and sits idle.
auto-offset-reset only applies without a committed offset: earliest applies to a new group. A group that already has a committed offset continues from that offset, not from the beginning.
Trade-offs
Strategy | Pro | Con |
|---|---|---|
| Offsets advance only after the logic finishes, safe from message loss | The listener must call |
| Commit per record, minimal reprocessing after a crash | More commit requests to the broker |
| Simple and few commits | A whole batch can be reprocessed after a crash |
Best practice: Commit after the logic finishes (manual ack or RECORD), give @KafkaListener a stable id as the group name, and make processing idempotent since messages can be read more than once.
Gotchas I Ran Into
With
ack-mode=manualand a listener that does not callacknowledge(), the three records are still consumed but the test result showsconsumed=3 committed=0. Offsets silently do not advance, with no error.@KafkaListener(id = "notification")automatically becomes thegroup.id, visible in the log asgroupId=notification, so thegroup.idin the consumer factory is not used.Killing an instance with SIGKILL does not immediately trigger a rebalance: 15 seconds later the remaining instance still holds its old partitions, and only takes over after waiting about another minute.
Production Checklist
Must messages not be lost when the listener fails? Commit offsets after the logic finishes, not before.
Can messages be read twice? Make processing idempotent.
Running multiple instances? Use the same listener
idand do not exceed the number of partitions.Lag keeps rising? Monitor
end - committedper partition, not just the number of processed messages.Events produced by another service? Set the default type in the deserializer, do not open trusted packages with
*.
References
Spring for Apache Kafka,
@KafkaListenerAnnotation: https://docs.spring.io/spring-kafka/reference/kafka/receiving-messages/listener-annotation.htmlSpring for Apache Kafka, Message Listener Containers (Committing Offsets): https://docs.spring.io/spring-kafka/reference/kafka/receiving-messages/message-listener-container.html
Spring for Apache Kafka, Pausing and Resuming Listener Containers: https://docs.spring.io/spring-kafka/reference/kafka/pause-resume.html
Spring for Apache Kafka, Serialization, Deserialization, and Message Conversion: https://docs.spring.io/spring-kafka/reference/kafka/serdes.html
Apache Kafka Documentation, Consumer Configs: https://kafka.apache.org/documentation