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

Streaming Engines

The engines that process endless streams of events (Kafka Streams, Flink, Spark Streaming).

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

01Quick Summary

A streaming engine is software that processes an endless flow of events as they arrive: counting, joining, filtering and summing them, and sending results on, all with low delay.

  • It groups events into windows (for example "clicks per minute"), because a stream has no end to sum up.
  • It must deal with late and out-of-order events, using event time and watermarks.
  • It keeps state (running counts, join tables) and saves checkpoints, so it survives crashes without losing or double counting events.

02Concept: What is it?

A normal batch job reads a finished file and stops. A streaming job never finishes. Events keep coming, so it must give answers while the data is still arriving. A streaming engine is the tool that runs such jobs on many machines, and handles the hard parts: ordering, time, state and failures.

An engine reads from a source (often a log such as Kafka), runs a pipeline of operators (filter, map, group, window, join), and writes to a sink (a database, another topic, a dashboard). The work is split by key across many parallel workers, and each worker keeps the state for its keys.

A streaming job
πŸͺ΅SourceKafka, logs
→↓
🧹Filter / mapclean events
→↓by key
πŸͺŸWindow + countkeeps state
→↓
πŸ—‚οΈSinkdatabase, topic
πŸ’ΎCheckpointsstate + position saved
Events flow through operators. State is kept per key and saved in checkpoints.

Two clocks

Event time is when something really happened (a phone taps "buy" at 10:00:05). Processing time is when the engine sees it (maybe 10:00:09, because the phone was in a tunnel). Good results use event time. The engine then needs a way to decide when a window is complete. That is the job of the watermark.

🧠What is a watermark?
A watermark is the engine's guess: "I do not expect any more events older than this time." When the watermark passes the end of a window, the window fires and sends its result. An event that arrives after that is late.

03Real-Life Example

🍡Counting Cars at a Toll Gate
A toll gate counts cars for every 10-minute period. Each car has a time stamp on its ticket, from the moment it passed the camera. But some tickets reach the counting room late because the road was jammed. The counter has two choices: close each 10-minute count right when the clock says so (fast, but late cars are lost or counted in the wrong period), or wait a few minutes for slow tickets (a more correct count, but a later result). A manager who says "I will close the 10:00 count when I see a ticket stamped 10:12" is using a watermark.
Toll gate
Streaming engine
The time stamp printed on a ticket
Event time
The time the ticket reaches the counting room
Processing time
A 10-minute count period
A tumbling window
Closing the count when a 10:12 ticket is seen
A watermark passing the window end
A ticket that arrives after the count is closed
A late event
The running tally sheet
State
Copying the tally sheet to a safe place
A checkpoint
Why the delay setting matters
⏩Short delayfast result, may drop late events
↔trade-off
⏳Long delaycomplete result, but later

04Why Do We Need It?

⚑Low delay
Results appear in seconds instead of waiting for a nightly job.
πŸ”„Continuous results
Dashboards, alerts and features stay up to date all the time.
🧠Handles time properly
Windows, watermarks and late data are built in, so you do not write them by hand.
πŸ’ΎSafe state
Checkpoints let a job restart after a crash without losing its counts.
πŸ“ˆScales out
Work is split by key over many machines.
🧱Reusable building blocks
Joins, aggregations and pattern matching ready to use, so you do not have to build them yourself.
A streaming engine turns an endless river of events into answers you can trust, even when events are late, out of order, or a machine dies.

05Where Do We Use It?

πŸ“ŠLive metrics
Requests per second, error rates and revenue per minute.
🚨Alerts and fraud
Spot a suspicious pattern across a few seconds of events.
πŸ”„Data pipelines
Clean, enrich and move events between systems continuously.
🎯Personalisation
Update a user's features from their last few actions.
🚚Tracking
Join vehicle positions with orders to show live delivery status.
πŸ“‘IoT
Process sensor readings per device as they arrive.

06Types / Parts / How It Works

Window types

Three ways to cut a stream
Tumbling
0 to 10 s
10 to 20 s
Sliding
0 to 10 s
5 to 15 s
Session
burst of activity
after a quiet gap
Tumbling windows do not overlap. Sliding windows overlap, so one event counts in several windows. Session windows end after a quiet gap.
WindowHow it is cutGood for
TumblingFixed size, no overlap (every 1 minute)Counts per minute or per hour
Sliding (hopping)Fixed size that moves by a smaller step, so windows overlapA moving average, such as the last 5 minutes updated every minute
SessionGrows while events keep coming, closes after a quiet gapUser visits, where the length depends on the user
GlobalOne window for everything, with a custom triggerSpecial cases with your own rules

Time, watermarks and late data

IdeaMeaningEffect
Event timeWhen the event really happenedCorrect results, even if events arrive late or out of order
Processing timeWhen the engine sees the eventSimple and fast, but results depend on network delays
WatermarkThe engine's estimate of how far event time has progressedDecides when a window can fire
Allowed latenessExtra time to still accept late events and update a resultMore correct, but results may be corrected after being sent
Side output for late dataSend events that missed their window to a separate placeNothing is silently lost

Delivery guarantees

GuaranteeMeaningCost
At most onceAn event is processed zero or one time. Nothing is repeated, but some may be lostCheapest, results may be too low
At least onceEvery event is processed, but some twice after a failureDuplicates must be handled (idempotent writes)
Exactly once (effect)Each event changes the state once, even after failures. Done with checkpoints and transactional or idempotent outputMore work and some delay

Example engines

EngineStyle
Apache FlinkTrue event-by-event streaming with strong state and event-time support
Kafka StreamsA library you embed in your app, reading and writing Kafka topics
Spark Structured StreamingTreats a stream as a growing table, usually processed in small chunks (micro-batches)
Cloud servicesManaged options such as Google Dataflow (Apache Beam) and Amazon Kinesis analytics
VisualizerWindows, event time and the watermarkMove the clock forward and watch windows fire. Make the watermark delay small and see late events (red) get dropped. Then switch to processing time and see events land in the wrong window.
Window type
Windows use
Window size
Each dot is an event, placed at the time it happened. Cyan = counted, red = dropped as late, dim = not arrived yet, outlined = arrived late but still counted.
0 s10 s20 s30 s40 s
Amber line = watermark (38 s): the engine believes nothing older than this will still arrive.
WindowTruthResultStatus
0s to 10s65fired at 12s, dropped 1 late
10s to 20s55fired at 23s
20s to 30s66fired at 33s
30s to 40s33…waiting: no newer event moves the watermark
40s to 50s11…waiting: no newer event moves the watermark
Watermark
38 s
newest event βˆ’ delay
Results out
3
of 5 windows
Late and dropped
1
5 events arrive late
Avg wait
2.7 s
after window end
In wrong window
0
event time is exact
The watermark is 2 s behind the newest event. 1 event(s) arrived after their window had already fired and were dropped. Raise the watermark delay to wait for them, and watch the results come out later.

A simplified model with fixed events. Sliding windows slide by half their size. Session windows are built from all events, even dropped ones. Real engines such as Flink or Spark can also keep late events with an allowed-lateness setting.

07How to Use It / Steps / Implementation

Building a streaming job

  1. 1
    Choose the time idea
    Use event time when correctness matters. Put a timestamp in every event when it is created.
  2. 2
    Pick the window
    Tumbling for simple periodic counts, sliding for moving averages, session for user activity.
  3. 3
    Set the watermark delay
    Look at how late your events usually are. Pick a delay that catches most of them, and accept the extra wait.
  4. 4
    Decide what to do with late events
    Drop them, allow some lateness so results are updated, or send them to a side output you can check.
  5. 5
    Choose the key
    Data is split by key (user id, device id). A good key spreads work evenly, and a bad one creates a hot worker.
  6. 6
    Turn on checkpoints
    Save state and source position now and then. After a crash the job goes back to the last checkpoint and continues.
  7. 7
    Make the sink safe
    Use idempotent writes or a transactional sink, so a replay after a failure does not create duplicates.
  8. 8
    Watch lag and state size
    Track how far behind the job is (consumer lag), the watermark, checkpoint time and state size.
πŸ’‘Start with the late data question
Ask: "What should happen to an event that arrives 5 minutes late?" The answer drives your watermark, allowed lateness and sink design.
⚠️Exactly once has limits
"Exactly once" inside the engine does not cover the outside world. If your job calls an email service or a database without idempotency, a retry can still repeat the effect.

08Key Terms to Know

TermMeaning in easy words
StreamAn endless, ordered flow of events
WindowA slice of the stream (by time or by gap) that is summarised together
Event timeThe time an event really happened
Processing timeThe time the engine handles the event
WatermarkThe engine's estimate that no older events are still to come
Late eventAn event that arrives after the watermark has passed its window
StateData a job remembers between events, such as counts or join tables
CheckpointA saved copy of state and source position, for recovery
Key / partitionHow events are divided among parallel workers
BackpressureSlowing the source when a later step cannot keep up
Exactly-onceEach event changes the state once, even if the job restarts

09Pros, Cons and Trade-offs

βœ… Pros
  • Results in seconds, not hours
  • Handles time, late data and state for you
  • Recovers from crashes with checkpoints
  • Scales by key across many machines
  • Same engine can often process old data too
⚠️ Cons
  • Time and watermarks are hard to get right
  • Large state can be slow to checkpoint and restore
  • Needs careful sinks for exact results
  • Harder to test and debug than a batch job
  • Always running, so it costs money all the time

Trade-offs

ChoiceWe gainWe lose
Longer watermark delayMore late events are countedResults come out later
Shorter watermark delayQuick resultsMore late events dropped or corrected later
Event timeCorrect resultsNeeds watermarks and more state
Processing timeSimple and fastResults change with network delays
Frequent checkpointsLess to redo after a crashMore overhead while running
Exactly-once outputNo duplicate or lost effectsMore complex, with some added delay
Micro-batchesSimpler, can share batch toolsA little more delay than event-by-event

10Common Problems and Mistakes

Common mistakes

  1. Using processing time for business results. A slow network moves events into the wrong window.
  2. A watermark that is too tight. Late events are dropped without anyone noticing.
  3. An idle source stops the watermark. If one partition has no events, the watermark may not move and windows never fire.
  4. A hot key. One key gets far more events than others and one worker is overloaded.
  5. State that grows forever. Keys are never removed, so memory and checkpoints keep growing. Use a time-to-live for state.
  6. Non-idempotent sinks. After a restart the same result is written twice.
  7. No monitoring of lag. The job falls behind and nobody sees it until users complain.

Things to watch

πŸ“‰Consumer lag
How far behind the newest event the job is. Growing lag means it cannot keep up.
🧱State size
Large state makes checkpoints and restarts slow. Keep state small and clean it up.
πŸ”„Rebalancing and restarts
A restart should resume from the last checkpoint. Test failure on purpose.
🧬Changing the job
Changing the logic or state format needs care, so the new version can load old state or replay.

11Real-World Examples

🌊Apache Flink
Widely used for stateful, event-time stream processing in large pipelines.
πŸͺ΅Kafka Streams
A library inside your service. Popular when the data is already in Kafka.
⚑Spark Structured Streaming
A good fit when a team already uses Spark for batch and wants one tool.
☁️Managed cloud streaming
Cloud services run the engine for you, such as Dataflow and Kinesis-based tools.
πŸ’³Payments and fraud
Rules over a short window of recent transactions.
πŸ“±App analytics
Live counts of active users, and sessions built from taps and views.
πŸ“Note
Features and defaults differ between engines and versions. Check the documentation of the one you use before relying on a guarantee.
Mini case: active users per minute
πŸ“±Appsevents with a timestamp
→↓
πŸͺ΅Kafka
→↓
🌊Streaming job1 min windows, 2 min delay
→↓
πŸ“ŠDashboard
Source Engine Result
Each tumbling window counts distinct users. A 2-minute watermark delay waits for phones that were offline for a moment.

12Related Topics to Read Next

Batch vs Stream Processing→

The big picture of the two styles.

Kappa Architecture→

A design built around one streaming path.

Lambda Architecture→

A design that adds a batch path next to streaming.

Message Brokers→

Kafka and similar systems feed most engines.

Delivery Semantics→

At most once, at least once and exactly once, in depth.

Idempotency→

The key to safe retries in sinks.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: an engine for endless event streams: windows, state, time and failures handled for you.
  • βœ”Time: event time (when it happened) beats processing time (when it arrived).
  • βœ”Watermark: β€œnothing older than this is expected.” Passing a window end fires the window.
  • βœ”Windows: tumbling (fixed), sliding (overlap), session (gap).
  • βœ”Late data: bigger delay, allowed lateness, or a side output. Completeness vs delay.
  • βœ”Recovery: checkpoints of state plus source offset.
  • βœ”Guarantees: at most once, at least once, exactly-once effect (needs idempotent or transactional sinks).
  • βœ”One line: β€œWait just long enough for late events, and save your state so a crash costs nothing.”
← Previous
Kappa Architecture
Next β†’
Spark and Hadoop