(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisbon

How to calculate session metrics in Real-Time Analytics: step by step

João Barros 03 de December de 2026 5 min read

Let's build a simple pipeline to calculate session metrics in Real-Time Analytics: identify sessions by user_id, calculate session duration and events per session in real time. This is useful to understand user behavior and feed dashboards and alerts.

Prerequisites

  • Source of telemetry events (e.g.: events with user_id, event_time, event_type) arriving to a streaming system (Kafka, Event Hubs, Kinesis).
  • Supported real-time processing engine (e.g.: Apache Flink, Spark Structured Streaming or Azure Stream Analytics).
  • Storage for results (e.g.: OneLake, Azure Data Lake, SQL database or Cosmos DB) and a visualizer (Power BI).
  • Tools to test: client to produce events (Python/Node script) and access to the streaming engine.

Step 1: Define session rules

Explain the "why": a session groups a user's events within an inactivity interval. The most common rule is inactivity timeout (e.g.: 30 minutes). Also decide if very short sessions should be ignored.

Step 2: Normalize and enrich events

Events should have at least: user_id, event_time (ISO 8601 or epoch), event_type. Enriching with useful fields makes aggregation easier (e.g.: page, device). Normalize timestamps to UTC.

# Exemplo mínimo de evento JSON  {
  "user_id": "user-123",
  "event_time": "2026-12-03T10:15:30Z",
  "event_type": "page_view",
  "page": "/home"
}

Step 3: Ingest into the streaming engine

Configure the engine input (e.g.: Kafka topic). JSON or Avro format is recommended. Ensure ordering by event_time when possible or handle timestamps during processing.

# Exemplo conceptual para Spark Structured Streaming (esquema simples)  from pyspark.sql.types import StructType, StringType, TimestampType
schema = StructType() \
  .add("user_id", StringType()) \
  .add("event_time", TimestampType()) \
  .add("event_type", StringType())

stream = spark.readStream.format("kafka") \
  .option("kafka.bootstrap.servers", "broker:9092") \
  .option("subscribe", "events") \
  .load()

events = spark.read.json(stream.selectExpr("CAST(value AS STRING)").rdd.map(lambda r: r[0]), schema=schema)

Step 4: Assign session_id based on timeout

Use stateful streaming operations: for each user_id order by event_time and assign a session_id that starts when the gap between events exceeds the timeout. In Spark Structured Streaming use mapGroupsWithState or flatMapGroupsWithState; in Flink use KeyedProcessFunction with timers.

# Exemplo simplificado com Spark Structured Streaming (pseudocódigo funcional)  from pyspark.sql.functions import col, unix_timestamp  from pyspark.sql.types import StructType, StructField, StringType, TimestampType

# parta por user_id e processe estados (pseudocódigo)  def update_sessions(key, values, state):
    # values são eventos ordenados por event_time
    # state guarda último timestamp e current session_id
    outputs = []
    for ev in sorted(values, key=lambda x: x.event_time):
        if state.exists():
            last_ts, sid = state.get()
            if (ev.event_time - last_ts).total_seconds() > 30*60:
                sid = generate_new_session_id(ev)
            # atualiza state
            state.update((ev.event_time, sid))
        else:
            sid = generate_new_session_id(ev)
            state.update((ev.event_time, sid))
        outputs.append((ev.user_id, sid, ev.event_time, ev.event_type))
    return outputs

# Registo com flatMapGroupsWithState(...) -> output stream com session_id

Step 5: Aggregate metrics per session

When a session_id is closed (timeout detected), compute metrics: session_start, session_end, duration, events_count, pages_unique. In engines with timers close the session when the inactivity timer expires.

# Lógica de agregação (pseudocódigo)  # Para cada session_id finalizado:  session_start = min(event_time)
session_end = max(event_time)
duration_seconds = (session_end - session_start).total_seconds()
events_count = count(events)
unique_pages = count(distinct page)

# Escreve o resultado para armazenamento/serviço de métricas

Step 6: Write and expose in real time

Write session results to a low-latency destination (e.g.: Cosmos DB for Power BI or OneLake/SQL for reports). Alternatively publish metrics to a queue or topic for dashboards and alerts.

# Exemplo de escrita com Spark
results.writeStream.format("delta") \
  .option("checkpointLocation", "/checkpoints/sessions") \
  .option("path", "/data/sessions") \
  .outputMode("append") \
  .start()

Step 7: Handle common errors and optimize

Common issues: out-of-order events, client clocks unsynchronized, high user cardinality causing state memory pressure. Strategies: watermarking, state TTL limits, sharding by key and state compression.

Verify the result

Confirm that sessions have coherent session_start/session_end and duration; compare original events with aggregated sessions; test edge cases (a single isolated event, sequence of events with gaps above/below the timeout). View dashboards in Power BI or directly query the delta file/table for recent rows.

Conclusion

With these steps you have a Real-Time Analytics pipeline to calculate session metrics: session identification, duration and event counts in real time. Next steps: add attributes (funnel steps, retention by session) and create alerts for anomalous sessions. Tip: start with a conservative timeout (e.g.: 30 min) and adjust after analyzing real data.