{"success":true,"name":"guard-money-and-stock-against-double-clicks-and-race-conditi","description":"Coding checkout, balance, coupon, or inventory logic that changes numbers","category":"ai-brimind","path":"ai-brimind/guard-money-and-stock-against-double-clicks-and-race-conditi/SKILL.md","file":"SKILL.md","content":"---\nname: guard-money-and-stock-against-double-clicks-and-race-conditi\ndescription: \"Coding checkout, balance, coupon, or inventory logic that changes numbers\"\n---\n\n# Guard Money and Stock Against Double-Clicks and Race Conditions\n\n## When to use\nYou are writing an operation where money, credits, stock, or one-time rewards change, and two requests could hit it at the same moment.\n\n## Example request\nCheck balance, then subtract, as two separate steps → two simultaneous requests both pass the check and the account goes negative; the check and update must be one atomic operation (race condition / TOCTOU). A coupon marked 'used' after applying it → parallel requests redeem it many times before the flag lands; use an atomic claim like a unique constraint or conditional update (atomic redemption). Buy button clickable many times while the request is slow → users are charged twice by accident; the operation needs an idempotency key so repeats are safe (idempotency). Reading stock into code, deciding, then writing it back → two buyers oversell the last item; push the decrement into the database with a guard like stock > 0 (database-level atomicity).\n\n## Instructions\nAct like an engineer who assumes every sensitive request will arrive twice at the same millisecond — because with real users and impatient clicks, it will. For any operation touching money, credits, stock, or one-time grants, stop trusting the read-then-write pattern: a check performed in application code can be stale by the time the write happens. Move the decision into the storage layer where it is atomic: conditional updates that only succeed when the guard still holds (balance >= amount, stock > 0, coupon unused), unique constraints that make double-claims impossible, or transactions with appropriate locking when several rows must change together. Make the operation idempotent by accepting a client-generated key and returning the original result for repeats, so retries and double-clicks never double-charge. Then attack your own code: fire the same request concurrently in a quick script and verify the invariant holds — exactly one success, no negative numbers. Only ship once the critical decision is enforced atomically by the database and repeats are provably harmless, and explain which race the design eliminates rather than pointing to a test where requests politely took turns.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #547\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}