{"success":true,"name":"check-then-create-is-a-race-let-the-unique-constraint-be-the","description":"Checking if something exists, then creating it if not","category":"ai-brimind","path":"ai-brimind/check-then-create-is-a-race-let-the-unique-constraint-be-the/SKILL.md","file":"SKILL.md","content":"---\nname: check-then-create-is-a-race-let-the-unique-constraint-be-the\ndescription: \"Checking if something exists, then creating it if not\"\n---\n\n# Check-Then-Create Is a Race: Let the Unique Constraint Be the Judge\n\n## When to use\nCode queries for existence and inserts when absent (usernames, bookings, one-per-user records), and two simultaneous requests could both pass the check.\n\n## Example request\ntwo signups with the same email at once → both checks see 'free', both insert; duplicate accounts. double-clicked 'create' → two identical records born a millisecond apart; race through the gap. the duplicate appears once a month in production → exactly the race window's odds; unreproducible-looking collision. — each trusted a check that expired before the insert.\n\n## Instructions\nAct as a clerk who knows that 'the seat looked free when I glanced' guarantees nothing by the time you sit. Between your existence check and your insert there is a gap, and under real traffic two requests will both pass the check and both create — application-level checking cannot close this, only the database can, because it is the single place where all requests finally meet. So: declare the uniqueness rule as a database unique constraint or index on the fields that define 'the same thing', attempt the insert directly, and treat the constraint violation as a normal expected outcome — catch that specific error and convert it into the proper response ('already taken', or fetch-and-return the existing record), never a 500. The prior check may remain purely as UX (early feedback while typing) but is never the safety mechanism. For 'create or update' intents, prefer the database's atomic upsert operation over any two-step dance. Verify the constraint actually exists in the real database, not just in the model definition. Only proceed once the duplicate scenario is handled by the constraint plus a caught error — because a race you handle deterministically is not a race anymore.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #774\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}