Apache Kafka
Delayed Queue
Message Queuing
Data Streaming
Coding Techniques

How to build a delayed queue with Apache Kafka

Codemia Knowledge Hub ·

Apache Kafka does not natively support delayed messages, where a message is held for a set time before delivery. It is built for real-time streaming. You can still build a delay queue on top of it with dedicated delay topics, a Kafka Streams application with a state store, or an external system that holds messages until they are due. Delays come up often in task scheduling, rate limiting and business workflows.

1. Topic-based delay

Create one topic per delay length, for example topic-delay-5m, topic-delay-10m and topic-delay-1h.

  1. Produce: when a message needs a delay, the application sends it to the matching delay topic.
  2. Poll: a separate consumer polls the delay topics and checks each message's timestamp.
  3. Forward: once the current time is past the intended delivery time (timestamp plus delay), the consumer produces the message to the real topic, where normal consumers process it.

The costs are managing many topics for different delays and the overhead of monitoring and checking timestamps.

2. Kafka Streams with a state store

Kafka Streams is a client library for applications whose input and output live in Kafka. It allows finer control over delays:

  • Read from the source topic in a Kafka Streams application.
  • Use a transformer that puts each message, which carries its delivery timestamp, into a state store.
  • Periodically (by wall-clock or stream time), pull the messages that are due out of the store and send them to the target topic.
java
1StreamsBuilder builder = new StreamsBuilder();
2builder.addStateStore(Stores.keyValueStoreBuilder(
3        Stores.persistentKeyValueStore("msg-store"), Serdes.String(), Serdes.String()));
4KStream<String, String> sourceStream = builder.stream("source-topic");
5
6sourceStream.transform(() -> new Transformer<String, String, KeyValue<String, String>>() {
7   private ProcessorContext context;
8   private KeyValueStore<String, String> store;
9
10   @Override
11   public void init(ProcessorContext context) {
12       this.context = context;
13       this.store = (KeyValueStore<String, String>) context.getStateStore("msg-store");
14       context.schedule(Duration.ofMinutes(1), PunctuationType.WALL_CLOCK_TIME, this::punctuator);
15   }
16
17   @Override
18   public KeyValue<String, String> transform(String key, String value) {
19       store.put(key, value);
20       return null;
21   }
22
23   private void punctuator(long timestamp) {
24       try (KeyValueIterator<String, String> it = store.all()) {
25           while (it.hasNext()) {
26               KeyValue<String, String> entry = it.next();
27               long delayUntil = Long.parseLong(entry.value.split(",")[1]);
28               if (delayUntil <= timestamp) {
29                   context.forward(entry.key, entry.value);
30                   store.delete(entry.key);
31               }
32           }
33       }
34   }
35
36   @Override
37   public void close() {}
38
39}, "msg-store").to("target-topic");

The value is expected as payload,deliveryTimestampMillis. transform() is deprecated by KIP-820 and removed in Kafka 4.0, where the same logic goes in process() with an api.Processor.

3. External systems

For complex requirements or very long delays (days or weeks), an external system can be more efficient:

  • Database or key-value store: save delayed messages with a timestamp and have a scheduled job or notifier push due messages to Kafka.
  • A queue with built-in delay, such as RabbitMQ or AWS SQS: use it only for the delay, then publish the messages back into Kafka for processing.

Trade-offs to watch

  • Accuracy vs resources: checking more often gives more accurate timing but uses more resources.
  • Error handling: handle failures carefully, especially when messages flow from an external system back into Kafka.
  • Monitoring: track delays, processing times and backlogs in every part of the delay pipeline.

Which approach fits depends on delay length, the volume of delayed messages and how precise the timing must be: a Kafka-only design for simple cases, an external service for the rest.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design