SkillSprout
Chapter 4 · Lesson 8
Intermediate
9 min read

Batch vs Stream Processing

Overview

Data keeps arriving: clicks, payments, sensor readings. You can collect it and process it in large chunks every hour or night (batch), or process each event within seconds of arrival (stream). Batch is simpler and cheaper per record. Stream gives fresh answers. This lesson shows how to choose by the latency the business needs, how streaming windows work, and how real systems combine both.

Detailed Notes

What Problem Are We Solving?

Many systems must turn raw events into results: daily revenue reports, fraud alerts, trending topics, billing totals. The question is when to compute.

  • Batch processing: collect data for a period (an hour, a day) in storage, then run one large job over all of it. The job has a start and an end. Examples: a nightly report, training a model, monthly invoices. Tools: MapReduce and Spark jobs over files in object storage.
  • Stream processing: process each event (or tiny groups of events) continuously as it arrives, keeping results always up to date. The job never ends. Tools: Kafka Streams, Flink, Spark Streaming. The input is usually a log or queue such as the partitioned queues in the queues lesson.

A key concept in streaming is the window. A stream is endless, so to compute "clicks per minute" you cut it into time slices and aggregate each one. A tumbling window is a fixed, non-overlapping slice (every minute). A sliding window overlaps (the last 5 minutes, updated every minute). Events can arrive late or out of order, so streams distinguish event time (when it happened) from processing time (when we saw it) and use a watermark, a rule such as "assume no events older than 2 minutes will still arrive", to decide when a window is complete.

The latency need drives the choice.

text
Traffic: 1 billion events per day, 1 KB each
  1B / 100,000 s = 10,000 events per second (30,000 at peak)
  Storage per day = 1B x 1 KB = 1 TB

Batch (hourly job):
  Each run reads 1 hour = 10,000 x 3,600 = 36M events = 36 GB
  Result freshness: 1 to 2 hours old (wait for the hour, then run)
  A cluster that runs 10 minutes per hour is idle 80% of the time

Stream:
  Result freshness: a few seconds after the event
  Needs a cluster sized for 30,000 events per second, running 24 hours a day

Fraud detection at the moment of purchase needs seconds. A weekly business report does not.

Batch vs Stream
Comparison

Batch

process in chunks

  1. 1

    Events land in storage

    object store or warehouse

  2. 2

    Wait for the period to close

    hour or day

  3. 3

    Run one big job

    36 GB per hourly run

  4. 4

    Write results; rerun if wrong

    same input, same output

  • Simple and testable
  • Cheap per record, easy reruns
  • Handles big joins
  • Results are hours old
  • Spiky load

Best for reports, billing, backfills

Stream

process every event

  1. 1

    Events enter a durable log

    partitioned by key

  2. 2

    Workers update state per event

    windows, counters

  3. 3

    Results emitted continuously

    seconds after the event

  4. 4

    Checkpoint, replay on failure

    state saved regularly

  • Seconds-fresh results
  • Reacts to events
  • Even load
  • Complex, always-on cluster
  • Late data and state handling

Best for alerts and live metrics

Key point. Ask what freshness the decision needs. If hours are fine, batch is the cheaper and simpler answer.

Same 1 billion events per day, processed at different moments.

Option 1: Batch processing

How it works

Events land in cheap storage (object storage or a data warehouse) as they arrive. On a schedule, a job reads the whole chunk, transforms and aggregates it using many machines in parallel, and writes results to a table. If the job fails, you rerun it on the same input and get the same output, because the input is fixed.

Pros

  • Simple mental model. Fixed input, deterministic output, easy to test and debug.
  • Easy correction. If the logic had a bug, fix it and recompute history.
  • Efficient throughput. Large sequential reads and aggregations are the cheapest way per record, and clusters can be started only for the run.
  • Handles complex logic and joins across huge data sets (for example joining a year of orders with customers).
  • Late data is easy. Wait until the period closes, so everything has arrived.

Cons

  • Stale results. The answer is as old as the last run, minutes to a day.
  • Spiky resource use. Heavy load when the job runs. A big job over 24 hours of data must finish before the next one starts.
  • Delayed failure discovery. A bad input is found when the job runs, hours later.

When to use it

Choose batch when freshness measured in hours is acceptable and the work is large, complex or must be exactly reproducible: financial reports, billing, data warehouse loads, search index rebuilds, machine learning training, backfills.

Realistic scenario. An online store computes seller payouts. Every night at 2 a.m. a job reads the day's 5M order records (5 GB), subtracts refunds and fees and writes payout rows. Finance reviews the result in the morning. If a bug is found, the team fixes the job and reruns the day. Nobody needs payouts in real time, and the nightly cluster costs a few dollars.

Option 2: Stream processing

How it works

Producers append events to a durable log, partitioned by a key such as user id so related events go to the same worker. Stream workers read from their partitions, keep state (running counts, the last event per user) in memory with periodic checkpoints saved to durable storage, and emit results continuously, for example to a dashboard store or an alert queue. After a crash a worker reloads its last checkpoint and replays events from the saved log position. Because delivery can repeat, results are made correct through idempotent writes or exactly-once features of the framework.

Pros

  • Low latency. Results in seconds or less. Enables alerts, live dashboards, personalisation.
  • Smooth load. Work is spread evenly over the day instead of spiking.
  • Reacts to events. Fraud blocking, rate limiting, inventory alerts.
  • Incremental. You never reprocess a whole day to update a counter.

Cons

  • Harder to build and operate. Always-on clusters, state management, checkpoints, partition skew, back pressure.
  • Late and out-of-order data. Needs event time, watermarks and rules for corrections.
  • Costly to run. A 24-hour cluster sized for peak.
  • Harder to fix mistakes. Recomputing history means replaying the log, so you need long retention.
  • Limited complex analytics. Big joins and ad hoc queries are more natural in batch or a warehouse.

When to use it

Choose streaming when the value of the answer decays quickly (seconds or minutes) or the system must react to events: fraud detection, monitoring and alerting, live leaderboards, trending topics, real-time bidding, operational dashboards.

Realistic scenario. A card processor must block a suspicious transaction before the payment completes. A stream job keyed by card id keeps the last 10 minutes of activity in a sliding window and flags "5 purchases in 3 countries". It decides within 200 ms and emits an alert event to a decision service. A nightly batch would detect the fraud a day after the money was gone.

The hybrid: lambda and kappa architectures

Combining both gives fast approximate answers and slow exact ones.

  • Lambda architecture: every event goes to both a speed layer (stream job, fresh but possibly approximate) and a batch layer (periodic job over the full history, exact). Queries merge the two: the batch result for older data and the stream result for the latest hour. Downside: two code paths to keep consistent.
  • Kappa architecture: use only the stream path, and treat reprocessing as "replay the log from the start with the new code". One code path, but it needs a long-retention log and a capable stream engine.
  • Practical hybrid: stream for operational numbers (clicks per minute, alerts), batch for official numbers (revenue reports, billing) that are reconciled the next day.
Hybrid: Speed Layer and Batch Layer on One Log
Architecture
Speed layerBatch layerEvent producersapps, devicesEvent logpartitioned, durableStream job5-min windowsLive storelast hourObject storageall raw eventsNightly batchjobexact resultsQuery layermerge bothconsumearchiverecenthistory
Key point. Stream gives fresh approximate numbers. Batch later produces the official exact ones.

The same event log feeds a fast stream path and an exact batch path. Queries merge them.

Interview Discussion

Choose by the freshness requirement, and say the number.

  1. Ask how fresh the result must be. "Is five minutes old fine, or must we react within seconds?"
  2. Estimate throughput. 10,000 events per second average, 30,000 at peak, 1 TB per day.
  3. Name the late-data policy. For stream: windows, watermark, how corrections are handled.
  4. Say how you recover. Batch: rerun. Stream: checkpoint plus replay from the log.
  5. Consider cost. An always-on cluster versus a 10-minute hourly job.

Interview tip. Do not say "streaming is better because it is real-time". Most reports do not need real-time, and a simple batch job is cheaper and easier to get right. Ask what decision the freshness enables.

Interview discussion. "For trending topics I'd use a stream job with five-minute sliding windows keyed by topic, writing counts to a key-value store for the UI. For the official daily analytics I'd keep the raw events in object storage and run a nightly batch job, which also lets me correct any stream bugs by recomputing."

Trade-off thinking. Batch trades freshness for simplicity, cost efficiency and easy reruns. Streaming trades complexity and always-on cost for low latency. Use stream only where seconds matter, and let batch be the source of truth for numbers people reconcile.

Final Takeaway

Choose batch when hours-old results are acceptable and the job is large, complex or needs exact reproducibility. Choose stream when value decays in seconds or the system must react to each event. Combine them with a speed layer plus a batch layer, or a replayable log for both. Always state the freshness target, the events per second and what happens to late data.

Common Interview Questions

Chapter quiz

Choosing Between Alternatives · 6 questions

  1. 1.A booking service must never sell the same seat twice and handles 300 writes per second on 100 GB of data. Which storage choice fits best?

  2. 2.Your product page triggers 40 internal service calls and p99 latency is too high. What is the most sensible change for the internal calls?

  3. 3.A social app has 20M posts per day with 200 followers on average, but a few accounts have 50M followers. What feed strategy is most appropriate?

  4. 4.A service runs 100 sustained requests per second all day with a strict 50 ms p99 target. Using break-even math where serverless costs about $1 per million requests and two small servers cost about $117 per month, what is the better fit?

  5. 5.A bank transfer and a video like counter run on the same replicated database. Which consistency setup is appropriate?

  6. 6.Five microservices are called in a chain for one request and each is 99.9% available. Roughly what availability does the chain have, and what is a good mitigation?

0 of 6 answered

Finished this lesson?

0 of 44 lessons done · 0% of the course