Skip to content

perf: four backend speed-ups with no behavior change - #110

Open
nisbenz wants to merge 4 commits into
MicroClub-USTHB:developfrom
nisbenz:perf/quick-wins
Open

nisbenz wants to merge 4 commits into
MicroClub-USTHB:developfrom
nisbenz:perf/quick-wins

Conversation

@nisbenz

@nisbenz nisbenz commented Nov 29, 2026

Copy link
Copy Markdown

Four small changes that make the API and the photo worker do less waiting and less work. None of them changes what users see or what gets saved; each section says how that was checked.

Backend only, 5 files (+119 / −28) plus one test file. No migrations, no new settings, no API changes.

At a glance (all measured; behavior unchanged in every case):

  1. Cache the enrollment check: 100 photo requests make 1 DB read instead of 100.
  2. Decode images off the event loop: the loop is blocked ~1 ms per phone photo instead of ~70 ms; the model input is pixel-identical.
  3. Open the worker's DB transaction after face detection: a connection is held ~1 ms per photo instead of ~370 ms; the same rows are saved.
  4. Copy approved photos 8 at a time: approving 200 photos takes 1.05 s instead of 3.1 s; the same rows and files result.

1. Cache the enrollment check (app/deps/token_auth.py)

Before: every photo endpoint read the whole users row, including the 512-number face vector, just to check face_embedding IS NOT NULL. That happened even though the session itself was already served from Redis.

Now: a "yes" is cached in Redis for an hour. A "no" is never cached, so a user who enrolls is let in right away. If Redis is down, the code falls back to the database as before.

Why it's safe: nothing in the codebase clears face_embedding; the only query that touches it sets a new value. So "enrolled" can't go stale. Blocked or deleted users are still stopped earlier, by the session check.

Proof

  • Gain: 100 requests from one enrolled user read the users table 1 time, versus 100 on develop.
  • Same behavior: old and new code were run side by side for an enrolled user, a not-yet-enrolled user (403), and a missing user (401), 3 requests each. All results were identical.

2. Decode images off the event loop (app/service/face_embedding.py)

Before: the model already ran in a thread, but cv2.imdecode and the color conversion ran on the event loop. The photo worker and the API's enrollment endpoint stalled on every large image.

Now: decode, conversion and inference all run in a single asyncio.to_thread call. The code is the same, in the same order, with the same errors.

Proof

  • Gain: on a 4032×3024 phone photo, the event loop was blocked for up to 69–72 ms on develop and 1–3 ms with this change.
  • Same behavior: the array given to the model is identical pixel for pixel at 640×480, 1920×1080, 3000×2000, 4032×3024 and 6000×4000. The enrollment selfie path is identical too, and a unit test covers it.

3. Photo worker: detect first, then open the transaction (app/worker/photo_worker/main.py)

Before: the worker opened engine.begin(), then downloaded the photo and ran face detection, keeping a pooled connection checked out the whole time.

Now: the work is split in two:

  • analyze() downloads the photo and runs detection, with no database access.
  • persist() does the same writes as before, inside the transaction.

handle_message() still calls both, so the existing tests run unchanged.

Proof

  • Gain: a DB connection was held for about 370 ms per photo on develop and about 1 ms with this change. That's with a stand-in model taking 300 ms; the real model takes longer, so the real gain is larger.
  • Same behavior: both versions were fed the same messages, and what gets saved was compared.
    • No faces, one face, three faces: the same database writes, in the same order, and the same NATS audit message.
    • Download fails, or detection crashes: both versions raise the same error, and nothing is saved. develop wrote a job row first, but it was rolled back.
  • test_photo_worker.py passes without modification.

One trade-off: if Postgres is down, the photo is now downloaded and analyzed before the failure. The outcome is the same (error, then redelivery); only some work is wasted.

4. Parallel MinIO copies on approval (app/service/upload_requests.py)

Before: approving a group copied each photo from staging to its final key one at a time, inside the HTTP request.

Now: the copies run with up to 8 at a time (asyncio.Semaphore(8)). Database writes stay sequential, in the same order. Copied keys are reported in input order, as before.

Proof

  • Gain: with a real MinIO and 200 photos of 5 MB, approval took 3.05–3.15 s on develop and about 1.05 s with this change (3×, over 3 runs).
  • Same behavior: old and new code were compared with mocks.
    • All copies succeed: the same return value, the same rows in the same order, and the same 30 files.
    • One copy fails: the same error, 0 rows saved (the request transaction rolls back), and 0 files left behind.
  • I checked that a failed request really rolls back: with FastAPI 0.135.1, a get_db-style dependency rolled back on both a crash and an HTTPException.

How "same behavior" was checked

Old modules were taken from develop (git show upstream/develop:…) and run beside the new ones on identical inputs. The outputs compared were return values or errors, database writes, and the files left in storage. In all 20 cases, what ends up saved is identical.

Tests

  • uv run pytest tests/unit: 250 passed (246 existing, all unchanged, plus 4 new in test_perf_quick_wins.py).
  • uv run ruff check . and uv run mypy .: clean.

Left out on purpose

These looked promising but either change behavior or couldn't be verified, so they're not in this PR:

  • Direct MinIO download links.
  • Thumbnails.
  • Retry backoff for failing NATS messages.
  • The mobile cache tweak.
  • Half-size decoding for face detection: it changes what the face model sees on phone-size photos.

Commits

One commit per change, and each one passes the tests, ruff and mypy on its own:

  1. perf(auth): cache the face-enrollment check in Redis
  2. perf(faces): decode images off the event loop
  3. perf(photo-worker): open the DB transaction after face detection
  4. perf(uploads): copy approved photos to final storage concurrently

Every photo endpoint re-read the full users row (including the 512-float
face embedding) just to check that the user has enrolled, even though
the session itself is already served from Redis.

A "yes" is now cached for an hour. Enrollment is one-way (nothing clears
face_embedding), so it cannot go stale. A "no" is never cached, and a
Redis outage falls back to the database as before.

100 photo requests from one user: 100 users-table reads -> 1.
The model already ran in a thread, but cv2.imdecode and the color
conversion ran on the event loop, stalling the photo worker and the
enrollment endpoint on every large image.

Decode, conversion and inference now run in one asyncio.to_thread call,
in the same order and with the same errors. The model input is
pixel-identical (checked from 640x480 to 6000x4000).

Event loop blocked per 4032x3024 photo: ~70 ms -> ~1 ms.
The worker opened engine.begin() before downloading the photo and
running face detection, keeping a pooled connection checked out for the
whole inference.

handle_message() is split into analyze() (download + detection, no
database) and persist() (the same writes as before). run_worker opens
the transaction only around persist(). The same rows are saved for 0, 1
and many faces; on a download or detection failure both versions save
nothing (the old job row was rolled back). The existing photo worker
tests pass unchanged.

DB connection held per photo: ~370 ms -> ~1 ms (with 300 ms of
stand-in inference; the real model is slower, so the gain is larger).
Approving a group copied each staged photo to its final key one at a
time inside the HTTP request.

The copies now run up to 8 at a time. Database writes stay sequential
and in the same order, and copied keys are reported in input order. If
a copy fails, the same error is raised, the request transaction rolls
back, and every copied object is cleaned up, as before.

200 photos x 5 MB on a real MinIO: 3.1 s -> 1.05 s.
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.

1 participant