00:00

How to Replay Messages in Kafka

Last updated:

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.

Replaying a time range with a separate consumer groupThe invoices partition holds records from 1 December to now. The production group billing has its committed offset near the end of the log and keeps consuming new records. A replay group named billing-replay-20261202 starts at the offset of the first record at 2 December 00:00 UTC and stops at the first record at 3 December 00:00 UTC. The two groups have separate offsets and do not affect each other. Partition invoices-0 Dec 1 Dec 2: records to replay Dec 3 (today) start: offsetsForTimes(Dec 2 00:00) stop: offsetsForTimes(Dec 3 00:00) group billing-replay-20261202 billing(production) Separate group, separate offsets: the production group is not affected.
The replay group reads only the chosen time range. The production group’s committed offsets are never touched.

2. Before You Replay

  • Is the data still there? Retention must not have deleted the range yet (retention.ms is 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

ApproachAffects the production group?Best for
New consumer group, offsets set with kafka-consumer-groups.shNoRe-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 timestampNoReplays built into a Spring Boot service, started on demand
Resetting the production group’s offsetsYesOnly 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:

Terminal
# 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:

ReplayWindow.java
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:

InvoiceReplayListener.java
@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:

  1. Stop all instances of the consumer application.
  2. Run kafka-consumer-groups.sh --reset-offsets ... --dry-run, check the new offsets, then repeat with --execute.
  3. 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=earliest for a new group, which replays the whole retained history instead of one day.
  • Forgetting the time zone: --to-datetime without 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.

12. References