Skip to content
LeetQuant
QD07 Databases, Pipelines and Distributed Systems

QD07 · Databases, Pipelines and Distributed Systems · Lesson 3 of 5

Streaming and Batching

Reason about event time versus processing time, assign out-of-order events to windows using watermarks, compare micro-batching with true streaming, and get exactly-once results from at-least-once delivery with idempotent sinks.

17 min

Objective

Batch jobs process a bounded dataset (yesterday's trades) and finish. Streaming jobs process an unbounded one (today's trades as they arrive) and never finish. The interview questions are about what changes when the data never ends: "how do you compute one-minute bars from a feed with out-of-order messages?", "what does exactly-once mean?", "when would you not bother with streaming?". By the end of this lesson you should be able to answer each with mechanisms, not slogans.

Event time versus processing time

Every record has at least two times:

  • Event time: when it happened (the exchange timestamp on a trade).
  • Processing time: when your system handles it (the clock of the machine running the job).

They differ by network delay, buffering, retries and outages, and the difference is not constant. If a feed handler pauses for 2 seconds, every message from those 2 seconds arrives in a burst, and a bar built on processing time puts them all in the wrong second. Results must be defined in event time if they are to be reproducible: rerunning the same input tomorrow gives the same one-minute bars only if bars are keyed by exchange time. Processing time is fine for operational metrics (messages per second through this box).

Windows

  • Tumbling: fixed, non-overlapping intervals; one-minute bars. Each event belongs to exactly one window, ⌊t/w⌋\lfloor t / w \rfloor.
  • Sliding (hopping): fixed length, advancing by a smaller step; a 5-minute volume updated every minute. Each event belongs to length/step windows.
  • Session: windows separated by gaps of inactivity; a burst of order activity from one client.

Watermarks: when is a window complete?

In event time, a window [0,10)[0, 10) can never be known to be complete, because an event stamped 9 could still arrive. A watermark is the system's assertion that "no more events with event time below WW are expected". When the watermark passes a window's end, the window is emitted. A simple, common heuristic is

W=max⁡(event time seen)−allowed lateness.W = \max(\text{event time seen}) - \text{allowed lateness}.

Events that arrive for an already-emitted window are late: drop them, send them to a side output for audit, or emit a corrected result (a retraction or an update). The allowed lateness is a trade-off: larger means fewer late events but longer delay before each result appears.

from collections import defaultdict

WINDOW = 10      # seconds per tumbling window
LATENESS = 3     # watermark lags the max event time seen by this much

def run(events):
    """events: (event_time, volume) in ARRIVAL order."""
    open_windows = defaultdict(int)   # window start -> volume
    max_seen = float("-inf")
    for t, vol in events:
        start = t - t % WINDOW
        watermark = max_seen - LATENESS
        if start + WINDOW <= watermark:
            print(f"t={t:>2}: window [{start},{start + WINDOW}) already closed -> late")
            continue
        open_windows[start] += vol
        max_seen = max(max_seen, t)
        watermark = max_seen - LATENESS
        for s in sorted(open_windows):
            if s + WINDOW <= watermark:
                print(f"emit [{s},{s + WINDOW}) volume={open_windows.pop(s)}")
    for s in sorted(open_windows):      # end of stream flushes the rest
        print(f"emit [{s},{s + WINDOW}) volume={open_windows.pop(s)} (flush)")

run([(1, 100), (4, 200), (12, 50), (9, 300), (14, 70), (6, 40), (21, 10), (25, 5)])
emit [0,10) volume=600
t= 6: window [0,10) already closed -> late
emit [10,20) volume=120
emit [20,30) volume=15 (flush)

Trace it. After the event at 12 the watermark is 9, so [0,10)[0, 10) stays open and the out-of-order event at 9 is still counted (100+200+300=600100 + 200 + 300 = 600). The event at 14 moves the watermark to 11, which closes [0,10)[0, 10). The event at 6 then arrives 8 seconds behind the maximum, more than the 3 allowed, and is dropped. With LATENESS = 8 the same input emits [0,10)[0, 10) with volume 640, but only when the event at 21 pushes the watermark to 13: completeness was bought with latency.

Real frameworks (Flink, Beam, Spark Structured Streaming, Kafka Streams) implement exactly this idea, with per-partition watermarks combined by taking the minimum across inputs: one slow partition holds back every window. An idle partition that sends nothing would hold the watermark forever, which is why they have idleness timeouts.

Micro-batching versus record-at-a-time

  • Micro-batching (Spark Structured Streaming's default) collects, say, 1 second of input and runs a small batch job on it. Simple fault tolerance (rerun the batch), high throughput, latency at least the batch interval.
  • Record-at-a-time (Flink, Kafka Streams) processes each event as it arrives with per-key state. Millisecond latency, more complex state management.
  • Plain batch on a schedule (an hourly or nightly job) is right far more often than people admit. Research datasets, end-of-day risk, daily signal generation and reconciliation need correctness and reproducibility, not sub-second latency.

In a trading firm, the latency-critical path (market data to order) usually does not use a general streaming framework at all; it is hand-written C++ on a single machine. Streaming frameworks sit in the middle: real-time risk aggregation, monitoring, surveillance, and live features for slower strategies. A sound interview answer names the latency requirement first and picks the simplest tool that meets it.

Delivery guarantees

  • At-most-once: commit progress before processing. A crash loses the in-flight records. Acceptable for metrics you can afford to undercount.
  • At-least-once: process, then commit progress. A crash after processing but before the commit replays the records. Nothing is lost; duplicates are possible.
  • Exactly-once: each record affects the result once. No network can deliver each message exactly once (the sender cannot distinguish "lost" from "slow ack"), so exactly-once is built as at-least-once delivery plus idempotent or transactional effects.

The two standard ways to get the effect are (1) an idempotent sink: write keyed by a unique event id so a replay overwrites rather than adds; and (2) transactional commit: write the output and the consumed offset in one atomic transaction (Kafka transactions, or storing the offset in the same database table as the results), so they are either both recorded or neither is.

Worked example

a crash between write and commit

A consumer reads four events (volumes 100, 200, 300, 400, with ids e1 to e4), writes each to a sink, then commits its offset. It crashes once, right after writing e3 and before committing. On restart it resumes from the last committed offset. What total volume does the sink hold if it appends, and if it upserts by event id?

Show solution

Step 1: what is replayed. The last committed offset points at e3, so after the restart e3 is read and written again, then e4.

Step 2: the two sinks.

log = [("e1", 100), ("e2", 200), ("e3", 300), ("e4", 400)]   # (event_id, volume)

def consume(sink_write, crash_after_write_of=None):
    committed = 0                       # offset of the next event to read
    crashed = False
    while committed < len(log):
        offset = committed
        event_id, vol = log[offset]
        sink_write(event_id, vol)
        if event_id == crash_after_write_of and not crashed:
            crashed = True              # crash before the offset commit
            continue                    # restart from the last committed offset
        committed = offset + 1

total = 0
def append_sink(event_id, vol):
    global total
    total += vol

seen = {}
def keyed_sink(event_id, vol):
    seen[event_id] = vol                # upsert by event id

consume(append_sink, crash_after_write_of="e3")
consume(keyed_sink, crash_after_write_of="e3")
print("append sink:", total)               # append sink: 1300
print("keyed sink:", sum(seen.values()))   # keyed sink: 1000

The appending sink double counts e3: 1000+300=13001000 + 300 = 1300. The keyed sink writes e3 twice to the same key and holds the correct 1,000.

Step 3: what to say. Delivery was at-least-once in both cases; only the sink made the result exactly-once. The idempotent sink requires a stable, unique id per event, assigned at the source (an exchange sequence number or a producer-generated id), not at the consumer, where a replay would get a new id.

Worked example

choosing the allowed lateness

You build one-second bars in event time. Measured over a week, the delay between exchange timestamp and arrival is below 40 ms for 99% of messages and below 250 ms for 99.99%, with rare multi-second gaps during feed failovers. Downstream, a risk monitor wants each bar within 0.5 s of the second's end. Propose a watermark policy and handling for late data.

Show solution

Step 1: latency budget. A bar for [t,t+1)[t, t+1) is emitted when the watermark reaches t+1t + 1, which happens when an event with time at least t+1+Lt + 1 + L has arrived, so emission is at least LL after the window end (plus processing). To meet 0.5 s, LL must be well under 0.5 s.

Step 2: completeness. With L=250L = 250 ms, about 1 in 10,000 messages is late; with L=40L = 40 ms, about 1 in 100. Bars contain many messages, so 1% late messages would make a large share of bars incomplete. Choose L=250L = 250 ms: inside the budget with margin for processing.

Step 3: the tail. Failover gaps exceed any reasonable LL. Do not drop those events silently: send late events to a side output, emit a corrected bar (an update keyed by the bar's start time, so the downstream store upserts it), and count late events as a monitored metric. The end-of-day batch rebuild from the complete recorded feed remains the source of truth for research.

This is the general shape of the answer: the streaming result is fast and almost always right; a batch recomputation over complete data is slow and authoritative, and both are keyed so the later one overwrites the earlier.

Knowledge check

A one-minute volume bar is computed by assigning each trade to the minute of the server clock when it was processed. After a 20-second network stall, what happens?

Knowledge check

A stream job reads three Kafka partitions. Two are at event time 10:00:05 and one has been delayed and is at 09:59:50. With zero allowed lateness, up to what event time can windows be closed?

Knowledge check

Which design gives exactly-once results for a per-trade P&L table fed by an at-least-once message queue?

Key takeaways

  • Define results in event time; use processing time only for operational metrics.
  • A watermark asserts "no more events below WW". Max-seen minus allowed lateness is the simple version; the job's watermark is the minimum over inputs.
  • Allowed lateness trades latency for completeness. Handle late data explicitly: side output, corrected result, or metric.
  • Micro-batching is simple and high-throughput; record-at-a-time gives lower latency; scheduled batch is often the right answer. Start from the latency requirement.
  • Exactly-once is at-least-once delivery plus idempotent (keyed by a source-assigned id) or transactional (output and offset together) writes.
  • Pair a fast streaming result with an authoritative batch rebuild, keyed so the later result overwrites the earlier.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).