ambitious-tent-31724
12/23/2025, 4:22 PM@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 cleanuptall-airline-16756
12/23/2025, 4:22 PMtall-airline-16756
12/23/2025, 4:23 PMlifespan 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:
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