Orphaned sessions / rooms I've got two sessions <...
# ask-ai
c
Orphaned sessions / rooms I've got two sessions RM_xRBrsBzhHDx2 and RM_xRBrsBzhHDx2 that are accumulating minutes (1000+) even though they've been closed. I tried using Python scripts to delete all rooms from the backend but it says there are no active sessions.
t
Thanks for reaching out, Thai. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m looking into the orphaned sessions issue you reported (the two RM_xRBrsBzhHDx2 sessions that keep accumulating minutes even after appearing closed). A few targeted checks and questions will help me pinpoint the cause and a fix. 1) Quick checks you can run now • Confirm no agents, egress/recording, or server processes are still connected to the room (these keep a room alive and accruing minutes). • Verify you’re calling the DeleteRoom API for the exact project and room name (room names and project IDs must match exactly). • Check analytics/session details for the room to see which participants or egress are still shown as active. 2) If deletion reports “no active sessions” but minutes keep accruing • It often means an agent or egress didn’t fully shut down. For agent workflows, ensure your agent server invoked its shutdown/cleanup (for example `session.shutdown()`/`ctx.shutdown()` equivalents). • If a recording/egress didn’t stop, stop it or delete the room via DeleteRoom API to forcibly terminate all connections. 3) Please share these details so I can help further • The exact project ID you’re targeting (looks like p_3i9kwx3mjdh — please confirm). • The Python code or API call you used to delete the room and the exact error message you received. • Whether you use agents, SIP, or egress/recording in these sessions. • A recent timestamp when you observed minutes increasing and any session analytics output (session details) if available. If you prefer, paste the deletion call and the error text here and I’ll review it and give the precise next step. Sources: Job lifecycle | LiveKit docs | Managing rooms | LiveKit docs | Analytics API | LiveKit docs | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name
c
python close_sessions.py 📋 Fetching active rooms... ✅ No active rooms found. All sessions already closed. Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x106a99550> Unclosed connector connections: ['deque([(<aiohttp.client_proto.ResponseHandler object at 0x106a676b0>, 4366655.319455)])'] connector: <aiohttp.connector.TCPConnector object at 0x106a996a0> #!/usr/bin/env python3 """ Close all active sessions on LiveKit Cloud Deletes all active rooms, forcibly disconnecting all participants. """ import os import asyncio from dotenv import load_dotenv from livekit import api from livekit.api import ListRoomsRequest, DeleteRoomRequest load_dotenv() async def close_all_sessions(): """ List all active rooms and delete them, closing all sessions. Environment variables required: - LIVEKIT_URL: Your LiveKit Cloud URL (e.g., https://your-project.livekit.cloud) - LIVEKIT_API_KEY: Your API key - LIVEKIT_API_SECRET: Your API secret """ api_client = None try: # Initialize LiveKit API client api_client = api.LiveKitAPI( os.getenv("LIVEKIT_URL"), os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET"), ) # List all active rooms print("📋 Fetching active rooms...") rooms_response = await api_client.room.list_rooms(ListRoomsRequest()) rooms = rooms_response.rooms if not rooms: print("✅ No active rooms found. All sessions already closed.") return print(f"🔍 Found {len(rooms)} active room(s):") for room in rooms: print(f" - {room.name} ({room.num_participants} participants)") # Delete each room (closes all sessions) print("\n🔄 Closing all sessions...") deleted_count = 0 failed_rooms = [] for room in rooms: try: await api_client.room.delete_room( DeleteRoomRequest(room=room.name) ) print(f" ✓ Deleted room: {room.name}") deleted_count += 1 except Exception as e: print(f" ✗ Failed to delete room {room.name}: {str(e)}") failed_rooms.append((room.name, str(e))) # Summary print("\n" + "="*50) print(f"✅ Successfully closed {deleted_count}/{len(rooms)} session(s)") if failed_rooms: print(f"\n⚠️ Failed to close {len(failed_rooms)} room(s):") for room_name, error in failed_rooms: print(f" - {room_name}: {error}") else: print("🎉 All active sessions have been closed!") print("="*50) except Exception as e: print(f"❌ Error: {str(e)}") print("\nMake sure you have:") print(" - .env file with LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET") print(" OR environment variables set") raise finally: # Allow pending operations to complete if api_client: await asyncio.sleep(0.1) async def close_specific_room(room_name: str): """ Close a specific room/session by name. Args: room_name: Name of the room to close """ api_client = None try: api_client = api.LiveKitAPI( os.getenv("LIVEKIT_URL"), os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET"), ) print(f"🔄 Closing room: {room_name}...") await api_client.room.delete_room(DeleteRoomRequest(room=room_name)) print(f"✅ Successfully closed room: {room_name}") except Exception as e: if "not_found" in str(e) or "404" in str(e): print(f"⚠️ Room not found (already closed): {room_name}") else: print(f"❌ Error closing room {room_name}: {str(e)}") raise finally: # Allow pending operations to complete if api_client: await asyncio.sleep(0.1) if name == "__main__": import sys if len(sys.argv) > 1: # Close specific room room_name = sys.argv[1] asyncio.run(close_specific_room(room_name)) else: # Close all rooms asyncio.run(close_all_sessions())
t
Thanks — this is helpful. I’m responding to your report about the script printing “No active rooms found” while usage for RM_xRBrsBzhHDx2 keeps increasing, plus the unclosed aiohttp warnings. What to try next (short list) • Confirm project ID is p_3i9kwx3mjdh and that the session ID(s) to target are exactly RM_xRBrsBzhHDx2 (you posted it twice; confirm if there are two distinct IDs). • Run the Analytics sessions list and paste the session JSON for RM_xRBrsBzhHDx2 (GET /api/project/{PROJECT_ID}/sessions). Look for fields: startedAt, endedAt, numActiveParticipants, participant list (types), connectionCounts, bandwidthIn/bandwidthOut, and any egress entries. • Run a targeted DeleteRoom call for the exact room name and paste the full response/stack trace. Example minimal snippet to run and paste output:
Copy code
await api_client.room.delete_room(DeleteRoomRequest(room="RM_xRBrsBzhHDx2"))
• Confirm whether you run any server-side participants (agents, egress/recording, SIP, bots). If yes, say which and whether you call shutdown (e.g.,
session.shutdown()
/
ctx.shutdown()
). Also fix the aiohttp warnings by closing the API client in your script:
Copy code
finally:
    if api_client:
        await api_client.aclose()
If you paste the Analytics JSON and the exact DeleteRoom output (error/HTTP status/trace), I’ll review it and give the exact command or action to stop the accruing minutes. Sources: Managing rooms | LiveKit docs | Job lifecycle | LiveKit docs | Rooms, participants, and tracks | LiveKit docs | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | Analytics API | LiveKit docs
c
There are two sessions involved. Here is the URL for one of them. https://cloud.livekit.io/projects/p_3i9kwx3mjdh/sessions/RM_xRBrsBzhHDx2 Show me how to get the analytics JSON and how to get the deleterooom output
t
Responding about retrieving the analytics JSON for session RM_xRBrsBzhHDx2 and capturing DeleteRoom output. 1) Create a token with room-list grant • Using the LiveKit CLI:
Copy code
export LIVEKIT_API_KEY=...
  export LIVEKIT_API_SECRET=...
  lk token create --api-key $LIVEKIT_API_KEY --api-secret $LIVEKIT_API_SECRET --list --valid-for 24h
• Or create a JWT in your app that includes the
roomList
grant for the project. 2) Fetch the session analytics JSON (curl) • Replace TOKEN with the token from step 1 and confirm project id `p_3i9kwx3mjdh`:
Copy code
curl -H "Authorization: Bearer $TOKEN" \
    "https://cloud-api.livekit.io/api/project/p_3i9kwx3mjdh/sessions/RM_xRBrsBzhHDx2"
• The returned JSON includes
startedAt
,
endedAt
,
numActiveParticipants
,
participants
(types like AGENT/EGRESS),
connectionCounts
,
bandwidthIn/Out
, etc. Paste that JSON if you want me to review it. 3) Run DeleteRoom and capture output • CLI (quick):
Copy code
lk room delete RM_xRBrsBzhHDx2
Capture stdout/stderr; it will indicate success or an error. • Python (using your existing pattern, with proper client close and printed response):
Copy code
from livekit.api import LiveKitAPI, DeleteRoomRequest
  import os, asyncio

  async def delete_room(room_name):
      lk = LiveKitAPI(os.getenv("LIVEKIT_URL"),
                      os.getenv("LIVEKIT_API_KEY"),
                      os.getenv("LIVEKIT_API_SECRET"))
      try:
          resp = await lk.room.delete_room(DeleteRoomRequest(room=room_name))
          print("DELETE RESPONSE:", resp)
      except Exception as e:
          print("DELETE ERROR:", repr(e))
      finally:
          await lk.aclose()

  asyncio.run(delete_room("RM_xRBrsBzhHDx2"))
• Save the printed output (or copy/paste here). If you get a 404/not_found, paste the full exception text. 4) If ListRooms shows no active rooms but analytics shows activity • Look in the analytics JSON for participant types (
AGENT
,
EGRESS
,
INGRESS
) and
endedAt
. If
endedAt
is null or participants of type AGENT/EGRESS remain, that explains continued minutes. • If analytics shows active server-side participants, run DeleteRoom (above) and paste the response. If you want, run the two commands (curl analytics and the Python delete) and paste both outputs here and I’ll interpret them and advise the exact next step. Sources: Analytics API | LiveKit docs | Managing rooms | LiveKit docs
c
How do I supply the correct LIVEKIT_URL
t
You're close — LIVEKIT_URL must point to your project’s LiveKit Cloud base URL (the same host shown in the Cloud dashboard). Quick guidance: • Format: use the HTTPS project host, no trailing slash. Example: ◦ https://cloud.livekit.io ◦ or if your project uses a custom subdomain: https://your-project.livekit.cloud • Where to find it: open the LiveKit Cloud dashboard for your project — the connection URL shown in the dashboard is the value to use. • Set it in your environment or .env: ◦ .env: LIVEKIT_URL=https://cloud.livekit.io • or export in shell: export LIVEKIT_URL="https://cloud.livekit.io" • In your Python script the LiveKitAPI expects that base URL plus your API key/secret; do not include a path like /api or /sessions. • Important: use HTTPS, and do not include a trailing slash. If you use a custom domain, use that exact domain. If you tell me the exact host shown in your dashboard (or paste the project URL), I’ll confirm the exact LIVEKIT_URL value to use.
c
lk room delete RM_xRBrsBzhHDx2 Using url, api-key, api-secret from environment twirp error not_found: requested room does not exist
t
Thanks — you're seeing
not_found
because the DeleteRoom call is being made with an identifier that isn’t the room name the Room/RoomService APIs expect. Let’s clarify steps to find the correct room name in analytics and how to retry deletion. 1) Confirm what DeleteRoom expects • The Room delete API/CLI expects the room's actual name (the value shown in the dashboard and analytics), not a session URL token or an internal session id. 2) Get the session analytics JSON (shows room name) • Create a token with the room-list grant (CLI example):
Copy code
export LIVEKIT_API_KEY=...
  export LIVEKIT_API_SECRET=...
  TOKEN=$(lk token create --api-key $LIVEKIT_API_KEY --api-secret $LIVEKIT_API_SECRET --list --valid-for 24h)
• Fetch session details (replace PROJECT_ID if different):
Copy code
curl -H "Authorization: Bearer $TOKEN" \
    "https://cloud-api.livekit.io/api/project/p_3i9kwx3mjdh/sessions/RM_xRBrsBzhHDx2"
• In the returned JSON look for the
room
or
roomName
field (or `room_id`/`room`), and
participants
and
participant.types
(AGENT/EGRESS). Copy the exact
room
name. 3) Delete using the room name • CLI:
Copy code
lk room delete <ROOM_NAME>
• Python (example that prints full response and closes client):
Copy code
from livekit.api import LiveKitAPI, DeleteRoomRequest
  import os, asyncio

  async def delete_room(room_name):
      lk = LiveKitAPI(os.getenv("LIVEKIT_URL"),
                      os.getenv("LIVEKIT_API_KEY"),
                      os.getenv("LIVEKIT_API_SECRET"))
      try:
          resp = await lk.room.delete_room(DeleteRoomRequest(room=room_name))
          print("DELETE RESPONSE:", resp)
      except Exception as e:
          print("DELETE ERROR:", repr(e))
      finally:
          await lk.aclose()

  asyncio.run(delete_room("THE_ROOM_NAME_FROM_JSON"))
4) If DeleteRoom still returns
not_found
• Paste the full analytics JSON you got for the session here (I can read it). Confirm the
room
value exactly as shown. • If analytics shows
endedAt
is non-null and participants are gone, the room is already closed and DeleteRoom returning
not_found
is expected — billing should stop once the session ends, but if minutes continue, check the analytics
bandwidth
/
connectionCounts
timestamps to confirm ongoing activity. 5) Quick checks to share if usage persists • Paste the analytics JSON for RM_xRBrsBzhHDx2 (I’ll inspect
endedAt
, participants, and participant types). • If analytics shows server-side participants (AGENT/EGRESS) still present, run DeleteRoom with the exact room name and share the command output here. Paste the analytics JSON and the exact room name you see and I’ll tell you the exact delete command and interpret the result.
c
curl -H "Authorization: Bearer $eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjU3ODU1NzAsImlkZW50aXR5IjoicGFydGljaXBhbnQtMjk5YTAxNmRkNGQwIiwiaXNzIjoiLi4uIiwibmFtZSI6InBhcnRpY2lwYW50LTI5OWEwMTZkZDRkMCIsIm5iZiI6MTc2NTY5OTE3MCwic3ViIjoicGFydGljaXBhbnQtMjk5YTAxNmRkNGQwIiwidmlkZW8iOnsicm9vbSI6InJvb20tMjAyNTEyMTQwNzU5MzAiLCJyb29tTGlzdCI6dHJ1ZX19.gg9a8QgN34VVf9m58Qi_fVMe42oICE5CQ4F2mKF2wC4" \ "https://cloud-api.livekit.io/api/project/p_3i9kwx3mjdh/sessions/RM_xRBrsBzhHDx2" invalid API key: ...
t
Thanks — the curl error "invalid API key" means the token you used isn't valid for the Analytics endpoint. Let's fix that and get the analytics JSON. 1) Create a token with the room-list grant (LiveKit CLI) • Export keys first:
Copy code
export LIVEKIT_API_KEY=your_api_key
  export LIVEKIT_API_SECRET=your_api_secret
• Create a token valid for 24h:
Copy code
TOKEN=$(lk token create --api-key $LIVEKIT_API_KEY --api-secret $LIVEKIT_API_SECRET --list --valid-for 24h)
  echo $TOKEN
2) Fetch the session analytics JSON (one-line curl) • Replace $TOKEN if not using variable:
Copy code
curl -H "Authorization: Bearer $TOKEN" \
    "https://cloud-api.livekit.io/api/project/p_3i9kwx3mjdh/sessions/RM_xRBrsBzhHDx2"
Notes: • Ensure the token printed by the CLI is what you use; do not paste the CLI output with extra quotes or line breaks. • Tokens expire — if you get auth errors, regenerate the token. • Use the cloud-api host shown above (no trailing slash). 3) If you prefer a quick Node/Python token example • Node (JWT with roomList grant) or ask and I’ll paste a Python snippet. 4) After you get the JSON • Paste the returned JSON here and I’ll identify the exact
room
value to use with DeleteRoom, and tell you the delete command to run. If you want, run the CLI token creation and paste the exact
TOKEN
value (I will only use it to verify format — do not share secrets you don’t want exposed).
c
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjU3ODU5OTcsImlkZW50aXR5IjoicGFydGljaXBhbnQtZWVhYWE1Y2M0NmExIiwiaXNzIjoiQVBJSEJ2TnRUNkVOSGtRIiwibmFtZSI6InBhcnRpY2lwYW50LWVlYWFhNWNjNDZhMSIsIm5iZiI6MTc2NTY5OTU5Nywic3ViIjoicGFydGljaXBhbnQtZWVhYWE1Y2M0NmExIiwidmlkZW8iOnsicm9vbSI6InJvb20tMjAyNTEyMTQwODA2MzciLCJyb29tTGlzdCI6dHJ1ZX19.TYp2j59XSoWg4FzBQ-NOtY2o6o13kmWHmmbv56FPxrE" \ "https://cloud-api.livekit.io/api/project/p_3i9kwx3mjdh/sessions/RM_xRBrsBzhHDx2" scale plan or higher is required
t
Thanks — that error explains why the Analytics API calls failed. • "scale plan or higher is required" means the Analytics API endpoint you tried is only available on the Scale (or higher) plan. You cannot fetch session analytics via that API until the project is on that plan. What you can do right now • Open the LiveKit Cloud dashboard for project p_3i9kwx3mjdh, navigate to Sessions/Rooms, find the session row for RM_xRBrsBzhHDx2, and copy the exact room name shown there. • Once you have the exact room name, run: ◦ CLI:
Copy code
lk room delete <ROOM_NAME>
• or Python (replace ROOM_NAME):
Copy code
from livekit.api import LiveKitAPI, DeleteRoomRequest
    import os, asyncio

    async def delete_room(room_name):
        lk = LiveKitAPI(os.getenv("LIVEKIT_URL"),
                        os.getenv("LIVEKIT_API_KEY"),
                        os.getenv("LIVEKIT_API_SECRET"))
        try:
            resp = await lk.room.delete_room(DeleteRoomRequest(room=room_name))
            print("DELETE RESPONSE:", resp)
        except Exception as e:
            print("DELETE ERROR:", repr(e))
        finally:
            await lk.aclose()

    asyncio.run(delete_room("ROOM_NAME"))
If you can’t find the room name in the dashboard, tell me: • Whether you can upgrade to Scale (I can walk through next steps), or • If you’d like, paste a screenshot or the session row text from the dashboard and I’ll identify the exact room name to use for deletion.
c
lk room delete Call-_0401154837_Wzyj6RvaXRLP Using url, api-key, api-secret from environment twirp error not_found: requested room does not exist
t
You're seeing
not_found
because the DeleteRoom call is using a name that doesn't match any existing room. I'll help you narrow this down. 1) Quick checks (pick one you can do now) • Open the LiveKit Cloud dashboard for project p_3i9kwx3mjdh → Sessions/Rooms. Copy the exact room name shown for the session(s) that match RM_xRBrsBzhHDx2 or Call-_0401154837_Wzyj6RvaXRLP and paste it here. • If no room rows appear in the dashboard, confirm that by pasting a screenshot or the exact text shown. 2) If you can access Analytics (Scale plan) run: • (CLI) TOKEN=$(lk token create --api-key $LIVEKIT_API_KEY --api-secret $LIVEKIT_API_SECRET --list --valid-for 24h) • (curl) curl -H "Authorization: Bearer $TOKEN" "https://cloud-api.livekit.io/api/project/p_3i9kwx3mjdh/sessions/RM_xRBrsBzhHDx2" Paste the returned JSON here. 3) If dashboard shows a room name, run (replace <ROOM_NAME> exactly): • lk room delete "<ROOM_NAME>" 4) If DeleteRoom still returns
not_found
after using the exact dashboard room name: • Paste the exact command you ran and the full error output. • Confirm you are using the same project credentials (LIVEKIT_URL, API key/secret) shown in that project’s dashboard. What I need from you now • The exact room name as shown in the dashboard (or confirm no room rows are listed), AND • The exact command + full error text you ran when deleting the dashboard room name. With those two pieces I’ll tell you the exact next step to stop the accruing minutes.
c
image.png
t
Thanks — I can see the dashboard row: the first column shows the room name as
RM_xRbrsBzHiDx2
and the secondary label shows
Call._0401514837_Wzyj6RvaXRLP
. That
RM_xRbrsBzHiDx2
is the room identifier you should pass to DeleteRoom. Please run this exact command (ensure your environment has the project’s LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET): lk room delete RM_xRbrsBzHiDx2 If that returns an error, copy the full command output here. If it still says
not_found
, confirm you are using the same project credentials shown in the dashboard for project p_3i9kwx3mjdh (same LIVEKIT_URL and key/secret). If the delete succeeds, the session should immediately stop being ACTIVE and minutes will stop accruing — paste the CLI output and I’ll confirm the next checks.
c
lk room delete RM_xRbrsBzHiDx2 Using url, api-key, api-secret from environment twirp error not_found: requested room does not exist
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!