Race Conditions Prompts
AI prompts for race conditions from the LearnWithHasan AI Coding Building Blocks (Security).
Protect a Shared Resource from Race Conditions
Start here. The most common race condition fix From the Race Conditions AI Coding Building Block.
My [web app / API / backend] has a feature where users can [redeem a coupon / claim a reward / reserve a seat / purchase a limited item]. Right now, if two users hit this at the same time, they can both succeed even though only one should. Handle race conditions for this feature: - Use locks or atomic database operations so only one request can read-check-write at a time - If a second request arrives while the first is processing, it should wait or get a clean "not available" response - Make sure the fix works under real traffic, not just single-user testing - Add clear error messages when a resource is no longer available My stack: [your language and framework here, e.g. Node + PostgreSQL, Python + Django, Ruby on Rails] I'm learning, so explain each part simply.
Build a Test That Catches Race Conditions
Race conditions hide in testing. This flushes them out From the Race Conditions AI Coding Building Block.
I want to test whether my [feature, e.g. token redemption / inventory checkout / balance deduction] is vulnerable to race conditions before I launch. Build a simple test script or admin tool that: - Simulates [10-50] users hitting the same [endpoint / action] at the exact same time - Targets a shared resource like [a coupon with 1 use left / an item with limited stock / a user balance] - Logs the result of every request (success or failure) - Checks the final database state against what it should be (e.g. balance should never go negative, stock should never go below zero) - Clearly reports if the race condition was triggered My stack: [your language and framework here] I'm learning, so explain each part simply.
Use a Queue to Process One Request at a Time
For complex operations where simple locks aren't enough From the Race Conditions AI Coding Building Block.
My [app] has a critical action where [describe action, e.g. users withdraw from a shared pool / admins approve payouts / players trade items]. Database locks alone aren't enough because the logic spans multiple steps. Set up a queue-based system that: - Accepts incoming requests immediately and returns "processing" to the user - Processes them one at a time (or in safe batches) in order - Updates the shared resource only inside the queue worker, never from direct API calls - Notifies the user when their request is complete or rejected - Handles failures gracefully (retry or refund) My stack: [your language and framework here] I'm learning, so explain each part simply.