FastAPI WebSocket server that broadcasts test notifications to connected clients and shuts down gracefully: each uvicorn worker waits for its own connections to close or forces shutdown after 30 minutes.
- Python 3.11+
python3 -m venv .venv
source .venv/bin/activate
pip install -e .[dev]uvicorn app.main:app --reload
# or multi-worker
uvicorn app.main:app --workers 4WebSocket endpoint: ws://localhost:8000/ws
- Connect with a client (e.g.,
wscat):
wscat -c ws://localhost:8000/ws- Every 10 seconds you should receive
"test notification". - Disconnect (Ctrl+C in wscat) — logs will show active count decreasing.
- Send
SIGINT(Ctrl+C in the uvicorn terminal) orSIGTERM. - Sequence:
- Background notification loop stops.
- Process waits for
ConnectionManagerto become idle (idle_event) or 30 minutes to elapse. - If clients remain after the timeout, it sends
close(1001, "Server shutdown")and exits.
- With multiple workers, each process manages only its own connections; no global sync by design.
- Console and
logs/app.log. - Rotation: 10 MB per file, up to 5 backups.
pytestruff check .
black .- To change the notification interval, adjust
notification_loopinapp/main.py. - Keep dependency versions pinned in
pyproject.tomlwhen upgrading.
License: MIT