Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

Streams, Tables and Two Kinds of Time

See why a stream and a table are two views of the same data, run a small example that folds a stream into a table and rebuilds it from its changelog, count the same clicks by event time and by processing time, and compare the lambda and kappa architectures for keeping results correct over time.

Contentsand lesson path

What you will learn

  • Distinguish event time from processing time and compute tumbling, sliding and session window aggregates with watermarks that bound lateness.

Prerequisites: Messaging & Event Streaming

01. Why it matters

A batch job reads a file that has an end. A stream has no end: events such as page views, payments or sensor readings keep arriving, and the job that reads them never sees "all" the data. Stream processing is the work of computing useful results, such as counts, totals or alerts, from data that keeps arriving, and keeping those results correct while it arrives.

Two ideas make this easier than it sounds. The first is that a stream and a table are two views of the same data, so the SQL and DataFrame thinking you already know from Spark batch processing still applies. The second is that every event carries two times, and the time you choose decides whether your numbers are right. This lesson builds both ideas with small Python programs that you can run, and ends with the two classic architectures that teams use to keep streaming results correct: lambda and kappa. Later lessons turn the ideas into real Spark jobs that read from Kafka.

02. Streams and tables are two views of the same data

Think of a page-view counter. The stream is the sequence of view events, in the order they arrived. The table holds the current count for each page. You get the table by folding the stream: start from an empty table and apply each event in turn. You can also go the other way. If you record every change made to the table, as "page, old value, new value", you get a changelog stream, and replaying the changelog from the start rebuilds exactly the same table. This two-way relationship is called the stream-table duality.

The example needs only Python 3.10 or later. Create a folder stream-lab/ for this skill and save the file there.

Python · stream-lab/duality.py
"""A stream folded into a table, and a table turned back into a stream."""
views = [  # the stream: one event per page view, in arrival order
    ("09:00:05", "home"), ("09:00:09", "search"), ("09:00:12", "home"),
    ("09:00:20", "basket"), ("09:00:31", "home"), ("09:00:40", "search"),
]

table = {}          # the table: the latest count per page
changelog = []      # every change to the table, in order
for at, page in views:
    old = table.get(page)
    table[page] = (old or 0) + 1
    changelog.append((at, page, old, table[page]))

print("table:", table)
print("changelog:")
for at, page, old, new in changelog:
    print(f"  {at} {page:<6} {old} -> {new}")

# Replaying the changelog from the start rebuilds exactly the same table.
rebuilt = {}
for _at, page, _old, new in changelog:
    rebuilt[page] = new
print("rebuilt from changelog equals table:", rebuilt == table)
Terminal
python3 duality.py
Expected output
table: {'home': 3, 'search': 2, 'basket': 1}
changelog:
  09:00:05 home   None -> 1
  09:00:09 search None -> 1
  09:00:12 home   1 -> 2
  09:00:20 basket None -> 1
  09:00:31 home   2 -> 3
  09:00:40 search 1 -> 2
rebuilt from changelog equals table: True

Each line of the changelog is one update to one key. Real systems use this idea all the time:

  • A Kafka topic with log compaction keeps at least the latest record for each key, so a new consumer that reads it from the start can rebuild the current table without the full history.
  • Kafka Streams calls a stream a KStream and a table built from a changelog a KTable; its documentation describes the duality in the same terms.
  • Spark Structured Streaming treats the input as a table that grows with every new row, and your query as a "result table" that it updates as the input grows.
  • Change data capture, covered in the Change Data Capture skill, turns a database table into a changelog stream.

The duality also explains stream-table joins. When a job enriches each click with the current category of its page, it looks the page up in a table. That table must be kept current, usually by applying a changelog of the page catalogue to it. Lesson 4 joins a stream of clicks to a page table in Delta Lake.

03. Event time and processing time

Every event has at least two times. Event time is when the event happened, recorded by the device or service that produced it. Processing time is when the stream processor handles it, read from the processor's own clock. A third time, ingestion time, is when the event reached the message broker; Kafka stores one timestamp on each record, which is either the time set by the producer or the broker's append time, depending on the topic setting.

The times differ because networks and devices are not perfect. A phone in a tunnel stores clicks and sends them minutes later. A producer retries after a timeout. A Kafka topic has several partitions, and the processor reads them at slightly different speeds. So events reach the job out of order, and some arrive very late. The program below counts eight clicks in 5-minute windows twice, once by each time.

Python · stream-lab/two_clocks.py
"""Count clicks per 5-minute window by event time and by processing time."""
from collections import Counter

# (event time on the phone, processing time when the job handled it)
clicks = [
    ("10:01", "10:01"), ("10:03", "10:04"), ("10:04", "10:05"), ("10:06", "10:06"),
    ("10:02", "10:07"),   # out of order: the phone was in a tunnel for 5 minutes
    ("10:08", "10:08"), ("10:09", "10:11"),
    ("09:58", "10:12"),   # late: sent when the app was opened again
]


def window(hhmm):
    hours, minutes = map(int, hhmm.split(":"))
    start = minutes // 5 * 5
    return f"{hours:02d}:{start:02d}"


by_event = Counter(window(event) for event, _ in clicks)
by_processing = Counter(window(processed) for _, processed in clicks)
print("window  by event time  by processing time")
for w in sorted(set(by_event) | set(by_processing)):
    print(f"{w}   {by_event[w]:>13}  {by_processing[w]:>18}")

# A replay the next morning handles all eight clicks within one minute.
replay = Counter(window("07:30") for _ in clicks)
print("replay by processing time:", dict(replay))
print("replay by event time:", dict(sorted(by_event.items())))
Terminal
python3 two_clocks.py
Expected output
window  by event time  by processing time
09:55               1                   0
10:00               4                   2
10:05               3                   4
10:10               0                   2
replay by processing time: {'07:30': 8}
replay by event time: {'09:55': 1, '10:00': 4, '10:05': 3}

The two columns disagree. By event time, the 10:00 window has four clicks, because four clicks happened between 10:00 and 10:05. By processing time it has two, because the tunnel click and the slow click were handled after 10:05. The late 09:58 click lands in the 10:10 window by processing time, which is simply wrong for a report about user behaviour.

The last two lines show the deeper problem. If you replay the same events the next morning, for example after fixing a bug, every click is processed at 07:30. Processing-time results change completely, while event-time results stay the same. Event time makes a streaming job deterministic: the same input gives the same output, whenever and however fast you process it. The price is that the job must decide how long to wait for late events before it treats a window as complete. That decision is called a watermark, and lesson 2 follows one event by event.

Processing time is still useful. Monitoring "how many events did we handle in the last minute" is a processing-time question, and processing time needs no waiting at all. Choose event time when the result describes the world, and processing time when it describes the pipeline.

04. Lambda and kappa architectures

Late data, bugs and changing business rules all mean that results computed in the past sometimes need to be computed again. Two architectures answer that need in different ways.

The lambda architecture runs two pipelines side by side. A batch layer recomputes complete, correct results from all historical data, for example every night. A speed layer, a streaming job, computes approximate results for the hours since the last batch run. Queries merge the two. Lambda is easy to reason about, because the batch layer repairs any mistake of the speed layer. Its cost is that the same logic lives in two code bases, often in two frameworks, and keeping them identical is hard. When the two disagree, users see numbers that change overnight.

The kappa architecture, proposed by Jay Kreps in 2014, keeps one streaming pipeline and treats reprocessing as replay. The durable log, such as a Kafka topic with long enough retention, is the source of truth. To fix a bug, you start a second copy of the fixed job that reads the log from the beginning, or from the point where the bug started, into a new output. When it has caught up, readers switch to the new output and the old job is stopped. Lesson 5 does exactly this.

Kappa works only when the log really holds the history you need, so retention, compaction and storage cost become design decisions. Many teams today use a middle path: one engine, such as Spark or Flink, runs the same code as a streaming job and as a batch backfill over a lakehouse table. What matters is that a single definition of the logic produces every result.

05. Check your understanding

Practice check · 3 questions

Streams, tables and time

Pick the best answer for each situation.

Q1. A service keeps the current delivery address of each customer in memory. After a restart it reads a log-compacted Kafka topic, keyed by customer id, from the first offset. What does it end up with?
Q2. In the clicks example, a click happened at 10:04 and the job processed it at 10:13. A report counts clicks in 5-minute windows by processing time. Which window does this click fall into?
Q3. A team computes daily revenue twice: a nightly Spark batch job and a Flink streaming job written separately. The morning figures often differ from the live figures of the evening before. What is the main thing a kappa design changes?
Practice only: not graded, not saved, not evidence.

06. Apply it

The practice project of this skill produces synthetic clickstream events to Kafka, some out of order and some late, and counts page views in 5-minute windows. Before you write any Spark code, write down, for that project:

  1. Which field of each event is its event time, and which clock sets it.
  2. Which questions in the project are about user behaviour (event time) and which are about the pipeline (processing time).
  3. How the project would recompute past results after a bug: which log or table holds the history, and for how long.

07. Review prompt

Without looking back, explain in your own words:

  • how a table can be rebuilt from a stream, and a stream obtained from a table;
  • why event time gives the same results on replay and processing time does not;
  • why events arrive out of order, with two concrete causes;
  • the difference between the lambda and kappa architectures, and what each costs.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check