Video in progress
You want to use Kafka to deliver real-time events to clients. Can you make a separate topic for each user, and if not, how do you build it?
A topic or partition per user is unfit for Kafka: it breaks under metadata and the number of open files. The right way is a small number of topics, partitioning by userId, and splitting out to the user in the gateway or delivery layer.
📖 Answer
In Kafka every partition is a set of separate segment files on disk, open file handles on the broker, and an entry in the controller metadata. A million topics will kill the cluster. KRaft mode raised the limit, but a number of partitions equal to the number of users is never the right design.
A scheme that works:
user-events (128 partitions, key = userId)
│
▼
delivery-service (consumer group, up to 128 instances)
│ routing table: userId -> gateway
▼
gateway-{id} (each gateway's private channel: Redis or a gRPC stream)
Because the key is userId, one user's events land in one partition and order is preserved. The delivery service splits the partitions among itself through the consumer group.
The delicate point is when to commit the Kafka offset: after handing off to the gateway, or after writing to the inbox? I write to the inbox and then commit, and treat the real-time push as "best effort". If a gateway goes down, the client reconnects and gets it from the inbox. That way the Kafka consumer doesn't stall because of slow clients.
Why don't gateways read directly from Kafka? If every gateway reads the whole topic, 50 gateways means 50 times the read traffic, and each one finds only ~2% of it useful. Splitting partitions among gateways doesn't work either: which gateway a user connects to is decided by the load balancer, not by the partition.
Kafka's value here is buffering and replay. If the delivery service goes down for an hour, events aren't lost. But Kafka adds from a few milliseconds up to tens of milliseconds to end-to-end latency (batching, linger.ms). Where 100 ms matters, like chat, tune the producer settings for latency.
Sign up to mark studied questions and save your progress.