YouTube's analytics backend processes raw events (play, pause, seek, like, comment)
and reconstructs them into sessions for cohort analysis.
A session is a sequence of events for a single user that are within 30 minutes of each other.
If the idle time between events exceeds 30 minutes, a new session starts.
You are given:
events: List[Dict] with keys:
- user_id: str
- video_id: str
- action_type: str (e.g. 'play', 'pause', 'seek', 'like')
- timestamp: int (unix timestamp in seconds)
- watch_seconds: int (if action_type == 'play', duration watched in this segment)
Implement:
def sessionize_events(
events: List[Dict],
session_gap_minutes: int = 30
) -> Dict[str, Dict]:
"""
Convert raw events into sessions using time-based gap detection.
Text
For each session, return:
{
session_id: {
"user_id": str,
"session_start": int (unix timestamp of first event),
"session_end": int (unix timestamp of last event),
"total_watch_time": int (sum of watch_seconds for this session),
"event_count": int (number of events in session),
}
}
Rules:
- Sessions are per-user (events from different users never merge)
- Session IDs are unique, formatted as "sess_{user_id}_{counter}"
- If gap between consecutive events > session_gap_minutes, start a new session
- session_end is the timestamp of the last event, not current time
"""
Constraints:
- Up to 10 million events
- Up to 1 million unique users
- Optimize for single-pass where possible