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