AI Hints
Home›System Design Tutorial›Batch, Stream and Schedules
System Design · Lesson 73 of 120

Batch vs Stream

Later or now.

⏱ 2 min read▶ Video at 1:27:32🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Shoply wants a report of sales per product. It could run once a night, over the whole day's orders. Or it could update every second, as orders arrive. These are batch and stream processing.

Batch vs Stream
From the video: Batch vs Stream
  • Sales per product
  • Once a night?
  • Or every second?

Batch vs stream

Batch processing collects data, and processes it in big chunks, on a schedule. It's simple, efficient, and easy to rerun, but the results are hours old. Stream processing handles each event as it arrives. Results are fresh within seconds, but the system is more complex, and must run all the time.

Batch

  • Big chunks, on a scheduleSimple and efficientResults hours old

Stream

  • Each event as it comesFresh within secondsMore complex, always on

The same totals, two ways

Here's the same calculation done both ways. Batch waits for all the orders, then adds them up. Stream keeps a running total, updated with every order. Run it. They reach the same answer, but the stream version knew the total at every moment along the way.

batchstream.pypython
orders = [("mug", 10), ("pot", 25), ("mug", 10), ("lamp", 40)]

# batch: once, at the end
print("batch total:", sum(price for _, price in orders))

# stream: update as each order arrives
running = 0
for item, price in orders:
    running += price
    print(f"stream: +{item:<4} total so far {running}")
Output
batch total: 85
stream: +mug  total so far 10
stream: +pot  total so far 35
stream: +mug  total so far 45
stream: +lamp total so far 85

Summary

Batch processes big chunks on a schedule, and stream processes each event as it comes. Choose by how fresh the results must be. Next, running jobs on a schedule, at scale.

Key takeaways
  • Batch: simple, delayed
  • Stream: fresh, complex
  • Freshness decides
Next up: Scheduled Jobs — cron at scale