Design: clickstream to dashboard
Part of the free LogicWiz Data Engineering course, Module 17: Pipeline design. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Friday, 11 a.m.: review number three. Marketing runs flash sales and wants to watch them: visitors, product views, carts and purchases per 5 minutes, no more than 15 minutes behind. The next morning they want sessions and conversion per session, exact. Dana adds three warnings from the app side. The app retries events on a bad connection. Phones send late. And a quarter of visitors are not logged in.
You'll learn to
- Size a clickstream: events a second, partitions, files a day
- Split the design into a live path and a nightly path
- Dedup by event id, and build sessions in SQL
- Budget the 15 minutes, and plan for falling behind
Learn
Steps 1 to 3: two clocks in one request
You ask your questions, and the request turns into a list.
- Live funnel: counts per 5-minute window by event type, at most 15 minutes behind. Small errors are fine.
- Sessions: a new one after 30 minutes of inactivity; conversion per session; exact, by 07:00.
- Keep: raw events 30 days, cleaned events 13 months.
- Known mess: retried events (the same
event_idtwice), late events, anonymous visitors. - Sources: the apps and the website. Sinks: a live dashboard and tables for analysts.
Nora circles two numbers: 15 minutes and 07:00. "Two clocks. That is a hint." Two freshness targets in one request usually mean two paths: a live one and a nightly one.
Step 2: size it, including files
import math
daily_users = 2_000_000
events_per_user = 60
bytes_per_event = 160
peak_factor = 5
per_consumer = 1_000 # events a second one streaming task handles
trigger_minutes = 1 # a micro-batch every minute
compression = 6 # JSON to Delta (Parquet), roughly
target_file_mb = 256
events_per_day = daily_users * events_per_user
peak = events_per_day / 86_400 * peak_factor
partitions = math.ceil(peak / per_consumer) * 2
raw_gb = events_per_day * bytes_per_event / 1e9
delta_gb = raw_gb / compression
files_written = 24 * 60 // trigger_minutes * partitions # about one file per partition per batch
files_after = math.ceil(delta_gb * 1000 / target_file_mb)
print(f'events a day {events_per_day:,}, peak {peak:,.0f}/s, partitions {partitions}')
print(f'raw {raw_gb:.1f} GB/day, as Delta {delta_gb:.1f} GB/day')
print(f'files a day: {files_written:,} written, {files_after} after compaction')
The surprise is the last line: writing every minute makes about 20,000 small files a day, which are slow to read. Compacted, the same day is 13 files. The design needs a nightly compaction (OPTIMIZE on Delta).
Step 4: the sketch, one box at a time
The numbers: 120 million events a day, a peak near 7,000 a second, 14 partitions. This time the size is real, and so is the freshness target. Nora wants the live path and the nightly path on the same page.
Step through the build below. Each step adds boxes and gives the reason for them. The finished picture, with its numbers, comes right after.
Clickstream to dashboard, built box by box
A graph built one box at a time: collectors in three regions and the dashboard, then the central Kafka topic, bronze, silver, the live 5-minute funnel and last the nightly sessions job.
The two ends. Collectors run near the shoppers: Tokyo, London, Sao Paulo. Each is an HTTP service the apps post to. It checks the event, adds
received_atand produces to its region's Kafka. At the other end is the dashboard.One central log. MirrorMaker 2 copies the regional topics to
clicksin the central region: 14 partitions, 7 days. The key is the visitor id: the user id, or a device id when the visitor is anonymous.Bronze. Structured Streaming writes the raw events to Delta every minute. Nothing is cleaned yet, so 30 days of raw events are there to replay.
Silver. Parse each event, and drop copies with the same
event_idwithin a watermark. The app's quick retries are removed here, early.Gold, live. Counts per 5-minute window of event time, with a 10-minute watermark, written in append mode. A window is final within 15 minutes of its end. That is the first clock.
Gold, nightly. The second clock. Once a night: sessions and conversion from yesterday's silver, a recount of yesterday's funnel that includes late events, and compaction of the small files.
Grey boxes are not drawn yet. Each step colours in the next part and gives the reason for it. Watch silver: two paths leave it.
The finished design, with its numbers
A graph: collectors with small Kafka clusters in Tokyo, London and Sao Paulo are mirrored into a central 14-partition clicks topic, streamed into bronze, deduplicated in silver, and split into a live 5-minute funnel and a nightly sessions job that both feed the dashboard.
Follow the arrows from the three regions to the dashboard. Two paths leave silver: the blue one is always on and approximate, the green one runs once a night and is exact. The 403 GB is 19.2 GB a day of raw events x 7 days x 3 replicas.
A topic with three partitions where every event with the same key lands in the same partition, in order, read by a consumer group that splits the partitions between its consumers.
Press Send 5 events and watch where each key lands. The picture keys orders by customer; the clickstream does the same with the visitor id, so each visitor's events stay in order (sessions need that) and load spreads evenly.
The design, component by component
| Component | Tool I would pick | Why |
|---|---|---|
| Collector | A small HTTP service, or Snowplow or Segment | Validates events and adds receivedat |
| Log | Kafka (Confluent, MSK or Event Hubs), 14 partitions, 7 days | Absorbs peaks; replay; several readers |
| Bronze | Structured Streaming to Delta, 1-minute trigger | Checkpoint gives exactly-once into Delta |
| Silver | Streaming dedup by eventid, 1-hour watermark | Retried events removed early |
| Live gold | 5-minute windows, 10-minute watermark, append | Final counts within 15 minutes |
| Nightly gold | Batch SQL on yesterday's silver (Airflow or Databricks Jobs) | Sessions need the whole day and its late events |
| Serving | Databricks SQL dashboard on the gold tables | Small, pre-aggregated tables |
| Upkeep | Nightly OPTIMIZE; bronze kept 30 days | Small files and storage cost |
Snowplow, Segment and RudderStack are this design packaged: a collector, a schema check, a stream and a loader. Teams often buy the collector and build the modelling (dedup, sessions, funnels) in dbt or Databricks.
The same click, counted twice
Dana's first warning: the app retries on a bad connection. So the same event_id can arrive twice, seconds or hours apart, and carts and purchases are inflated.
The stream can drop copies, but only if it remembers the ids it has seen, and that memory cannot grow forever. So it remembers an id only until the watermark passes it. (The watermark is the line behind which the stream stops waiting for late events. In Spark: withWatermark, then dropDuplicates(['event_id', 'ts']).) A copy that arrives later slips through.
So you dedup twice. The live path drops what it can. The nightly job dedups the whole day again: ROW_NUMBER() per event_id, keep the first received copy. Live numbers are nearly right within minutes. Nightly numbers are exactly right by morning.
One cart event, sent three times
Four boxes followed over four steps: what arrives, the ids the stream remembers, the live silver table and the nightly dedup; a quick retry is dropped, a retry three hours later slips into silver, and the nightly job removes it.
The first copy. Event e77, a cart at 10:00, arrives. Its id is not remembered yet, so it goes into silver, and the stream remembers the id.
A quick retry. The app sends e77 again 40 seconds later. The id is still remembered, so the copy is dropped. This is the case streaming dedup is built for.
A slow retry. The phone was in a tunnel, and a third copy arrives at 13:00. The watermark passed 10:00 long ago and the id was forgotten. The copy goes into silver, and the live funnel counts this cart twice.
The nightly job. It reads the whole day, numbers the copies of each
event_idbyreceived_at, and keeps the first. One cart again, exactly.
The four boxes are the same in every step: what arrives, what the stream remembers, what the live table holds, and what the nightly job leaves. The event and its times are made up for the picture.
Prove it: the retried events, and the dedup
SELECT COUNT(*) AS rows_loaded, COUNT(DISTINCT event_id) AS events
FROM raw_clicks;
SELECT event_type, COUNT(*) AS events
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY received_at) AS rn
FROM raw_clicks
) ranked
WHERE rn = 1
GROUP BY event_type
ORDER BY event_type;
Change the first query to count carts before the dedup: every cart and purchase is there twice, so a naive funnel would double the conversion rate.
Sessions: cut where the gap is long
Now the morning question. A session is a run of one visitor's events with no gap longer than 30 minutes. Picture a visitor's clicks as dots on a line. Wherever two dots are more than 30 minutes apart, you cut.
In SQL that is three steps (the gaps-and-islands pattern from Module 2):
LAG(event_ts)per visitor gives the previous event's time.- A flag is 1 when there is no previous event, or when the gap is over 30 minutes.
- A running
SUMof the flag per visitor numbers the sessions.
Inside the query: user 6
Eight of user 6's events in time order, shown three times: first with the gap since the previous event, then with a flag on the first event and after each gap over 30 minutes, then coloured by the running sum of the flags into four sessions.
Step 1: look back.
LAGputs each event next to the one before it, for the same visitor. Now every event knows its gap.Step 2: flag the long gaps. The flag is 1 on the first event and wherever the gap is over 30 minutes. Everywhere else it is 0. Four flags.
Step 3: add the flags up. A running sum goes up by one at each flag, and that number is the session. Four sessions, and two of them ended in a purchase.
Read the events top to bottom, oldest first. Some of user 6's events are left out to keep the picture short, which is why a gap can be shorter than the time between two boxes.
Sessionise two shoppers
WITH ordered AS (
SELECT user_id, event_id, event_type, event_ts,
LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts, event_id) AS prev_ts
FROM events
WHERE user_id IN (6, 15)
),
numbered AS (
SELECT *,
SUM(CASE WHEN prev_ts IS NULL OR event_ts - prev_ts > INTERVAL '30 minutes' THEN 1 ELSE 0 END)
OVER (PARTITION BY user_id ORDER BY event_ts, event_id) AS session_no
FROM ordered
)
SELECT user_id, session_no,
MIN(event_ts) AS session_start,
MAX(event_ts) AS session_end,
COUNT(*) AS events,
BOOL_OR(event_type = 'purchase') AS purchased
FROM numbered
GROUP BY user_id, session_no
ORDER BY user_id, session_no;
User 6 has the four sessions from the picture. Remove the WHERE user_id IN (6, 15) line to sessionise every logged-in shopper: 35 sessions. Why nightly? A session can span many windows and midnight, and one late event can join two sessions. Computing them once, on the complete day, gives one exact answer.
Fifteen minutes is a budget
Back to the live path and its promise: "no more than 15 minutes behind". Measured from the end of a 5-minute window, those 900 seconds have to cover everything between a tap and a pixel.
- Watermark wait, 600 s. In append mode a window is written only when the watermark (the latest event time seen, minus 10 minutes) passes its end.
- Trigger, up to 60 s. The batch that moves the watermark may start a minute later.
- Processing, about 30 s a batch, measured at peak.
- Mirroring, about 5 s from a regional Kafka.
- Dashboard cache, 60 s.
That is 755 s of 900, leaving 145 s of slack.
Where the 900 seconds go
A bar of 900 seconds from the end of a window to the dashboard, mostly the 600-second watermark wait, then the trigger interval, processing, mirroring, the dashboard cache and 145 seconds of slack.
Read the bar left to right. Two thirds of the budget is a choice, not a cost: the watermark trades freshness against completeness. To promise 5 minutes, cut the watermark wait, and accept that more late events miss the live view. The nightly recount still has them.
When the stream falls behind
At peak the topic takes 6,944 events a second. That is only 1.1 MB/s, so Kafka is not the bottleneck. The consumers are.
- Bound every batch with
maxOffsetsPerTrigger. Without it, the first batch after an outage tries to read the whole backlog at once and can run out of memory. - Know the catch-up time: backlog / (capacity - arrival rate). A 2-hour outage at the average 1,389 a second leaves 10 million events. 14 tasks at 1,000 a second drain 12,611 a second net: about 13 minutes.
- Know when the collector must refuse. With Kafka unreachable, the producer's 32 MB
buffer.memoryholds about 30 s of peak traffic. Thensend()blocks up to 60 s (max.block.ms) and fails. The collector answers 503, and the apps keep events on the device and retry with backoff.
Replay needs a new checkpoint
Two stores make a replay possible, and the design names both. Kafka keeps 7 days: 19.2 GB a day x 7 x 3 replicas = 403 GB of broker disk. Bronze keeps 30 days of raw events.
To fix a bug in silver, start the fixed query with a new checkpoint location, reading bronze from the start of the bad period. Write to silver_v2, compare, then switch the readers. Reusing the old checkpoint would only resume where the buggy query stopped.
For writes made in foreachBatch, pass Delta's txnAppId (one fixed string per query) and txnVersion (the batch id). Delta records the pair, so a batch replayed after a crash is recognised and skipped. A retry cannot double a count.
Step 5, all of it: the failure modes, answered
| What goes wrong | The design answer |
|---|---|
| The app retries an event | Streaming dedup within a watermark, full dedup nightly |
| A phone sends events hours late | Live windows drop them; the nightly recount includes them |
| Anonymous visitors | Key and sessionise by device id, not a NULL user id |
| A new app version adds a field | Bronze keeps raw JSON; silver adds it on purpose |
| Bots flood the site | A filter in silver (user agent, impossible rates) |
| A bug in silver logic | Replay from bronze (30 days) or from Kafka (7 days) |
| 20,000 small files a day | Nightly OPTIMIZE |
| Kafka unreachable for minutes | Producer buffer, then 503; apps keep events and retry |
| A region goes down | Apps fail over to the next collector; lose only unmirrored seconds |
Three regions, and the promise
The collectors run where the shoppers are. Each produces to a small regional Kafka, and MirrorMaker 2 copies the topics to the central region. Event time travels inside each event, so mirroring lag never moves an event to the wrong window.
If a region fails, the apps switch to the next-nearest collector. The RPO is what that region acknowledged but had not yet mirrored: about 5 s of its traffic, some 11,600 events if it carries a third of the peak. The RTO is the DNS switch: a few minutes.
The SLOs: 99% of 5-minute windows on the dashboard within 15 minutes of window end, over 28 days, and sessions ready by 07:00 UTC on 98% of days. Track the duplicate rate too: the share of events the live view counted twice.
The anonymous hot key. A fifth of SwiftKart's events have no user_id. Keying them by a placeholder such as "anonymous" sends all of them to one partition, which then lags. COUNT(DISTINCT user_id) as "visitors" has the same blind spot. Give every visitor a device or cookie id at the collector.
Remember: split the paths. The funnel is live and approximate. Sessions are nightly and exact. Then name the key (visitor id), the dedup (event id, twice) and the watermark with its trade-off.
Numbers to remember
| Number | Value | Where it comes from |
|---|---|---|
| Events a day | 120 million | 2 million visitors x 60 events |
| Peak | 6,944 a second, about 1.1 MB/s | 5 times the average of 1,389 |
| Partitions | 14 | 7 tasks at 1,000 a second, doubled |
| Kafka disk | 403 GB | 19.2 GB a day x 7 days x 3 replicas |
| Files a day | 20,160 written, 13 after OPTIMIZE | one per partition per 1-minute batch; 256 MB target |
| Live budget | 900 s: 755 used, 145 slack | the watermark wait is 600 of them |
| Catch-up after a 2-hour outage | about 13 minutes | 10 million events at 12,611 a second net |
| Budget of the live SLO | 80 late windows of 8,064 in 28 days | 99% of 5-minute windows within 15 minutes |
| Live sessions in Spark | sessionwindow | possible, at the cost of more state |
What changed at SwiftKart
Nora approves two paths on one page. During the next flash sale, marketing watches carts and purchases per 5 minutes, never more than 15 minutes behind. The numbers run a little high when the app retries, and everyone knows why.
At 07:00 the exact version is waiting: the whole day deduplicated, late events counted, sessions cut at every 30-minute gap, and 20,000 small files compacted into 13.
Those clicks came from apps you control. In Lesson 17.4 the source is Dana's Postgres database, the target is the lakehouse within 10 minutes, and the hard part is a row that gets deleted.
In one line
Clickstream: key by visitor, dedup by event id (live within a watermark, nightly in full), count the live funnel in event-time windows, build sessions nightly with gaps and islands, and compact the small files.
Interview corner
Design a pipeline from app clicks to a near-real-time funnel dashboard.
"The apps post events to a collector that validates them and produces to Kafka, keyed by visitor id. Structured Streaming lands them in a bronze Delta table every minute, dedups by event id within a watermark in silver, and builds 5-minute event-time windows with a 10-minute watermark for the live funnel. A nightly job dedups the full day, builds sessions and conversion, recounts yesterday's funnel with the late events, and compacts the small files. The dashboard reads the small gold tables."
How do you deduplicate events in a streaming pipeline?
"Every event carries a unique id from the client, so I drop repeats of that id. In the stream, the memory of seen ids has to be bounded, so I use a watermark: in Spark, withWatermark and then dropDuplicates on the id and the event time. Copies arriving later than that slip through, so a nightly batch dedups the whole day again with ROW_NUMBER per id."
Kafka was unreachable for two hours during a sale. Walk me through what your design does.
"The producer in each collector buffers about 30 seconds of peak traffic in its 32 MB buffer.memory, then send() blocks and fails, so the collector answers 503 and the apps keep events on the device and retry with backoff. When Kafka returns, the backlog is about 10 million events. The stream reads it in bounded batches with maxOffsetsPerTrigger, and with 14,000 a second of capacity against 1,389 arriving it is current in about 13 minutes. The live dashboard misses the late events for those windows; the nightly recount puts them back."
How do you sessionise clickstream data?
"Per visitor, ordered by time, I compare each event with the previous one using LAG. A gap over 30 minutes starts a new session, so I flag those events and take a running sum of the flag as the session number. Then I group by visitor and session number for start, end, events and whether it converted. I run it nightly on the complete day, because late events can merge or split sessions."