# Find and fix a race condition or concurrency bug

Analyzes code for race conditions, deadlocks, and lost updates, explains the exact interleaving that fails, and proposes a safe fix.

- Topic: Software Development
- Framework: Few-Shot
- Level: Standard
- Tags: Coding, Write, Code, Fill-in Template, Step-by-step
- Source: https://www.thinkwithprompt.com/prompts/find-and-fix-a-race-condition-or-concurrency-bug

## Prompt

```text
Help me find and fix a concurrency bug.

**Symptoms:** [e.g. "duplicate orders", "counter occasionally wrong", "requests hang under load"]
**Code involved:** [PASTE THE RELEVANT FUNCTIONS, INCLUDING DATABASE QUERIES AND LOCKING]
**Concurrency model:** [THREADS, ASYNC/EVENT LOOP, MULTIPLE PROCESSES OR INSTANCES, QUEUE WORKERS]
**Shared resources:** [DATABASE ROWS, CACHE KEYS, FILES, IN-MEMORY STATE, EXTERNAL APIs]
**Database and isolation level:** [e.g. "PostgreSQL, read committed" - or "default/unknown"]

Steps:
1. Identify every shared resource and every read-modify-write sequence on it.
2. For each suspected race, write the exact interleaving step by step (Request A reads..., Request B reads..., A writes..., B writes...) and what goes wrong.
3. Check for: check-then-act bugs, lost updates, non-atomic counters, deadlocks from inconsistent lock order, async code that assumes no interleaving across `await`, and in-memory locks that don't work across multiple instances.
4. Propose fixes, comparing options such as atomic database operations, unique constraints, row locks (`SELECT ... FOR UPDATE`), optimistic locking with version columns, distributed locks, or serializing through a queue. Explain the trade-offs (throughput, deadlock risk, complexity) and recommend one.
5. Show how to reproduce it in a test (parallel requests, barriers, or injected delays) so the fix can be verified.

Return: the ranked list of races with interleavings, the recommended fix as code, the test, and any data cleanup needed for records already corrupted.
```

## What to fill in

- e.g. "PostgreSQL, read committed" - or "default/unknown"

Free to copy and use. From ThinkWithPrompt (https://www.thinkwithprompt.com/), a library of 2,663 curated AI prompts.
