Sessionize Viewing Events With a 30-Minute Inactivity Gap
Last updated: November 29, 2026
Quick Overview
Using SQL window functions, split each viewer's playback events into sessions where a gap of more than 30 minutes starts a new session, and report each session's start, end, and number of distinct titles.
Tubi
November 29, 20260
0
0 solved
Using SQL window functions, split each viewer's playback events into sessions where a gap of more than 30 minutes starts a new session, and report each session's start, end, and number of distinct titles.
Viewing sessions are a building block for Tubi's engagement metrics and for training sequence-aware recommendation models in Spark. The screen tests the gaps-and-islands pattern with LAG and a running sum, and whether the candidate thinks about late events and partitions.
What the Interviewer Expects
- Uses LAG within viewer partitions ordered by time
- Flags session starts and numbers sessions with a running SUM
- Treats exactly 30 minutes consistently and says which way
- Counts distinct titles per session correctly
- Mentions how this would run incrementally in Spark
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you handle sessions that cross midnight in a daily partitioned table?
- Events can arrive up to two hours late. How would you make the job idempotent?
- How would you compute the average number of titles sampled before a viewer commits to one?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
playback_events(viewer_id, event_ts, title_id, ...) with one row per event. A new session starts on a viewer's first event or when the gap since the previous event is more than 1800 seconds; exactly...
Approach
Gaps and islands: compute the previous timestamp with LAG, flag a new session when the gap exceeds the threshold, then a running SUM of flags gives a session number per viewer. Aggregate by viewer and...