Sessionize For You Feed Watches With a 30-Minute Gap
Last updated: November 29, 2026
Quick Overview
Given per-video watch events with user_id, timestamp and watch duration, assign session numbers using a 30-minute inactivity rule, then report each user's session count, average videos per session and average watch time per session.
TikTok
November 29, 20260
0
0 solved
Given per-video watch events with user_id, timestamp and watch duration, assign session numbers using a 30-minute inactivity rule, then report each user's session count, average videos per session and average watch time per session.
Session depth on the For You feed is one of TikTok's core engagement lenses, since the product is built around continuous swiping. Interviewers use this to see if you know the LAG plus running SUM pattern for gaps and islands and whether you can defend the gap threshold.
What the Interviewer Expects
- Use LAG to find the previous event per user
- Flag a new session when the gap exceeds 30 minutes or there is no previous event
- Use a running SUM of the flag as a session id
- Aggregate to session level, then to user level
- Discuss how the threshold choice changes the metric
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 choose the inactivity threshold from the data itself?
- What changes if the app also logs background and foreground events?
- How would you do this incrementally for a daily job when sessions cross midnight?
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
watch_events(user_id, video_id, event_ts, watch_ms), one row per video view start.
- A session ends after more than 30 minutes with no new watch event.
- Session length uses watch time summed, not ...
Approach
LAG(event_ts)per user ordered by time.is_new = 1when there is no previous event or the gap is over 30 minutes.- A running
SUM(is_new)gives a per-user session number. - Aggregate eve...