Session duration and count

How can I calculate number of sessions and session duration using InfluxDB or Kapacitor?

A session is defined as a group of interactions one user takes within a given time frame (a session lasts until there’s 30 minutes of inactivity).

The schema may be something like this: time, user_id, action

Kapacitor processes on data that exists, as such detecting the absence of activity for 30m requires a slightly indirect approach.

Using the stats node you can get counts about the activity of a user and then perform operations on those counts.

// Select the data that exists and group it by user
var data = stream
     |from()
          .measurement('user_actions')
          .groupBy('user')

var stats = data
    // Compute stats about the number of user events every minute.
    |stats(1m)
        .align()

// Now determine the length of the each session
var sessions = stats
    |window()
        .period(30m)
        .every(1m)
    |spread('emitted')
        .as('count')
    // Note: stateDuration is a new feature coming out in the next 1.3 release. 
    |stateDuration(lambda: "count" > 0)
        .as('duration')
        .unit(1m)
    
// Do something with the session durations.
sessions
    |alert()
        .info(lambda: "duration" > 120)
        .message('User {{index .Tags "user"}} has been logged in for 2+ hours.')

// Count the number of active sessions
var count = sessions
    // Remove group by user tag.
    |groupBy()
    // Filter out all users that are no longer active.
    |where(lambda: "duration" > 0)
    // Count them
    |count('duration')
   

// Do something with the session count
count 
    |influxDBOut()
        .database('session_count')

Hope, that helps. Let me know which parts may be confusing.

1 Like