Search RU
Tasks / Kafka / Partitioning by key
Statement medium

Partitioning by key

Implement two functions for a Kafka partitioner.

`partition_for_key(key, partitions)`:

- `partitions` is an integer greater than zero, otherwise `ValueError`;
- `key` is a non-empty string;
- the partition number is
`int(sha256(key.encode("utf-8")).hexdigest(), 16) % partitions`;
- the same key always lands in the same partition.

`group_by_partition(records, partitions)`:

- `records` is a list of `(key, value)` pairs;
- return a dict `{number: [(key, value), ...]}` for every partition from `0` to
`partitions - 1`, even when the input is empty;
- the order of records inside a partition is preserved;
- an empty list of records yields empty lists for every partition.

kafkapartitioninghashing
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 has to stay the same for a given key across runs: the partition number or
the broker number?

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