Skip to content

Instantly share code, notes, and snippets.

@muety
Created October 24, 2022 19:51
Show Gist options
  • Save muety/be2f306ec1a37a00620512f78b002b60 to your computer and use it in GitHub Desktop.
Save muety/be2f306ec1a37a00620512f78b002b60 to your computer and use it in GitHub Desktop.
Single FastAPI on_startup() hook with multiple Gunicorn workers (run only once for all processes combined)
# run with gunicorn:
# gunicorn --preload --workers 4 --worker-class=uvicorn.workers.UvicornWorker app.main:app
# ('preload' is the important bit here)
# alternatively, set GUNICORN_CMD_ARGS='--preload'
import ctypes
import multiprocessing as mp
from fastapi import FastAPI
app = FastAPI(
title='Demo App',
lifespan='on'
)
workers_started: mp.Value = mp.Value(ctypes.c_ushort)
async def on_started():
'''Called when the first worker process is up and running'''
pass
@app.on_event('startup')
async def on_startup():
'''Called for every new Gunicorn worker'''
with workers_started.get_lock():
workers_started.value += 1
if workers_started.value == 1:
await on_started()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment