Is there a lifecycle for a call similar to fastapi...
# ask-ai
a
Is there a lifecycle for a call similar to fastapi's? SOmething like:
Copy code
@asynccontextmanager
async def lifespan(app: FastAPI):
    yield
    await Provider.disconnect()
but for livekit - guaranteed cleanup, before the call is obvious, but not sure about the cleanup
t
Thanks for reaching out, Stepan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you're asking whether LiveKit offers a lifecycle hook like FastAPI's
lifespan
so you can guarantee cleanup (e.g.,
await Provider.disconnect()
) when a call/session ends. Yes — LiveKit provides a shutdown callback mechanism that serves the same purpose. You can register cleanup functions that are guaranteed to run when the agent/session shuts down. Key points: • Use
ctx.add_shutdown_callback()
(or
session.add_shutdown_callback()
) to register async cleanup functions. • Callbacks run after
session.shutdown()
during the session’s teardown, and will execute even if the session ends due to errors. • You can call
session.shutdown(drain=True)
to allow graceful draining of pending work before callbacks run. Example:
Copy code
async def entrypoint(ctx: JobContext):
    async def my_cleanup():
        await Provider.disconnect()

    ctx.add_shutdown_callback(my_cleanup)
Would you like an example that shows registering multiple callbacks, ordering guarantees, or how to combine
drain=True
with your cleanup steps? Sources: Job lifecycle | LiveKit docs