Group
  • Database

    Add unique constraints where duplicates are bugs

    Enforces uniqueness at the database level for emails, slugs, and one-per-user records so races can't create duplicates.

    • Improve quality
    • Plan & validate
    • Intermediate
    • General

Free Prompt

Find every place in my data model where a duplicate record would be a bug, and enforce uniqueness at the database level. Go through each table or collection and identify natural unique fields: user emails, usernames, slugs, external provider IDs (stripe_customer_id, oauth provider IDs), and compound uniqueness like one membership per (user_id, team_id) or one vote per (user_id, post_id). For each, add a unique constraint or unique index. Then check the write paths: anywhere the code does a check-then-insert (look up, see nothing, insert), replace it with insert-and-handle-the-unique-violation, because two requests arriving at once both pass the check and both insert. Before adding constraints, find and tell me about existing duplicates so I can clean them up first; adding the constraint with dirty data will fail. Handle case sensitivity deliberately for emails and usernames (store or compare normalized). Do not change the user-facing error design; map unique violations to friendly messages ('that email is already registered'). Deliver: the constraint list per table, the duplicate report, the write-path fixes, and a verification: fire two identical signups concurrently and confirm one wins and the other gets a clean error instead of creating a second account.

What This Does / How This Helps

Moves uniqueness rules out of application code and into the database, where races can't bypass them. Check-then-insert is the pattern AI tools generate by default, and it's broken by design: two requests at the same moment both see 'no existing record' and both write. That's how apps end up with two accounts on one email, duplicate charges records, or five memberships for the same user. The database constraint is the only version that holds under concurrency. The prompt handles the practical blockers too: cleaning existing duplicates first, case sensitivity on emails, and mapping violations to friendly errors instead of raw database exceptions.

Want to skip doing this by hand?

Fortivibe audits your app for all of the areas these prompts cover (and more).

See What We Check

Related Prompts