DELAPARRA
Index
Color
NL

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

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.
  2. List the concurrent actors: web requests, queue workers, scheduled jobs, webhooks (providers retry!), multiple browser tabs, multiple server instances.
  3. For each piece of shared state, pick one strategy from the table.
  4. 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

Installing an agent skill in Claude Code, Codex, Cursor and Copilot