How to add graceful shutdown for agent worker? My...
# ask-ai
e
How to add graceful shutdown for agent worker? My calls are getting disconnected after doing ctrl + c. I want to wait for my all calls to get drained before my application exits
Copy code
if __name__ == "__main__":

    worker = WorkerOptions(
            entrypoint_fnc=entrypoint,
            prewarm_fnc=prewarm,
            worker_type=WorkerType.ROOM,
            shutdown_process_timeout=60,
            job_memory_warn_mb=5000,
            drain_timeout=1800,
            initialize_process_timeout=float(os.getenv("WORKER_INIT_TIME") or "30.0"),
        )
    # Run worker in main thread (required for signal handling)
    cli.run_app(worker)
m
I think drain timeout is what you're looking for. You can see how it's being used here: https://docs.livekit.io/agents/server/options/#options For a more specific explanation: https://docs.livekit.io/agents/server/options/#drain-timeout
e
But
drain_timeout
doesn't seem to be working Calls are getting interrupted after ctrl + c
t
To help you implement a graceful shutdown for your agent worker and make sure calls aren’t interrupted when you stop the process with
Ctrl+C
, you can configure the
drain_timeout
parameter in
WorkerOptions
. This setting allows the worker to patiently wait for any active jobs to finish before shutting down. Here’s a simple way to do it: 1. Set
drain_timeout
: This tells the worker how long to wait for active jobs to complete. For example:
Copy code
python worker = WorkerOptions( entrypoint_fnc=entrypoint, drain_timeout=1800, # Wait up to 30 minutes for jobs to complete ) cli.run_app(worker)
2. Use Shutdown Callbacks: You can add your own cleanup steps using
ctx.add_shutdown_callback()
inside your
entrypoint
function. For example:
Copy code
python async def on_shutdown(reason): print(f"Shutting down agent: {reason}") # Perform cleanup tasks here async def entrypoint(job_context): job_context.add_shutdown_callback(on_shutdown) await job_context.connect() # Your agent logic here
3. Signal Handling: If you’re running your agent with the LiveKit CLI, it already handles signals like
SIGINT
and
SIGTERM
for you. It will stop accepting new jobs, finish the active ones, and then close connections smoothly. 4. Avoid Force Kill: Just a heads up—pressing
Ctrl+C
twice or using
kill -9
will immediately stop the process and interrupt any ongoing calls. If you’ve set
drain_timeout
but calls are still getting interrupted, please double-check that your worker is running in production mode and that no force kill signals are being sent. I’m here to help if you want to dive deeper or have any other questions! Sources: Job lifecycle | LiveKit Docs | agents/src/cli.ts | Operational Best Practices | livekit/livekit_composite | DeepWiki | livekit-agents/livekit/agents/worker.py | Worker options | LiveKit Docs