Event Stream Analytics: Sessions, Funnels, and Segment Performance
SQL & DataModel answerLast updated
Process user activity logs to build sessions, compute conversion metrics by segment, construct a deduplicated funnel, and identify high-performing segments with confidence intervals.
You're analyzing user behavior from activity logs to produce actionable metrics for a product team.
Data Schema
You have two tables:
activity_log: records every user action
log_id(unique identifier for each event)timestamp_utc(when the action occurred, UTC)user_id(guest identifier)platform(either "desktop" or "mobile")channel(acquisition channel: "direct", "seo", "sem", "email", "partner")action_type(one of: "page_view", "add_to_cart", "checkout_start", "order_completed")url(page URL)agent_string(browser user agent)
users: basic user metadata
user_idregistration_date_utc
Analysis Window
Use the 7-day period from August 26, 2025 through September 1, 2025 (inclusive), treating September 1 as "today."
Required Tasks
1. Sessionization
Create sessions for each user using a 30-minute inactivity threshold. Sessions should be consistent across platform switches (a user moving from mobile to desktop within 30 minutes stays in the same session). Assign stable session identifiers and compute start/end times.
2. Segment-Level Metrics
For each (channel, platform) combination, calculate:
- Distinct users
- Total sessions
- Session conversion rate (% of sessions containing at least one order)
- User conversion rate (% of users who completed at least one order)
- Average number of sessions before first order (for converting users)
- Median time from initial page view to first order
3. Funnel Analysis
Build a user-level funnel with these steps: page_view → add_to_cart → checkout_start → order_completed. Each user should be counted once at their furthest step reached. Report the number reaching each step, step-through percentages, and absolute drop-off between consecutive steps.
4. Top Performing Segments
Identify the top 5 segments by conversion lift compared to the overall site average. Exclude segments with fewer than 100 sessions. For each, report the lift multiplier and a 95% Wilson confidence interval for the segment's conversion rate.
Data Quality Rules
- Filter out automated traffic: remove any events where
agent_stringcontains "bot" (case-insensitive) - After filtering, exclude users with fewer than 2 valid events in the window
- Handle edge case: users whose first in-window event is an order
- Look back up to 24 hours before the window for their most recent prior event
- If found, include that event in the analysis
- If not found, attribute the order to "direct" channel and treat as valid
Attribution Logic
- Sessions inherit the (channel, platform) from their first event
- Users are attributed to their first-touch (channel, platform) across all their activity
- Time-to-order is only meaningful when a page view precedes the order
Deliverables
Provide vectorized Pandas code (avoid row-by-row iteration) with clear variable names and comments. Briefly discuss how your approach would translate to PySpark for production-scale data.
Hints
Hint 1
Start by cleaning and sorting the entire event stream once—sessionization and all downstream metrics depend on a single canonical sort order.
Hint 2
Use cumulative sum on gap indicators to generate session IDs; this vectorized approach scales much better than iterating through rows.
Hint 3
For the funnel, assign each user to their maximum step reached, then compute reverse cumulative sums to get 'reached at least step N' counts.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Event Stream Analytics
Approach
This problem requires transforming raw event logs into three derived views: sessions, user summaries, and funnel progression. The key insight is to perform one comprehensive data cleaning and sorting pass, then derive all metrics from that canonical representation.
Core steps:
- Clean once, globally: Parse timestamps as UTC-aware, remove bot traffic, handle edge cases (orphan orders), apply minimum event thresholds
- Sessionize with vectorized operations: Sort by (user_id, timestamp, log_id) and use gap detection with cumulative sum
- Build three aggregated tables: sessions (for session metrics), users (for user metrics), funnel (for step progression)
- Compute segment metrics and statistical confidence: Group by channel and platform, calculate rates, apply Wilson score interval
Key Design Decisions
Timestamp handling: Use pd.to_datetime(..., utc=True) to ensure all comparisons are timezone-aware and avoid naive datetime pitfalls.
Sessionization stability: Key sessions by user_id only (not user + platform), so platform switches within 30 minutes don't break sessions. Use stable sort with log_id as tiebreaker for deterministic session IDs across runs.
Orphan orders: When a user's first in-window event is an order, look back 24 hours for context. If none exists, attribute to "direct" channel and exempt from the 2-event minimum (they legitimately have one event).
Attribution: First-touch attribution for users ensures segment counts are additive (sum of segment users equals total users). Sessions inherit attributes from their opening event.
Funnel logic: Assign each user to their maximum step, then compute reverse cumulative sums. This guarantees monotonic funnel (each step ≤ previous step) even when users skip steps.
Statistical rigor: Wilson score interval handles edge cases (small samples, extreme rates) better than normal approximation.
Complexity Analysis
- Time: O(N log N) for initial sort, then O(N) for all groupby and cumulative operations
- Space: O(N) for event frame, O(S + U) for derived session and user tables where S = sessions, U = users
Code
import numpy as np
import pandas as pd
from scipy import stats
ANALYSIS_DATE = pd.Timestamp("2025-09-01", tz="UTC")
WINDOW_START = ANALYSIS_DATE - pd.Timedelta(days=6)
WINDOW_END = ANALYSIS_DATE + pd.Timedelta(days=1)
SESSION_TIMEOUT = pd.Timedelta(minutes=30)
FUNNEL_STEPS = ["page_view", "add_to_cart", "checkout_start", "order_completed"]
SEGMENT_COLS = ["channel", "platform"]
def clean_and_prepare(activity_log, analysis_window_start, analysis_window_end):
"""Clean events, handle orphan orders, apply data quality filters."""
df = activity_log.copy()
df["timestamp_utc"] = pd.to_datetime(df["timestamp_utc"], utc=True)
# Remove bot traffic
df = df[~df["agent_string"].fillna("").str.contains("bot", case=False, regex=False)]
# Sort once for all downstream operations
df = df.sort_values(["user_id", "timestamp_utc", "log_id"], kind="mergesort")
# Identify in-window events
in_window = df[(df.timestamp_utc >= analysis_window_start) &
(df.timestamp_utc < analysis_window_end)].copy()
# Find orphan orders (users whose first in-window event is an order)
first_events = in_window.groupby("user_id").first()
orphan_user_ids = first_events[first_events.action_type == "order_completed"].index
# Look back 24h before window for context
orphan_orders = in_window[in_window.user_id.isin(orphan_user_ids)].groupby("user_id")["timestamp_utc"].first()
lookback = df.merge(orphan_orders.rename("order_time"), left_on="user_id", right_index=True)
lookback = lookback[(lookback.timestamp_utc >= lookback.order_time - pd.Timedelta(hours=24)) &
(lookback.timestamp_utc < analysis_window_start)]
carried_events = lookback.groupby("user_id").first().drop(columns="order_time").reset_index()
# Orphans with no lookback: mark as direct
orphans_no_history = set(orphan_user_ids) - set(carried_events.user_id)
in_window.loc[in_window.user_id.isin(orphans_no_history) &
(in_window.action_type == "order_completed"), "channel"] = "direct"
# Combine carried events with in-window events
all_events = pd.concat([carried_events, in_window]).sort_values(
["user_id", "timestamp_utc", "log_id"], kind="mergesort").reset_index(drop=True)
# Apply 2-event minimum (except orphans without history)
event_counts = all_events.groupby("user_id").size()
valid_users = event_counts[event_counts >= 2].index.union(orphans_no_history)
all_events = all_events[all_events.user_id.isin(valid_users)].copy()
all_events["is_order"] = all_events.action_type == "order_completed"
return all_events
def create_sessions(events):
"""Sessionize events using 30-minute inactivity threshold."""
time_gaps = events.groupby("user_id")["timestamp_utc"].diff()
events["new_session"] = (time_gaps.isna() | (time_gaps > SESSION_TIMEOUT)).astype(int)
events["session_seq"] = events.groupby("user_id")["new_session"].cumsum()
events["session_id"] = events.user_id.astype(str) + "-" + events.session_seq.astype(str)
sessions = events.groupby("session_id").agg(
user_id=("user_id", "first"),
channel=("channel", "first"),
platform=("platform", "first"),
session_start=("timestamp_utc", "min"),
session_end=("timestamp_utc", "max"),
has_order=("is_order", "any")
).reset_index()
return events, sessions
def compute_segment_metrics(events, sessions):
"""Calculate all required metrics by segment."""
# Add session numbering per user
sessions["user_session_num"] = sessions.groupby("user_id").cumcount() + 1
# User-level data: first touch attribution
users = events.groupby("user_id").agg(
channel=("channel", "first"),
platform=("platform", "first"),
has_order=("is_order", "any"),
first_page_view=("timestamp_utc", lambda x: x[events.loc[x.index, "action_type"] == "page_view"].min()),
first_order=("timestamp_utc", lambda x: x[events.loc[x.index, "is_order"]].min() if events.loc[x.index, "is_order"].any() else pd.NaT)
).reset_index()
users["time_to_order_sec"] = (users.first_order - users.first_page_view).dt.total_seconds()
# Session number at first order
first_order_sessions = sessions[sessions.has_order].groupby("user_id")["user_session_num"].min()
metrics = []
for (ch, plat), sess_grp in sessions.groupby(SEGMENT_COLS):
user_grp = users[(users.channel == ch) & (users.platform == plat)]
if len(sess_grp) < 100:
continue
converters = user_grp[user_grp.has_order]
avg_sessions_to_order = first_order_sessions[first_order_sessions.index.isin(converters.user_id)].mean()
metrics.append({
"channel": ch,
"platform": plat,
"unique_users": len(user_grp),
"total_sessions": len(sess_grp),
"session_conversion_rate": sess_grp.has_order.mean(),
"user_conversion_rate": user_grp.has_order.mean(),
"avg_sessions_to_first_order": avg_sessions_to_order,
"median_time_to_order_sec": user_grp.time_to_order_sec.median()
})
return pd.DataFrame(metrics)
def build_funnel(events):
"""Construct deduplicated user funnel."""
step_map = {step: i for i, step in enumerate(FUNNEL_STEPS)}
events["step_num"] = events.action_type.map(step_map)
max_step = events.groupby("user_id")["step_num"].max()
step_counts = max_step.value_counts().sort_index()
# Reverse cumsum for "reached at least"
reached = step_counts.iloc[::-1].cumsum().iloc[::-1]
funnel = []
for i, step in enumerate(FUNNEL_STEPS):
count = reached.get(i, 0)
prev_count = reached.get(i - 1, reached.iloc[0]) if i > 0 else count
funnel.append({
"step": step,
"users_reached": count,
"step_through_rate": count / prev_count if prev_count > 0 else 0,
"dropoff_from_previous": prev_count - count
})
return pd.DataFrame(funnel)
def wilson_ci(successes, trials, confidence=0.95):
"""Wilson score confidence interval."""
if trials == 0:
return 0, 0
z = stats.norm.ppf((1 + confidence) / 2)
p = successes / trials
denom = 1 + z**2 / trials
center = (p + z**2 / (2 * trials)) / denom
margin = z * np.sqrt(p * (1 - p) / trials + z**2 / (4 * trials**2)) / denom
return center - margin, center + margin
def top_segments(segment_metrics, overall_conversion):
"""Identify top 5 segments by lift with confidence intervals."""
segment_metrics = segment_metrics.copy()
segment_metrics["lift"] = segment_metrics.user_conversion_rate / overall_conversion
ci_bounds = segment_metrics.apply(
lambda row: wilson_ci(
int(row.user_conversion_rate * row.unique_users),
int(row.unique_users)
), axis=1
)
segment_metrics["ci_lower"], segment_metrics["ci_upper"] = zip(*ci_bounds)
return segment_metrics.nlargest(5, "lift")[[
"channel", "platform", "lift", "user_conversion_rate", "ci_lower", "ci_upper"
]]
# Main execution
events = clean_and_prepare(activity_log, WINDOW_START, WINDOW_END)
events, sessions = create_sessions(events)
segment_metrics = compute_segment_metrics(events, sessions)
funnel = build_funnel(events)
overall_conv = events.groupby("user_id")["is_order"].any().mean()
top_5 = top_segments(segment_metrics, overall_conv)
Scaling to PySpark
For production volumes, translate this approach to PySpark:
- Replace
sort_valueswithorderBywith deterministic partitioning - Use window functions (
lag,row_number) over partitions for sessionization - Broadcast small lookup tables (user metadata)
- Use
approxQuantilefor median calculations on large datasets - Materialize intermediate results (sessions, users) with
cache()before multiple aggregations
The core logic remains identical; PySpark provides distributed execution while preserving the vectorized, non-iterative approach.
Common Pitfalls
- Naive timestamps: Mixing timezone-aware and naive datetimes causes subtle bugs
- Unstable sorting: Without tiebreakers, session IDs can vary between runs
- Funnel double-counting: Counting users at every step they touch inflates totals
- Platform-keyed sessions: Creates artificial session breaks when users switch devices
- Wald confidence intervals: Fail for small samples or extreme proportions; Wilson intervals are more robust