SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Batch vs Stream Processing
  • Change Data Capture (CDC)
  • MapReduce
  • ETL Pipelines
  • Data Lakes
  • Data Warehousing
  • Data Lakehouse
  • Lambda Architecture
  • Kappa Architecture
  • Streaming Engines
  • Spark and Hadoop
  • Workflow Orchestration (Airflow)
  • Parquet and Columnar File Formats
  • Data Governance and Feature Stores
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Big Data Processing

Batch vs Stream Processing

Process data in big chunks later, or one event at a time as it arrives.

⏱ 13 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

There are two ways to process data. Batch processing collects data for a while and processes it in one big job. Stream processing handles each event as soon as it arrives.

  • Batch: high throughput, simple, cheap. Results are late (minutes to hours old).
  • Stream: low latency, results within seconds or less. More complex, and it must run all the time.
  • The choice depends on one question: how fresh must the answer be?

02Concept: What is it?

Data does not always arrive in neat files. Clicks, payments, sensor readings and logs flow in continuously. We can treat this data in two ways.

Batch processing works on a bounded set of data: all of yesterday's orders, for example. A job reads the whole set, computes the result and stops. It usually runs on a schedule (every hour, every night).

Stream processing works on an unbounded flow of events that never ends. A job runs all the time, updates its result with each event, and answers with low delay. Because the stream has no end, it usually computes over windows (for example, the last 5 minutes).

Batch and stream side by side
Batch
πŸ“₯Collecthours of data
→↓on a schedule
βš™οΈBig joball at once
→↓
πŸ“ŠResultminutes or hours late
Typical delay to a resultminutes to hours
Stream
⚑Eventone at a time
→↓right away
βš™οΈAlways-on job
→↓
πŸ“ŠResultseconds or less
Typical delay to a resultmilliseconds to seconds
Batch waits and then works in bulk. Stream works on each event as it arrives.
🧠A batch is just a stream with a very big window
You can see a batch job as processing a stream that has been cut into big pieces. Many modern engines can do both with the same code.

03Real-Life Example

🍡The Laundry and the Water Tap
A laundry shop collects dirty clothes all day. At night it runs one big wash. Each load is efficient and cheap per shirt, but a customer who drops a shirt in the morning only gets it back the next day. That is batch. A water tap works the other way: each drop of water is available as soon as it flows, but the pipes must be open all the time. That is stream.
Laundry and tap
Data processing
Dirty clothes piling up all day
Events collected into a batch
One big wash at night
A scheduled batch job
Cheap per shirt, but slow to return
High throughput, high latency
Water flowing through open pipes
A stream job that is always running
Each drop usable at once
Each event processed right away
Counting water used in the last minute
A window over the stream
A pipe that cannot carry a sudden flood
A stream job that falls behind on a spike
Same question, two answers
πŸ›’Orders arriveall day long
↓
πŸŒ™Batchsales report next morning
↓
⚑Streamsales counter updates live

04Why Do We Need It?

⏱️Freshness
Fraud checks, alerts and live dashboards cannot wait for tomorrow's job. Stream gives answers while they still matter.
πŸ’°Cost and simplicity
Reports, billing and model training rarely need live answers. A batch job is simpler and uses machines only while it runs.
πŸ“ˆThroughput
Reading a huge set in one go is very efficient, so batch can chew through enormous volumes.
πŸ”Reprocessing
Batch makes it easy to re-run history after fixing a bug or changing a rule.
🌊Never-ending data
Sensors, clicks and logs have no end. Stream fits data that never stops.
🧩Right tool for each job
Most companies use both: stream for what is happening now, batch for deep analysis.
Choose by freshness. If the answer is useless an hour from now, stream it. If tomorrow is fine, batch is simpler and cheaper.

05Where Do We Use It?

🧾Batch: reports and billing
Daily sales reports, monthly invoices, payroll and data warehouse loads.
πŸ€–Batch: machine learning
Training a model on months of data, and scoring many records at once.
🚨Stream: fraud and alerts
Flag a suspicious card payment before it completes, or alert when errors spike.
πŸ“ŠStream: live dashboards
Active users right now, orders per minute, delivery tracking.
πŸ””Stream: reacting to events
Send a notification when something happens, or update a search index as data changes.
🌑️Stream: IoT and logs
Sensor data and application logs are processed as they flow in.

06Types / Parts / How It Works

Comparing the two

BatchStream
InputA bounded set (a file, a table, a day of data)An unbounded flow of events
When it runsOn a schedule or on demand, then stopsAll the time
LatencyMinutes to hoursMilliseconds to seconds
ThroughputVery high, reads data in bulkHigh, but limited by how fast events can be handled
ComplexitySimpler to write, test and rerunHarder: ordering, state, late events, failures
Cost shapePay while jobs runPay for always-on capacity
Typical toolsHadoop MapReduce, Spark batch, SQL on a warehouseKafka Streams, Apache Flink, Spark Structured Streaming

Ideas you meet only in streams

IdeaMeaningWhy it matters
WindowA slice of the stream to aggregate over (tumbling, sliding, session)A stream never ends, so counts need a time frame.
Event time vs processing timeWhen it happened vs when we saw itEvents can arrive late or out of order.
WatermarkThe system's estimate of how far event time has progressedDecides when a window can be closed and its result emitted.
StateData the job remembers between events (counts, sums)Must survive crashes, so it is checkpointed.
Delivery guaranteesAt most once, at least once, exactly onceDecides whether results can be lost or counted twice.
BackpressureA slow job tells the source to slow downPrevents overload and a growing backlog.
Three kinds of window
Tumbling
🟦Fixed, no overlapevery 5 min
Sliding
πŸŸͺFixed, overlappinglast 5 min, every 1 min
Session
🟩Ends after a quiet gapone user visit
Tumbling Sliding Session
The same stream can be cut in different ways.
VisualizerHow old is the result? Batch vs streamSlide the batch interval from 30 s down to 5 s and watch the saw-tooth shrink. Then turn on the spike and push the event rate up, and see the stream fall behind.
Traffic
Batch: how old is the newest result? (amber, one bar per second, the saw-tooth is the wait for the next job)
Stream: how old is the newest result? (cyan)
0 s30 s60 s
Both charts use the same scale: the tallest bar is 26.0 seconds old.
Batch: average age
14.5 s
worst 26.0 s
Stream: average age
0.2 s
worst 0.2 s
Batch compute
12 s
of 60 s, jobs only
Stream compute
60 s
always running
Batch results are 14.5 s old on average, stream results 0.2 s. Batch is simpler and used only 12 s of compute, but you wait for the next window. Make the interval shorter and the gap shrinks (each job still has a 3 s start-up cost).

A simplified model with no random numbers. A batch job starts when its window ends and takes 3 s plus 4 ms per event. The stream job answers in about 0.2 s and can handle 150 events per second. Real numbers depend on the system.

07How to Use It / Steps / Implementation

Choosing and running one or the other

  1. 1
    Ask how fresh the answer must be
    Write it down: seconds, minutes, hours or a day. This one number drives the choice.
  2. 2
    Check the data shape
    A finite table or file points to batch. An endless flow of events points to stream.
  3. 3
    Start with batch if you can
    If an hourly or daily result is enough, a batch job is simpler to build, test and fix.
  4. 4
    Use stream when delay costs money
    Fraud, alerts, live ranking and monitoring need answers in seconds. Pick a streaming engine and a log such as Kafka as the source.
  5. 5
    Design for failure
    Make jobs safe to re-run (idempotent). In streams, checkpoint state and decide between at-least-once and exactly-once.
  6. 6
    Handle late and out-of-order events
    Use event time, windows and watermarks, and decide what to do with events that arrive after a window closed.
  7. 7
    Monitor lag
    For batch, watch job duration against the schedule. For stream, watch consumer lag and the age of results.
πŸ’‘Many systems use both
A common setup streams events for live numbers and also stores them for a nightly batch job that computes exact, corrected results. Lambda and Kappa architectures are two ways to organise this.
βš οΈβ€œReal time” is a range
Sub-second, a few seconds and a few minutes are all called real time by someone. Agree on the actual number before you choose a design.

08Key Terms to Know

TermMeaning in easy words
Batch processingProcessing a bounded set of collected data in one job
Stream processingProcessing events continuously, as they arrive
Bounded / unbounded dataA data set with an end (bounded) or an endless flow of events (unbounded)
LatencyHow long it takes from an event happening to a result being available
ThroughputHow much data is processed per unit of time
WindowA slice of a stream (by time or count) used for an aggregate
Event timeThe moment an event really happened
Processing timeThe moment the system handles the event
WatermarkAn estimate of how far event time has progressed, used to close windows
CheckpointA saved copy of a job's state, used to recover after a crash
BackpressureA slow consumer signals the source to slow down

09Pros, Cons and Trade-offs

βœ… Pros
  • Batch: simple, cheap and efficient on huge data
  • Batch: easy to re-run and to debug
  • Stream: results within seconds or less
  • Stream: reacts to events as they happen
  • Stream: spreads work evenly over time
⚠️ Cons
  • Batch: results are always late
  • Batch: a big job failing late wastes hours
  • Stream: harder to build, test and operate
  • Stream: needs always-on capacity
  • Stream: late and out-of-order events complicate results

Trade-offs

ChoiceWe gainWe lose
Batch every daySimplicity and low costAnswers up to a day old
Batch every few minutes (micro-batch)Fresher answers, simple modelMany small jobs, each paying start-up cost
True streamLowest delayComplexity, always-on cost
Exactly-once resultsNo lost or double countsExtra coordination and some overhead
At-least-once resultsSimpler and fasterDuplicates unless your logic handles them
Both (batch and stream)Live view and exact historyTwo pipelines to build and keep consistent

10Common Problems and Mistakes

Common mistakes

  1. Streaming everything. Many reports do not need live data. Stream adds cost and complexity for no gain.
  2. Batching what needs speed. A fraud check that runs overnight stops nothing.
  3. Using processing time for business logic. A delayed event lands in the wrong window. Use event time.
  4. Ignoring late events. Decide how long to wait and what to do with stragglers.
  5. Jobs that are not safe to re-run. A retry then double-counts. Make the output idempotent.
  6. No headroom for spikes. A stream job at its limit builds a backlog and results get older and older.

Things to watch

🐒Consumer lag
Events arrive faster than they are handled. Results grow stale. Add capacity or reduce work.
πŸ•³οΈState size
A long window or many keys makes the job's state huge, with slow checkpoints.
⏰Batch overrun
A job that takes longer than its schedule interval starts piling up.
βš–οΈTwo answers
A live number and a nightly number disagree. Explain why, and prefer one source of truth.

11Real-World Examples

🐘Hadoop and Spark
Classic batch engines for processing very large data sets on clusters of machines.
🌊Kafka and Flink
Kafka stores event logs, and engines such as Flink and Kafka Streams process them as streams.
⚑Spark Structured Streaming
Treats a stream as a table that grows, often running small micro-batches.
πŸ’³Payments
Card networks and banks score transactions in streams, then settle in batches.
πŸš•Ride apps
Live driver locations and surge prices come from streams. Earnings reports come from batch jobs.
🎬Video platforms
View counts update live, while recommendation models are retrained in batch.
πŸ“Note
Products blur the line: many engines handle both batch and stream. Look at the guarantees and the latency you need, not at the label.
Mini case: an online shop
πŸ›’Order events
→↓log
πŸ“¨Kafka
↓stream
πŸ“ŠLive dashboardseconds old
↓nightly batch
🧾Finance reportexact, next morning
Stream path Batch path Shared log
The same events feed both a live view and a nightly report.

12Related Topics to Read Next

MapReduce→

The classic batch model for splitting a huge job over many machines.

Streaming Engines→

The engines that run stream jobs: Flink, Kafka Streams, Spark Streaming.

Lambda Architecture→

Runs a batch path and a stream path side by side.

Kappa Architecture→

Uses only a stream path and replays the log to recompute.

Change Data Capture (CDC)β†’

Turns database changes into a stream of events.

Message Queues→

A common source and buffer for streams of events.

ETL Pipelines→

Often built as scheduled batch jobs, or as streaming pipelines.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Batch: bounded data, runs on a schedule, high throughput, results are late.
  • βœ”Stream: unbounded events, always running, low latency, harder to build.
  • βœ”Choose by: how fresh must the answer be? Seconds means stream. Hours or days means batch.
  • βœ”Windows: tumbling, sliding, session. Needed because a stream never ends.
  • βœ”Time: use event time. Watermarks decide when a window is complete.
  • βœ”Safety: make jobs idempotent, checkpoint state, pick at-least-once or exactly-once.
  • βœ”Tools: Hadoop and Spark for batch. Kafka, Flink and Spark Structured Streaming for stream.
  • βœ”One line: β€œBatch is cheap and late. Stream is fast and always on. Pick by how fresh you need it.”
← Previous
MinHash
Next β†’
Change Data Capture (CDC)