Skip to main content
Version: 0.7.x

Sessionization

Pattern. Assign events to sessions: a new session starts when the gap since the previous event exceeds a threshold. Pure SQL, per batch, with window functions.

The query​

Gap threshold: 3,000 ms.

SELECT user, session, min(ts) AS session_start, max(ts) AS session_end, count(*) AS events
FROM (
SELECT user, ts,
sum(CASE WHEN gap IS NULL OR gap > 3000 THEN 1 ELSE 0 END)
OVER (PARTITION BY user ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session
FROM (
SELECT user, ts, ts - lag(ts) OVER (PARTITION BY user ORDER BY ts) AS gap
FROM flow
) gapped
) sessionized
GROUP BY user, session

How it works:

  1. lag(ts) computes the gap to the previous event per user.
  2. The running sum of "gap exceeded" markers gives each event a monotonically increasing session number.
  3. GROUP BY user, session collapses each session into one row.

Input and output​

Input (session gap 3000 ms):

useractionts
aview1000
aclick1100
abuy5100

Output:

usersessionsession_startsession_endevents
a1100011002
a2510051001

Runnable example​

examples/sql_sessionization.yaml (manifest name sql-sessionization).

Boundaries​

  • Per-batch scope. A session split across two batches becomes two sessions. For streaming sessions with state, use a Job with event time, or the session window buffer (processing time).
  • Timestamps here are plain Int64 milliseconds; to use event-time windows instead, declare them on the Job source (see event time and watermarks).