How to implement per user metering, so that we can...
# ask-ai
n
How to implement per user metering, so that we can keep track of how many minutes particular users have completed?
t
Thanks for reaching out, William. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to implement per-user metering to track how many minutes each user completes. I can help — quick question first: Do you want to track time in real time as users connect/disconnect (recommended), or pull completed session data after the fact? • If you want real-time/near-real-time counts (recommended): I'll outline a webhook-driven implementation that records join and leave times and updates per-user minutes. • If you prefer post-hoc reporting: I'll show how to use the Analytics API to fetch session details and compute minutes. Which method should I detail? Sources: server-sdk-ruby | livekit/livekit_composite | DeepWiki | Rooms, participants, and tracks | LiveKit docs | Analytics API | LiveKit docs
n
real time, so we can turn off the session if they exceed the time
t
Acknowledged — you want real-time tracking so you can immediately end a participant’s session when they exceed their allotted minutes. Below is a concise, practical webhook-driven approach you can implement. 1) Overview • Use LiveKit webhooks
participant_joined
and
participant_left
to record session start/stop times. • Maintain a per-user minutes counter in your database. • On join, check remaining minutes; if none, immediately disconnect the participant. • While in a session, enforce limits by scheduling a disconnect or checking elapsed time periodically. 2) Data model (minimal) • users: { identity, minutes_allowed } • user_usage: { identity, total_seconds_used } • active_sessions: { room_id, participant_sid, identity, joined_at } 3) Flow and key actions • participant_joined webhook: a. Insert active_sessions record with
joined_at
timestamp. b. Compute remaining = minutes_allowed*60 - total_seconds_used. c. If remaining <= 0 -> disconnect now (see API call below). d. Else schedule a job to disconnect after
remaining
seconds (or store scheduled job id). • participant_left webhook: a. Lookup active_sessions by
participant_sid
(or identity + room_id). b. Compute session_seconds = now - joined_at. c. Add session_seconds to user_usage.total_seconds_used. d. Remove active_sessions record. e. If you had a scheduled disconnect job, cancel it. • Periodic safety check (optional): ◦ Run a short cron (e.g., every 30s) that scans active_sessions and enforces disconnects for any that exceed allowed time (guards against missed webhooks or clock skew). 4) How to disconnect a participant (LiveKit REST call) • Use the LiveKit REST/admin API to remove a participant from a room by participant SID (server-side). Call the participant removal endpoint when you decide to end the session. • Perform this from your backend (server-authenticated) — do not rely on client-side disconnects for enforcement. 5) Race conditions & reliability tips • Use participant SID as the canonical session key (safer than identity alone). • Persist joined_at immediately on webhook receipt to avoid lost events. • Use idempotent updates when adding session seconds (e.g., mark processed events). • Schedule a server-side job for the disconnect rather than trusting client timers. • Implement periodic reconciliation via the Analytics API or room queries to repair missed updates. 6) Example sequence (summary) 1. participant_joined -> store joined_at, calc remaining, schedule disconnect in remaining seconds. 2. participant_left -> compute elapsed, increment usage, cancel scheduled disconnect. 3. Scheduled disconnect fires -> call LiveKit participant remove API, update usage as needed. If you’d like, I can: • Provide example webhook payload handling pseudo-code in your language (Node/Python/Go). • Show the exact REST call payload to remove a participant (with
participant_sid
) and error handling. Which would you prefer?
n
Your sales rep told me you offered a solution this is totally DIY
t
I’m sorry for the frustration — I hear that you were told there’d be a provided solution and don’t want a fully DIY implementation. To clarify so I can help correctly: are you asking for • a turnkey, LiveKit-managed per-user metering feature that we would enable/configure for you, OR • a partially managed or example implementation (sample code, hosted webhook handler, or middleware) that reduces your engineering work? If you want a non‑DIY option, I can: • Check what packaged/managed metering options exist and summarize them, or • Prepare a targeted implementation plan (architecture + sample code) you can drop into your backend, or • Provide ready-to-run webhook handler examples (Node/Python/Go) and the exact REST call to disconnect participants. Tell me which option you'd prefer and which language/runtime your backend uses.
n
The first one a turnkey livekit managed per user metering
t
I hear your frustration — you were told there’d be a turnkey LiveKit‑managed per‑user metering feature. To be direct: LiveKit does not currently offer a fully managed, turn‑key per‑user metering + automatic enforcement product that you can enable and have LiveKit enforce individual user time limits for you. What LiveKit does provide: • Participant minutes are metered and available for retrieval via the Analytics API (per‑participant join/leave times and connectionMinutes). • Server control APIs let you remove or update participants programmatically. These building blocks allow enforcement, but the enforcement logic (tracking per‑user quotas and calling the remove API when a user exceeds their limit) must be implemented on your side. If you want, I can help in one of three ways (pick one): • Provide a ready-to-run webhook + worker implementation (Node/Python/Go) that records joins/leaves, maintains per-user minutes, schedules disconnects, and calls the participant remove API. • Produce a concise implementation plan and architecture you can hand to your engineers (data model, webhooks, scheduling, reconciliation). • Submit and prioritize a feature request for a managed per-user metering product on your behalf (I can capture your requirements to convey to the product team). Which option do you want me to do next, and which runtime/language does your backend use? Sources: Quotas and limits | LiveKit docs | Analytics API | LiveKit docs | Authentication | LiveKit docs
n
Wait this is waht we need: Participant minutes are metered and available for retrieval via the Analytics API (per‑participant join/leave times and connectionMinutes).
t
You confirmed that participant minutes via the Analytics API is what you need. I’ll provide the exact steps to retrieve per‑participant join/leave times and connection minutes, and ask which language/runtime you want sample code for. 1) What I’ll show (pick a runtime: Node / Python / Go): • How to call the Analytics API to list sessions and get session details. • Where to find per‑participant
joinedAt
,
leftAt
, and
connectionMinutes
. • A short example request + minimal response parsing to compute/aggregate minutes per user. 2) Quick facts you can rely on • Use the Analytics API endpoints: List Sessions, then Get Session Details for each session. Session details include per‑participant timestamps and
connectionMinutes
. • Authenticate with your project/server credentials (server-side only). • You can aggregate
connectionMinutes
per participant identity across sessions to get total minutes. Which runtime would you like the sample code in (Node, Python, or Go)?
n
need connectionMinutes in node / python
t
Below are concise Node and Python examples showing how to call the LiveKit Analytics API to list sessions, fetch session details, and extract per‑participant
connectionMinutes
. Replace
API_KEY
,
API_SECRET
, and
ANALYTICS_BASE_URL
with your project credentials and the Analytics API base URL. Node (fetch + HMAC auth signing)
Copy code
// Node 18+ or environment with fetch
import crypto from "crypto";

const API_KEY = "API_KEY";
const API_SECRET = "API_SECRET";
const BASE = "https://analytics.livekit.io/v1"; // replace if different

function makeAuthHeader(path, method = "GET", body = "") {
  const ts = Math.floor(Date.now() / 1000);
  const payload = `${ts}\n${method}\n${path}\n${body}`;
  const sig = crypto.createHmac("sha256", API_SECRET).update(payload).digest("hex");
  return `LiveKit ${API_KEY}:${sig}:${ts}`;
}

async function listSessions(limit = 100, pageToken = "") {
  const path = `/sessions?limit=${limit}${pageToken ? `&pageToken=${pageToken}` : ""}`;
  const headers = { Authorization: makeAuthHeader(path) };
  const res = await fetch(BASE + path, { headers });
  return res.json();
}

async function getSessionDetails(sessionId) {
  const path = `/sessions/${sessionId}`;
  const headers = { Authorization: makeAuthHeader(path) };
  const res = await fetch(BASE + path, { headers });
  return res.json();
}

async function aggregateConnectionMinutes() {
  let pageToken = "";
  const totals = {}; // identity -> minutes
  do {
    const sessionsResp = await listSessions(100, pageToken);
    for (const s of sessionsResp.sessions || []) {
      const details = await getSessionDetails(s.sessionId);
      for (const p of details.participants || []) {
        const id = p.participantIdentity || p.identity || p.participantIdentity;
        const minutes = p.connectionMinutes ?? 0;
        totals[id] = (totals[id] || 0) + minutes;
      }
    }
    pageToken = sessionsResp.nextPageToken || "";
  } while (pageToken);
  return totals;
}

// Example usage
aggregateConnectionMinutes().then(console.log).catch(console.error);
Python (requests + HMAC auth signing)
Copy code
import time
import hmac
import hashlib
import requests

API_KEY = "API_KEY"
API_SECRET = b"API_SECRET"
BASE = "https://analytics.livekit.io/v1"  # replace if different

def make_auth_header(path, method="GET", body=""):
    ts = str(int(time.time()))
    payload = f"{ts}\n{method}\n{path}\n{body}".encode()
    sig = hmac.new(API_SECRET, payload, hashlib.sha256).hexdigest()
    return f"LiveKit {API_KEY}:{sig}:{ts}"

def list_sessions(limit=100, page_token=""):
    path = f"/sessions?limit={limit}"
    if page_token:
        path += f"&pageToken={page_token}"
    headers = {"Authorization": make_auth_header(path)}
    r = requests.get(BASE + path, headers=headers)
    r.raise_for_status()
    return r.json()

def get_session_details(session_id):
    path = f"/sessions/{session_id}"
    headers = {"Authorization": make_auth_header(path)}
    r = requests.get(BASE + path, headers=headers)
    r.raise_for_status()
    return r.json()

def aggregate_connection_minutes():
    page_token = ""
    totals = {}  # identity -> minutes
    while True:
        sessions_resp = list_sessions(100, page_token)
        for s in sessions_resp.get("sessions", []):
            details = get_session_details(s["sessionId"])
            for p in details.get("participants", []):
                identity = p.get("participantIdentity") or p.get("identity")
                minutes = p.get("connectionMinutes", 0)
                totals[identity] = totals.get(identity, 0) + minutes
        page_token = sessions_resp.get("nextPageToken") or ""
        if not page_token:
            break
    return totals

if __name__ == "__main__":
    print(aggregate_connection_minutes())
Notes and tips • The examples use HMAC signing (timestamp + method + path + body). Adjust if your Analytics endpoint uses a different auth scheme; ensure server-side only usage of the API key/secret. •
connectionMinutes
is available in session details per participant; aggregate by participant identity to get totals. • Handle pagination (
nextPageToken
) when listing sessions. • Use session detail timestamps (`joinedAt`/`leftAt`) if you need raw times instead of the precomputed
connectionMinutes
. If you want, I can: • Convert these into production-ready snippets with retries, backoff, and error handling. • Provide an example that aggregates minutes for a single participant over a given date range. Which would you like?