Concurrency pitfalls
Use when code runs things at the same time - threads, async/await, queues and workers, parallel requests, cron jobs, webhooks that retry - or when a bug only happens "sometimes" or under load. Covers race conditions, deadlocks, mutexes/locks, atomic operations, idempotency, message queues and backpressure, with Laravel and database examples.
Licence MIT
Source delaparra-original
Download zipConcurrency pitfalls
If two things can happen at the same time, assume they will. Find the shared state, decide how access to it is coordinated, and prove it with a test or a reproduction under load.
Workflow
- List the shared state: database rows, cache keys, files, in-memory globals, external API resources.
- List the concurrent actors: web requests, queue workers, scheduled jobs, webhooks (providers retry!), multiple browser tabs, multiple server instances.
- For each piece of shared state, pick one strategy from the table.
- Reproduce: fire parallel requests (
xargs -P 10 curl …, a load tool, or a test that dispatches jobs twice) before and after the fix.
Strategies
| Problem | Strategy | Laravel / SQL example |
|---|---|---|
| Lost update (read-modify-write) | Atomic operation | Product::whereKey($id)->decrement('stock'); SQL UPDATE … SET stock = stock - 1 WHERE stock > 0 and check affected rows |
| Two processes doing the same job | Lock / mutex | Cache::lock('order:'.$id, 10)->block(5, fn () => …); ShouldBeUnique jobs; ->withoutOverlapping() on scheduled tasks |
| Read then write in one transaction | Row lock | DB::transaction(fn () => Order::lockForUpdate()->find($id) …) |
| Duplicate inserts | Unique constraint | Unique index + upsert() / firstOrCreate() inside a transaction, catch the duplicate-key exception |
| Retried webhooks / requests | Idempotency | Store the event or idempotency key with a unique index; skip if already processed |
| Deadlocks | Consistent lock order, short transactions, retry | DB::transaction(fn () => …, attempts: 3); lock rows in the same order everywhere |
| Producer faster than consumer | Backpressure | Bounded queues, rate limits (RateLimiter, Redis::throttle), the RateLimited job middleware |
| Shared global / static state | Avoid; pass data explicitly | No mutable statics in long-running workers (Octane, queue workers) |
Async code (JavaScript / Python)
awaitinside a loop runs sequentially;Promise.all/asyncio.gatherruns concurrently, so limit concurrency for external APIs.- A check-then-act across an
awaitis a race: the state can change during the await. - Always handle rejections; one failed promise in
Promise.allrejects the whole batch (usePromise.allSettledwhen partial success is fine).
Rules
- Never "fix" a race with
sleep()or a retry loop alone. - A fix needs a reproduction that failed before and passes after.
- Explain in the summary which actor/state pair caused the bug.
Files
LICENSESKILL.mdSOURCE.md
Related terms
- ACID
- Actor
- Actor Model
- Asynchronous
- Atomic Operation
- Backpressure
- BEGIN / COMMIT / ROLLBACK
- Concurrent Programming
- Data Parallelism
- Deadlock
- DeadlockError
- dirty read
- Event Loop
- Mailbox
- Message Passing
- Message Queue
- Mutex (Mutual Exclusion)
- Mutex / Lock
- Parallel Programming
- Payload
- phantom read
- Queue
- Race condition
- Race Condition
- READ COMMITTED
- READ UNCOMMITTED
- REPEATABLE READ
- SERIALIZABLE
- Supervision
- Task Parallelism
- Thread
- TimeoutError
- Webhook
Installing an agent skill in Claude Code, Codex, Cursor and Copilot