FastAPI 0.139.2 is now available, addressing a subtle thread-safety bug in the internal router route building logic. While this issue mainly affects developers running tests in parallel threads, it's a critical reliability fix for anyone using pytest-xdist or similar parallel test runners.
Concrete changes in this patch:
- Refactored router route building to be thread-safe, preventing race conditions when multiple threads concurrently add routes to the same router instance.
- The fix is primarily relevant for tests running in parallel threads, though it also improves overall stability for any multi-threaded application scenario.
- Implementation by @tiangolo in pull request #16013.
- No API changes or deprecations introduced; this is a pure internal fix.
Why this matters to developers:
If you use parallel test execution (e.g., pytest -n auto with pytest-xdist) to speed up your FastAPI test suite, this update eliminates intermittent failures caused by RuntimeError: dictionary changed size during iteration or similar race conditions during route registration. While FastAPI's router is designed to be thread-safe for request handling, the route-building phase (during app startup or test setup) was not fully thread-safe. This patch closes that gap, making test suites more reliable without any code changes on your part.
To upgrade: pip install --upgrade fastapi.
Source: https://github.com/fastapi/fastapi/releases/tag/0.139.2