Improve handling of FASTAPI Asyncio in API#4924
Open
JC-wk wants to merge 6 commits into
Open
Conversation
added 3 commits
June 5, 2026 10:13
…ollection of background tasks.
Unit Test Results673 tests 673 ✅ 8s ⏱️ Results for commit a51b3eb. ♻️ This comment has been updated with latest results. |
Contributor
There was a problem hiding this comment.
Pull request overview
This pull request improves reliability of long-running background Service Bus workers in the FastAPI API by managing their lifecycle within the application lifespan, aiming to prevent silent task garbage collection and to make shutdown behavior more controlled/observable.
Changes:
- Track background worker tasks in
app.stateto keep strong references scoped to the FastAPI application lifecycle. - Add controlled shutdown logic that cancels tracked tasks, awaits completion, and logs failures.
- Add an unreleased changelog entry describing the fix.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
api_app/main.py |
Refactors FastAPI lifespan to track, name, cancel, and gather background tasks during shutdown. |
CHANGELOG.md |
Adds an Unreleased BUG FIXES entry for the background task lifecycle fix. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Resolves #4923
What is being addressed
This pull request resolves a reliability issue where background Service Bus message processors (
DeploymentStatusUpdaterandAirlockStatusUpdater) could potentially be silently garbage-collected. It refactors task lifecycle management to use application-scoped state, implements safe concurrent task cancellation during shutdown, and enhances background worker observability.Problem Description
Previously, background workers were instantiated and launched using:
In Python, the
asyncioevent loop only maintains weak references to tasks. Discarding the return value ofasyncio.create_task()without keeping a strong reference elsewhere left the task instances vulnerable to garbage collection during runtime, leading to silent processing failures.Additionally, this introduced other architectural concerns:
RuntimeError: Set changed size during iteration.Solution
Refactored
lifespanin api_app/main.py to implement a correct and robust asyncio background worker pattern:1. App-Scoped State Tracking
Instead of a global module-level set, background tasks are now registered under the FastAPI
app.statelifecycle:This ensures task contexts are cleanly isolated per application instance.
2. Task Naming and Observability
Tasks are created with human-readable names for improved debuggability and stack tracing:
name="deployment-status-updater"name="airlock-status-updater"3. Safe, Controlled Shutdown
During teardown (after
yield), tasks are copied to a list before cancellation to prevent mutation-during-iteration errors.4. Traceback Preservation on Failures
Exceptions raised by background tasks are retrieved and logged using
exc_info=resultto preserve full tracebacks for debugging:Changes
Testing
pytest.673test cases completed successfully with no regressions.How is this addressed