Skip to content

Fix race condition in username update endpoints (v1 and v2) #817

@coderabbitai

Description

@coderabbitai

Problem

The username update endpoints in both v1 and v2 have a race condition between the uniqueness check and the database insert/update.

Affected endpoints:

  • v1: /pages/api/user/update-username.ts
  • v2: /src/app/api/v2/profiles/update-username/route.ts

Current behavior:
The availability query can match the caller's own row, causing unchanged usernames to incorrectly return 409 Conflict. Additionally, there's a race window between checking username availability and updating the database where another request could claim the same username.

Root cause:
Both endpoints use a check-then-insert pattern:

  1. Query to check if username exists
  2. If available, update the database

This creates a race condition where two concurrent requests for the same username could both pass the availability check.

Proper fix:
Rely on a database-level UNIQUE constraint on user_name to catch conflicts atomically, rather than the check-then-insert pattern. This eliminates the race condition entirely by letting the database enforce uniqueness at commit time.

Context

Acceptance Criteria

  • Add UNIQUE constraint on user_name column in profiles table (database migration)
  • Update v1 endpoint to remove manual check and handle unique constraint violation
  • Update v2 endpoint to remove manual check and handle unique constraint violation
  • Ensure proper error messages for username conflicts (409 status)
  • Add tests to verify race condition is resolved

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions