Repository navigation
Conversation
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.
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.
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 (
app/deps/token_auth.py)Before: every photo endpoint read the whole
usersrow, including the 512-number face vector, just to checkface_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
userstable 1 time, versus 100 ondevelop.2. Decode images off the event loop (
app/service/face_embedding.py)Before: the model already ran in a thread, but
cv2.imdecodeand 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_threadcall. The code is the same, in the same order, with the same errors.Proof
developand 1–3 ms with this change.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
developand 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.developwrote a job row first, but it was rolled back.test_photo_worker.pypasses 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
developand about 1.05 s with this change (3×, over 3 runs).get_db-style dependency rolled back on both a crash and anHTTPException.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 intest_perf_quick_wins.py).uv run ruff check .anduv 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:
Commits
One commit per change, and each one passes the tests, ruff and mypy on its own:
perf(auth): cache the face-enrollment check in Redisperf(faces): decode images off the event loopperf(photo-worker): open the DB transaction after face detectionperf(uploads): copy approved photos to final storage concurrently