Events and logs
Part of the free LogicWiz Data Engineering course, Module 15: Streaming. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 10:05 on Friday, an hour into SwiftKart's first flash sale. Tess opens the sale dashboard and it says 0 carts for the discounted earbuds. The app is taking about a thousand clicks a second. Your warehouse loads once a night, so the honest answer to "how many so far?" is "tomorrow at 6 am". Tess asks if the number can be live. Nora asks something else: "What would you do with it if you had it now?"
You'll learn to
- Say what an event, a log and an offset are
- Fold a log of changes into a table
- Tell batch from streaming by whether the data ever ends
- Decide when a live number is worth what it costs
Learn
The clicks happened. The table has not heard.
The dashboard reads the warehouse, and the warehouse loads once a night. The carts are not missing. They are in the app, as a list of things that happened.
Each item on that list is an event: one thing that happened at one moment. "User 19 viewed the category page at 08:42:39." An event has a time and an id, and it never changes. You cannot un-happen a page view. A mistake is corrected by a new event.
A row in the orders table is different. It is state: the current answer to "what is order 1005's status?", overwritten every time the order moves on.
Events say what happened. State says what is true now.
Read the clicks one at a time
import json
def read_events(path):
"""Yield one event at a time, the way a stream hands them over."""
with open(path) as f:
for line in f:
yield json.loads(line)
counts = {}
for i, event in enumerate(read_events('data/events.jsonl')):
if i < 3:
print(i, event['event_id'], event['type'], event['ts'])
counts[event['type']] = counts.get(event['type'], 0) + 1
print(sorted(counts.items()))
The file is JSON Lines: one event per line, in the order the app sent them. The loop never holds the whole file. It handles one event and moves on, which is how a streaming job works. The last line is the tally: 33 add-to-carts among 192 events.
A notebook that only gets longer
Where do events live? In the simplest storage there is: a list you only add to. New events go on the end. Nothing in the middle ever changes. That list is called a log.
Think of a paper notebook written in pen. You write on the next free line and you never erase.
Every line has a number: 0, 1, 2 and so on. That number is the event's offset.
A reader of the log has to remember one thing only: the offset of the next line to read. Restart the reader and it carries on from that number. Lose the number and it must read everything again, or skip events.
A reader and its one number
A log of click events beside a reader that keeps the offset it will read next: four events arrive, the reader takes two, then a fifth event is appended.
Four events arrive. The app appends them and they get offsets 0 to 3. The reader has read nothing yet, so its number is 0.
The reader takes two. It reads offsets 0 and 1 and moves its number to 2. Nothing left the log: the two events are still there for anyone else.
A new event arrives.
view 101goes on the end, at offset 4. The reader's number does not move. What will it get when it asks again?
Watch the reader's box: its whole memory is one number.
A reader that remembers its offset
log = [] # the log: we only ever append
def append(event):
log.append(event)
return len(log) - 1 # the offset it got
def read(offset, n):
"""Up to n entries from offset, and the offset to read next time."""
batch = log[offset:offset + n]
return batch, offset + len(batch)
for e in ['view 114', 'cart 114', 'view 120', 'buy 114']:
print(append(e), e)
pos = 0
batch, pos = read(pos, 2)
print(batch, 'next:', pos)
append('view 101') # new events keep arriving
batch, pos = read(pos, 10)
print(batch, 'next:', pos)
The reader's whole memory is pos. Kafka, the log you meet in the next lesson, calls it the committed offset and stores it for you.
Remember: reading a log removes nothing. A reader is one number: the offset it reads next.
Three teams, one log
Reading removes nothing, so many readers can share one log. Each keeps its own number and reads at its own speed.
Look at the picture below. The app appends clicks on the left. The fraud service reads each event as it lands. The dashboard job catches up once a minute. The warehouse load reads once a night, so its number is far behind, and that is fine.
A log is also fast. Adding to the end of a file is the cheapest write a disk does. The newest lines are still in the server's memory (the operating system's page cache), so readers near the end never touch the disk.
One log, three readers, three offsets
The app appends click events to one log; a fraud service, a dashboard job and a nightly warehouse load read the same log, each from its own offset.
Read it left to right. The log holds one copy of each event, and a reader costs it one stored number, so a slow reader slows neither the others nor the app.
Fold the log and you get a table
Now the idea that connects events to tables. Replay a log of changes in order. For each key, keep only the newest value. What is left is a table. This is called folding the log.
Databases work this way inside. Every change goes to a log first (the write-ahead log of Lesson 6.7), and the tables follow from it.
It does not work backwards. From the table alone you cannot tell that order 1005 was ever shipped: the history is gone. That is why teams keep the raw events.
Four events become two rows
A log of four order changes is replayed one entry at a time into a table that keeps the latest status of each order, ending with two rows.
Offset 0: 1005 placed. The table is empty, so order 1005 gets its first row.
Offset 1: 1006 placed. A key the table has not seen, so a new row.
Offset 2: 1005 shipped. The key is already there, so its value is overwritten. Still two rows. Stop the replay here and you have the table as it was at that moment.
Offset 3: 1005 delivered. Overwritten again. Four events, two rows, and the table no longer knows that 1005 was ever shipped.
Read each step left to right: one more log entry is replayed, and the table on the right shows what it changed.
Fold the order change log into a table
import csv
import glob
state = {} # order_id -> latest status
changes = 0
for path in sorted(glob.glob('landing/orders/*.csv')):
with open(path) as f:
for row in csv.DictReader(f):
state[row['order_id']] = row['status']
changes += 1
print('change rows:', changes)
print('orders now:', len(state))
counts = {}
for status in state.values():
counts[status] = counts.get(status, 0) + 1
print(sorted(counts.items()))
68 change rows fold into 40 orders. The retry file's seven repeated rows changed nothing: the fold assigns, it does not add.
A batch ends. A stream never does.
You now have two ways to work with the same events.
Read a bounded piece, such as yesterday's file. Write a result. Stop. That is batch, and your nightly load does it.
Or keep reading a log that has no last line, and handle each event (or a few seconds of them) as it arrives. That is streaming. The data is unbounded: there is never a moment when you have it all.
The code can look almost the same. What changes is everything around it. The job never finishes, a rerun means replaying the log, and the compute never switches off.
Batch and streaming, side by side
| Batch | Streaming |
|---|---|
| Reads a bounded piece: yesterday's file, last week's orders | Reads unbounded data: events keep coming, there is no last one |
| Starts on a schedule, reads everything, writes a result, stops | Runs all the time and handles each event (or a few seconds of them) as it arrives |
| Results are minutes to hours old | Results are seconds old |
| A rerun is easy: run the day again | A rerun means replaying the log from an offset, and rebuilding what the job remembered |
| You pay for compute only while it runs | You pay for compute 24 hours a day |
| Typical tools: Airflow with Spark or dbt | Typical tools: Kafka with Spark Structured Streaming or Flink |
The data lifecycle from source to serving with the ingest stage highlighted, where app events arrive either through a stream such as Kafka or through scheduled batch loads.
Click the highlighted stage. Streaming changes ingest and transform. The source (the app) and the serving side (a table, a dashboard) look much the same either way.
Nora's question: what if it is late?
Back to the flash sale. Nora's question decides it: what goes wrong if the answer is an hour late?
Streaming earns its cost when acting late loses money or trust: blocking a stolen card before the order ships, pausing a sale when stock runs out, alerting when checkout errors spike.
It is the wrong tool when people read the numbers once a day: the finance report, the daily sales dashboard, monthly cohorts.
Between the two sits the micro-batch: a small batch every minute, or every 15 minutes. Spark Structured Streaming works this way, and it covers most "live" requests with far less effort.
The freshness ladder
| Approach | How fresh | Compute runs | Fits |
|---|---|---|---|
| Nightly batch | up to a day old | 30 minutes a night | finance, cohorts |
| Streaming code on a schedule (availableNow every 15 min) | 15 to 20 minutes | a few minutes per run | sales dashboard |
| Always-on micro-batches, one a minute | about a minute | 24 hours a day | ops dashboards, stock alerts |
| Always-on micro-batches, back to back (Spark's default) | seconds; about 100 ms at best | 24 hours a day | alerting |
| Per-event engines (Flink, Kafka Streams; Spark continuous mode) | each event as it arrives; about 1 ms for Spark continuous | 24 hours a day | fraud scoring |
Read it top to bottom: each rung is fresher, runs more compute, and needs more care with late and duplicate events. availableNow is Spark's way to say "read what is there, then stop".
What live costs, step by step
Tess's counter would read about 1,000 events a second, each about 800 bytes. Storage first:
- 1,000 x 800 bytes = 800 KB every second
- x 86,400 seconds in a day = 69.1 GB a day into the log
- kept 7 days, on 3 copies (called replicas): 69.1 x 7 x 3 = 1.45 TB of disk
Compute is the bigger difference. Take a cluster of 4 machines at $0.50 a machine-hour, so $2 an hour:
- always on: $2 x 24 x 30 = $1,440 a month
- a run every 15 minutes, 3 minutes each: 96 runs x 3 min = 4.8 hours a day, $288 a month
- one 30-minute batch a night: $30 a month
The prices are made up. The ratios are the point.
A month of compute, three ways
Three bars compare a month of compute cost: 1,440 dollars for an always-on job, 288 dollars for a run every 15 minutes, and 30 dollars for one nightly batch.
Each step closer to live multiplies the bill, so the freshness has to be worth it.
"Real time" is a requirement, not a feature. When someone asks for live data, ask how fresh it must be and what they will do differently when it is. "Within 15 minutes" is a batch on a schedule. A streaming pipeline for a dashboard someone opens once a morning is a cluster that never sleeps, plus late and duplicate events to handle, for nothing.
Fix a bug by replaying the log
A log gives you one more thing. Say the revenue logic was wrong for a week. Start a second copy of the job, reading from an earlier offset into a new output, then switch the readers over. One streaming pipeline, repaired by replay: this design is called Kappa. It works only while the log still holds those events, in Kafka or as raw events in the lake.
The older design, Lambda, runs two pipelines over the same events. A batch layer recomputes exact results, a speed layer streams fresh approximate ones, and a serving layer merges them. It works, but the same logic lives in two codebases that drift apart.
Most lakehouse teams land in between: one streaming job into Delta tables, plus a batch job that recomputes the last few days so stragglers reach the final numbers.
Lambda runs two pipelines, Kappa runs one
Two designs side by side: Lambda has a batch layer, a speed layer and a serving layer that merges them; Kappa has one streaming job, plus a second copy that replays the log when the logic changes.
The dashed box exists only during a fix: once the new output has caught up, readers switch to it and the old job is stopped.
Numbers to remember
| What | Number | Use it for |
|---|---|---|
| Seconds in a day | 86,400 | events a second x bytes x 86,400 = bytes a day |
| Disk for a log | bytes a day x days kept x replicas | 69.1 GB x 7 x 3 = 1.45 TB, before compression |
| Hours in an always-on month | 24 x 30 = 720 | the compute bill of a streaming job |
| Spark micro-batches, best case | about 100 ms end to end | with exactly-once delivery (Lesson 15.3 explains the term) |
| Spark continuous mode | about 1 ms | at-least-once only, and only map-like queries |
| The usual log | Kafka | managed cousins: Amazon Kinesis, Azure Event Hubs, Google Pub/Sub |
The two Spark figures are the Structured Streaming guide's own.
What changed at SwiftKart
You go back to Tess with two questions instead of a cluster: how fresh, and what for? Marketing wants to watch the count climb during the sale and decide whether to extend it. Fifteen minutes old is fine for that.
So the earbuds counter becomes streaming code started every 15 minutes: about $288 a month, not $1,440. The clicks go into a log first, so the fraud service, the dashboard and the nightly load each read them at their own pace, and a bug can be fixed by replaying.
At most companies that log is Kafka. The next lesson opens it up: how one log is split so it can take a thousand clicks a second, and how a team of readers shares the work.
In one line
An event is a fact that never changes, a log keeps events in order by offset, a table is the log folded, and you stream only when a late answer costs something.
Interview corner
When would you not use streaming?
When nobody acts on the data faster than the batch delivers it: a daily finance report, a dashboard read each morning, monthly cohorts. I would ask for the freshness target and the action behind it. If 15 minutes is fine, a micro-batch on a schedule is cheaper and easier to rerun than an always-on streaming job.
What is a log, and why do Kafka and databases use one?
A log is an append-only, ordered list of records, each with an offset. Appending is a sequential write, the cheapest disk operation, and recent entries are served from the page cache. Nothing is overwritten, so any number of readers can read it at their own pace by remembering one offset. Databases write every change to a log before the tables, and Kafka is essentially a distributed log, so both can rebuild state by replaying it.
Marketing wants live cart counts for a flash sale. Walk me through your decision.
I would first ask how fresh the number must be and what they will do with it: pausing the sale when stock runs out needs a minute, a recap for the team needs nothing live. Then I would size it: at 1,000 events a second of 800 bytes that is about 69 GB a day, 1.45 TB on Kafka for 7 days at 3 replicas. An always-on job runs 720 hours a month against a few minutes a night for a batch, so if 15 minutes is fine I would run the streaming code with availableNow every 15 minutes. I would also plan for late and duplicate events, with an event id and a watermark.
Lambda or Kappa?
Lambda runs a batch layer and a speed layer over the same events and merges them, which gives exact and fresh results but two codebases that drift. Kappa keeps one streaming job and reprocesses by replaying the log from an earlier offset into a new output, which needs the log, or a raw copy of it in the lake, kept long enough. On a lakehouse I usually use one streaming pipeline into Delta and a batch recompute of the last few days for stragglers.