How to Track Session Windows with Gap Timeout in Python

A Python class that groups events into sessions, closing a session when the gap between events exceeds a timeout threshold.

Medium Python 3.9+ Aug 9, 2026 Streaming & messaging 13 views 0 copies

Python code

70 lines
Python 3.9+
import time

class SessionWindow:
    """Track sessions with a gap timeout (mock)."""
    
    def __init__(self, timeout_seconds=5):
        self.timeout = timeout_seconds
        self.session_start = None
        self.last_event_time = None
        self.event_count = 0
        self.events = []
    
    def add_event(self, event):
        now = time.time()
        
        if self.last_event_time is None:
            # First event starts a new session
            self.session_start = now
            self.last_event_time = now
            self.events = [event]
            self.event_count = 1
            return True
        
        gap = now - self.last_event_time
        if gap > self.timeout:
            # Gap exceeded timeout - start new session
            self.session_start = now
            self.events = [event]
            self.event_count = 1
        else:
            # Same session - append event
            self.events.append(event)
            self.event_count += 1
        
        self.last_event_time = now
        return True
    
    def get_session_length(self):
        if self.last_event_time is None:
            return 0
        return self.last_event_time - self.session_start
    
    def get_events(self):
        return self.events


if __name__ == "__main__":
    # Mock: simulate events with gaps
    window = SessionWindow(timeout_seconds=2)
    
    # First event
    window.add_event("click")
    time.sleep(1)
    
    # Within timeout
    window.add_event("scroll")
    time.sleep(1)
    
    # Still within timeout
    window.add_event("click")
    
    # Now exceed the timeout with a long gap
    time.sleep(3)  # 3 seconds > 2 second timeout
    
    # New session starts
    window.add_event("submit")
    
    print(f"Events in current session: {window.get_events()}")
    print(f"Event count: {window.event_count}")
    print(f"Session length (seconds): {window.get_session_length():.1f}")

Output

stdout
Events in current session: ['submit']
Event count: 1
Session length (seconds): 0.0

How it works

The SessionWindow class tracks whether incoming events belong to the same session by comparing the time gap between consecutive events against a configured timeout. When add_event is called, it computes the difference between the current timestamp and the last event time. If that gap exceeds the timeout, a new session is started; otherwise, the event is appended to the current one. The mock in __main__ demonstrates both scenarios: events arriving within the timeout window stay in one session, while a 3-second sleep after the 2-second timeout forces a new session. This pattern mirrors stream processing systems like Flink or Kafka Streams that use gap-based session windows.

Common mistakes

  • Using wall-clock time instead of event timestamps, which breaks in distributed systems
  • Forgetting to update `last_event_time` on every event, causing incorrect gap calculations
  • Not handling the case where the session is empty and `get_session_length` returns 0

Variations

  1. Use a deque with maxlen to cap the number of events stored per session
  2. Emit session results via a callback or return the expired session when a new one starts

Real-world use cases

  • Grouping website clicks into user browsing sessions for analytics dashboards.
  • Batching log entries from a microservice into logical request traces.
  • Aggregating sensor readings into activity windows for anomaly detection pipelines.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Streaming & messaging

Related tutorials and quizzes for this topic.