How to listen for session disconnect from the user
# ask-ai
f
How to listen for session disconnect from the user
t
Thanks for reaching out, Rex. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to listen for when a user session disconnects in LiveKit, you can easily subscribe to the
RoomEvent.Disconnected
event from the LiveKit client SDK. This event fires whenever someone leaves the room, so your app can jump in and handle things smoothly. Here’s a quick example in JavaScript/TypeScript:
Copy code
room.on(RoomEvent.Disconnected, () => {
  console.log("User disconnected from the room");
  // You can do cleanup or update the UI here
});
And for native platforms: • Swift: Just use the
room(_:didUpdateConnectionState:from:)
delegate method and watch for the state
.disconnected
. • Android (Kotlin/Java): Keep an eye on the
RoomEvent.Disconnected
event. If you want me to walk you through more examples or details for a particular platform, just let me know—I’m here to help! Sources: avatars/hedra/education_avatar/education-frontend/components/app.tsx | components/app.tsx | Multiplatform/Controllers/RoomContext.swift | livekit-android-test/src/test/java/io/livekit/android/room/RoomMockE2ETest.... | livekit-agents/livekit/agents/voice/room_io/room_io.py
f
On the server side
t
If you want to catch when a user disconnects from a session on the server side in LiveKit, the best way is to use webhooks. LiveKit will send a
participant_left
webhook event whenever someone leaves a room. Here’s a simple way to get it going: 1. Enable Webhooks: Set the
webhook_url
in your LiveKit server configuration (
livekit.yaml
) to point to your server’s endpoint. Don’t forget to add a
webhook_secret
to keep things secure. 2. Listen for the
participant_left
Event:
Your server should be ready to handle POST requests at that webhook URL. The event payload will give you useful info like
participant_identity
,
room_name
, and
disconnect_reason
. 3. Verify Webhook Signature: Use the
webhook_secret
to check the
X-LiveKit-Signature
header, so you know the request is legit. Here’s a quick example in Python to help you get started:
Copy code
import hmac
from flask import Flask, request, jsonify

app = Flask(__name__)
WEBHOOK_SECRET = "your-webhook-secret"

@app.route('/livekit-webhooks', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-LiveKit-Signature')
    body = request.get_data()

    # Verify signature
    expected = hmac.new(WEBHOOK_SECRET.encode(), body, 'sha256').hexdigest()
    if not hmac.compare_digest(expected, signature):
        return 'Invalid signature', 401

    data = request.json
    if data['event'] == 'participant_left':
        print(f"Participant {data['participant_identity']} left room {data['room_name']}")
        # You can do cleanup, logging, or analytics here

    return jsonify(success=True)
If you’d like, I’m happy to help with more details or examples tailored to your server setup—just let me know! Sources: livekit-plugins/livekit-plugins-google/livekit/plugins/google/beta/realtime... | Multiplatform/Controllers/RoomContext.swift | livekit-android-test/src/test/java/io/livekit/android/room/RoomMockE2ETest....
f
In an agent session how do I listen for user disconnected on server side and then stop the TTS playback and close the session.
t
Hey there! To gracefully handle user disconnection in an agent session on the server side—like stopping TTS playback and closing the session—here’s a simple approach you can follow: 1. Listen for the "close" Event: The
AgentSession
fires a
close
event when the session ends, including if a user disconnects. You can catch this event to stop TTS playback and tidy things up. For example:
Copy code
@session.on("close")
def on_close(ev: CloseEvent):
    print(f"Agent Session closed, reason: {ev.reason}")
    # Here’s where you can do cleanup or other tasks
1. Stop TTS Playback and Close the Session: If you want to manually stop TTS playback and close the session, just call
session.aclose()
. This makes sure everything gets cleaned up properly. Like this:
Copy code
await session.aclose()
1. Automatic Closure: By default,
RoomInputOptions.close_on_disconnect
is set to
True
. This means it automatically stops TTS playback and closes the session when the user disconnects. But if you want to handle it yourself, you can set it to
False
and add your own logic. If anything’s unclear or you’d like more examples, just let me know—I’m happy to help! Sources: agents/src/voice/room_io/room_io.ts | livekit-agents/livekit/agents/voice/agent_activity.py | basics/exit_message.py | How to capture real-time agent transcriptions during conversations
f
There is a shutdown callback function that takes a little time to close the session. So if the user starts a session and closes it and then again starts a fresh session the same worker thread responds which is already open. And multiple voices can be heard from the agent
t
Hey there! To help you manage overlapping sessions or worker threads in LiveKit agent sessions and avoid having multiple voices talking over each other, here are some friendly tips you can follow: 1. Keep Sessions Separate: Make sure each agent session runs in its own process. This way, they stay isolated from each other, and you don't have to worry about thread safety manually. 2. Manage Voice Overlap: When you set up your
AgentSession
, tweak the
VoiceOptions
to stop multiple voices from playing at once. For example:
Copy code
session = AgentSession(\n    allow_interruptions=False,\n    discard_audio_if_uninterruptible=True,\n    min_interruption_duration=0.5,\n)
1. Use Turn Detection: Set up
turn_detection
so the system knows when the user has stopped talking and it's the agent's turn to respond. You can choose between
vad
(voice activity detection) or
stt
(speech-to-text) depending on what fits your needs. 2. Clean Up Smoothly: Don't forget to add shutdown callbacks to tidy things up and close sessions properly:
Copy code
ctx.add_shutdown_callback(cleanup)
If you want me to walk you through any of these steps or need more examples, just let me know—I’m here to help! Sources: Job lifecycle | LiveKit Docs | examples/other/transcription/multi-user-transcriber.py | Quotas and limits | LiveKit Docs | Anatomy of an Agent | LiveKit Docs | Inside a session | LiveKit Docs
f
Cleanup function
t
Here’s a friendly guide to help you implement a cleanup function for LiveKit agent sessions: 1. Centralized Cleanup: It’s a good idea to create a dedicated
aclose()
method that takes care of canceling tasks and closing sessions neatly. Here’s a quick example:
Copy code
async def aclose(self):
    await utils.aio.cancel_and_wait(*self._tasks)  # Cancel active tasks
    await asyncio.gather(*[self._close_session(session) for session in self._sessions.values()])  # Close sessions
    self.ctx.room.off("participant_connected", self.on_participant_connected)
    self.ctx.room.off("participant_disconnected", self.on_participant_disconnected)
1. Ensure Cleanup with `try`/`finally`: Wrapping your session logic in a `try`/`finally` block is a great way to make sure cleanup always happens, no matter what:
Copy code
try:
    session = AgentSession()
    await session.start(agent=MyAgent(), room=ctx.room)
    await shutdown_future_or_room_empty()
finally:
    if session:
        await session.aclose()
1. Resource-Specific Cleanup: For individual resources, defining a
cleanup
method that can be safely called multiple times is super helpful:
Copy code
async def cleanup(self):
    if self.livekit_api:
        await self.livekit_api.aclose()
        self.livekit_api = None
1. Combine Session Close Events with Job Shutdown: You can use the
close
event for quick cleanup and
ctx.add_shutdown_callback()
to handle any final tasks gracefully:
Copy code
@session.on("close")
def on_close_session(ev: CloseEvent):
    print(f"Session closed: {ev.reason}")

ctx.add_shutdown_callback(save_user_state_to_db)
If you want me to walk you through any part of this or need more examples, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_session.py | agent.py | Inside a session | LiveKit Docs
f
Once the user discconects, I want to fire a function on shutdown. However, this thread should not accept any other jobs. How to ensure this ?
t
Hey there! To make sure a LiveKit worker thread stops accepting new jobs after a user disconnects and triggers a shutdown, here’s a simple way to handle it: 1. Trigger Shutdown: When the user disconnects, just call
ctx.shutdown(reason="User disconnected")
inside your
entrypoint
function. This lets the worker know it should stop taking new jobs and start shutting down. 2. Graceful Draining: The worker will then automatically stop accepting new jobs and wait for any active ones to finish up. If you want, you can tweak how long it waits by setting the
drain_timeout
in
WorkerOptions
like this:
Copy code
opts = WorkerOptions(\n    entrypoint_fnc=entrypoint,\n    drain_timeout=60  # seconds\n)
1. Run Cleanup: You can also add cleanup tasks that run after shutdown by using `ctx.add_shutdown_callback()`:
Copy code
async def my_cleanup():\n    # Perform cleanup actions\n    pass\n\nctx.add_shutdown_callback(my_cleanup)
So, once
ctx.shutdown()
is called, the worker won’t accept any new jobs and will run your cleanup tasks. If you want me to walk you through this with more examples or have any questions, just let me know—I’m here to help! Sources: Job lifecycle | LiveKit Docs | examples/voice_agents/realtime_joke_teller.py | Deploying to custom environments | LiveKit Docs | Worker options | LiveKit Docs | agents/src/job.ts
f
So on user discconect I will fire a function.. and then once that function is done executing i will send the session..but I want to ensure is that while the last function is being executed, the thread should not accept any new jobs.
t
Hey there! To make sure a LiveKit worker thread doesn’t take on new jobs while it’s wrapping up a final function after a user disconnects, here’s a friendly step-by-step guide: 1. Trigger Draining State: Once the user disconnects, just call
ctx.shutdown(reason="User disconnected")
. This gently tells the worker to stop accepting new jobs and start shutting down. 2. Use Shutdown Callbacks: You can register a cleanup function with
ctx.add_shutdown_callback()
. This way, your cleanup runs right after the user disconnects but before the job process ends. For example:
Copy code
async def my_cleanup():
    # Perform cleanup actions
    pass

ctx.add_shutdown_callback(my_cleanup)
1. Set Drain Timeout: Make sure to set the
drain_timeout
in
WorkerOptions
so there’s enough time for your final function to finish smoothly. Like this:
Copy code
opts = WorkerOptions(
    entrypoint_fnc=entrypoint,
    drain_timeout=60  # seconds
)
1. Leverage Load-Based Rejection: If you want, you can add a custom
load_fnc
to politely reject new jobs when the worker is busy finishing up. Here’s a quick example:
Copy code
def compute_load(worker):
    return min(len(worker.active_jobs) / 10, 1.0)

opts = WorkerOptions(
    load_fnc=compute_load,
    load_threshold=0.9,
)
These handy steps help make sure your worker finishes its final tasks without taking on anything new. If you want me to walk you through any part or share more examples, just let me know—I’m here to help! Sources: Deployment and scaling | LiveKit Docs | livekit-agents/livekit/agents/worker.py | Job lifecycle | LiveKit Docs | Worker options | LiveKit Docs | Deploying to custom environments | LiveKit Docs
f
Explain load based rejection
t
Load-based rejection in LiveKit workers helps make sure a worker doesn’t take on more jobs than it can handle by stopping new jobs once it hits a certain capacity. This is managed through two parameters in `WorkerOptions`: 1. `load_fnc`: This is a function that figures out how busy the worker is, giving a value between 0 and 1. By default, it looks at the average CPU usage over 5 seconds, but you can tweak it to use other things like the number of active jobs or memory usage. For example:
Copy code
def compute_load(worker):\n    return min(len(worker.active_jobs) / 10, 1.0)
1. `load_threshold`: This sets the maximum load the worker will accept before it stops taking new jobs. The default is 0.7 (or 70%). If the load goes over this, the worker politely says no to new jobs and lets the server send them elsewhere. When the load is too high, the worker keeps working on the jobs it already has but won’t take on more, which helps handle busy times smoothly. If you’re using autoscaling, it’s a good idea to set it to add more workers before hitting the threshold—like scaling up at 0.5 if your
load_threshold
is 0.7. If you want me to walk you through this more or need some examples, just let me know—I’m happy to help! Sources: Worker options | LiveKit Docs | Deploying to custom environments | LiveKit Docs | README.md
f
def compute_load(worker): return min(len(worker.active_jobs) / 10, 1.0) opts = WorkerOptions( load_fnc=compute_load, load_threshold=0.9, ) explain
t
Hey there! Let me walk you through the code snippet you provided—it’s all about managing the workload for a LiveKit worker in a smart way. Here’s a quick breakdown: 1. `compute_load(worker)`: This little function figures out how busy the worker is by checking how many active jobs it has. It takes the number of active jobs (
len(worker.active_jobs)
) and divides that by 10, so the load is a number between 0 and 1. Plus, it uses
min
to make sure the load never goes above 1.0, even if there are more than 10 jobs running. 2. `opts = WorkerOptions(...)`: Here’s where we set up the worker with some options: ◦ `load_fnc=compute_load`: This tells the worker to use our custom load function to keep track of how busy it is. ◦ `load_threshold=0.9`: This means the worker will stop taking new jobs once it hits 90% of its capacity (so, a load of 0.9 or higher). So, with this setup, the worker can comfortably handle up to 9 active jobs before it starts saying “hold on, I’m full!” If anything’s unclear or you want to dive deeper, just let me know—I’m here to help!
f
show me some demo code
t
Here’s a friendly demo showing how to implement load-based rejection using the code snippet you provided:
Copy code
from livekit import WorkerOptions

# Define a custom load function
def compute_load(worker):
    # Calculate load as the ratio of active jobs to a maximum capacity of 10
    return min(len(worker.active_jobs) / 10, 1.0)

# Configure WorkerOptions with the custom load function and threshold
opts = WorkerOptions(
    load_fnc=compute_load,  # Use the custom load function
    load_threshold=0.9     # Reject new jobs if load reaches 90%
)

# Example worker entrypoint
def entrypoint(ctx):
    print("Worker started")
    # Simulate job processing
    async def process_job():
        print("Processing job...")
        await asyncio.sleep(5)  # Simulate job duration
        print("Job completed")

    ctx.add_shutdown_callback(lambda: print("Worker shutting down"))

    # Main loop to simulate job handling
    while True:
        if len(ctx.worker.active_jobs) >= 10:
            print("Worker at capacity, rejecting new jobs")
            break
        await process_job()

# Start the worker with the configured options
if __name__ == "__main__":
    from livekit import Worker
    Worker(entrypoint, opts).run()
This snippet shows you how to set up and use load-based rejection in a LiveKit worker. Basically, the worker will politely say “no thanks” to new jobs once it hits 90% of its capacity (that’s 9 out of 10 active jobs). If you want me to walk you through it more or need extra examples, just let me know—I’m here to help!
f
def compute_load(worker): return min(len(worker.active_jobs) / 10, 1.0) opts = WorkerOptions( _load_fnc_=compute_load, # Use the custom load function _load_threshold_=0.9 # Reject new jobs if load reaches 90% ) if name == "__main__": agents.cli.run_app( agents.WorkerOptions(entrypoint_fnc=start_session, prewarm_fnc=prewarm, agent_name="Evi", ws_url=API_URL, api_key=API_KEY,api_secret=API_SECRET) )
t
Hey there! It looks like you’re trying to combine a custom load function with the LiveKit worker setup. No worries—I’ve got you covered with a simple way to integrate your custom load function into the worker configuration:
Copy code
from livekit import WorkerOptions, agents\n\n# Define a custom load function\ndef compute_load(worker):\n    # Calculate load as the ratio of active jobs to a maximum capacity of 10\n    return min(len(worker.active_jobs) / 10, 1.0)\n\n# Configure WorkerOptions with the custom load function and threshold\nopts = WorkerOptions(\n    load_fnc=compute_load,  # Use the custom load function\n    load_threshold=0.9     # Reject new jobs if load reaches 90%\n)\n\n# Define your entrypoint function\ndef start_session(ctx):\n    print(\"Session started\")\n    # Add your session logic here\n    pass\n\n# Define a prewarm function (optional)\ndef prewarm():\n    print(\"Worker prewarming...\")\n    # Add any pre-initialization logic here\n    pass\n\n# Run the worker\nif __name__ == \"__main__\":\n    agents.cli.run_app(\n        agents.WorkerOptions(\n            entrypoint_fnc=start_session,\n            prewarm_fnc=prewarm,\n            agent_name=\"Evi\",\n            ws_url=API_URL,\n            api_key=API_KEY,\n            api_secret=API_SECRET,\n            load_fnc=compute_load,\n            load_threshold=0.9\n        )\n    )
So, this example ties your
compute_load
function right into the worker setup. Basically, the worker will politely say “no thanks” to new jobs once it hits 90% capacity (which is 9 active jobs in this case). If anything’s unclear or you want to tweak it further, just let me know—I’m happy to help!
f
if it just accepts 1 job, will a new worker thread be opened for new jobs
t
Hey! Just to clarify, LiveKit starts a new process for each job by default, even if your current worker is set up to handle only one job at a time. This way, each job runs in its own little bubble, keeping things stable and making sure one job’s hiccup doesn’t mess with the others. Here are the main things to keep in mind: • LiveKit uses separate processes (not threads) for running jobs. This keeps each job nicely isolated. • If a worker is busy or only set for one job, new jobs will be sent to other workers or processes as they become available. • You can tweak this behavior with the
job_executor_type
in
WorkerOptions
, but sticking with process-based execution is the default and usually the best way to go. If you want me to walk you through anything else or have more questions about setting up your workers, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/worker.py | Worker lifecycle | LiveKit Docs | Deploying to custom environments | LiveKit Docs