The Deadlock Only Load Found
The repo is my own experiment, SAAS_experimental: a questionnaire application started from my django_react_template starter and split into two Django REST services,
catalog(users, tokens, questionnaire and battery types) andinstances(the questionnaires themselves). It runs on Proxmox LXC containers with a k6 load generator, the same kind of harness as the k3s post and the Postgres vs MongoDB post. It is a home lab with synthetic load, and every number below should be read as that.
The order of work is the part worth copying: pin the behaviour first, port second, measure third, delete last. Each step had its own GitHub issue, and none started before the previous one was green.
What was ported, and what was not
Only catalog moved, about 1.5k lines of Django. instances stayed on Django. Three decisions kept the comparison honest:
- Sync first. Plain
defendpoints and a sync SQLAlchemy session. It is a port, not a redesign, so the load test measures the framework and not a switch to async. Async is a separate, separately measured change. - No schema change. SQLAlchemy models map onto the tables Django created. Alembic’s first revision is that schema, and existing databases are
stamped, not migrated. Django could run against the same database again at any point until it was deleted. - Same secrets on the wire. Passwords stay in Django’s
pbkdf2_sha256$<iterations>$<salt>$<hash>format, verified withhashlibat Django 6.0’s iteration count, so a rollback still logs everyone in. Tokens keep simplejwt’s claims, RS256 and lifetimes, soinstancesverifies them with no change.
The stack is the standard one: FastAPI, Pydantic v2, pydantic-settings, SQLAlchemy 2.0 on psycopg3, Alembic, PyJWT, and uvicorn workers under gunicorn. The FastAPI for Django developers post covers that stack itself.
Pin the behaviour before rewriting anything
catalog had 2.1k lines of tests, but they used DRF’s APIClient and the Django ORM. None of them could check a FastAPI service. So the first plan wrote a new suite that imports neither framework. It starts the service under test as a real server on a free port, next to a stub instances built on the standard library’s http.server, and talks to it only with httpx. A boundary test fails if the suite ever imports service code.
It had to be green against Django before a line of FastAPI existed. Then I broke Django on purpose (removed one field from a serializer) and checked that the suite failed.
Writing it turned up behaviour the frontend depends on that nobody had written down:
| Behaviour | Django REST Framework | FastAPI default |
|---|---|---|
| Validation error | 400 {"field": ["message"]} |
422 {"detail": [...]} |
| Page shape | {count, next, previous, results}, absolute URLs |
none |
| API vs event timestamps | ...123456Z vs ...123456+00:00 |
one format |
/internal/ without a token |
403 (no authenticator there) | usually 401 |
previous on page 2 |
the list URL without page=1 |
not applicable |
Each row became a test. The FastAPI version was done when the same suite passed against it. It ended at 84 of 84 on both targets.
Functional tests passed. The first real deploy did not.
The parity suite runs on SQLite. The first deploy to the LXC stack ran on Postgres, and migrate failed: the databases were created as SQL_ASCII, and psycopg returned text as bytes. Django had been hiding this all along, because it sets client_encoding=utf8 and TimeZone=UTC on every connection. The FastAPI engine now does the same, and the schema test’s throwaway database is SQL_ASCII too, so the test fails without the fix.
That is a small version of the whole story. The things a framework does for you are part of its behaviour, and a port has to find each one.
The first measurement could not tell them apart
The existing k6 scenarios are mostly instances traffic. At a fixed 200 req/s, catalog received only 26 to 34 req/s at about 3% CPU on both implementations. Its own request groups differed by fractions of a millisecond: questionnaire-type-list had a mean of 2.9 ms on Django and 3.2 ms on FastAPI in the mixed run. Whole-run numbers were instances’ numbers.
That is a real result, and it is easy to misread as “same performance”. It only says that catalog was not the bottleneck. The stress runs were more useful, because one of them broke.
The deadlock
One stress run (stress-20261111T080102Z) ended with 93 HTTP 502s, all on catalog, in waves 30 seconds apart, and they continued for 2 minutes after k6 had stopped. The log said:
QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30
The cause is two pools that wait on each other.
- FastAPI runs every sync dependency and every sync endpoint on a thread from AnyIO’s thread pool. That pool has 40 threads by default.
- SQLAlchemy keeps 15 connections per worker (pool size 5 plus overflow 10).
- The auth dependency,
current_user, runs on one thread, loads the user and returns. The endpoint then needs a second trip to the thread pool. The request session lives for the whole request, so the connection stays checked out while the request waits for that second thread.
Under load, all 15 connections end up held by requests that are queued for a thread. All 40 threads are running requests that are blocked waiting for a connection. Nothing can move until the pool checkouts time out after 30 seconds. Then the gateway returns 502s, the cycle forms again, and you get waves.
The fix is one line at the end of the dependency. expire_on_commit is off, so the User object stays usable after the commit:
def current_user(request: Request, session: Annotated[Session, Depends(get_session)]) -> User:
...
# Hand the connection back before the endpoint waits for a thread, or a busy
# worker deadlocks: every thread waits for a connection that a request waiting
# for a thread holds.
session.commit()
return userA deadlock test that runs in a second
A load test found it. A load test is a poor regression test, because it takes an hour and needs a lab. So the test shrinks both pools until the cycle forms with a handful of requests: 2 threads, 1 connection, 8 concurrent requests.
@pytest.fixture
def one_connection(tmp_path, monkeypatch):
engine = create_engine(
f"sqlite:///{tmp_path / 'pool.sqlite3'}",
connect_args={"check_same_thread": False},
poolclass=QueuePool, pool_size=1, max_overflow=0, pool_timeout=3,
)
...
async def _concurrent_requests(token: str) -> list[int]:
anyio.to_thread.current_default_thread_limiter().total_tokens = 2
transport = httpx.ASGITransport(app=create_app(), raise_app_exceptions=False)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver",
headers={"Authorization": f"Bearer {token}"}) as client:
responses = await asyncio.gather(*(client.get("/api/accounts/me/") for _ in range(8)))
return [r.status_code for r in responses]
def test_concurrent_requests_do_not_starve_the_pool(one_connection):
assert asyncio.run(_concurrent_requests(one_connection)) == [200] * 8It returned 500s before the fix and passes after it. The technique generalises: a resource bug that needs 600 req/s to show up usually needs only 2 of each resource in a test. Make the pools tiny and the race becomes certain.
The second pool bug, found by verifying the first
The rerun after the fix failed in a new way. At the start of the read stress (23 failures) and the soak (101 failures), every k6 user logged in at once. Each login held a connection through the pbkdf2 password hash, which takes long by design, and a login burst starved the pool.
Three changes fixed it:
authenticatecommits before it hashes.create_userhashes before its first query.- AnyIO’s thread limit is set to the pool size, 15, in the app’s lifespan. A thread can then never wait for a connection, because there are never more threads than connections.
Two more tests in the same file cover this. The login test makes the hash sleep 0.5 s, runs 4 logins on 2 threads, and sets a 1 s pool timeout. If the connection is held through the hash, the logins queue past the timeout. A third test asserts that the thread limit equals the pool size.
Measuring catalog on its own
With the deadlocks fixed, FastAPI matched Django on the mixed traffic. That still said little, because catalog sat at 3 to 8% CPU in every run. So a follow-up plan added a k6 scenario that loads only catalog: lists, details, /me, token refresh, and create, update and delete of a type. Django was deployed again from the last commit that had it, and the two ran back to back.
The first FastAPI runs were much worse than Django:
| Django | FastAPI, first runs | FastAPI, fixed | |
|---|---|---|---|
| CRUD knee | ~409 to ~431 req/s | ~176 to ~183 | ~532 to ~594 |
At ~240 req/s: p95 / catalog CPU |
27.6 ms / 41% | not measured | 16.5 ms / 25% |
| Login knee | ~17.0/s | ~11.1/s | ~16.8/s |
Two more bugs explained the gap, and both were things Django’s libraries had done for me:
- The signing key was parsed on every token. PyJWT parses a PEM string for each signature: 25 ms of CPU, against 0.19 ms with a loaded key object.
token-refreshtook 65 ms against Django’s 2.8 ms. The fix caches the loaded key withlru_cache. - A new
httpxclient for every call toinstances. That cost 3.6 ms against 0.42 ms per call, and it leaked memory: workers grew from about 135 to about 275 MiB each in 5 minutes. One shared client per process fixed both. Anonymous memory had doubled from 416 to 836 MiB in 5 minutes before the fix. After it, it stayed flat: 414 to 443 MiB.
Each fix has a test that fails without it.
The final numbers
| Measurement | Django | FastAPI |
|---|---|---|
| Parity suite | 84 / 84 | 84 / 84 |
| Mixed traffic stress knee | ~575 to ~614 req/s | ~600 req/s |
| Read-mostly stress knee | ~495 to ~526 req/s | ~518 req/s |
| 1 h soak at ~352 req/s | held (2026-11-06 run) | 0 failed of 1,268,223, p95 22.1 ms |
catalog alone, CRUD knee |
~409 to ~431 req/s | ~532 to ~594 req/s |
catalog alone, ~240 req/s |
p95 27.6 ms, CPU 41% | p95 16.5 ms, CPU 25% |
| Login knee | ~17.0/s | ~16.8/s |
| Memory | baseline | ~100 to 170 MiB more |
token p95 in a re-login burst |
3.8 s | 6.4 s |
In the mixed and read stress runs, both implementations broke on instances at 80 to 90% CPU, not on catalog. The soak had zero QueuePool timeouts in catalog’s log.
FastAPI is not free. It uses more memory, and a burst of logins is slower, because it runs up to 15 password hashes per worker at once where Django ran 4. Every stress run on both ended the same way: k6 adding users who all log in at the same moment. So the knees understate what catalog serves to users who are already logged in.
Then delete Django
Only after the numbers were recorded did the Django catalog go, migrations included. The parity suite lost its --target option and became catalog’s API test suite. The repo-level tests changed to guard the new contracts:
test_catalog_schema.pycompares Alembic’s first revision with a frozen dump of the Django-built schema, and tests adopting a Django-built database.test_catalog_compat.pychecks that hashes and tokens made by FastAPI work ininstances’ Django, with seed ids frozen from Django’s.- A boundary test fails if
catalogimports Django. A search formanage.pyor a Django import inbackend/catalogfinds nothing.
The final checks: catalog 97 tests, parity 84, instances 243 and the repo tests 132 all passed, then a k6 smoke run on the deploy passed 640 of 640 checks.
What this is not
catalog is a small, CRUD-shaped service, and it is not the hot path. The rewrite says nothing about porting a large Django app with admin-heavy workflows. The admin did get worse: sqladmin cannot edit ordered inline items or reset passwords the way Django’s admin could. The load is synthetic, from one generator, on a home lab.
The FastAPI version runs sync endpoints only, so these numbers say nothing about async FastAPI. The work lives on the feature/FastAPI branch and is not merged into main yet. Django’s own tables (django_session, django_migrations and others) are still in the database, waiting for a follow-up Alembic migration. instances still builds a new httpx client per call to catalog, the same bug fixed above in the other direction.
Takeaway
| Step | What it caught | Lesson |
|---|---|---|
| Black-box parity suite | Undocumented DRF contracts (400 shape, page URLs, 403 vs 401) | Pin behaviour before you change the code under it |
| First real deploy | SQL_ASCII databases Django had hidden |
A framework’s defaults are part of its behaviour |
| Mixed-traffic stress | Thread pool vs connection pool deadlock | Never hold a connection across a wait for a thread |
| Verifying that fix | Logins holding a connection through the hash | Rerun the load test after every fix, not only the unit test |
catalog-only scenario |
PEM parsed per token, httpx client per call |
Load the component itself, or you measure its neighbours |
Functional tests proved the port did the same things. Only load proved it could do them at the same time. All four performance bugs were invisible at one request per second, and each now has a test that runs in seconds.