Design a Distributed Stream Processing System like Kafka
1. Introduction
A Distributed Stream Processing System is the backbone of modern data infrastructure. It enables organizations to publish, subscribe to, store, and process streams of records in real-time at massive scale. Apache Kafka, the de facto standard in this space, processes over 7 trillion messages per day at LinkedIn alone.
Consider the scale of Uber's event streaming platform: every ride request, GPS update, payment transaction, and driver location change generates an event. These events flow through a stream processing system that powers real-time pricing, ETA calculations, fraud detection, and driver dispatch. Without a robust stream processing system, these real-time features would be impossible.
The Problem
Traditional message queues (RabbitMQ, ActiveMQ) were designed for task queuing and RPC-style communication. They excel at decoupling producers and consumers but struggle with:
- Throughput: Processing millions of messages per second across distributed systems.
- Replay: Re-reading historical messages for debugging or reprocessing.
- Retention: Storing days or weeks of message history for batch processing.
- Ordering: Maintaining message order across partitions while scaling horizontally.
- Exactly-Once: Ensuring each message is processed exactly once despite failures.
Business Motivation
- Real-Time Analytics: Process clickstream data, calculate metrics in real-time.
- Event Sourcing: Maintain complete audit trail of all state changes.
- Microservices Communication: Decouple services with asynchronous event-driven patterns.
- Data Integration: Connect heterogeneous systems through a common data backbone.
- Machine Learning Pipelines: Feed real-time data to ML models for inference.
Real-World Examples
- LinkedIn: Kafka was invented here. Handles 7 trillion messages/day, 4 petabytes of data daily.
- Netflix: Uses Kafka for real-time monitoring, A/B testing, and content delivery.
- Uber: M3 (metrics) and Kafka process trillions of events for ride matching and pricing.
- Airbnb: Kafka powers real-time search indexing, pricing, and fraud detection.
- Goldman Sachs: Uses Kafka for trade execution, risk management, and compliance.
- Twitter: Kafka processes billions of events for timeline generation and trending topics.
Evolution of Stream Processing
- Message Queues (1990s): IBM MQ, TIBCO. Point-to-point, low throughput.
- Enterprise Service Bus (2000s): Centralized routing, transformation, orchestration.
- Log-Based Messaging (2010s): Kafka introduced distributed commit log. Decoupled storage from processing.
- Stream Processing Frameworks (2015+): Apache Flink, Spark Streaming, Kafka Streams. Stateful processing at scale.
- Cloud-Native Streaming (2020+): Confluent Cloud, AWS Kinesis, Azure Event Hubs. Managed services.
- Real-Time Data Platforms (2023+): Apache Pulsar, Redpanda. Unified batch and stream processing.
2. Real Interview Context
This is one of the most commonly asked system design questions because it tests fundamental distributed systems concepts while being deeply practical.
Companies That Ask This Question
| Company | Variation | Level |
|---|---|---|
| Design Kafka's successor | Staff+ | |
| Confluent | Design a managed Kafka service | L5-L6 |
| Uber | Design real-time event streaming | Staff+ |
| Netflix | Design event-driven architecture | L6-L7 |
| Amazon | Design Kinesis streaming backend | SDE III |
| Design Cloud Pub/Sub | L5-L6 | |
| Apple | Design real-time data pipeline | ICT4-ICT5 |
| Stripe | Design payment event streaming | Staff+ |
Skills Being Evaluated
- Storage Engine Design: Append-only log, segment files, indexing.
- Distributed Coordination: Partitioning, replication, leader election.
- Consistency Models: At-least-once, exactly-once, ordered delivery.
- Consumer Group Protocol: Partition assignment, rebalancing, offset management.
- High Availability: Replication, failover, data durability.
- Performance Engineering: Zero-copy, batching, compression, page cache.
Common Mistakes
- Confusing with Message Queue: Designing a task queue instead of a log-based streaming system.
- Ignoring Ordering: Not discussing how ordering is maintained across partitions.
- Skip Consumer Groups: Not explaining how consumers coordinate and rebalance.
- No Durability: Not discussing how data survives node failures.
- Forget Offset Management: Not explaining how consumers track their position in the log.
3. Functional Requirements
Core Messaging (FR-01 to FR-15)
- FR-01: Support creating and deleting topics (logical categories of messages).
- FR-02: Support partitioning of topics across multiple brokers for horizontal scaling.
- FR-03: Producers can publish messages to any partition within a topic.
- FR-04: Messages within a partition are strictly ordered by offset.
- FR-05: Messages are assigned monotonically increasing offsets within each partition.
- FR-06: Producers can specify a partition key for deterministic partition assignment.
- FR-07: Support batch publishing of multiple messages in a single request.
- FR-08: Messages are persisted to disk before acknowledgment (durability guarantee).
- FR-09: Support configurable replication factor per topic (1, 2, 3, or more).
- FR-10: Support configurable retention period per topic (time-based and size-based).
- FR-11: Support compacted topics (retain latest value per key for changelog semantics).
- FR-12: Support topic-level configuration for compression, cleanup policy, and segment size.
- FR-13: Support message headers/metadata in addition to key and value.
- FR-14: Support multiple serialization formats (JSON, Avro, Protobuf, raw bytes).
- FR-15: Support schema registry for schema evolution and validation.
Consumer Operations (FR-16 to FR-25)
- FR-16: Support consumer groups where multiple consumers share partition consumption.
- FR-17: Within a consumer group, each partition is consumed by exactly one consumer.
- FR-18: Support consumer group rebalancing when consumers join or leave.
- FR-19: Consumers can read from any offset (beginning, end, specific offset, timestamp).
- FR-20: Support manual offset commit for at-least-once processing.
- FR-21: Support automatic offset commit for simpler at-most-once processing.
- FR-22: Support consumer lag monitoring (distance between latest offset and consumer offset).
- FR-23: Support consumer pause/resume without leaving the group.
- FR-24: Support read replicas for consumers that need isolated read throughput.
- FR-25: Support dead letter queues for messages that fail processing after retries.
Cluster Operations (FR-26 to FR-35)
- FR-26: Support adding and removing brokers without downtime.
- FR-27: Support partition reassignment for rebalancing across brokers.
- FR-28: Support leader election for partition leadership changes.
- FR-29: Support controlled shutdown of brokers with leader migration.
- FR-30: Support topic creation with specified partition count and replication factor.
- FR-31: Support dynamic configuration changes without restart.
- FR-32: Support cluster metadata management (topic configs, broker configs, ACLs).
- FR-33: Support multiple data centers with cross-DC replication.
- FR-34: Support tiered storage (hot data on local disk, cold on object storage).
- FR-35: Support transactional writes across multiple partitions (atomic multi-partition publish).
4. Non-Functional Requirements
| Attribute | Requirement | Rationale |
|---|---|---|
| Throughput | 1 million messages/sec per broker, 100 million/sec cluster-wide | Enterprise workloads with millions of events per second |
| Latency | P99 end-to-end < 10ms for small messages (< 1KB) | Real-time applications require sub-10ms delivery |
| Durability | Zero data loss with acks=all and replication factor 3 | Messages are the source of truth for downstream systems |
| Availability | 99.99% uptime (52 min/year) | Central infrastructure; downtime affects all services |
| Scalability | Scale from 1 to 1000 brokers without re-architecture | Workload grows with business; seamless scaling required |
| Ordering | Strict ordering within a partition | Event sourcing and changelog patterns require ordering |
| Retention | Configurable from minutes to weeks (default 7 days) | Different use cases need different retention windows |
| Replay | Full replay capability from any offset | Debugging, reprocessing, and disaster recovery |
| Security | mTLS, SASL, ACLs, encryption at rest | Multi-tenant environments require strong security |
| Observability | Metrics, logging, tracing for all operations | Operational visibility is essential for debugging |
5. Requirement Prioritization
Must Have
- Topic creation with configurable partitions and replication
- Message publishing with partition key routing
- Consumer groups with partition assignment
- Persistent, ordered, replayable commit log
- Consumer offset tracking and management
- Replication for durability and availability
- Leader election for partition failover
- Configurable retention policies
Should Have
- Transactional writes across partitions
- Exactly-once semantics (producer + consumer)
- Schema registry integration
- Consumer lag monitoring
- Dynamic topic configuration
- Compacted topics for changelog semantics
- Dead letter queue support
Nice to Have
- Tiered storage (hot/cold)
- Cross-datacenter replication
- Kafka Streams API for stream processing
- Connect API for source/sink connectors
- Multi-tenancy with resource isolation
Out of Scope
- SQL query engine over streams (use ksqlDB separately)
- Machine learning model serving
- Full-text search over messages
- Complex event processing (CEP)
6. Capacity Estimation
Assumptions
| Parameter | Value | Justification |
|---|---|---|
| Number of topics | 10,000 | Enterprise with many microservices |
| Average partitions per topic | 12 | Balanced parallelism |
| Total partitions | 120,000 | 10,000 x 12 |
| Messages per second (cluster) | 10,000,000 (10M) | Large-scale event streaming |
| Average message size | 1 KB | Mixed: events, metrics, logs |
| Peak message size | 10 KB | Larger payloads for batch events |
| Replication factor | 3 | Durability requirement |
| Retention period | 7 days | Standard retention |
| Compression ratio | 3:1 | Gzip/LZ4 on similar data |
Storage Calculations
With Compression = 864 / 3 = 288 TB/day (compressed)
With Replication (3x) = 2,016 x 3 = 6,048 PB total storage
With 20 TB SSDs: need ~3 SSDs per broker (or use tiered storage for older data)
Broker Sizing
| Parameter | Per Broker | Calculation |
|---|---|---|
| Message throughput | 100K msg/sec | 10M / 100 brokers |
| Network throughput | 333 MB/s write, 1 GB/s read | Includes replication traffic |
| Disk IOPS | 50,000 | Sequential writes, batched flushes |
| Disk throughput | 1 GB/s write, 3 GB/s read | Sequential I/O pattern |
| CPU | 16 vCPU | Compression, network handling, replication |
| Memory | 64 GB | Page cache, broker state, network buffers |
| Network | 25 Gbps | Write + replication + consumer traffic |
Infrastructure Summary
| Component | Instances | Specs |
|---|---|---|
| Kafka Brokers | 100 | 16 vCPU, 64 GB RAM, 3x 20 TB NVMe |
| Controller Nodes (KRaft) | 5 | 8 vCPU, 32 GB RAM, 500 GB SSD |
| Schema Registry | 3 | 4 vCPU, 8 GB RAM |
| REST Proxy | 10 | 8 vCPU, 16 GB RAM |
| Connect Workers | 20 | 8 vCPU, 32 GB RAM |
| ZooKeeper/KRaft (if legacy) | 5 | 4 vCPU, 16 GB RAM, 500 GB SSD |