Session ids for app events

mediumPipelines~25 min · 4 tests · ridelog

Product analytics counts “sessions”, but the app never sends a session id. You have to derive one.

The rule: a user’s events belong to the same session until there’s a gap of more than 30 minutes between one event and the next. The event after that gap starts a new session.

Tag every row of events with its session number:

column type meaning
event_id integer the event
user_id integer the user
session_id integer 1 for the user’s first session, 2 for the next, and so on

Edge cases:

  • A gap of exactly 30 minutes does not start a new session. 31 minutes does.
  • Order a user’s events by event_ts. Some timestamps repeat (duplicate ingests). Break those ties with event_id. A repeated timestamp is a gap of zero, so it never starts a session.
  • Every row of events appears once in the output, duplicates included.

Row order doesn’t matter.

Tables: events.

Learn the ideaRead the lesson →
solution.sqlDuckDB · ridelog

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run