glamorous-oil-12326
09/25/2025, 7:40 PM@ctx.room.on("disconnected") vs shutdown_callback?tall-airline-16756
09/25/2025, 7:40 PMtall-airline-16756
09/25/2025, 7:40 PMglamorous-oil-12326
09/25/2025, 7:42 PMctx.add_shutdown_callback(shutdown_callback) but it's not obvious to me why that is preferred over @ctx.room.on("disconnected")tall-airline-16756
09/25/2025, 7:42 PMctx.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:
@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