How to Replay Messages in Kafka
Replaying messages in Kafka means reading records again that were already consumed, for example to rebuild a database after a bug, to backfill a new service, or to re-run yesterday’s processing. Because Kafka keeps records after they are read, replay is a matter of starting a consumer at an earlier offset. The important part is doing it without disturbing the consumer group that runs in production.
This article shows the safe ways to replay a time range: a separate consumer group positioned with the CLI, a Java tool that seeks by timestamp, and a Spring for Apache Kafka listener. It also covers resetting an existing group when that is really what you want, and the pitfalls of replaying into systems with side effects.
1. Why Replay Works in Kafka
A Kafka topic is a log, not a queue: consuming a record does not remove it. Records stay until retention or compaction removes them, and each consumer group keeps its own committed offset per partition. A second group reading the same topic is completely independent: it has its own position and its own commits, and it does not take records away from the first group.
2. Before You Replay
- Is the data still there? Retention must not have deleted the range yet (
retention.msis 7 days by default). On compacted topics, older values of a key may already be gone. - What do the timestamps mean? Timestamp-based seeking uses record timestamps: the producer’s create time by default, or the broker’s append time if the topic uses
message.timestamp.type=LogAppendTime. - What will the replay do? Writes to a database, emails, payments and downstream topics all happen again. Decide where the output goes before you start.
3. Replay Approaches Compared
| Approach | Affects the production group? | Best for |
|---|---|---|
New consumer group, offsets set with kafka-consumer-groups.sh | No | Re-running a normal application on a range, with progress tracked in Kafka |
Java tool with assign(), offsetsForTimes() and seek() | No (no group, no commits) | One-off replays with exact start and stop points |
| Spring listener with its own group that seeks by timestamp | No | Replays built into a Spring Boot service, started on demand |
| Resetting the production group’s offsets | Yes | Only when the production consumer itself must reprocess |
4. Option 1: New Consumer Group Positioned with the CLI
Create the offsets for a new group before any consumer joins it. A group that does not exist yet can be reset because it is inactive:
# 1. Preview: where would the new group start?
$ bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--group billing-replay-20261202 --topic invoices \
--reset-offsets --to-datetime 2026-12-02T00:00:00.000Z --dry-run
GROUP TOPIC PARTITION NEW-OFFSET
billing-replay-20261202 invoices 0 418230
billing-replay-20261202 invoices 1 409877
billing-replay-20261202 invoices 2 415002
# 2. Apply it
$ bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--group billing-replay-20261202 --topic invoices \
--reset-offsets --to-datetime 2026-12-02T00:00:00.000Z --execute
Then start the application, or a copy of it, with group.id=billing-replay-20261202. A datetime without a zone is interpreted as UTC; add an offset such as +05:30 for local time. Instead of a fixed time, --by-duration P1D moves to one day before now. The group reads until you stop it, so either stop it once it passes the end of the range, or make the application ignore records after that time.
5. Option 2: Java Replay Tool with offsetsForTimes
For an exact window, a small tool can assign() partitions directly, without a group ID, so nothing is committed and no group is involved. offsetsForTimes() returns, per partition, the earliest offset whose timestamp is at or after the given time:
package com.javabytechie.replay;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
public class ReplayWindow {
public static void replay(String topic, Instant from, Instant to,
Consumer<ConsumerRecord<String, String>> handler) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); // no group.id, nothing committed
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
List<TopicPartition> partitions = consumer.partitionsFor(topic).stream()
.map(p -> new TopicPartition(p.topic(), p.partition()))
.toList();
consumer.assign(partitions);
Map<TopicPartition, OffsetAndTimestamp> starts = consumer.offsetsForTimes(at(partitions, from));
Map<TopicPartition, OffsetAndTimestamp> stops = consumer.offsetsForTimes(at(partitions, to));
Map<TopicPartition, Long> ends = consumer.endOffsets(partitions);
Map<TopicPartition, Long> stopAt = new HashMap<>();
for (TopicPartition tp : partitions) {
OffsetAndTimestamp start = starts.get(tp); // null: no record at or after 'from'
long stop = stops.get(tp) != null ? stops.get(tp).offset() : ends.get(tp);
if (start == null || start.offset() >= stop) {
consumer.pause(List.of(tp)); // nothing to replay here
} else {
consumer.seek(tp, start.offset());
stopAt.put(tp, stop);
}
}
while (!stopAt.isEmpty()) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
TopicPartition tp = new TopicPartition(r.topic(), r.partition());
Long stop = stopAt.get(tp);
if (stop == null) continue; // partition already finished
if (r.offset() < stop) handler.accept(r);
if (r.offset() + 1 >= stop) { // reached the end of the window
stopAt.remove(tp);
consumer.pause(List.of(tp));
}
}
}
}
}
private static Map<TopicPartition, Long> at(List<TopicPartition> partitions, Instant time) {
return partitions.stream().collect(Collectors.toMap(tp -> tp, tp -> time.toEpochMilli()));
}
}
Call it as ReplayWindow.replay("invoices", Instant.parse("2026-12-02T00:00:00Z"), Instant.parse("2026-12-03T00:00:00Z"), invoiceRebuilder::apply). Each partition stops at the first offset of the next day, so the window is exact even while producers keep writing. If the tool crashes, it simply starts again from the beginning of the window, so the handler must be idempotent.
6. Option 3: Spring for Apache Kafka Listener
Spring’s AbstractConsumerSeekAware lets a listener seek when partitions are assigned. Give the replay listener its own group and keep it stopped until needed:
@Component
public class InvoiceReplayListener extends AbstractConsumerSeekAware {
private final Instant replayFrom = Instant.parse("2026-12-02T00:00:00Z");
private final Set<TopicPartition> positioned = ConcurrentHashMap.newKeySet();
private final InvoiceRebuilder rebuilder;
public InvoiceReplayListener(InvoiceRebuilder rebuilder) {
this.rebuilder = rebuilder;
}
@Override
public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) {
super.onPartitionsAssigned(assignments, callback);
// Seek only the first time; after a rebalance, continue from the committed offsets
List<TopicPartition> fresh = assignments.keySet().stream().filter(positioned::add).toList();
callback.seekToTimestamp(fresh, replayFrom.toEpochMilli());
}
@KafkaListener(id = "invoiceReplay", topics = "invoices",
groupId = "billing-replay-20261202", autoStartup = "false")
public void replay(ConsumerRecord<String, String> record) {
rebuilder.apply(record); // idempotent: safe to run again
}
}
Start it on demand through the KafkaListenerEndpointRegistry, for example registry.getListenerContainer("invoiceReplay").start() from an admin endpoint, and stop it when the replay has caught up to the end of the range.
7. Resetting the Existing Group
Sometimes the production consumer itself must reprocess, for example after deploying a fix for records it handled wrongly. Kafka only allows resetting offsets of an inactive group, so that a running member cannot overwrite the new offsets with its own commits:
- Stop all instances of the consumer application.
- Run
kafka-consumer-groups.sh --reset-offsets ... --dry-run, check the new offsets, then repeat with--execute. - Start the application; it resumes from the new position and processes everything from there, up to the present.
The Offset Management tutorial lists all reset options (--to-earliest, --shift-by, --to-offset and more).
8. Side Effects and Safety
- Idempotent handlers: a replay is a deliberate duplicate. Handlers that use event IDs or upserts, as described in Idempotent Consumer in Kafka, can replay safely.
- Turn off external actions: emails, payments and webhooks should be disabled or routed to a no-op in replay mode.
- Downstream topics: a replay that produces events makes downstream services process them again. Write to a separate topic or mark records with a replay header if consumers must tell the difference.
- Throttle: a replay reads old data from disk rather than the page cache and can compete with live traffic; limit its speed or run it off-peak.
- Clean up: delete the replay group afterwards with
kafka-consumer-groups.sh --delete --group ...so it does not appear in lag dashboards.
9. Common Mistakes
- Resetting the production group while it is running; the tool refuses, and stopping it in a hurry causes an outage.
- Relying on
auto.offset.reset=earliestfor a new group, which replays the whole retained history instead of one day. - Forgetting the time zone:
--to-datetimewithout an offset is UTC. - Replaying into a handler that is not idempotent, creating duplicate rows or charges.
- Waiting too long: the data needed for the replay has been deleted by retention.
10. Summary
Kafka keeps records after they are consumed, and every consumer group has its own offsets, so replaying data is safe as long as the production group is left alone. To replay yesterday’s records, position a new consumer group with kafka-consumer-groups.sh --reset-offsets --to-datetime, use a Java tool that assigns partitions and seeks with offsetsForTimes() between a start and stop time, or use a Spring listener that seeks by timestamp. Check retention first, make handlers idempotent, disable external side effects, and reset the production group only when it is stopped and really needs to reprocess.
11. Related Reading
12. References
Kafka Message Replay Interview Questions and Answers
Common interview questions on Kafka Message Replay, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Why can Kafka replay messages when a traditional queue cannot?
Answer: Kafka stores messages in a log and does not delete them when they are consumed; they stay until retention or compaction removes them. Progress is tracked per consumer group as a committed offset, which is just a position in the log. Replay therefore means starting a consumer at an earlier position. In a traditional queue, a consumed and acknowledged message is removed, so it cannot be read again.
Q. What does offsetsForTimes() return, and how precise is replay by timestamp?
Answer: For each partition, it returns the earliest offset whose record timestamp is greater than or equal to the requested time, or null if there is no such record. The broker answers it with each segment’s time index. Precision depends on what the timestamps mean: with the default CreateTime, the producer sets them, so clock skew or late sends can place a record slightly out of time order. LogAppendTime gives broker-assigned, monotonic timestamps per partition.
Intermediate questions
Q. Why does kafka-consumer-groups.sh only reset offsets of an inactive group?
Answer: Active members keep committing their own positions. If the tool changed the offsets of a running group, the members would overwrite them with their next commit, or continue from their in-memory position, so the reset would be lost or only partly applied. The tool therefore requires the group to be empty or not to exist yet. To reset a production group, stop all its consumers first.
Q. When would you replay with assign() and no group ID instead of a new consumer group?
Answer: For one-off tools that need an exact start and stop point and do not need progress stored in Kafka. With assign(), the tool chooses its partitions and seeks itself, joins no group, triggers no rebalances and commits nothing, so it leaves no trace in group listings. A new consumer group is better when you rerun a normal application that expects subscribe(), wants to scale over several instances, or must resume after a crash from its committed position.
Tricky and scenario questions
Q. You need to replay messages that were successfully processed yesterday without affecting the existing consumer group. How do you do it?
Answer: Leave the production group untouched and read with a different identity. Either create a new group and position it with kafka-consumer-groups.sh --reset-offsets --to-datetime <yesterday 00:00, with time zone> --execute before starting a replay instance, or run a tool that uses assign(), offsetsForTimes() and seek() to read exactly from yesterday’s start to today’s start. Check that retention still holds the data, make the handler idempotent, disable external side effects such as emails, and delete the replay group afterwards.
Q. A team replays three days of order events through the normal order service, and customers receive duplicate confirmation emails. What went wrong?
Answer: The replay ran the full processing path, including side effects outside Kafka. Offsets and consumer groups only control what is read; they do not make the handler’s actions safe to repeat. The service should have had a replay mode that disables emails and other external calls, or idempotent handlers that record which events already triggered a notification, keyed by a stable event ID. Replays should also be tested on a small window first.