Search RU
Tasks / Kafka / Idempotent producer with a dedup store
Statement hard

Idempotent producer with a dedup store

`send_idempotent(producer, message, dedup_store)` publishes a message so that a
repeated call does not create a duplicate, and returns the record offset.

`Message` is a dataclass with `key` and `value` (both strings).

`producer.send(message)` returns the offset of the published record (an integer
`>= 0`) or raises `ProducerError`.

`dedup_store` holds already published messages:

```python
dedup_store.get(key, value) -> int | None # offset or None
dedup_store.put(key, value, offset) -> None
dedup_store.clear() -> None
```

Rules:

- the dedup key is the pair `(key, value)`. The same `key` with a different
`value` is a new message; the same `value` with a different `key` is also new;
- `get` returned an offset — return it and **do not call** `producer.send`;
offset `0` is as valid an answer as any other;
- `get` returned `None` — call `producer.send(message)`, remember the offset via
`put(key, value, offset)` and return it;
- do not catch `ProducerError`. Store nothing before the producer confirms:
the next call must retry the publish;
- `dedup_store` is the only source of truth. If the store was cleared with
`clear()`, the same message is published again and gets a new offset;
- `producer.send` returned a non-integer, a `bool` or a negative number —
`ValueError`, do not store the offset;
- `get` returned something other than `None` and a valid offset — `ValueError`;
- `message` is not a `Message`, `key` is empty or not a string, `value` is not a
string (empty is allowed) — `ValueError`;
- the original message is not mutated.

Write tests: the first send, a repeat without publishing, offset `0`, the same
key with a different payload, the same value with a different key, a producer
error and a retry after it, clearing the dedup store and argument validation.

Python
kafkaproduceridempotencydeduplicationoffsets
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

What happens on a repeat: call the producer again or return the old offset? Where does that offset come from?

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