# 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 zip](<https://delaparra-services.nl/skills/concurrency-pitfalls/download>)   

# Concurrency 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

 

1. **List the shared state:** database rows, cache keys, files, in-memory globals, external API resources. 
1. **List the concurrent actors:** web requests, queue workers, scheduled jobs, webhooks (providers retry!), multiple browser tabs, multiple server instances. 
1. **For each piece of shared state, pick one strategy** from the table. 
1. **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)

 

- ` await ` inside a loop runs sequentially; ` Promise.all ` / ` asyncio.gather ` runs concurrently, so limit concurrency for external APIs. 
- A check-then-act across an ` await ` is a race: the state can change during the await. 
- Always handle rejections; one failed promise in ` Promise.all ` rejects the whole batch (use ` Promise.allSettled ` when 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

 

- ` LICENSE ` 
- ` SKILL.md ` 
- ` SOURCE.md `

 

## Related terms

 

- [ACID](<https://delaparra-services.nl/knowledge-hub/acid>) 
- [Actor](<https://delaparra-services.nl/knowledge-hub/actor>) 
- [Actor Model](<https://delaparra-services.nl/knowledge-hub/actor-model>) 
- [Asynchronous](<https://delaparra-services.nl/knowledge-hub/asynchronous>) 
- [Atomic Operation](<https://delaparra-services.nl/knowledge-hub/atomic-operation>) 
- [Backpressure](<https://delaparra-services.nl/knowledge-hub/backpressure>) 
- [BEGIN / COMMIT / ROLLBACK](<https://delaparra-services.nl/knowledge-hub/begin-commit-rollback>) 
- [Concurrent Programming](<https://delaparra-services.nl/knowledge-hub/concurrent-programming>) 
- [Data Parallelism](<https://delaparra-services.nl/knowledge-hub/data-parallelism>) 
- [Deadlock](<https://delaparra-services.nl/knowledge-hub/deadlock>) 
- [DeadlockError](<https://delaparra-services.nl/knowledge-hub/deadlockerror>) 
- [dirty read](<https://delaparra-services.nl/knowledge-hub/dirty-read>) 
- [Event Loop](<https://delaparra-services.nl/knowledge-hub/event-loop>) 
- [Mailbox](<https://delaparra-services.nl/knowledge-hub/mailbox>) 
- [Message Passing](<https://delaparra-services.nl/knowledge-hub/message-passing>) 
- [Message Queue](<https://delaparra-services.nl/knowledge-hub/message-queue>) 
- [Mutex (Mutual Exclusion)](<https://delaparra-services.nl/knowledge-hub/mutex-mutual-exclusion>) 
- [Mutex / Lock](<https://delaparra-services.nl/knowledge-hub/mutex-lock>) 
- [Parallel Programming](<https://delaparra-services.nl/knowledge-hub/parallel-programming>) 
- [Payload](<https://delaparra-services.nl/knowledge-hub/payload>) 
- [phantom read](<https://delaparra-services.nl/knowledge-hub/phantom-read>) 
- [Queue](<https://delaparra-services.nl/knowledge-hub/queue>) 
- [Race condition](<https://delaparra-services.nl/knowledge-hub/race-condition>) 
- [Race Condition](<https://delaparra-services.nl/knowledge-hub/race-condition-paradigms>) 
- [READ COMMITTED](<https://delaparra-services.nl/knowledge-hub/read-committed>) 
- [READ UNCOMMITTED](<https://delaparra-services.nl/knowledge-hub/read-uncommitted>) 
- [REPEATABLE READ](<https://delaparra-services.nl/knowledge-hub/repeatable-read>) 
- [SERIALIZABLE](<https://delaparra-services.nl/knowledge-hub/serializable>) 
- [Supervision](<https://delaparra-services.nl/knowledge-hub/supervision>) 
- [Task Parallelism](<https://delaparra-services.nl/knowledge-hub/task-parallelism>) 
- [Thread](<https://delaparra-services.nl/knowledge-hub/thread>) 
- [TimeoutError](<https://delaparra-services.nl/knowledge-hub/timeouterror>) 
- [Webhook](<https://delaparra-services.nl/knowledge-hub/webhook>)

 

[Installing an agent skill in Claude Code, Codex, Cursor and Copilot](<https://delaparra-services.nl/manuals/een-skill-installeren-in-je-ai-assistent>)

[HTML version](https://delaparra-services.nl/skills/concurrency-pitfalls)
