Prompt
How do I stream and process millions of events per second?
Latest observation
To stream and process millions of events per second, you need to design for throughput, parallelism, low latency, backpressure, and failure tolerance from the start. The main idea is: don’t process events one-by-one in a single place—build a distributed pipeline with batching, partitioning, and stateless or near-stateless workers.
1) Start with the right architecture
A common high-throughput pattern is:
Producers → Durable log / broker → Stream processors → Storage / sinks
Examples:
- Kafka / Pulsar / Kinesis as the event backbone
- Flink / Spark Structured Streaming / Kafka Streams / Beam for processing
- Fast sinks like ClickHouse, Cassandra, Elasticsearch, S3/data lake, Redis, or custom services
Why this works:
- Producers can write quickly without waiting for downstream systems.
- Brokers buffer bursts and enable replay.
- Stream processors scale horizontally.
- Sinks can be isolated from ingestion pressure.
2) Partition everything
To get millions of events/sec, your system must be able to process in parallel.
Key rule:
Use a partition key that distributes load well.
Examples:
- user ID
- device ID
- tenant ID
- session ID
Benefits:
- Events for the same key stay ordered.
- Work is split across many partitions and consumers.
Watch out for:
- Hot keys causing one partition to overload.
- Skewed traffic patterns.
If you have hot keys, use:
- key salting
- sub-partitioning
- local aggregation
- separate handling for top heavy hitters
3) Batch aggressively, but keep latency acceptable
Per-event network and serialization overhead kills throughput.
Use:
- batch writes from producers
- batched consumption
- bulk inserts to databases
- vectorized processing where possible
Typical optimizations:
- larger producer batches
- compression like LZ4 or Snappy
- fewer synchronous acknowledgments
- asynchronous I/O
Tradeoff:
- Larger batches improve throughput
- But increase latency
You need to choose the batch size based on SLA.
4) Keep processing stateless when possible
Stateless tasks scale much better.
Examples of good stateless operations:
- filtering
- enrichment from in-memory caches
- simple transforms
- routing
If you need state:
- use a stateful stream processor
- keep state local and checkpoint it
- use RocksDB or embedded state stores
- design for recovery and replay
Common stateful operations:
- windowed counts
- joins
- deduplication
- anomaly detection
- sessionization
5) Use backpressure and flow control
At high scale, some component will slow down.
You need:
- backpressure in stream processors
- bounded queues
- retry policies with jitter
- circuit breakers
- load shedding for non-critical work
Without backpressure:
- memory grows unbounded
- latency spikes
- failures cascade
6) Choose efficient data formats
Serialization overhead matters a lot.
Prefer:
- Protobuf
- Avro
- FlatBuffers
- compact binary formats
Avoid:
- verbose JSON for the hot path, unless convenience matters more than cost
Also:
- keep events small
- avoid large nested structures
- split large payloads from metadata
7) Scale consumers horizontally
A typical setup:
- many consumer instances
- each handles one or more partitions
- autoscaling based on lag, CPU, or throughput
Important:
- partition count must be high enough to allow scaling
- consumer group rebalance cost can hurt at large scale
- keep processing idempotent so retries are safe
8) Make sinks fast and resilient
Often the bottleneck is not the broker—it’s the destination.
For sinks:
- use bulk upserts or append-only writes
- avoid per-event database transactions
- use separate sinks for analytics and operational workloads
- write raw data to object storage for cheap long-term retention
For very high throughput, common sinks include:
- ClickHouse for analytics
- S3 + Iceberg/Delta/Hudi for lakehouse storage
- Cassandra/ScyllaDB for high-write workloads
- Redis for low-latency ephemeral state
9) Build for at-least-once, then deduplicate if needed
Exactly-once processing is expensive and sometimes unnecessary.
A practical approach:
- aim for at-least-once
- make consumers idempotent
- use event IDs and deduplication
- checkpoint progress
This is simpler and often much faster.
10) Measure the whole pipeline
You can’t optimize what you don’t measure.
Track:
- end-to-end latency
- broker lag
- consumer lag
- CPU, memory, GC pauses
- batch sizes
- serialization time
- sink write latency
- dropped/retried events
- partition skew
Use:
- distributed tracing
- structured logs
- metrics dashboards
- load testing with realistic traffic
11) Avoid common bottlenecks
Common bottlenecks:
- too few partitions
- hot partitions
- sync calls in the hot path
- small batch sizes
- slow serialization
- chatty microservices
- expensive joins against remote databases
- GC pressure from too many allocations
- shared locks or single-threaded components
12) A practical reference design
For millions of events/sec:
-
Producers
- async batching
- compression
- idempotent writes
-
Broker
- Kafka/Pulsar with many partitions
- replication for durability
-
Processors
- Flink/Kafka Streams
- keyed partitioning
- local state for windows/joins
- checkpointing
-
Sinks
- batch writes to ClickHouse/Cassandra/S3
- async retries
- idempotent upserts or append-only storage
-
Ops
- monitor lag, skew, throughput, error rates
- autoscale consumers
- replay from the broker if needed
13) If you need ultra-low latency
If you need sub-millisecond or very low-millisecond processing:
- minimize hops
- use in-memory state
- pin threads / CPU affinity in some cases
- avoid GC-heavy runtimes on the critical path
- use kernel-bypass / high-performance networking only if truly necessary
- consider C++/Rust/Java tuned for low latency
But for most cases, a well-designed Kafka + Flink-style architecture is enough.
Rule of thumb
To hit millions of events/sec, prioritize:
- Horizontal scaling
- Partitioning
- Batching
- Compression
- Backpressure
- Idempotency
- Efficient sinks
- Observability
If you want, I can also give you:
- a reference architecture diagram
- a Kafka/Flink example setup
- a capacity planning formula for events/sec
- or advice tailored to your language/cloud stack.