Search RU
Tasks / Kafka / Routing failed messages to a DLQ
Statement medium

Routing failed messages to a DLQ

`route_failed(message, attempts, max_attempts, dlq_topic)` decides what happens
to a message whose processing failed.

`Message` is a dataclass with `topic`, `key`, `value` and `headers`;
`headers` is a `str -> str` dict. `attempts` is the number of failed attempts so
far (`>= 0`), `max_attempts` is the limit (`>= 1`).

The function returns a dict with exactly three keys:

```python
{"action": "retry", "message": message, "attempts": attempts}
```

`attempts` in the result is the same number that was passed in; the function
does not increment it.

Decision order:

1. **drop** — if `message.topic == dlq_topic` or `headers` already contains the
`dlq-original-topic` key. The message has already been in a DLQ and must not
be routed again. Return the original `message`.
2. **retry** — if `attempts < max_attempts`. Return the original `message`
unchanged.
3. **dlq** — if `attempts >= max_attempts`, including `attempts` above the
limit. Return a new `Message`:
- `topic = dlq_topic`;
- `key` and `value` are copied from the original;
- `headers` is a copy of the original headers plus `dlq-original-topic` (the
source topic) and `dlq-attempts` (`str(attempts)`);
- a metadata header is added only when the key is absent: an existing value
is never overwritten;
- the original message and its `headers` are not mutated.

Errors — `ValueError`:

- `message` is not a `Message`;
- `message.topic` is empty or whitespace-only;
- `message.key` or `message.value` is not a string;
- `message.headers` is not a dict or contains non-string keys/values;
- `attempts` is not an integer (`bool` does not count) or is negative;
- `max_attempts` is not an integer (`bool` does not count) or is less than `1`;
- `dlq_topic` is empty or whitespace-only.

Write tests: retry below the limit and on the last allowed attempt, DLQ at and
above the limit, a message already in the DLQ (by topic and by header), key and
header preservation, no mutation of the original message, an empty topic and
argument validation.

Python
kafkadlqretryheadersrouting
test_solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

How do you tell a message that has already been in a DLQ from a regular one? Where can that information live?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts