Video in progress

You need delayed jobs like "cancel the order if it isn't paid after 30 minutes". Kafka doesn't support delayed messages. How do you design it?

Kafka has no "deliver this message in 30 minutes" feature. If the delays are few and fixed, delay topics work (the consumer pauses the partition until the time comes); for varied and cancellable deadlines I prefer a scheduled-jobs table in the DB.

📖 Answer

First I pin down the requirements: are the delays the same (30 minutes for every order) or different? Does the job need to be cancellable (if the customer pays, the cancellation has to stop)? Are there millions of them?

Option 1: a delay topic. An orders.cancel-check.30m topic. The producer writes to it when an order is created. The consumer checks the time on every message:

@KafkaListener(topics = "orders.cancel-check.30m", groupId = "order-timeouts")
void on(ConsumerRecord<String, OrderCreated> rec, Acknowledgment ack) {   // AckMode.MANUAL
    long dueAt = rec.timestamp() + Duration.ofMinutes(30).toMillis();
    long wait = dueAt - System.currentTimeMillis();
    if (wait > 0) {
        // it will be re-read later, starting from this record
        ack.nack(Duration.ofMillis(Math.min(wait, 30_000)));
        return;
    }
    cancelIfUnpaid(rec.value().orderId());
    ack.acknowledge();
}

Messages within a partition are ordered by time, so if the first one is "early", the following ones are early too, and waiting works correctly. You have to split the wait into short pieces, otherwise max.poll.interval.ms is exceeded. @RetryableTopic does the same idea more neatly under the hood by pausing the partition. But that's only for a single, uniform delay. For different deadlines, a separate topic for each (5m, 30m, 24h). There's no cancellation either: when the time comes, the consumer checks the order status and quietly moves on if it's been paid.

Option 2: a DB table.

CREATE TABLE scheduled_jobs (id uuid PRIMARY KEY, kind text, due_at timestamptz,
  payload jsonb, status text);
CREATE INDEX ON scheduled_jobs (due_at) WHERE status = 'PENDING';

Every few seconds a scheduler picks up jobs with ... WHERE due_at <= now() AND status='PENDING' FOR UPDATE SKIP LOCKED LIMIT 100. The deadline can be anything, cancelling is a single UPDATE, and SQL answers "how many jobs are waiting?". There are ready-made libraries too (db-scheduler, Quartz JDBC). Kafka only distributes the result here: an OrderCancelled event.

I usually pick option 2 for business timers, and Kafka delay topics for technical delays like retries. With very high volume and complex timers, it's time to think about a workflow engine (Temporal).

In both cases, make the cancellation idempotent: if the job runs twice, the second run should see "already cancelled" and exit.