When to use `@ctx.room.on("disconnected")` vs `shu...
# ask-ai
g
When to use
@ctx.room.on("disconnected")
vs
shutdown_callback
?
t
Thanks for reaching out, Aumesh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you please share a bit more about the situation where you're choosing between @ctx.room.on("disconnected") and shutdown_callback? For instance, are you working with user disconnections, server shutdowns, or maybe something else? I’m here to help you figure this out!
g
I am trying to decide when to use one vs the other. In the entrypoint I am doing
ctx.add_shutdown_callback(shutdown_callback)
but it's not obvious to me why that is preferred over
@ctx.room.on("disconnected")
t
Let's explore the difference between
ctx.add_shutdown_callback(shutdown_callback)
and
@ctx.room.on("disconnected")
together, so you can see when each is most helpful: •
ctx.add_shutdown_callback(shutdown_callback)
: This is a job-level shutdown hook that triggers when the agent job is ending—like during a planned shutdown, room deletion, or if an external process stops it. It’s perfect for important tasks such as saving user state, flushing telemetry, or logging those final metrics. •
@ctx.room.on("disconnected")
: This one listens for room-level events and fires when the local client loses connection to the LiveKit room, whether due to network hiccups or an intentional disconnect. It’s great for handling network disconnections, debugging, or reacting to changes in connection status. For dependable cleanup tasks,
ctx.add_shutdown_callback
is usually the go-to since it’s guaranteed to run during the job’s shutdown phase. But
@ctx.room.on("disconnected")
shines when you want to keep an eye on and respond to real-time connection challenges. In fact, using both together can give you a well-rounded approach to managing different parts of the agent’s lifecycle. Here’s a simple example to illustrate:
Copy code
@ctx.room.on("disconnected")
def on_disconnect(reason):
    logger.warning(f"Agent lost connection: {reason}")

async def on_shutdown():
    logger.info("Performing final cleanup...")
    await flush_metrics()

ctx.add_shutdown_callback(on_shutdown)
Sources: Speech & Audio Processing | livekit/livekit_composite | DeepWiki | livekit-rtc/livekit/rtc/room.py | Job lifecycle | LiveKit Docs | examples/voice_agents/basic_agent.py | Inside a session | LiveKit Docs