Skip to content

Replace deprecated @app.on_event with lifespan context manager - #389

Open
Qiaochu Hu (hobostay) wants to merge 1 commit into
microsoft:mainfrom
hobostay:fix/deprecated-fastapi-lifespan
Open

Replace deprecated @app.on_event with lifespan context manager#389
Qiaochu Hu (hobostay) wants to merge 1 commit into
microsoft:mainfrom
hobostay:fix/deprecated-fastapi-lifespan

Conversation

@hobostay

Copy link
Copy Markdown

Summary

  • Replace deprecated @app.on_event("startup") with the recommended lifespan context manager pattern in demo/web/app.py
  • @app.on_event("startup") is deprecated since FastAPI 0.103.0 and will be removed in a future version

Details

Affected file: demo/web/app.py (lines 335-356)

The deprecated on_event("startup") pattern has known issues with auto-reload where the startup event may fire multiple times, loading multiple copies of the large model into GPU memory and causing OOM. The lifespan context manager is the recommended replacement.

Test plan

  • Start the web app with MODEL_PATH set and verify it loads correctly
  • Verify WebSocket streaming still works after the change
  • Verify startup errors (e.g., missing MODEL_PATH) are still properly raised

🤖 Generated with Claude Code

FastAPI deprecated @app.on_event("startup") since version 0.103.0
and it will be removed in a future release. Replace with the
recommended lifespan context manager pattern.

This also prevents potential issues with auto-reload loading the
model multiple times into GPU memory.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: Approve — replace deprecated @app.on_event with lifespan

Correctness: @app.on_event("startup") and @app.on_event("shutdown") are deprecated in FastAPI 0.95+ in favor of the lifespan context manager pattern. This is a forward-compatibility fix.

Changes are correct: The async context manager properly yields between startup (model loading) and shutdown (model cleanup), matching the original semantics exactly.

Verdict: Approve. Non-breaking forward-compat fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants