i want to see active sessions at a time for same m...
# ask-ai
e
i want to see active sessions at a time for same meeting
t
Thanks for reaching out, Guess. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — do you mean the number of simultaneous participants in a room, multiple device logins by the same user, or viewer count in a livestream? Which method would you like to use to check this: • LiveKit Cloud Dashboard (visual, real-time) • Analytics API (
numActiveParticipants
) • Server SDK / list participants • Webhooks/events for real-time tracking Also tell me whether you're on LiveKit Cloud and which plan you have (Scale+ if you want Analytics API access). I'll give the exact steps once you confirm. Sources: Analytics API | LiveKit docs | Say hello to improved Cloud analytics | server-sdk-ruby | livekit/livekit_composite | DeepWiki | Rooms, participants, and tracks | LiveKit docs | Livestream Mode
e
MULTIPLE ACTIVE SESSIONS
t
Thanks — when you say "MULTIPLE ACTIVE SESSIONS" do you mean: • A single user connected from multiple devices/tabs (multiple connections with the same identity), or • Multiple different participants connected at the same time, or • Many viewers in a livestream (viewer vs interactive participant distinction)? Also confirm: • Are you using LiveKit Cloud or a self-hosted LiveKit server? • If Cloud, which plan are you on (need Scale+ for Analytics API)? Once you confirm, I’ll provide the exact steps (Dashboard, Analytics API, Server SDK calls, or webhook/event setup) to list and monitor those active sessions.
e
LIVEKIT CLOUD WE ARE SEEING TWO SESSIONS RM_WCsHpwXCrnpg interview-24295ac6-dcd1-4123-9186-fff1ac5d0c10-1764659007 2 Dec 2025, 123327 2 Dec 2025, 123922 6 mins 4 Closed RM_oFnqxiv4v5yq interview-24295ac6-dcd1-4123-9186-fff1ac5d0c10-1764658988 2 Dec 2025, 123308 2 Dec 2025, 123827 6 mins 3 Closed
t
Thanks — I see two session records for the same meeting name and you want to know why and how to interpret them. What this means • Each session entry is a separate session instance: different session IDs, start/end times, and participant counts. • LiveKit records sessions independently; sessions aren’t automatically merged even if they share the same room name. • Common reasons you’ll see multiple sessions for the same room name: ◦ The room was closed and then reopened (new session). ◦ Multiple server-side room instances were created with the same room name. ◦ Client reconnects that created a new session record while an older connection was still being finalized. How to investigate • Compare the session start/end timestamps and session IDs you posted to see if one started after the other or overlapped. • Use the Analytics API and filter by
roomName
to list sessions for that room and check
numActiveParticipants
and
lastActive
. • Check participant lists for each session via Server SDK
list_participants(roomName)
to see which identities appear in each session. • If you need continuous real-time tracking, subscribe to participant events (webhooks or server SDK events) to detect joins/leaves and correlate them to session IDs. If you want, I can: • Provide the Analytics API call and example query to list sessions for
interview-24295ac6-dcd1-4123-9186-fff1ac5d0c10-1764659007
. • Show the Server SDK call to list participants for a given session/room ID. Which would you prefer?
e
◦ The room was closed and then reopened (new session). ◦ Multiple server-side room instances were created with the same room name. ◦ Client reconnects that created a new session record while an older connection was still being finalized. WANT TO HANDLE THESE SO IF TEHRE IS ACTIVE SESSION SO DONT CREATE FOR THE ROOM SO I WANT TO HANDLE THIS .
t
You're asking how to prevent creating a new session/room when an active session for the same room already exists. Below are concise, practical options and recommended approach — pick the one that matches your architecture. 1) Quick guard (recommended server-side check before create) • Before creating a room/session, call the Server SDK to check if the room already exists and has active participants. ◦ Use
list_participants(roomName)
(or equivalent) and if the returned list length > 0, skip creating a new session. • This keeps decision logic on your server where you issue tokens and control room lifecycle. 2) Use Analytics API for authoritative session state (Cloud Scale+) • Query the Analytics API
/sessions
filtered by
roomName
and check
numActiveParticipants
or
numParticipants
. • If an active session exists, do not create another. • Use this when you need historical / cross-instance awareness (requires Scale+). 3) Handle race conditions and reconnects • When creating a room, perform a short-lived lock (e.g., Redis lock) keyed by `roomName`: a. Acquire lock b. Re-check participants/sessions c. Create room if still empty d. Release lock • On client reconnects, prefer reusing the same identity rather than creating a new session. If your app issues tokens, ensure tokens map to the correct identity so reconnects replace old connections instead of creating new overlapping sessions. 4) Prevent duplicate server-side room instances • Ensure only one service process is responsible for room creation for a given
roomName
. Use leader-election or a single creator service to avoid multiple server instances creating the same room concurrently. 5) Reconnect and cleanup strategies • Shorten room idle timeout or explicitly close rooms when all participants leave, if appropriate. • When you detect overlapping sessions for the same
roomName
, you can: ◦ Merge logic: redirect new joiners to the active session ID (if you track session->room mapping) ◦ Auto-close stale sessions whose
lastActive
is old Next step — I can provide concrete code for your stack. Which do you want? • Server SDK snippet for checking participants (Node, Python, or Go) • Analytics API example request to check
numActiveParticipants
• Example Redis lock pattern for safe creation
e
GIVE ME APIS
t
Below are the API options you can use to detect active sessions and avoid creating a new session for the same room. I’ll include the Analytics API (Cloud Scale+), a Server SDK example (Node), and a short Redis lock pattern to avoid races. Pick whichever fits your setup. 1) Analytics API — list sessions for a room (Cloud Scale+) • Endpoint: GET /v1/sessions • Filter by roomName and time range. Check
numActiveParticipants
(or
numParticipants
) and
lastActive
. Example curl (replace placeholders):
Copy code
curl -X GET "https://api.livekit.cloud/v1/sessions?roomName=interview-24295ac6-dcd1-4123-9186-fff1ac5d0c10" \
  -H "Authorization: Bearer YOUR_API_KEY"
Example relevant fields in response: •
sessionId
•
roomName
•
numParticipants
•
numActiveParticipants
•
lastActive
Use: If any session returned has
numActiveParticipants > 0
(or recent
lastActive
), do not create a new session. 2) Server SDK — list participants and conditionally create (Node example) • Use server SDK to list participants for
roomName
. If count > 0, skip creation. Example (Node.js, pseudocode using LiveKit Server SDK):
Copy code
const { LiveKitServer } = require('livekit-server-sdk'); // replace with actual package import

const server = new LiveKitServer({
  apiKey: 'API_KEY',
  apiSecret: 'API_SECRET',
  url: 'https://your-livekit-instance' // for Cloud use project-specific URL
});

async function ensureSingleSession(roomName) {
  // 1. List participants in the room
  const participants = await server.listParticipants(roomName); // returns array
  if (participants.length > 0) {
    return { created: false, reason: 'active_session_exists', participants };
  }

  // 2. No active participants -> create room/session (if your flow creates rooms)
  const room = await server.createRoomIfNotExists(roomName); // pseudocode
  return { created: true, room };
}
Use: Place this check on the service that issues tokens or triggers room creation. 3) Redis lock pattern to avoid race conditions (recommended when multiple creators exist) • Acquire a short lock keyed by
roomName
before checking/creating. • Re-check participants after acquiring lock, then create if still empty, then release lock. Example pseudocode:
Copy code
// using ioredis
const lockKey = `lock:room:${roomName}`;
if (await redis.set(lockKey, '1', 'NX', 'EX', 5)) { // 5s lock
  try {
    const participants = await server.listParticipants(roomName);
    if (participants.length === 0) {
      // create room/session
    }
  } finally {
    await redis.del(lockKey);
  }
} else {
  // wait/retry or fetch participants again
}
4) Reconnect handling (identity reuse) • Ensure clients reconnect with the same identity so reconnects replace old connection instead of creating overlapping sessions. • When issuing tokens, map tokens to consistent identities. Which snippet do you want as a full, ready-to-run example? • Full Node Server SDK code for listing participants + conditional create • Analytics API request with pagination and time-range examples • Redis lock implementation with retries I can provide the full code for your chosen option.
e
{ "meeting_id": "4521c3ca-eec5-404c-b820-670b96302816", } } we create room based on this so our room name willl be like interview-4521c3ca-eec5-404c-b820-670b96302816-1764661387 so next time when i trigger with same meeting id i have to check if room is not active for this meeting id and if its not active then go create a session
t
Understood — you want an API-ready way to check whether any active room exists for a given meeting_id (room name prefix like
interview-{meeting_id}-...
) and only create a new session if none are active. Below are two production-ready options (prefer ListRooms if you only care about currently active rooms; use Analytics API if you need recently-ended sessions visibility). I include Node and Python examples plus the lock pattern to avoid races. 1) Preferred: Server SDK — list live rooms (active only) • Use server SDK ListRooms (returns currently active rooms). Filter by prefix
interview-{meeting_id}
and check
numParticipants > 0
. Node (ready-to-run pattern)
Copy code
// requires livekit-server-sdk (or your project's equivalent)
const { RoomServiceClient } = require('livekit-server-sdk'); // replace with real import
const client = new RoomServiceClient({ baseUrl: 'https://your-livekit-host', apiKey: process.env.API_KEY, apiSecret: process.env.API_SECRET });

async function hasActiveRoomForMeeting(meetingId) {
  const rooms = await client.listRooms(); // returns array of room objects
  const prefix = `interview-${meetingId}`;
  return rooms.some(r => r.name.startsWith(prefix) && (r.numParticipants || 0) > 0);
}

// usage
if (!await hasActiveRoomForMeeting('4521c3ca-eec5-404c-b820-670b96302816')) {
  // create room/session
}
Python
Copy code
# pseudo import - use your LiveKit server SDK client
from livekit_server import RoomServiceClient
client = RoomServiceClient(base_url='https://your-livekit-host', api_key=API_KEY, api_secret=API_SECRET)

def has_active_room_for_meeting(meeting_id):
    rooms = client.list_rooms()  # list of room dicts
    prefix = f"interview-{meeting_id}"
    return any(r['name'].startswith(prefix) and r.get('numParticipants', 0) > 0 for r in rooms)
When to use: fast real-time check, no time-range required. Requires server SDK access to your LiveKit instance. 2) Analytics API — authoritative across project (active + recent) • Call GET /v1/sessions for your project, filter by time range, then match
roomName
prefix and check
numActiveParticipants > 0
. Curl example
Copy code
curl -H "Authorization: Bearer $ANALYTICS_TOKEN" \
 "https://cloud-api.livekit.io/api/project/$PROJECT_ID/sessions?start=2025-12-01&end=2025-12-02&limit=200"
Then in code, parse JSON: • For each session where
roomName
startsWith
interview-{meeting_id}
, if
numActiveParticipants > 0
=> active. Python parsing example
Copy code
import requests
def analytics_has_active(meeting_id, project_id, token):
    url = f"https://cloud-api.livekit.io/api/project/{project_id}/sessions"
    params = {'start': '2025-12-01', 'end': '2025-12-02', 'limit': 200}
    resp = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
    for s in resp.json().get('sessions', []):
        if s['roomName'].startswith(f"interview-{meeting_id}") and s.get('numActiveParticipants', 0) > 0:
            return True
    return False
When to use: cross-instance authoritative view; requires LiveKit Cloud Scale+ and
roomList
grant. 3) Avoid race conditions — Redis lock pattern (recommended if multiple creator processes) • Acquire short lock keyed by
room:{meeting_id}
before checking/creating. • Re-check active-room after acquiring lock, create only if still none, then release lock. Pseudocode
Copy code
if acquire_lock("lock:room:{meeting_id}", ttl=5s):
  try:
    if not hasActiveRoomForMeeting(meeting_id):
      create_room(...)
  finally:
    release_lock(...)
else:
  wait/retry or return that creation is in progress
4) Token/identity best practices • Ensure clients reconnect with the same identity so reconnect replaces the old connection rather than leaving stale overlapping sessions. • Shorten idle timeouts or explicitly close rooms when all participants leave if appropriate for your workflow. Permissions required • Server SDK: service API key/secret that can list rooms and create rooms. • Analytics API: token with
roomList
grant and project scope (Scale+). Which exact code do you want implemented now? • Full Node server example with Redis lock and creation flow • Full Python server example with Analytics API call and create flow Sources: Managing rooms | LiveKit docs | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | Analytics API | LiveKit docs