Skip to content

75. Click Counts in 5-Minute Windows with Late Data

Difficulty: Medium · Topics: Streaming, Aggregations, Filtering & Selection

Clicks arrive as a stream clicks (page, ts), where ts is when the click happened. Phones send clicks late and out of order.

Count clicks per page in 5-minute tumbling windows of event time. Accept clicks that are up to 10 minutes late: use a 10-minute watermark on ts, so a window is final once the watermark passes its end, and clicks for a window that is already final are dropped.

Each window must be written exactly once, when it is final. Return window_start, window_end, page, clicks.

The stream arrives in micro-batches: batch in the preview is the batch an event arrives in, not a column of the stream. The expected output lists every row your query writes, with batch set to the micro-batch after which it is written.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

clicks

batchpagets
1home2024-05-01 10:01:00
1home2024-05-01 10:03:00
1docs2024-05-01 10:04:00
1home2024-05-01 10:07:00
2home2024-05-01 10:12:00
2docs2024-05-01 10:16:00
3home2024-05-01 10:04:00
3docs2024-05-01 10:09:00
3home2024-05-01 10:27:00
4docs2024-05-01 10:41:00

Expected output

batchwindow_startwindow_endpageclicks
22024-05-01 10:00:002024-05-01 10:05:00home2
22024-05-01 10:00:002024-05-01 10:05:00docs1
32024-05-01 10:05:002024-05-01 10:10:00home1
32024-05-01 10:10:002024-05-01 10:15:00home1
32024-05-01 10:05:002024-05-01 10:10:00docs1
42024-05-01 10:15:002024-05-01 10:20:00docs1
42024-05-01 10:25:002024-05-01 10:30:00home1

Hints

Hint 1Group by an event-time window: groupBy(F.window("ts", "5 minutes"), "page"). The window column is a struct with start and end fields, read with F.col("window.start").
Hint 2Call withWatermark("ts", "10 minutes") before the groupBy. Spark sets the watermark to the latest event time seen minus 10 minutes, at the end of each batch.
Hint 3Written once, when final, is append mode. With a watermark, append mode writes a window when the watermark passes its end, in the extra batch Spark runs right after the watermark moves.

Learn the concepts

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance

Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice