fix: eliminate race condition in UserSheetProgress saveProgress#427
Open
Srejoye wants to merge 3 commits into
Open
fix: eliminate race condition in UserSheetProgress saveProgress#427Srejoye wants to merge 3 commits into
Srejoye wants to merge 3 commits into
Conversation
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
Fixes #371.
This PR resolves a race condition in
saveProgressthat could create duplicateUserSheetProgressdocuments for the same{ userId, sheetId }pair under concurrent requests.Previously, the controller followed a non-atomic read-then-write pattern:
findOne({ userId, sheetId })When two requests arrived simultaneously, both could pass the
findOnecheck before either write completed, resulting in duplicate progress documents.Changes
{ userId: 1, sheetId: 1 }in theUserSheetProgressschema.saveProgresswith a single atomicfindOneAndUpdate()using:upsert: truenew: truesetDefaultsOnInsert: trueE11000) errors by fetching and returning the existing document, making concurrent requests retry-safe.Why this Fix
Using an atomic upsert removes the race window between checking for an existing document and creating one. The unique compound index guarantees that only one document can ever exist for a given
{ userId, sheetId }pair, even under heavy concurrent load.This ensures:
getAllProgress.getProgress.Testing
E11000) races are handled gracefully without creating duplicate records.Impact
This change is backward compatible and does not modify the API contract. It only improves data consistency and eliminates duplicate progress documents caused by concurrent writes.