All the processing in the previous four lessons shares one assumption: the data is already there. You read a closed dataset, compute and finish. But NovaMarket's architecture (lesson 01-04) set stream processing aside for two cases in which waiting for the nightly batch is no good: detecting fraud while the order can still be held back, and feeding a live sales dashboard.

Processing in streaming mode means computing over data that never ends, and that changes the questions. When do I accept the count for 10:05 as final if an event from that time might arrive late? What happens if the process goes down halfway: do I lose events or count them twice? In this lesson you will learn the concepts that answer those questions, get to know Apache Kafka, the messaging system that transports the events, and write your first streaming application with Spark Structured Streaming, reusing almost everything you already know about DataFrames.

What "real time" means

Lesson 01-04 distinguished batch processing (accumulated data, processed at intervals, latency of hours) from stream processing (each piece of data is processed shortly after it arrives, latency of seconds). "Real time" is a marketing label that covers very different situations; it is always worth pinning down the latency:

Level Latency Example at NovaMarket Typical technology
Batch Hours Daily sales report Batch Spark, orchestrated every night
Frequent micro-batches Minutes Stock updated every 15 minutes Small batches in quick succession
Near real time Seconds Live sales dashboard Streaming engine (Structured Streaming, Flink)
Strict real time Milliseconds Blocking a fraudulent payment before authorising it Low-latency streaming engine and a NoSQL database

Each step down multiplies complexity and cost: a streaming system runs 24 hours a day, has to be monitored continuously and is harder to test and to fix. The right question is not "can it be done in real time?" but "what decision changes if the data arrives in five seconds instead of an hour?". If the answer is "none", a batch is the right choice.

Fundamental concepts of stream processing

Events and unbounded streams

An event is the record of something that happened at an instant: a click, a purchase, a sensor reading. It is immutable: what happened does not change. A stream is an unbounded sequence of events: it has a beginning, but no end. The lines in web_events.json are events; the file is a June snapshot of a stream that, in the real shop, is still growing right now.

Over a bounded dataset, "count the purchases" has an answer. Over a stream, the count never ends, and the question must be bounded in time: "count the purchases in each minute".

Event time and processing time

Every event has two times:

  • Event time: when it happened. It is set by the source and travels inside the data: it is event_time.
  • Processing time: when the system processing it receives it.

They never coincide exactly, and sometimes they differ a great deal. A customer adds a product to the cart in the app at 10:04 inside an Underground tunnel; the phone gets its signal back at 10:09 and sends the event then. Event time, 10:04; processing time, 10:09. What is more, events arrive out of order: that 10:04 event arrives after others from 10:08.

If the dashboard counted by processing time, it would attribute that cart to 10:09, and the results would depend on the whims of the network. Correct analyses are done by event time, which forces you to decide what to do with the stragglers.

Windows

A window groups events by time intervals so that they can be aggregated.

Type How it is defined Overlap Example
Tumbling Intervals of fixed duration, one after another No: each event falls into one window Purchases per minute
Sliding Fixed duration, but a new one opens at every step Yes: an event falls into several Purchases in the last 10 minutes, updated every 5
Session Closes after a period without activity No; variable duration Activity during a visit: it ends after 30 minutes without events
gantt
    dateFormat HH:mm
    axisFormat %H:%M
    section Tumbling 5 min
    Window 1 :10:00, 5m
    Window 2 :10:05, 5m
    Window 3 :10:10, 5m
    section Sliding 10 min every 5
    Window A :10:00, 10m
    Window B :10:05, 10m
    section Session
    Session 1 :10:01, 6m
    Session 2 :10:11, 3m

Watermarks and late data

If events can arrive late, when is the 10:04 window considered closed? Waiting for ever is not possible: the system would have to keep every window in history in memory. The solution is a watermark: a threshold that advances with the data and expresses "I no longer expect events earlier than this instant".

It is defined as a tolerance for delay. With a tolerance of 10 minutes:

watermark = latest event time seen so far − 10 minutes

If the most recent event received is from 10:20, the watermark is at 10:10. Windows ending before 10:10 are closed: their final result is emitted and their memory is released. A 10:04 event arriving afterwards is late data and is discarded.

Choosing the tolerance is a trade-off: if it is large, less data is lost, but final results take longer and more memory is used; if it is small, the opposite happens.

State

Counting by windows requires remembering the partial counts of the open windows from one event to the next. That memory is the state. The operations that need it (aggregations, joins between streams, removing duplicates) are called stateful; a simple filter is stateless. State must survive failures, which is why engines periodically save it to durable storage.

Delivery semantics

When something fails and the process restarts, what happens to the events that were in progress?

Semantics Guarantee Risk Acceptable for
At-most-once No event is processed twice Events may be lost Approximate metrics
At-least-once No event is lost There may be duplicates Almost everything, if the destination tolerates or removes duplicates
Exactly-once The result is the same as if each event were processed once Greater complexity and cost Money, inventory, billing

Exactly-once does not mean that nothing is retried, but that retries do not alter the result. It is achieved by combining three things: a source that allows you to reread from a known point, an engine that saves its progress and its state consistently, and a destination that is idempotent or transactional. Idempotent means that repeating an operation leaves the same result as doing it once; it is a central idea, which will come back in lesson 03-06.

Messaging with Apache Kafka

Between the website that generates the events and the processes that consume them, an intermediary is needed. Without one, the website would have to know about every consumer, and it would take just one of them being slow or going down for data to be lost. That intermediary is the messaging layer from lesson 01-04, and its de facto standard is Apache Kafka.

Kafka is a distributed event log: a system in which producers append events at the end and consumers read them in order, each at its own pace, without reading deleting them.

Concept What it is
Broker Each server in a Kafka cluster
Topic A named stream of events, such as web_events. It is the equivalent of a table or a folder
Partition Each of the ordered sequences a topic is divided into, distributed and replicated across the brokers
Offset The position of a message within its partition: 0, 1, 2…
Producer The application that publishes messages to a topic
Consumer The application that reads them
Consumer group A set of consumers that share out the partitions of a topic to read it in parallel
Retention The time or size for which Kafka keeps messages, whether they have been read or not
flowchart LR
    W[Web] --> T
    A[App] --> T
    subgraph T[Topic web_events]
        direction TB
        P0["Partition 0: 0 1 2 3 4 5 →"]
        P1["Partition 1: 0 1 2 3 →"]
        P2["Partition 2: 0 1 2 3 4 →"]
    end
    subgraph G1[Group: fraud-detection]
        C1[Consumer 1]
        C2[Consumer 2]
    end
    subgraph G2[Group: lake-load]
        C3[Single consumer]
    end
    P0 --> C1
    P1 --> C1
    P2 --> C2
    P0 --> C3
    P1 --> C3
    P2 --> C3

Four ideas explain how it works:

  • The key decides the partition. Each message can carry a key; messages with the same key always go to the same partition. Publishing with session_id as the key, all the events in a session end up in one partition.
  • Order is only guaranteed within a partition. That is why the choice of key matters: the events of a session will be read in the order in which they were published, but there is no global order across partitions.
  • Each group keeps its own count. Kafka stores, per group and partition, the offset up to which it has read. fraud-detection and lake-load read the same messages independently; if one stops for an hour, when it comes back it carries on where it left off. Within a group, each partition is read by a single consumer: the number of partitions is the ceiling on parallelism.
  • Reading does not delete. Messages are removed when the retention period expires (7 days by default), not when they are read. A new consumer can start from the beginning, and one that failed can reread: it is the basis of delivery guarantees and of the Kappa architecture.

You will recognise the pieces: partitioning by key, replication and fault tolerance, the fundamentals from lesson 01-04. And skew exists here too: if the key were customer_id, all the anonymous events, 30% of them, would land in a single partition.

Optional hands-on: Kafka in a container

This exercise requires Docker (optional since lesson 01-05). If you do not have it, read it through and move on to the next section: the main hands-on exercise does not use Kafka. Image names and paths may vary between versions; if you hit an error, check the current Apache Kafka documentation.

1. Start a broker. The official image starts a single-node Kafka with no further configuration:

docker run -d --name nm-kafka -p 9092:9092 apache/kafka:latest

2. Create the web_events topic with three partitions, using the utilities included in the container:

docker exec nm-kafka /opt/kafka/bin/kafka-topics.sh \
    --bootstrap-server localhost:9092 \
    --create --topic web_events --partitions 3

docker exec nm-kafka /opt/kafka/bin/kafka-topics.sh \
    --bootstrap-server localhost:9092 --describe --topic web_events

3. Install a Python client. We will use confluent-kafka, the client maintained by the company founded by Kafka's creators; kafka-python is an alternative written purely in Python. Check in its documentation that the current version supports your version of Python.

cd ~/novamarket
source .venv/bin/activate
pip install confluent-kafka

4. A producer that replays events. Create event_producer.py:

import json
import time
from pathlib import Path

from confluent_kafka import Producer

SOURCE = Path.home() / "novamarket" / "data" / "web_events.json"
producer = Producer({"bootstrap.servers": "localhost:9092"})

with open(SOURCE, encoding="utf-8") as f:
    for i, line in enumerate(f):
        if i >= 500:
            break
        event = json.loads(line)
        producer.produce(
            "web_events",
            key=event["session_id"],     # same session -> same partition
            value=line.strip(),          # the whole event, as JSON text
        )
        producer.poll(0)                 # handles pending acknowledgements
        time.sleep(0.01)                 # simulates gradual arrival

producer.flush()                         # waits until everything has been sent
print("Sent 500 events")

bootstrap.servers is the entry address to the cluster. produce does not send straight away: it accumulates messages and sends them in batches, which is why the flush() at the end is essential.

5. A consumer. Create event_consumer.py:

import json

from confluent_kafka import Consumer

consumer = Consumer({
    "bootstrap.servers": "localhost:9092",
    "group.id": "sales-dashboard",       # consumer group
    "auto.offset.reset": "earliest",     # no saved offset: from the beginning
})
consumer.subscribe(["web_events"])

try:
    while True:
        message = consumer.poll(1.0)     # waits for up to 1 second
        if message is None:
            continue
        if message.error():
            print("Error:", message.error())
            continue
        event = json.loads(message.value())
        print(f"partition {message.partition()} offset {message.offset()}: "
              f"{event['session_id']} {event['event_type']}")
except KeyboardInterrupt:
    pass
finally:
    consumer.close()                     # saves offsets and leaves the group

Run the consumer in one terminal and the producer in another. You will see the 500 events go by, each with its partition and offset. Stop the consumer with Ctrl+C. Two experiments:

  • Launch the consumer again: it shows nothing, because the sales-dashboard group had already read up to the end and Kafka remembers it.
  • Change group.id to other-group and launch it: it reads all 500 again, because to Kafka it is a new reader.

6. Clean up. When you have finished, stop and remove the container:

docker rm -f nm-kafka

Spark Structured Streaming

Structured Streaming is Spark's streaming engine. Its central idea lets you reuse almost everything you have learnt: a stream is treated as an unbounded table to which rows are continuously added, and a streaming query is an ordinary DataFrame query that Spark keeps up to date as rows arrive.

flowchart LR
    F[Source<br/>Kafka, files] --> T[Unbounded<br/>input table]
    T --> Q[Query<br/>DataFrame / SQL]
    Q --> R[Result table]
    R --> S[Sink<br/>console, files, Kafka, tables]
    CK[(Checkpoint:<br/>progress and state)] -.-> Q

Underneath, Spark works in micro-batches: every few seconds (or as soon as the previous one finishes) it takes the new data, runs a small job on it and updates the result. Typical latency ranges from hundreds of milliseconds to a few seconds; recent versions also include a real-time mode with lower latency for certain cases.

Element In batch In streaming
Reading spark.read spark.readStream
Schema It can be inferred Mandatory with files: there is no closed dataset to infer it from
Transformations select, where, groupBy, join… The same, plus withWatermark
Writing df.write df.writeStream + start()
Duration It finishes on its own It runs until it is stopped

Output modes

Since the result changes over time, you have to decide what is written in each micro-batch:

Mode What it emits Use
append Only new, final rows. With windowed aggregations it requires a watermark, and each window is emitted once, when it closes Writing to files or tables
update The rows that have changed since the previous micro-batch Dashboards, databases that support updates
complete The whole result table, every time Small aggregations; debugging

Checkpoint

The checkpoint is a directory in which Spark records, for each micro-batch, how far it has read from the source and the state of the aggregations. If the application stops or fails, when it starts again with the same checkpoint it carries on where it left off, without losing or repeating data. With a source that can be reread and an idempotent or transactional sink, it provides exactly-once guarantees.

Each query needs its own checkpoint directory, on durable storage.

Hands-on: counting events in windows without Kafka

Structured Streaming accepts a directory as a source: each new file that appears in it is processed as newly arrived data. It is ideal for learning without infrastructure. You will use two scripts: one that simulates the arrival of events and another that counts them by window.

Create ~/novamarket/simulate_arrival.py:

import time
from pathlib import Path

BASE = Path.home() / "novamarket"
SOURCE = BASE / "data" / "web_events.json"
INPUT_DIR = BASE / "stream" / "input"
TMP_DIR = BASE / "stream" / "tmp"

DAY = "2026-06-01"           # the events of this day are replayed
LINES_PER_FILE = 100         # about 20 minutes of shop activity
NUM_FILES = 6
PAUSE_SECONDS = 5

INPUT_DIR.mkdir(parents=True, exist_ok=True)
TMP_DIR.mkdir(parents=True, exist_ok=True)

with open(SOURCE, encoding="utf-8") as f:
    of_day = (line for line in f if f'"event_time": "{DAY}T' in line)
    for n in range(1, NUM_FILES + 1):
        lines = [next(of_day) for _ in range(LINES_PER_FILE)]
        name = f"events_{n:04d}.json"
        # Written to a temporary folder and then moved: that way the
        # file appears in the input folder all at once, already complete.
        (TMP_DIR / name).write_text("".join(lines), encoding="utf-8")
        (TMP_DIR / name).rename(INPUT_DIR / name)
        print(f"Delivered {name}")
        time.sleep(PAUSE_SECONDS)

The simulator takes the first 600 events of 1 June and delivers them in six files of 100, one every five seconds. Two details:

  • It filters by day. The original file is sorted by time, but the 500 deliberate duplicates are interspersed at random positions: a duplicate from 13 June appears among the events of day 1. You will soon see why that would ruin the exercise.
  • It writes and then moves. If Spark saw a half-written file, it would read only part of it and never come back to it. Moving a file within the same disk is instantaneous: it either appears complete or does not appear at all.

Now, count_in_stream.py:

from pathlib import Path

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

STREAM = Path.home() / "novamarket" / "stream"
(STREAM / "input").mkdir(parents=True, exist_ok=True)

spark = SparkSession.builder.master("local[*]").appName("count_in_stream").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
spark.conf.set("spark.sql.shuffle.partitions", 4)

SCHEMA = ("event_id STRING, customer_id BIGINT, session_id STRING, event_type STRING, "
          "product_id BIGINT, event_time TIMESTAMP, device STRING")

# 1. Source: an "unbounded table" fed by the files as they arrive
events = (
    spark.readStream
    .schema(SCHEMA)
    .option("maxFilesPerTrigger", 1)
    .json(str(STREAM / "input"))
)

# 2. Transformation: the same DataFrame API, plus window and watermark
counts = (
    events
    .withWatermark("event_time", "10 minutes")
    .groupBy(F.window("event_time", "1 minute"), "event_type")
    .count()
)

# 3. Sink: the rows that change in each micro-batch are shown on the console
query = (
    counts.writeStream
    .outputMode("update")
    .format("console")
    .option("truncate", False)
    .option("numRows", 4)
    .option("checkpointLocation", str(STREAM / "checkpoint" / "counts"))
    .trigger(processingTime="5 seconds")
    .start()
)

query.awaitTermination(180)        # left to work for 3 minutes...
query.stop()                       # ...and then stopped
spark.stop()
  • Block 1. readStream with the declared schema (the same one as in lesson 03-02, in string form). maxFilesPerTrigger=1 makes each micro-batch take a single file, so that you can watch the progress step by step.
  • Block 2. withWatermark("event_time", "10 minutes") declares the event-time column and the tolerance for delay. F.window("event_time", "1 minute") assigns each event to its one-minute tumbling window; with a third argument, F.window(col, "10 minutes", "5 minutes"), it would be a sliding one. The rest is an ordinary groupBy.
  • Block 3. writeStream defines the sink (console), the output mode, the checkpoint and the trigger: one micro-batch every 5 seconds. Nothing happens until start(), which launches the query in the background and returns control; awaitTermination(180) keeps the program alive for three minutes (you can stop it earlier with Ctrl+C). A real application would use awaitTermination() with no argument, and would never finish on its own.
  • The number of shuffle partitions is reduced to 4 because AQE's automatic partition merging does not operate in streaming: with 200, each micro-batch would launch 200 minuscule tasks.

Open two terminals in ~/novamarket, both with the virtual environment activated. In the first:

python count_in_stream.py

Wait about ten seconds for it to start; it will show nothing, because there are no files yet. Then launch, in the second:

python simulate_arrival.py

The micro-batches will start appearing in the first terminal (output from a real run, abbreviated):

-------------------------------------------
Batch: 0
-------------------------------------------
+------------------------------------------+------------+-----+
|window                                    |event_type  |count|
+------------------------------------------+------------+-----+
|{2026-06-01 00:01:00, 2026-06-01 00:02:00}|purchase    |1    |
|{2026-06-01 00:04:00, 2026-06-01 00:05:00}|product_view|3    |
|{2026-06-01 00:07:00, 2026-06-01 00:08:00}|add_to_cart |1    |
|{2026-06-01 00:11:00, 2026-06-01 00:12:00}|product_view|3    |
+------------------------------------------+------------+-----+
only showing top 4 rows

The window column is a structure with the start and end of each window. Each micro-batch shows only the windows that have changed, and only their first four rows. Every so often a micro-batch appears with an empty table: Spark runs it to advance the watermark and close windows, even when there are no rows to show.

Checking the watermark

With the query still running (you have about two minutes; if it stops, launch it again and it will carry on from where it was) and the simulator finished, the last event received is from 02:25:02, so the watermark is at 02:15:02. Deliver by hand a file with two delayed events, one from 00:05 and another from 02:20:

cat > stream/tmp/late.json <<'EOF'
{"event_id": "ev-late-1", "customer_id": 7, "session_id": "s-999999", "event_type": "purchase", "product_id": 1, "event_time": "2026-06-01T00:05:10", "device": "mobile"}
{"event_id": "ev-late-2", "customer_id": 7, "session_id": "s-999999", "event_type": "purchase", "product_id": 1, "event_time": "2026-06-01T02:20:10", "device": "mobile"}
EOF
mv stream/tmp/late.json stream/input/
+------------------------------------------+----------+-----+
|window                                    |event_type|count|
+------------------------------------------+----------+-----+
|{2026-06-01 02:20:00, 2026-06-01 02:21:00}|purchase  |1    |
+------------------------------------------+----------+-----+

The 02:20 event arrives five minutes late, within the tolerance, and is counted. The 00:05 one arrives more than two hours late: its window closed long ago and it is silently discarded.

Now the simulator's precaution makes sense. A single event from 13 June slipped in among those of day 1 would have pushed the watermark forward twelve days in one go, and all the subsequent events would have been discarded as late. It actually happened while this lesson was being prepared. In production, the equivalent is a device with a badly set clock: a real risk, countered by validating timestamps on the way in.

Restarting

Run count_in_stream.py again without touching anything else: it does not reprocess the files it has already read, because the checkpoint remembers which they are. To repeat the exercise from scratch, delete the whole folder with rm -rf ~/novamarket/stream.

Reading from Kafka with Structured Streaming

At NovaMarket, the source is not a directory but the web_events topic. The change is limited to the reading block (illustrative code; it requires the container from the optional exercise and the Kafka connector for Spark):

raw = (
    spark.readStream
    .format("kafka")
    .option("kafka.bootstrap.servers", "localhost:9092")
    .option("subscribe", "web_events")
    .option("startingOffsets", "earliest")
    .load()
)

events = (
    raw
    .select(F.from_json(F.col("value").cast("string"), SCHEMA).alias("e"))
    .select("e.*")
)
# From here on, the same withWatermark + groupBy + writeStream

Kafka delivers each message as a row with the columns key, value, topic, partition, offset and timestamp; key and value are binary. That is why value is converted to text and parsed with from_json and the schema. The rest of the application does not change: that is the advantage of the unbounded table model.

The connector does not come with PySpark. It is added when launching the application, with a version that must match your Spark version (and its Scala version):

spark-submit \
    --packages org.apache.spark:spark-sql-kafka-0-10_2.13:<Spark version> \
    count_from_kafka.py

The checkpoint stores the Kafka offsets already processed: on restart, the application carries on exactly from them.

Spark is neither the only streaming engine nor the most specialised one. Apache Flink was designed from the outset for streaming: it processes event by event, not in micro-batches, with latencies of milliseconds, and treats batches as a special case of a stream that ends. It stands out for its state management (very large state, with consistent snapshots) and for its fine control of event time. Kafka Streams, for its part, is not a cluster but a Java library embedded in an ordinary application to transform data from one topic to another.

Spark Structured Streaming Apache Flink Kafka Streams
Model Micro-batches Event by event Event by event
Typical latency Hundreds of ms to seconds Milliseconds Milliseconds
Deployment Spark cluster Flink cluster Library inside your application
Languages Python, SQL, Scala, Java Java, SQL, Python Java, Scala
Sources and sinks Many Many Kafka only
Strong point Same engine and same API as batch Low latency, complex state Operational simplicity
A good fit when… The team already uses Spark and seconds are enough Streaming is the core of the business Microservices on top of Kafka are needed

These and other tools, including managed services, are presented in more detail in lesson 06-03.

NovaMarket case: fraud and the live dashboard

This is how Laura designs the streaming part of the platform:

flowchart LR
    W[Web and app] --> K[Kafka<br/>topic web_events]
    K --> P[Structured Streaming:<br/>live dashboard]
    K --> F[Structured Streaming:<br/>fraud rules]
    K --> L[Continuous load<br/>to bronze]
    P --> R[(Redis:<br/>dashboard counters)]
    F --> AL[Topic fraud_alerts]
    AL --> RV[Order review]
    L --> B[(Data lake)]

A single topic feeds three independent consumer groups:

  • Live dashboard. Sales and events per minute, with the query from the hands-on exercise, written to Redis (lesson 02-03) so that the dashboard can read them instantly. It tolerates occasional duplicates: at-least-once is enough.

  • Fraud detection. A simple first rule: the same customer with three or more purchases in ten minutes. It is a sliding window:

    suspects = (
        events.where("event_type = 'purchase' AND customer_id IS NOT NULL")
        .withWatermark("event_time", "5 minutes")
        .groupBy(F.window("event_time", "10 minutes", "5 minutes"), "customer_id")
        .agg(F.count("*").alias("purchases"))
        .where("purchases >= 3")
    )
    

    A practical advantage of Structured Streaming is that the rule can be tested in batch before deploying it: applying the same groupBy (without the watermark) to silver/web_events, it flags 38 windows and 32 customers over the whole of June. With that figure, the team decides whether the threshold is reasonable before bothering a single customer. Rules are the first step; machine learning models, covered in lesson 04-03, are the next.

  • Load into the lake. The events are stored in bronze continuously, for the batch processes. It is the stream that feeds the rest of the architecture.

Warning: fraud detection makes automated decisions that affect people (holding an order, blocking an account) based on their personal data. The criteria, human involvement in the review and data retention must be validated with the organisation's regulatory compliance and data protection officers. Privacy is covered in lesson 07-02.

Common Mistakes and Tips

  • Asking for real time without needing it. A streaming system costs several times as much as an equivalent batch. Demand a concrete decision that depends on latency.
  • Aggregating by processing time. The results are no longer reproducible. Use event time and a watermark.
  • Aggregating by window without a watermark. The state grows without limit until memory runs out, after days or weeks.
  • Not validating timestamps. An event with a future date pushes the watermark forward and causes all the legitimate ones to be discarded.
  • Deleting or sharing the checkpoint. Without it, the query starts from scratch; if two queries share it, they become corrupted. After changing the logic of an aggregation, the old checkpoint may be incompatible and the restart has to be planned.
  • Leaving half-written files in an input directory. Write to another folder and move.
  • Choosing the wrong key in Kafka. Without a key, ordering per entity is lost; with a skewed key, one partition becomes saturated.
  • Confusing "exactly-once" with "never fails". It is a property of the source + engine + destination combination; if the destination is not idempotent, it does not hold.
  • Tip: develop and test the logic in batch over historical data and move it to streaming once it works. With Structured Streaming, the code is almost the same.

Exercises

Exercise 1: streaming or batch?

For each need, state the appropriate level of latency and why:

  1. The monthly accounting close for sales.
  2. Alerting the warehouse when a product drops below 5 units.
  3. Recomputing the "bought together" recommendations.
  4. Blocking an account after 10 failed login attempts in one minute.

Exercise 2: events by device in one-hour windows

Modify count_in_stream.py to count events by device in tumbling windows of one hour, with the complete output mode. Replace the nulls in device with unknown. Use a new checkpoint. What does the last micro-batch show after running the simulator?

Exercise 3: reasoning with watermarks

A query uses 5-minute tumbling windows and a 10-minute watermark. The most recent event received is from 10:27. State what happens to an event that arrives now with an event time of: (a) 10:21, (b) 10:16, (c) 10:02.

Solutions

Exercise 1

  1. Batch. Nobody decides anything differently by having the close a few seconds earlier, and it demands accuracy and reproducibility.
  2. Minutes (frequent micro-batches), or seconds if turnover is high. The decision, restocking, is not taken in milliseconds.
  3. Batch, daily or weekly: joint purchase patterns change slowly.
  4. Real time, seconds or less: each additional attempt is a risk. It is a typical case of a short window with per-account state.

Exercise 2

counts = (
    events
    .fillna({"device": "unknown"})
    .withWatermark("event_time", "10 minutes")
    .groupBy(F.window("event_time", "1 hour"), "device")
    .count()
)

query = (
    counts.writeStream
    .outputMode("complete")
    .format("console")
    .option("truncate", False)
    .option("checkpointLocation", str(STREAM / "checkpoint" / "by_device"))
    .trigger(processingTime="5 seconds")
    .start()
)

Before running it, empty stream/input (or delete the whole of stream) and relaunch the simulator. With the six files processed, complete mode shows the whole table, with no guaranteed order; sorted, it contains:

Window desktop mobile tablet unknown
00:00 – 01:00 88 143 5 0
01:00 – 02:00 78 160 14 1
02:00 – 03:00 30 76 3 2

600 events in total. The 02:00 window is incomplete because the simulator stops at 02:25. In complete mode, Spark has to keep every window so that it can re-emit them, so the watermark does not release any state: this mode is only suitable for small results. Changing the checkpoint is mandatory because the previous one stores the state of a different query.

Exercise 3

The watermark is at 10:27 − 10 minutes = 10:17.

  • (a) 10:21: it is later than the watermark. It is counted in the 10:20–10:25 window, no more to it.
  • (b) 10:16: it is earlier than the watermark, but it belongs to the 10:15–10:20 window, which ends after 10:17 and is therefore still open. It is counted. What decides is not the instant of the event, but whether its window has already closed.
  • (c) 10:02: its window, 10:00–10:05, ended before the watermark. It is closed: the event is discarded.

Conclusion

Stream processing works over unbounded streams of events and forces you to reason with time: you aggregate by event time, not by processing time; events are grouped into tumbling, sliding or session windows; the watermark sets how long to wait for late data and makes it possible to release the state; and the delivery semantics determine whether a failure can lose events, duplicate them or neither. Apache Kafka transports the events as a distributed log of topics divided into partitions, in which each consumer group advances through its offsets at its own pace and retention makes rereading possible. Spark Structured Streaming treats the stream as an unbounded table: with readStream, the usual transformations, an output mode and a checkpoint, you have counted events by window and seen how one delayed event is accepted and another that is too late is discarded. Flink and Kafka Streams cover the cases of lower latency or lighter deployment.

You now know the pieces of processing: batch transformations, their optimisation and streaming. But a script run by hand in your terminal is not a data system. At NovaMarket, the load from bronze to silver and gold has to run every night, on its own, in the right order, recover if it fails and be repeatable without duplicating anything. In the next lesson, Data Pipelines: Ingestion, ETL/ELT and Orchestration, you will learn to turn loose scripts into reliable, automated processes, and with that we will close the processing module.

© Copyright 2026. All rights reserved