Skip to content

fix(auth): prevent race condition on user creation with DB-level uniqueness #159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

anshifmonz
Copy link

Description:

This PR fixes a race condition that could occur when two users tried to register simultaneously with the same email or username.

Previously, we manually checked for existing emails and usernames before creating a user using the checkUserUniqueness function, which allowed a brief window where concurrent requests could bypass these checks and attempt duplicates. Although the database’s unique constraints prevented actual duplicate records, the application did not handle the resulting errors properly because user creation was not wrapped in a try-catch block. This led to unhandled errors without clear validation feedback.

Now, we have removed the checkUserUniqueness function and rely on Prisma’s built-in unique constraints at the database level to enforce uniqueness atomically. The user creation logic is wrapped in a try-catch block that catches Prisma’s P2002 error and returns clean, detailed validation messages when duplicates are attempted.

Benefits:

  • Eliminates the race condition fully
  • Reduces database queries from 3 to 1, improving performance
  • Simplifies code by removing manual uniqueness checks

Previously, we checked for existing email and username before user creation.
This opened a race condition where simultaneous requests could bypass checks
and insert conflicting records.

Now we rely on Prisma's unique constraints and remove the manual pre-checks.
If a duplicate is attempted, we catch the P2002 error and return proper validation.

This also reduces DB queries from 3 to 1, improving performance and atomicity.

Micro-Learning Topic: Race condition (Detected by phrase)

Matched on "race condition"

What is this? (2min video)

A race condition is a flaw that produces an unexpected result when the timing of actions impact other actions.

Try a challenge in Secure Code Warrior

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