Skip to content

Instantly share code, notes, and snippets.

Created October 24, 2022 19:51
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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',
workers_started: mp.Value = mp.Value(ctypes.c_ushort)
async def on_started():
'''Called when the first worker process is up and running'''
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