Is there any configurations for LiveKit room maxim...
# ask-ai
b
Is there any configurations for LiveKit room maximum duration?
✅ 1
t
Thanks for reaching out, toshi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m responding to your question about whether LiveKit supports configuring a maximum room duration. Short answer: • No — LiveKit does not provide a built‑in setting to enforce a hard maximum lifetime (for example, “close this room exactly 60 minutes after creation”). What you can use instead: • Departure timeout: A room with no participants will automatically close after the configured departure timeout (default is 20 seconds). This controls cleanup when a room is empty, not total room lifetime. • Manual deletion: Your application can call the
DeleteRoom
API to immediately terminate a room and disconnect participants. • Application-side scheduling: Track room start time in your app and schedule a job to call
DeleteRoom
when your desired maximum duration is reached. • Agent session pattern: If you use agent sessions, you can set
delete_room_on_close
in
RoomOptions
so the room is removed when the agent session ends. If you’d like, I can help with next steps — tell me which approach you prefer and share: • Whether you need automatic enforcement (no manual step) or are fine with server-side scheduled deletion. • Which SDK or server environment you’re using (Node, Go, Python, etc.) so I can provide concrete code/examples for scheduling a
DeleteRoom
call or configuring
delete_room_on_close
. Sources: Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | Ensuring Unique Room IDs with Dynamic Room Names | LiveKit | CreateRoom() is taking too long | LiveKit | Job lifecycle | LiveKit Documentation | Python Agents: Handling exceptions in your entrypoint | LiveKit, with interactive elements
b
I use Java SDK and Python SDK for livekit agents
t
Thanks — I’m following up on your question about configuring a maximum room duration, and I see you use the Java and Python SDKs for LiveKit agents. LiveKit does not provide a built‑in “max duration” setting for a room, but you can enforce a maximum session length with server-side logic. Below are practical options and examples you can use with Java and Python. What you can do (options) • Use scheduled deletion: When a room starts (or when an agent session is created), schedule a job that calls DeleteRoom after your desired duration. • Use webhooks: Listen for a
room_started
(or similar) webhook, start a timer, and call DeleteRoom when the timer expires. • Use agent sessions with `delete_room_on_close`: If you model sessions as agents, set
delete_room_on_close
in
RoomOptions
so the room is deleted when that agent session ends. • Periodic cleanup: Run a cron job that queries rooms and deletes any that exceed your allowed lifetime. Python example (server-side scheduling) 1. Create room, start a background timer, then call DeleteRoom after desired seconds.
Copy code
import asyncio
import os
from livekit import api

async def create_room_and_enforce_duration(room_name: str, duration_seconds: int):
    lk_api = api.LiveKitAPI(
        url=os.getenv("LIVEKIT_URL"),
        api_key=os.getenv("LIVEKIT_API_KEY"),
        api_secret=os.getenv("LIVEKIT_API_SECRET"),
    )

    # Create the room
    await lk_api.room.create_room(api.CreateRoomRequest(name=room_name))

    # Wait for the chosen max duration
    await asyncio.sleep(duration_seconds)

    # Delete the room to enforce max duration
    await lk_api.room.delete_room(api.DeleteRoomRequest(room=room_name))
Java example (scheduled task) 1. Schedule a task to call your server-side DeleteRoom endpoint or REST API after the duration.
Copy code
import java.util.concurrent.*;

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

String roomName = "my-room";
int minutes = 60; // desired max duration

scheduler.schedule(() -> {
    try {
        // Call your server endpoint that deletes the room, or call DeleteRoom REST API directly
        // e.g., use an HTTP client to call DELETE /v1/rooms/{roomName} (server authentication required)
        System.out.println("Time limit reached — deleting room: " + roomName);
    } catch (Exception e) {
        e.printStackTrace();
    }
}, minutes, TimeUnit.MINUTES);
Notes and recommendations • DeleteRoom is immediate and will disconnect participants. Make sure clients handle unexpected disconnects gracefully (notify users or save state). • If you want automatic deletion tied to an agent lifecycle, use
delete_room_on_close
in your agent session
RoomOptions
. • Webhooks are useful if you prefer event-driven timers and avoid holding in-memory timers across server restarts. Use a durable scheduler (e.g., Redis, database rows with worker jobs) for reliability. • If you’d like code that actually calls the DeleteRoom REST endpoint from Java, tell me whether you use the server SDK or plain HTTP and I’ll provide a concrete snippet for authenticated requests. Would you like: • A complete Python example that runs as a background worker and uses durable storage (DB/Redis) for timers? • A Java example that calls the DeleteRoom REST endpoint with authentication (I can include an OkHttp or HttpClient sample)? • Guidance on configuring
delete_room_on_close
with your agent session objects? Tell me which option you prefer and which environment (framework, deployment style) you’re using, and I’ll provide the concrete example you need. Sources: Python SDKs | livekit/livekit_composite | DeepWiki | server-sdk-kotlin | livekit/livekit_composite | DeepWiki | Server-side | livekit/livekit_composite | DeepWiki | livekit/livekit_composite | DeepWiki, with interactive elements
b
Please give me an example for Python LiveKit agent SDK
t
Thanks — I’ll show a practical Python example using the LiveKit Python server SDK to enforce a maximum room duration for agent sessions. I’ll include two approaches so you can pick what fits your architecture: • Approach A: Use
delete_room_on_close
with an agent session (room deleted when the agent session ends). • Approach B: Schedule a durable background job that calls
DeleteRoom
after a max duration (works for any room). Both snippets assume you have LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET set as environment variables. Approach A — Agent session with delete_room_on_close • Use this if your rooms map to agent sessions and you want the room removed automatically when the agent session closes.
Copy code
# agent_session_example.py
import os
import asyncio
from datetime import timedelta
from livekit import api

# Initialize LiveKit REST client
lk = api.LiveKitAPI(
    url=os.getenv("LIVEKIT_URL"),
    api_key=os.getenv("LIVEKIT_API_KEY"),
    api_secret=os.getenv("LIVEKIT_API_SECRET"),
)

async def create_agent_session_room(agent_id: str, room_name: str):
    # Example RoomOptions using delete_room_on_close
    room_options = api.RoomOptions(
        # other options as needed
        delete_room_on_close=True
    )

    # Create or update a room associated with agent session
    create_req = api.CreateRoomRequest(
        name=room_name,
        // room_options=room_options  # for some SDK variants, pass as room_options
    )

    # Some SDK variants expose agent/session APIs; if not, create the room and
    # store agent session metadata in your app (agent->room mapping).
    await lk.room.create_room(create_req)

    # Track agent session in your app; when the agent session ends,
    # end the session (and LiveKit will delete the room due to delete_room_on_close).
Notes: • If your agent workflows use a specific agent/session API surface, set
delete_room_on_close
inside the agent session creation flow (
RoomOptions
) so LiveKit deletes the room when that session closes. • Your application should explicitly close the agent session when the time limit is reached (see Approach B for scheduled deletion). Approach B — Durable scheduled DeleteRoom (recommended if you want a strict max duration) • Use a background worker with durable storage (DB, Redis) so timers survive restarts. • Example uses asyncio + Redis to store expiration times and a worker that enforces deletion.
Copy code
# enforce_max_duration.py
import os
import asyncio
import aioredis
from datetime import datetime, timedelta
from livekit import api

LIVEKIT_URL = os.getenv("LIVEKIT_URL")
LIVEKIT_API_KEY = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.getenv("LIVEKIT_API_SECRET")
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")

lk = api.LiveKitAPI(url=LIVEKIT_URL, api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET)

# Keys in Redis: "room_expiry:{room_name}" -> ISO timestamp of expiry
async def schedule_room_deletion(room_name: str, max_seconds: int):
    redis = await aioredis.from_url(REDIS_URL)
    expiry = datetime.utcnow() + timedelta(seconds=max_seconds)
    await redis.set(f"room_expiry:{room_name}", expiry.isoformat())
    await redis.close()

async def delete_room_if_expired(room_name: str):
    redis = await aioredis.from_url(REDIS_URL)
    expiry_iso = await redis.get(f"room_expiry:{room_name}")
    if not expiry_iso:
        await redis.close()
        return
    expiry = datetime.fromisoformat(expiry_iso.decode())
    if datetime.utcnow() >= expiry:
        try:
            await lk.room.delete_room(api.DeleteRoomRequest(room=room_name))
            await redis.delete(f"room_expiry:{room_name}")
            print(f"Deleted expired room: {room_name}")
        except Exception as e:
            print(f"Failed to delete room {room_name}: {e}")
    await redis.close()

async def worker_loop(poll_seconds: int = 5):
    redis = await aioredis.from_url(REDIS_URL)
    try:
        while True:
            # Fetch keys with prefix (for scale, use Redis SCAN)
            keys = await redis.keys("room_expiry:*")
            for key in keys:
                room_name = key.decode().split("room_expiry:")[1]
                expiry_iso = await redis.get(key)
                expiry = datetime.fromisoformat(expiry_iso.decode())
                if datetime.utcnow() >= expiry:
                    try:
                        await lk.room.delete_room(api.DeleteRoomRequest(room=room_name))
                        await redis.delete(key)
                        print(f"Deleted expired room: {room_name}")
                    except Exception as e:
                        print(f"Error deleting room {room_name}: {e}")
            await asyncio.sleep(poll_seconds)
    finally:
        await redis.close()

# Example usage:
# 1) When you create/accept an agent session, call schedule_room_deletion(room_name, max_seconds)
# 2) Run worker_loop() as a background process/service on your server fleet

if __name__ == "__main__":
    # Example: create a room and schedule deletion after 1 hour
    async def main():
        room_name = "agent-room-123"
        await lk.room.create_room(api.CreateRoomRequest(name=room_name))
        await schedule_room_deletion(room_name, max_seconds=3600)
        # Start the worker in the same process for demo; in prod run it separately
        await worker_loop()

    asyncio.run(main())
Key implementation notes and best practices • Use durable storage (Redis, DB) so scheduled deletions survive restarts and crashes. • Prefer a separate worker/service for deletion rather than in-memory timers inside request handlers. • Inform clients when you will terminate a room (send a message or use data channels) so clients can gracefully wrap up. • Deleting a room immediately disconnects participants; ensure your client apps handle sudden disconnects. • If you want deletion tied to agent lifecycle, use
delete_room_on_close
in RoomOptions for agent sessions. If you want, I can: • Provide a concrete example that calls the DeleteRoom REST endpoint using an authenticated HTTP client from Java or Python. • Adapt the Python worker to use a specific persistent store (Postgres, DynamoDB) or a job queue (RQ, Celery). • Show client-side handling patterns to gracefully handle forced room deletions. Which follow-up would you like? , with interactive elements