Skip to main content

Session-Based Recommendation

Session models answer a short-horizon question: given the ordered actions in the current visit, what is a plausible next item? This differs from estimating a user's durable taste. The sessionization rule is part of the model input and must be versioned.

Prerequisites​

Understand timestamps, temporal splits, and the cold-start routing contract.

Learning goals​

  • Define session boundaries using observable product semantics.
  • Preserve event order without crossing the global evaluation cutoff.
  • Distinguish transition tables, nearest-session methods, and learned sequence models.
  • Provide a fallback for empty or one-item sessions.

Model contract​

PartThis lesson's contract
ObjectivePredict the next eligible lesson from the current visit's ordered context.
Input representationPer-user timestamped events split after 30 minutes of inactivity, deduplicated to item order within each session.
Learned stateTraining-only item transitions or sequence-model parameters, plus the timeout, event filter, and vocabulary.
Inference pathAssign the request to a session, encode its ordered prefix, retrieve next-item candidates, then fall back if support is absent.
Evaluation boundaryCut data globally first, build session prefixes inside each split, and score next-item predictions without future events.
Principal failure modesArbitrary timeout, cross-device identity, repeated refreshes, merged journeys, sparse transitions, and popularity-only fallback.

Worked example: make the boundary observable​

The example sessionizes u1 independently within train and test. Multiple event types for the same item collapse inside a session, because the target here is next item, not next event type.

import csv
from datetime import datetime, timedelta
from pathlib import Path

path = Path("tests/fixtures/recommender-systems/interactions.csv")
with path.open(encoding="utf-8", newline="") as handle:
rows = [row for row in csv.DictReader(handle) if row["user_id"] == "u1"]

def timestamp(value):
return datetime.fromisoformat(value.replace("Z", "+00:00"))

def sessions(split):
events = sorted((row for row in rows if row["split"] == split), key=lambda row: row["timestamp"])
result = []
previous = None
for row in events:
current = timestamp(row["timestamp"])
if previous is None or current - previous > timedelta(minutes=30):
result.append([])
if not result[-1] or result[-1][-1] != row["item_id"]:
result[-1].append(row["item_id"])
previous = current
return result

training_sessions = sessions("train")
current_session = sessions("test")[0]
print(f"u1_sessions={training_sessions} boundaries={len(training_sessions)}")
print(f"current_session={current_session} fallback=content_then_popularity")

Output:

u1_sessions=[['i1'], ['i1'], ['i2']] boundaries=3
current_session=['i5'] fallback=content_then_popularity

There is no supported next-item transition in these u1 training sessions, so the honest path is a content-then-popularity fallback. A recurrent or attention model cannot manufacture sequence evidence absent from the data. For next-item evaluation, create prefixes only from events that would have been known at each prediction time.

Limitations and common mistakes​

  • A 30-minute session boundary is a product assumption, not a natural law.
  • Sorting after mixing train and test leaks future sequence context.
  • Anonymous sessions can be shared by several people; logged-in sessions can span devices.
  • Repeated impressions may reflect rendering rather than intent.
  • Large neural session models should beat strong recency, popularity, and nearest-session baselines under the same candidates before their complexity is justified.

Practice​

Change the timeout to two days and list which u1 sessions merge. Explain how that changes the target rather than merely adding data.

Next steps​

Individual models are usually only sources. Candidate generation combines their nominations and measures whether relevant items survive retrieval.

Primary sources​

Checked 2026-10-17: Hidasi et al., “Session-based Recommendations with Recurrent Neural Networks”, and Ludewig and Jannach, “Evaluation of Session-based Recommendation Algorithms”.