Coding
AI Prompt for Race Condition Bugs
Debug race conditions and concurrency bugs with this AI prompt: get an interleaving analysis, a thread-safe fix, and a stress test to prove it.
The prompt
Role: You are a concurrency expert in [LANGUAGE] who finds and fixes race conditions and thread-safety bugs. Context: I suspect a race condition in my [LANGUAGE] code ([CONCURRENCY_MODEL: threads / async-await / goroutines / actors / etc.]). Code: [CODE_SNIPPET]. Symptom: [SYMPTOM, e.g. counter occasionally wrong, duplicate records, intermittent deadlock]. It happens under [LOAD_CONDITIONS]. Task: 1) Show a concrete thread/interleaving scenario — step by step — where two executions interleave to produce the wrong result. 2) Identify the shared mutable state and the unprotected critical section. 3) Provide a fixed version using the idiomatic [LANGUAGE] synchronization primitive (mutex, lock, atomic, channel, synchronized block — whichever fits). 4) Explain why your fix is correct and cannot deadlock. 5) Suggest a stress test that reproduces the race reliably. Format: Start with the interleaving timeline, then the diagnosis, then fixed code, then the deadlock-safety argument, then the stress test. Constraints: Prefer the smallest synchronization scope that fixes the race — do not lock entire functions unnecessarily. Explain any performance trade-off of the fix.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [CONCURRENCY_MODEL] [CODE_SNIPPET] [SYMPTOM] [LOAD_CONDITIONS]
Example input
LANGUAGE=Go, model=goroutines, symptom=map shows wrong counts under load, load=1000 concurrent requests, suspect=unsynchronized map writes
How to use this prompt
Describe the symptom precisely ('occasionally wrong' with numbers is gold) and the load that triggers it. State your concurrency model so the fix uses the right primitives.
Tips for the best results
- Ask the AI to show the interleaving as a two-column timeline — it makes the bug click instantly.
- After the fix, ask for a stress test with N goroutines/threads and run it to verify.
- If deadlocks are the symptom instead, ask for a lock-ordering analysis.
Frequently asked questions
Can AI really reason about concurrency correctly?
It is good at constructing interleavings and suggesting idiomatic primitives, but always verify with a real stress test — concurrency is where you must not trust blindly.
What if I am not sure it is a race condition?
Say so in the prompt: ask it to first rule out simpler causes (caching, stale reads) before doing the interleaving analysis.