Skip to content

Instantly share code, notes, and snippets.

@BnJam
Last active March 5, 2026 18:08
Show Gist options
  • Select an option

  • Save BnJam/8123540b1716c81922169fa4f7c43cf0 to your computer and use it in GitHub Desktop.

Select an option

Save BnJam/8123540b1716c81922169fa4f7c43cf0 to your computer and use it in GitHub Desktop.
Graceful shutdown of a FastAPI application using uvicorn

Gracefully Shutting Down Uvicorn running FastAPI Application

The key libraries to achieve graceful shutting down to a Uvicorn server running a FastAPI application are the built in os and signal modules. Given an endpoint with which a client can request the server to shutdown.

os.kill(os.getpid(), signal.SIGTERM)

os.getpid() retrieves the running process' system ID and then signal.SIGINT is passed to the process to signal an interrupt.

Links:

import requests
if __name__ == '__main__':
print(requests.get('http://localhost:8000/hello').content)
print(requests.get('http://localhost:8000/shutdown').content)
import os
import signal
import fastapi
import uvicorn
from fastapi.responses import JSONResponse
app = fastapi.FastAPI()
def hello():
return fastapi.Response(status_code=200, content='Hello, world!')
def shutdown():
os.kill(os.getpid(), signal.SIGTERM)
return fastapi.Response(status_code=200, content='Server shutting down...')
@app.on_event('shutdown')
def on_shutdown():
print('Server shutting down...')
app.add_api_route('/hello', hello, methods=['GET'])
app.add_api_route('/shutdown', shutdown, methods=['GET'])
if __name__ == '__main__':
uvicorn.run(app, host='localhost', port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment