Batch and stream processing
Overview
Operational databases answer questions about one user or one order. Many questions are about everything: total sales per region, trending videos, fraud patterns, creator payouts. Those need data pipelines that process large volumes, either in periodic batches or continuously as streams. Design problems involving analytics, counters, recommendations or notifications often need one or both.
Two ways to process data
Batch processing
A batch job reads a large, bounded dataset (yesterday’s events, the whole orders table), computes something and writes the results.
- Storage: raw data lands in a data lake (object storage, often in columnar formats like Parquet, partitioned by date); cleaned and modelled data goes to a data warehouse (BigQuery, Snowflake, Redshift, ClickHouse) for SQL analysis.
- Engines: Spark, warehouse SQL (often managed with dbt), historically Hadoop MapReduce. They split the work across many machines: map (process each record independently), shuffle (group by key), reduce (aggregate each group).
- Orchestration: schedulers such as Airflow or Dagster run jobs in order and retry failures.
Strengths: huge throughput, simple mental model, easy to rerun when logic changes (jobs should be idempotent and deterministic). Weakness: results are hours or a day old.
Stream processing
A stream job processes an unbounded sequence of events as they arrive, typically from Kafka or Kinesis.
- Engines: Apache Flink, Kafka Streams, Spark Structured Streaming, cloud dataflow services.
- Stateless operations (filter, transform, enrich each event) are simple.
- Stateful operations (counts, joins, detecting patterns) keep state, which must be checkpointed so the job can recover after a crash without losing or double-counting.
Strengths: results in seconds: live dashboards, fraud alerts, trending topics, real-time counters. Weaknesses: more complex to build, test and operate.
Time, windows and watermarks
Streams aggregate over windows:
- tumbling: fixed, non-overlapping (every minute),
- sliding: overlapping (the last 5 minutes, updated every minute),
- session: bursts of activity separated by gaps of inactivity.
Events carry an event time (when it happened) that differs from processing time (when it arrived); mobile events can arrive minutes late. A watermark is the stream’s estimate that “all events up to time T have probably arrived”, which tells the job when to close a window. Late events beyond the allowed lateness are dropped, sent to a side output, or used to update results.
Combining batch and stream
- Lambda architecture: a speed layer (stream) gives fresh, approximate results; a batch layer periodically recomputes exact results from the raw data; queries merge both. Accurate and fresh, but the logic is written twice.
- Kappa architecture: a single streaming pipeline over a replayable log; to fix a bug or change logic, replay the log through a new version of the job. Simpler, if the stream engine and retention allow it.
In practice, many teams use streams for real-time features and batch for authoritative reports and billing.
Good pipeline habits
- Keep raw events (immutable, in cheap storage) so you can reprocess and answer new questions.
- Make jobs idempotent: rerunning a day overwrites that day’s output rather than adding to it.
- Define schemas and evolve them compatibly (a schema registry helps).
- Monitor freshness (how old is the latest data?) and completeness, not just job success.
- For approximate counting at huge scale, use sketches such as HyperLogLog (distinct counts) and Count-Min Sketch (frequencies).
In an interview
For analytics-heavy features: “Events go to Kafka partitioned by video ID. A Flink job keeps live counts in Redis with 10-second windows. Raw events are archived to S3, and a nightly Spark job deduplicates and filters bots to produce the exact counts used for creator payouts.”
Recap
Batch jobs process bounded datasets periodically with high throughput and easy reruns; stream jobs process events continuously for results in seconds, using windows and watermarks to handle time and late data. Keep raw events in a data lake, make jobs idempotent, and combine both approaches where you need freshness and accuracy, through Lambda or Kappa-style architectures.
Count video views
A video platform needs: (1) a live view counter on each video that updates within a few seconds, (2) accurate daily view counts per video for paying creators, excluding bots and duplicate views, and (3) a monthly report of top videos by country. Events arrive at 500,000 views per second at peak. Design the data processing: which parts are stream and which are batch, and how they fit together.
Event collection:
Live counter (stream):
Accurate daily counts (batch):
Monthly report:Event collection: clients/servers send view events to an ingestion API that writes to
Kafka (topic partitioned by video_id). Events are also archived to the data lake
(object storage, partitioned by date) for batch processing and replay.
Live counter (stream): a Flink/Kafka Streams job aggregates views per video in short
windows (e.g. 5-10 s tumbling windows) and adds them to counters in Redis or a
key-value store; the video page reads the counter. Approximate: no full bot filtering,
late events handled by watermarks with small allowed lateness.
Accurate daily counts (batch): a daily Spark/SQL job over the lake's raw events for
that day: deduplicate by (viewer, video, session), filter bots using fraud signals,
then write final counts to the warehouse and to the payouts system. This corrects any
stream inaccuracy.
Monthly report: SQL over the warehouse (BigQuery/Snowflake/ClickHouse) aggregating
daily counts by country; scheduled monthly.Summary
- Batch processing handles large, bounded datasets periodically: high throughput, simple to rerun, but results are hours old.
- Stream processing handles unbounded event streams continuously, producing results in seconds.
- Streams group events into windows (tumbling, sliding, session) and use watermarks to handle late, out-of-order events.
- Raw events are kept in a data lake (object storage) so jobs can be rerun and new questions answered later.
- Lambda architecture runs both a batch and a speed layer; Kappa uses a single replayable stream for both.