enough-dentist-75383
12/02/2025, 7:31 AMtall-airline-16756
12/02/2025, 7:31 AMtall-airline-16756
12/02/2025, 7:31 AMnumActiveParticipants)
• 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 Modeenough-dentist-75383
12/02/2025, 7:32 AMtall-airline-16756
12/02/2025, 7:32 AMenough-dentist-75383
12/02/2025, 7:34 AMtall-airline-16756
12/02/2025, 7:34 AMroomName 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?enough-dentist-75383
12/02/2025, 7:36 AMtall-airline-16756
12/02/2025, 7:36 AMlist_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 creationenough-dentist-75383
12/02/2025, 7:38 AMtall-airline-16756
12/02/2025, 7:39 AMnumActiveParticipants (or numParticipants) and lastActive.
Example curl (replace placeholders):
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):
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:
// 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.enough-dentist-75383
12/02/2025, 7:48 AMtall-airline-16756
12/02/2025, 7:48 AMinterview-{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)
// 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
# 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
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
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
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