The two previous lessons dealt with processes that run once every night. It is the simplest way of working, and for most of DataCorp's data it is enough. But RQ-04 contains two requirements that a nightly load does not meet: stock levels cannot be more than 15 minutes old and the clickstream, no more than an hour. The instinctive reaction to requirements like these is to ask for "real time".

This lesson explains what lies behind that expression. We will look at the three processing modes (batch, micro-batch and continuous streaming), the magnitudes that set them apart, the concepts specific to stream processing (which change the way you think about time, order and failures) and the infrastructure that supports it. And we will finish with the question an architect should always ask before adding that complexity: do I really need it? ADR-010 will record DataCorp's answer.

The choice of specific products is left for lesson 04-04; here we work with concepts.

Three processing modes

Lesson 01-03 distinguished, at the level of the idea, batch processing from streaming. Let's be more precise, adding the point in between:

Batch Micro-batch Streaming
Unit of work A large, closed set of data A small set, every few seconds or minutes Each event, one by one, as it arrives
When it runs At a scheduled time At short, regular intervals Always: the process never ends
Typical age of the data Hours to a day Seconds to minutes Milliseconds to seconds
The process Starts, works and finishes Starts, works and finishes, many times over Stays running
Example The nightly load of orders Stock levels every 10 minutes Blocking a fraudulent payment on the spot

Two remarks avoid misunderstandings:

  • "Real time" is an imprecise expression. Strictly speaking, it refers to systems with guaranteed deadlines (controlling a brake). In data it is used loosely to mean "very fresh". It is always worth replacing it with a figure: "maximum age of 15 minutes".
  • A micro-batch is a batch. It has a beginning and an end, it can be retried and it is built with the same techniques as in the previous lessons. What sets it apart is the frequency. That continuity is its great practical advantage.

Latency, throughput, cost and complexity

Four magnitudes make it possible to compare the modes:

  • Latency: the time between a fact happening and its effect being available. It is the technical side of freshness (lesson 01-04).
  • Throughput: the amount of data processed per unit of time.
  • Cost: of infrastructure and, above all, of people.
  • Complexity: the number of components, of failure modes and of concepts the team has to master.
Magnitude Batch Micro-batch Streaming
Latency High Medium Very low
Throughput per resource The best: processing in bulk is the most efficient Good Lower per event; requires reserved resources
Infrastructure cost Low: you pay only while it runs Medium High: always on, sized for the peak
Operational complexity Low Low to medium High: state, out-of-order data, restarts without loss
Reprocessing after an error Trivial: the batch is rerun Trivial Hard: the stream has to be "rewound"
Debugging a failure Easy: data at rest and reproducible Easy Hard: it depends on the order of arrival

The table sums up a trade-off with no trick to it: every reduction in latency is paid for in cost and in complexity. Besides, latency and throughput pull in opposite directions: grouping many events and handling them together is more efficient, but it forces you to wait for them to accumulate.

Events and unbounded streams

To understand stream processing you have to change your mental model. We will use DataCorp's clickstream.

An event is the immutable record of something that happened at a point in time. It is not modified: if the customer removes the product from the cart, that is another event.

{"event_id": "e-7f3a91", "type": "add_to_cart",
 "event_time": "2026-11-18T10:04:10Z", "customer_id": 1042,
 "device": {"type": "mobile", "os": "android"},
 "product": {"product_id": 3301, "quantity": 1}}

A stream is an unbounded sequence of events: it has no end. That is the essential difference from a batch:

Bounded set (batch) Unbounded stream
You know how much data there is You never have "all" the data
"Count the events" has an answer "Count the events" never finishes: you have to bound it in time
It can be sorted before processing It is processed in order of arrival, which may not be the real order
If it fails, the whole thing is repeated If it fails, it has to resume where it left off

All the concepts that follow stem from those four differences.

Event time and processing time

Every event has two times:

  • Event time: when it happened, according to the device that generated it (the event_time field).
  • Processing time: when the system that processes it receives it.

Ideally they would coincide, but they do not. DataCorp's app stores the events on the phone and sends them as soon as there is coverage: a customer who adds a product to the cart on the subway at 10:04 may not send the event until 10:09. And the events of different users travel along different network paths, so they arrive out of order.

If you group by... Advantage Drawback
Processing time Trivial: you just look at the clock The result depends on the network and on when it ran; reprocessing gives a different figure
Event time It reflects what happened; reprocessing gives the same result You have to decide how long to wait for stragglers

For analysis, event time is almost always used: Laura is interested in how many products were added to the cart between 10:00 and 10:05, not in how many notifications a server received in that interval.

Windows

Since "counting all the events" never finishes, calculations on a stream are bounded with windows: time intervals over which you aggregate.

Type Definition Do they overlap? An event belongs to... Example at DataCorp
Fixed (tumbling) Consecutive intervals of equal length No Exactly one window Add-to-cart events per product every 5 minutes
Sliding Fixed length, but a new one starts at every slide interval Yes Several windows Searches in the last 15 minutes, updated every 5
Session Groups a user's activity until some time passes with no events No (per user) One session, of variable length A customer's visit: it closes after 30 minutes of inactivity
Time             10:00     10:05     10:10     10:15     10:20
Fixed (5 min)    |----A----|----B----|----C----|----D----|
Sliding          |------------A------------|                  (15 min, slide 5)
                           |------------B------------|
Session          |--x-x--x--|          |-x---x-|              (gap > inactivity)
                  session 1             session 2

Session windows are the ones the conversion funnel (UC-04) needs: the steps "search → view product → add to cart → purchase" only make sense within the same visit.

Late data and watermarks

If the window [10:00, 10:05) is grouped by event time and events can arrive late, a dilemma arises: when is it considered closed? If it is closed at 10:05 sharp, the stragglers are lost; if you wait indefinitely, there is never a result.

The solution is the streaming watermark: an estimate, maintained by the system, of the point in event time up to which practically everything has already arrived. A common way of calculating it:

watermark = highest event time seen so far - allowed lateness

With an allowed lateness of 2 minutes, on receiving an event from 10:07:45 the watermark moves to 10:05:45. Since it is past the end of the window [10:00, 10:05), the window is closed and its result is emitted. An event from 10:03 that arrives afterwards is late data, and you have to decide what to do with it:

Policy Effect When
Discard it (and count it) A fast, slightly incomplete result Approximate indicators
Correct the emitted result Exact, but the consumer has to accept corrections Figures that feed decisions
Divert it to a separate output It is processed later, in batch When there is a downstream process that consolidates

The allowed lateness is, once again, a trade-off: more lateness allowed means results that are more complete and arrive later.

A warning about vocabulary: this watermark is not the one from lesson 03-05. That one recorded how far an incremental extraction had got; this one estimates up to where a stream is complete. They share a name and an underlying idea (a point in time that separates what has been handled from what is pending), but they are different mechanisms.

State

A stateless process handles each event in isolation: converting a format, filtering a type. A stateful one needs to remember something between events: the count for the open window, each customer's ongoing session, the identifiers already seen so as not to count duplicates.

That state is what makes stream processing hard:

  • It has to survive a restart. If the process goes down at 10:04, the counts for the open window cannot be lost. Streaming engines periodically save a copy of the state (a checkpoint) and, on startup, resume from it.
  • It grows. One session for every active customer; if the state of closed windows is not released, memory runs out.
  • It complicates scaling. Spreading the work across several machines requires spreading the state as well.

In a batch the problem does not exist: the "state" is the data itself, which sits at rest in storage.

Delivery guarantees and idempotency

Between whoever emits an event and whoever processes it there are networks and machines that fail. Depending on how failures are handled, a system offers one of three guarantees:

Guarantee What it means How it is achieved Risk
At-most-once Each event is processed 0 or 1 times It is sent and not retried Loss of events
At-least-once Each event is processed 1 or more times It is retried until an acknowledgment is received Duplicates
Exactly-once The effect of each event is applied only once At-least-once plus a mechanism that neutralizes the repetitions Greater complexity and cost

The third deserves a clarification: there is no network that delivers every message exactly once. What can be achieved is that the effect is that of a single delivery, and there are two ways: transactions that span the read and the write (which some engines offer), or at-least-once delivery with an idempotent destination.

The second way is the one we already know. If every event carries a unique identifier (event_id) and the destination removes duplicates by it, it does not matter if an event arrives twice:

-- Cleansing the clickstream: one row per event, even if it arrived more than once
SELECT *
FROM (
    SELECT e.*,
           ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY load_date) AS row_num
    FROM raw.events e
) copies
WHERE row_num = 1;

It is the same deduplication technique as in lesson 03-05, and the reason why idempotency appears in every lesson of this module: it turns the cheap guarantee (at-least-once) into the expensive one (exactly-once).

Queues and event logs

Events do not travel directly from the producer to whoever processes them. They go through an intermediate messaging system, the pattern that lesson 03-05 introduced. There are two families:

Traditional message queue Distributed event log
When a message is consumed It is removed from the queue It stays; each consumer records how far it has read
Several consumers They share out the messages: each message is received by only one consumer Each consumer group reads the whole stream, at its own pace
Reading the past again Not possible Yes, within the retention period
Order Not always guaranteed Guaranteed within each partition
Typical use Distributing tasks among workers Event streams with several destinations and the option to reprocess

For analytical data the event log is preferred, because it allows reprocessing and adding consumers without touching the producer. Its concepts:

  • Topic: a named stream of events. At DataCorp, clickstream.events.
  • Partition: each topic is divided into partitions, which are ordered sequences that are only appended to at the end. They make it possible to spread the load across machines. Order is guaranteed within a partition, not across partitions.
  • Partition key: the value in the event that decides which partition it goes to. With customer_id as the key, all of a customer's events go to the same partition and keep their order.
  • Offset: the position of an event within its partition (0, 1, 2...).
  • Consumer group: a set of processes that cooperate to read a topic; the partitions are shared out among them, and the group stores the offset it has reached. Two different groups read the topic independently.
  • Retention: the time for which events are kept, whether they have been read or not.
graph LR
    W["Web"] --> T
    A["App"] --> T
    subgraph T["Topic clickstream.events"]
        P0["Partition 0: e0 e1 e2 e3 ..."]
        P1["Partition 1: e0 e1 e2 ..."]
        P2["Partition 2: e0 e1 e2 e3 e4 ..."]
    end
    T --> G1["Group file-collector<br/>(writes files every 15 min)"]
    T -.-> G2["Future group<br/>(e.g. recommendations)"]

The diagram shows the most valuable property: the day DataCorp wants a second use for the clickstream, adding another consumer group will be enough. Neither the website nor the current collector will notice. And if the collector fails for two hours, on startup it carries on from its last offset: as long as the retention has not expired, nothing is lost.

Example: a fixed window in Python

The following program, with no external libraries, simulates what a streaming engine does: it counts the add_to_cart events per product in fixed 5-minute windows, grouping by event time, with events that arrive out of order and a watermark with 2 minutes of allowed lateness.

from collections import defaultdict
from datetime import datetime, timedelta

WINDOW = timedelta(minutes=5)             # size of the fixed window
ALLOWED_LATENESS = timedelta(minutes=2)   # maximum delay that is accepted

# Events IN ORDER OF ARRIVAL: (time of the event, type, product_id)
EVENTS = [
    ("10:00:40", "add_to_cart", 3301),
    ("10:01:15", "search",      None),
    ("10:02:30", "add_to_cart", 5120),
    ("10:04:50", "add_to_cart", 3301),
    ("10:05:20", "add_to_cart", 4410),
    ("10:04:10", "add_to_cart", 3301),   # out of order, but it arrives in time
    ("10:06:30", "add_to_cart", 5120),
    ("10:07:45", "add_to_cart", 4410),
    ("10:03:05", "add_to_cart", 5120),   # too late: its window has already closed
    ("10:11:10", "add_to_cart", 3301),
    ("10:12:30", "search",      None),
]


def window_start(event_time: datetime) -> datetime:
    """Returns the start of the 5-minute window the timestamp belongs to."""
    minute = event_time.minute - event_time.minute % 5
    return event_time.replace(minute=minute, second=0)


def process(events):
    state = defaultdict(lambda: defaultdict(int))    # window -> product -> count
    closed = set()                                   # windows already emitted
    watermark = datetime.min                         # current watermark
    late = 0

    for clock_time, event_type, product_id in events:
        event_time = datetime.strptime("2026-11-18 " + clock_time, "%Y-%m-%d %H:%M:%S")

        # 1. The watermark advances with the highest event time seen
        watermark = max(watermark, event_time - ALLOWED_LATENESS)

        # 2. The event is assigned to its window according to its event time
        if event_type == "add_to_cart":
            window = window_start(event_time)
            if window in closed:
                late += 1
                print(f"  [late] event at {clock_time}: window {window:%H:%M} is already closed")
            else:
                state[window][product_id] += 1

        # 3. The windows whose end the watermark has passed are closed and emitted
        for window in sorted(state):
            if window + WINDOW <= watermark:
                end = window + WINDOW
                print(f"Window [{window:%H:%M}, {end:%H:%M}) -> {dict(state[window])}")
                closed.add(window)
                del state[window]                    # the state is released

    print(f"Windows still open: {[f'{w:%H:%M}' for w in state]}; late events: {late}")


process(EVENTS)

Output:

Window [10:00, 10:05) -> {3301: 3, 5120: 1}
  [late] event at 10:03:05: window 10:00 is already closed
Window [10:05, 10:10) -> {4410: 2, 5120: 1}
Windows still open: ['10:10']; late events: 1

What happens, step by step

  • state is a dictionary of dictionaries: for each open window, the count per product. defaultdict(int) makes a new product start at 0 without having to check for it. This is the state we were talking about: if the program stopped, it would be lost.
  • window_start rounds down to the multiple of 5 minutes: 10:04:50 belongs to the window that starts at 10:00.
  • The 10:04:10 event arrives after the 10:05:20 one. It is out of order, but when it arrives the watermark is at 10:03:20 (10:05:20 minus 2 minutes): the 10:00 window is still open and the event is counted. That is why product 3301 adds up to 3.
  • When the 10:07:45 event arrives, the watermark moves to 10:05:45, goes past 10:05 and the first window is closed and emitted. Its state is deleted.
  • The 10:03:05 event arrives after that close. It is late data: here it is discarded and counted. Without it, product 5120 appears with 1 instead of 2.
  • The 10:10 window is never emitted: no event has arrived that takes the watermark beyond 10:15. In a real stream, there is always an open window.

Try changing ALLOWED_LATENESS to 5 minutes: the 10:03:05 event will get in on time, but the first window will not be emitted until the 10:11:10 event arrives. More complete, later.

Now compare this with doing the same thing in batch: at 11:00 all the events of the hour are read, they are grouped with a GROUP BY by window and product, and the result is exact, with no watermarks, no state and no late data (except for events delayed by more than an hour). All the difficulty of the example comes from wanting the result before having the complete data.

Do I really need real time?

The question that decides the mode is not "how fast can the data arrive?", but "how fast is anyone going to act on it?". Data that is updated every second and looked at once a day does not need continuous streaming. Three questions help:

  1. Who acts, and how often? If the decision is made by a person in a morning meeting, D+1 is enough. If it is made by a system automatically on every event, streaming is needed.
  2. What is lost if the data arrives 15 minutes later? If the answer is "nothing measurable", there is no requirement.
  3. How much does the difference cost? Going from one day to 15 minutes is done with the same tools; going from 15 minutes to 5 seconds requires different infrastructure and different skills.

Applied to the freshness requirements of RQ-04:

Use case Data Required freshness Who acts Mode Frequency
UC-01 Daily net sales Orders D+1, 07:00 Management, every morning Batch Daily, 01:15
UC-02 Campaign profitability Campaigns and orders D+1, 07:00 Marketing, daily Batch Daily, 04:00
UC-05 Issue reasons Tickets D+1, 07:00 Customer Support, weekly Batch Daily, 02:00
UC-03 Stockout alert Stock levels 15 minutes Operations, on receiving the alert Micro-batch Every 10 minutes
UC-04 Conversion funnel Clickstream 1 hour Marketing, during a campaign Micro-batch Every 15 minutes
UC-06 Demand forecast Historical sales and inventory Not urgent Purchasing, weekly Batch Weekly

No case requires continuous streaming. Let's check that micro-batches comply, by calculating the age in the worst case:

Flow Wait until collection Wait until processing Duration of the process Worst case Limit
Stock levels 10 min (the ERP API is queried every 10 min) 0 (it is processed in the same run) Up to 3 min 13 min 15 min
Clickstream 15 min (the collector closes a file every 15 min) 5 min (the micro-batch starts at minutes 5, 20, 35 and 50) Up to 5 min 25 min 60 min

The stock levels flow complies with a margin of just two minutes: its process cannot take more than three minutes, and that duration will have to be watched. The clickstream complies comfortably.

This split, mostly batch and a small part run more frequently, has architectural implications. There are two reference architectures for combining batch and streaming, called Lambda and Kappa, which we will study in lesson 06-05; for now it is enough to know that DataCorp needs neither of them, because its micro-batches are simply frequent batches that share tools and code with the nightly load.

ADR-010: DataCorp's processing modes

ADR-010: Batch and micro-batch processing; continuous streaming deferred
Status: accepted            Date: 2026-12-01

CONTEXT
RQ-04 requires D+1 for sales, campaigns and tickets; 15 minutes for
stock levels; 1 hour for the clickstream. No current use case requires
reacting to individual events. The team is two people (RQ-13) and the
budget is limited (RQ-12).

DECISION
1. Default mode: daily batches (sales, campaigns, tickets, inventory
   snapshot).
2. Stock levels: micro-batch every 10 minutes; the process must not take
   more than 3 minutes (maximum age in the worst case: 13 minutes).
3. Clickstream: micro-batch every 15 minutes, at minutes 5, 20, 35 and 50,
   on the files delivered by the collector (worst case: 25 minutes).
   Sessions and the funnel are calculated in batch on the cleansed
   events, grouping by event time.
4. Events travel through an event log (topic clickstream.events,
   key customer_id, 7-day retention), with at-least-once delivery and
   deduplication by event_id when cleansing.
5. No continuous stream processing engine is deployed.

ALTERNATIVES CONSIDERED
A. Continuous streaming for stock levels and clickstream. Rejected for
   now: it would give seconds where minutes are asked for, in exchange for
   permanent stateful processes that two people cannot operate.
B. Everything in daily batches. Rejected: it breaches RQ-04 in UC-03 and
   UC-04.
C. Change data capture (CDC) and streaming for orders. Deferred (ADR-007).

CONDITIONS FOR RECONSIDERING CONTINUOUS STREAMING
- A use case that requires an age of less than 1 minute or an automatic
  reaction per event (payment fraud, recommendations during the visit).
- The freshness required of stock levels dropping below 5 minutes.
- A micro-batch failing to finish reliably within its interval.

CONSEQUENCES
Positive: a single set of tools and techniques; trivial reprocessing;
low cost. The event log leaves the door open: a future streaming
consumer would be added without touching the producers.
Negative: a margin of only 2 minutes for stock levels; the clickstream
indicators are not instantaneous.

Common Mistakes and Tips

  • Asking for "real time" without a figure. Always demand a maximum age and a business reason. Most requests for real time are satisfied with 15 minutes.
  • Confusing the speed of arrival with the need to process instantly. The fact that the clickstream arrives continuously does not force you to process it continuously.
  • Grouping by processing time. The figures change every time you reprocess, and network spikes look like activity spikes. Group by event time.
  • Ignoring late data. There is always some. Decide on a policy and measure how much there is.
  • Assuming there will be no duplicates. With at-least-once delivery, there will be. Every event needs a unique identifier and every destination, deduplication.
  • Choosing the wrong partition key. If order matters per customer, the key must be the customer. A key with few distinct values concentrates the load on a few partitions.
  • Micro-batches that step on each other. If a run takes longer than the interval, the next one must not start on top of it. We will see this when orchestrating (lesson 04-05).
  • Tip: design batches so that they can run more frequently without being rewritten: parameterized by interval and idempotent. Going from daily to hourly will be a matter of changing a schedule.
  • Tip: adopt an event log early even if you process in batch. It decouples the producers and keeps the continuous streaming option open.

Exercises

Exercise 1: Assigning events to windows

A customer generates events at 10:02, 10:04, 10:13, 10:50 and 10:58 (event time). State:

  1. How many fixed 10-minute windows they fall into and how many events each one contains.
  2. How many sessions they form with an inactivity timeout of 30 minutes, and which ones they are.
  3. Which sliding windows of 10 minutes with a slide of 5 minutes the 10:13 event belongs to.

Exercise 2: Which mode does it need?

Propose the processing mode for each case and justify it:

  1. Blocking an order if the card has been used in five countries within an hour.
  2. A monthly sales report for the board of directors.
  3. Showing "3 units left" on the website next to each product.
  4. A dashboard that the Marketing team checks during Black Friday to see how the BF26-HOGAR campaign is going.

Exercise 3: Watermark and guarantees

In the program from the lesson:

  1. What would have to change so that late events were not discarded, but stored for a later process?
  2. If the producer resent the 10:02:30 event by mistake, what result would the first window give? How would you avoid it?

Solutions

Exercise 1

  1. Three windows with events: [10:00, 10:10) with 2 events (10:02 and 10:04); [10:10, 10:20) with 1 (10:13); [10:50, 11:00) with 2 (10:50 and 10:58). The 10:20, 10:30 and 10:40 ones are empty and are normally not emitted.
  2. Two sessions. Between 10:13 and 10:50 there are 37 minutes, more than the limit of 30. Session 1: 10:02, 10:04 and 10:13. Session 2: 10:50 and 10:58.
  3. Two windows: [10:05, 10:15) and [10:10, 10:20). In a sliding window, each event belongs to as many windows as the ratio length / slide indicates (here, 10 / 5 = 2).

Common mistake: counting empty windows, or closing the session by total duration instead of by inactivity.

Exercise 2

  1. Continuous streaming. The decision is automatic, per event, and has to be made before the payment is confirmed: seconds. It is precisely the first condition of ADR-010.
  2. Batch. The daily load is more than enough; the report is generated once a month.
  3. No analytical mode. It is operational data that must be read from the transactional system or from the ERP at the moment the page is displayed. The analytical platform does not serve data to the website: mixing up the two worlds is an architecture mistake (lesson 01-01).
  4. Micro-batch. People look at the dashboard every so often and adjust the campaign over the course of the day. The clickstream at 25 minutes is enough; orders arrive D+1, so to see sales during the day they would have to be extracted more frequently that week (for example, every hour), which is still a batch.

Exercise 3

  1. Replace the counter with a list: in the if window in closed branch, append the event to late_events and, at the end, write the list to a file. It is the "separate output" policy; a later batch process would recalculate the affected windows.
  2. The first window would give {3301: 3, 5120: 2}: the duplicate is counted as one more event. It is avoided by giving each event an event_id and keeping in the state the set of identifiers already seen for each open window: if a repeated one arrives, it is ignored. That set is more state to maintain, which illustrates why "exactly-once" has a cost. At DataCorp it is solved more cheaply: by deduplicating by event_id when cleansing.

Conclusion

There are three ways of processing data: in batch, in micro-batches and in continuous streaming. They differ in latency, throughput, cost and complexity, and every reduction in latency is paid for in the other three. Stream processing forces you to reason about unbounded sequences of events: telling event time apart from processing time, bounding calculations with fixed, sliding or session windows, using a watermark to decide how long to wait for late data, maintaining state that survives failures and choosing a delivery guarantee, knowing that "exactly-once" is achieved in practice with at-least-once delivery and idempotency. Distributed event logs, with their topics, partitions, consumer groups and retention, are the infrastructure that supports it, and they provide decoupling even when you process in batch. The decisive question is how fast anyone is going to act on the data; at DataCorp, the answer is daily batches for almost everything and micro-batches for stock levels and the clickstream, as ADR-010 sets out.

We now know which approach to follow (ELT, with versioned SQL) and in which mode to process each source. What remains is deciding what to do it with. The market offers SQL engines, single-machine libraries, distributed engines, messaging platforms and managed connectors, and it is easy to choose more than you need. The next lesson surveys that landscape and selects, with explicit criteria, DataCorp's processing tools.

© Copyright 2026. All rights reserved