Imagine millions of cars emitting telemetry to a service that uploads each event to a Kafka topic. A topic is split into partitions, and every event has to be routed to exactly one of them. How you assign partitions determines both load balance and ordering guarantees.
The standard approach for a keyed message is: hash the key, then take the hash modulo the partition count. Keying by car_id guarantees that all events from a given car always land on the same partition — which is what preserves per-car ordering. For a message with no key, the producer spreads load with a simple round-robin.
You are given the mmh3 library (MurmurHash3). Implement KafkaPartitioner:
__init__(self, num_partitions: int)assign_partition(self, key: str | None) -> int:
key is not None: return abs(mmh3.hash(key, seed=42)) % num_partitions. This must be deterministic — the same key always maps to the same partition.key is None: return the next partition in round-robin order, starting from 0 and wrapping at num_partitions.You do not implement the hash function yourself — call mmh3.hash(key, 42). Note that mmh3.hash returns a signed 32-bit int, so wrap it in abs() before taking the modulus.
Example (num_partitions = 10):
assign_partition("car_1")→ 3assign_partition("car_2")→ 8assign_partition("car_3")→ 7assign_partition(None)→ 0, then 1, then 2, ... (round-robin)
Constraints:
1 <= num_partitions <= 10^642Official solution locked
Give the problem a real attempt before peeking — revealing it affects your credit for this problem for 4 hours.