Session Window and Device Online Analysis
# Session Window and Device Online Analysis
# Business Scenario
Device reports often come in "bursts": continuous while online, silent when stopped. We want to carve each "active period" into a session — for the same device, consecutive reports (gap below a timeout) belong to one session; once the gap exceeds the timeout the session closes and emits its stats (message count, last report time). This "split by activity gap" need calls for a session window.
# SQL
SELECT deviceId,
COUNT(*) AS msgs,
MAX(ts) AS last_ts
FROM stream
GROUP BY deviceId, SessionWindow('5s')
2
3
4
5
SessionWindow('5s'): within the same deviceId, adjacent events less than 5s apart belong to the same session; a gap over 5s triggers the previous session to close and emit.
# Input
dev-01 sends 3 messages in quick succession then stops; dev-02 sends only 1:
{"deviceId": "dev-01", "ts": 1000}
{"deviceId": "dev-01", "ts": 2200}
{"deviceId": "dev-01", "ts": 3000}
{"deviceId": "dev-02", "ts": 1500}
2
3
4
(After 5s of silence, the session closes on timeout.)
# Output
The batch callback fires when the session closes, one row per device session:
{deviceId:dev-01 msgs:3 last_ts:3000}
{deviceId:dev-02 msgs:1 last_ts:1500}
2
# Behavior Notes
- The session window splits by activity gap, with no fixed boundary: each event extends the current session; once no new data arrives for
timeout, it closes. GROUP BY deviceId, SessionWindow(...): each device maintains its own session independently.- The session window uses processing-time semantics (it fires on "no data for the timeout"); to get output immediately in a test, call
ssql.TriggerWindow()to force-close the current session instead of waiting out the timeout. - Typical uses: user/device online segments, a continuous burst of one operation, activity-bucketed statistics.
How to run
A session window is an aggregation query; use Emit + AddSink to receive session results in batches. See How to Run Case SQL for the full boilerplate.
# 📚 Related Docs
- How to Run Case SQL
- SQL Reference — SessionWindow syntax
- IoT Temperature Alerting and Metrics Aggregation — other window modes