The situation
The product team wants session-level numbers: how many sessions a user has and how long they last. The tracking system only records individual page views, so the sessions have to be derived.
Input tables
page_views
One row per page view.
| Column | Type | Description |
|---|---|---|
user_id |
BIGINT | The user. |
viewed_at |
TIMESTAMP_NTZ | When the page was viewed. Two views of a user can share the same instant. |
page |
STRING | The page path. |
Requirement
Group each user's page views into sessions and return one row per session.
- A user's first view starts their first session.
- A view starts a new session if it comes more than 30 minutes after the user's previous view. A gap of exactly 30 minutes continues the session.
- The gap is always measured from the previous view, not from the start of the session. A session can last for hours as long as no gap exceeds 30 minutes.
- Sessions do not stop at midnight.
session_numbercounts a user's sessions in time order, starting at 1.
Expected output
One row per session.
| Column | Type | Description |
|---|---|---|
user_id |
BIGINT | |
session_number |
BIGINT | 1 for the user's first session, 2 for the next, and so on. |
session_start |
TIMESTAMP_NTZ | Time of the first view in the session. |
session_end |
TIMESTAMP_NTZ | Time of the last view in the session. |
page_views |
BIGINT | Number of views in the session. |
Explanation
Show explanationGives the answer away. Try the problem first.
The approach
Sessionization is a "gaps and islands" problem, and it has a standard three-step solution.
1. Flag the views that start a session. Look at the user's previous view with
lag. A view starts a session if there is no previous view, or the previous view is
more than 30 minutes back.
by_time = Window.partitionBy("user_id").orderBy("viewed_at")
previous = F.lag("viewed_at").over(by_time)
starts_session = F.when(
previous.isNull() | (F.col("viewed_at") > previous + F.expr("INTERVAL 30 MINUTES")), 1
).otherwise(0)
2. Turn the flags into a session number. A running sum of the flags goes up by one at every session start and stays level in between. That running sum is the session number.
F.sum("starts_session").over(by_time)
3. Aggregate. Group by user_id and session_number and take min, max and
count.
The 219 views of 30 users form 55 sessions.
A detail in step 2: the window has no rowsBetween. With the default frame, two views
at the same instant are peers and get the same running sum, so they cannot be split
across two sessions whichever of them Spark happens to sort first. For a running
balance that peer behaviour is a bug; here it is what you want. Know which frame you
are getting and why.
Common wrong answers
>= instead of >. Returns 60 sessions. A gap of exactly 30 minutes is still the
same session by the rule given. Boundaries like this are a business decision, so use
the comparison the requirement states and test the exact boundary.
Partitioning by user and date. Returns 56 sessions. User 9 views a page at 23:50 and another at 00:05. Adding the date to the partition cuts that session in two.
Fixed 30-minute buckets (F.window("viewed_at", "30 minutes"), or dividing the
timestamp by 1800). Buckets measure time from the clock, not from the previous view.
A view at 10:29 and one at 10:31 land in different buckets, and a three-hour session
with a view every 20 minutes (user 7) is chopped into pieces.
Measuring the gap from the start of the session. This caps every session at 30 minutes. The rule is about inactivity: user 7's ten views, 20 minutes apart, are one session three hours long.
Forgetting the first view. lag returns NULL for a user's first view, and NULL
compared with anything is NULL. Without the explicit isNull() check the first view
gets flag 0, and the user's sessions are numbered from 0.
Edge cases in the data
| Case | Users | What it catches |
|---|---|---|
| Gap of exactly 30 minutes | 3, 11, 19 | >= instead of >. |
| Gap of 30 minutes and 1 second | 5, 14 | A tolerance that is too generous. |
| Ten views, 20 minutes apart | 7 | Buckets; measuring from the session start. |
| Session across midnight | 9 | Partitioning by date. |
| Two views at the same instant | 12 | A row-based frame splitting peers; duplicates dropped by mistake. |
| Single view | 30 | Sessions of one view, where start equals end. |