feat(api): make photo storage quota reservation race-safe - #41
Merged
Merged
Conversation
Check-then-insert was two statements outside a transaction, so two concurrent upload-urls calls for the same uploader (or one client spread across two API instances) could both read usage below the cap and both insert, overshooting PHOTO_STORAGE_LIMIT_BYTES. - Add PhotoStorageService.reserveUploadBytes: SUM(sizeBytes) over the caller's PENDING/READY photos and photo.createMany now run in one Prisma transaction at Serializable isolation, so Postgres commits one overlapping reservation per round and aborts the rest, which re-read usage on retry - Retry aborted reservations up to 5 times with jittered linear backoff, then fail with 409 STORAGE_RESERVATION_CONFLICT; recognise both shapes Prisma produces for SQLSTATE 40001 (P2034 when a statement in the callback fails, the raw driver adapter error when COMMIT fails) - Mint presigned S3 URLs only after the transaction commits so no DB transaction is held open across S3 calls - Keep assertCanUpload as a read-only pre-check; GET /users/me/storage is unchanged - Cover the transaction path, retries, and 409 in unit and e2e tests; document the design, the measured retry budget, and the advisory lock alternative in photos-architecture.md
MehrshadFb
force-pushed
the
feat/race-safe-storage-quota
branch
from
September 2, 2026 16:00
27a6686 to
b18ccbb
Compare
API unit-test coverage
Unit suite only; controllers are exercised by the e2e suite. |
6 tasks
This was referenced Sep 6, 2026
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.
Summary
PhotoStorageService.reserveUploadBytes, which runs the quota check (SUM(sizeBytes)forPENDING+READY) andphoto.createManyin one Prisma transaction atSerializableisolationSTORAGE_RESERVATION_CONFLICT40001:P2034when a statement inside the callback fails, and the raw driver adapter error whenCOMMITfailssrc/prisma/prisma.errors.tsrather than in the photo service, with its own unit testssleepand the jittered linear backoff intosrc/common/utils/async.utils.ts, also with their own testsassertCanUploadas a read-only pre-check; document the design, the measured retry budget, and the advisory-lock alternative inphotos-architecture.mdWhy
The quota check and the
PENDINGinsert inPOST /events/:eventId/photos/upload-urlswere two statements outside a transaction. Two concurrent calls for the same uploader (or one client spread across two API instances) could both read usage below the cap and both insert, overshootingPHOTO_STORAGE_LIMIT_BYTES. UnderSerializableisolation Postgres commits one overlapping reservation per round and aborts the rest, which re-read usage on retry.Notes
photo.storage.reservation_conflictwith the attempt countGET /users/me/storageis unchangedAPI
Storage reservation conflicted with a concurrent upload, please retry)Notes on what moved out of the service
isSerializationFailureis Prisma and Postgres dialect, not photo logic, so it now lives besidePrismaServicein the layer that already owns the adapter. A feature module should not have to learn that the same failure arrives mapped asP2034from inside a transaction callback but unmapped from the driver adapter atCOMMIT.That drops about 20 lines from
photo-storage.service.tsand gives the next predicate an obvious home. Three read-then-write uniqueness checks already exist in the codebase (resolveByProviderSub,assertEmailIsUnique,joinByInvitationUrl) that should catchP2002instead of pre-checking and hoping. That fix belongs in its own PR, but it will land in this file when it comes.sleepandjitteredLinearBackoffMsmoved tosrc/common/utils/async.utils.ts. The backoff takes its base delay as an argument rather than readingSTORAGE_RESERVATION_RETRY_DELAY_MSdirectly, so it is callable by anything, and the tuning constant stays inphotos.constants.tswhere the measurement that justifies it lives. Its tests pin the linear growth, the jitter window, and the property the jitter exists for: that concurrent losers of the same round do not wake together.The retry loop itself deliberately stays in the photo service. The attempt budget and the choice to surface 409 are quota decisions, and one caller is not enough to design a general retry wrapper around. Between them these three commits take
photo-storage.service.tsfrom 160 lines to 134, all of it removal of things that were never about photos.Test plan
npx jest photo-storage photos.service --watchman=falsenpx jest --config ./test/jest-e2e.json photos.e2e --watchman=falsenpm run typecheck