Skip to content

Designing for Concurrency ​

"Design for concurrency concerns how software is refined into concurrent units such as processes, tasks, and threads and the consequences of those decisions with respect to efficiency, atomicity, synchronization and scheduling." — IEEE Computer Society, SWEBOK Guide V4.0, Software Design KA, §3.1 Concurrency (2024)

Summary: Concurrency design is deciding which activities in a system may proceed independently, who owns each piece of state while they do, and how they hand work and results to each other without races, deadlocks or unbounded queues. Focus: Concurrency vs parallelism vs asynchrony, shared memory vs message passing (CSP, actors), the design-level pattern catalogue (worker pool, pipeline, fan-out/fan-in, futures, reactor, active object, monitor, leader/followers), the hazards (race, deadlock, livelock, starvation, priority inversion, lost update, ABA), and how Go goroutines and Laravel queue workers express the same design across processes and services. Learning goal: Look at a feature, find the independent activities and the shared state, pick an ownership model and a pattern, bound every queue and every wait, and prove it with the race detector, a lock-order rule and an overlap test in Go and Laravel.

This page is the design-level view: how to decide where concurrency goes and how to keep it safe, in any language. It deliberately does not re-teach the tools. Goroutines, channels, select, context, the sync package, worker pools and the race detector each have a deep chapter in the Go path (start with Goroutines & Channels and Worker Pools & Pipelines). Row locks, isolation levels and database deadlocks belong to the database path: Locks & Concurrency Control, Isolation Levels, Deadlocks and Optimistic vs Pessimistic Locking. Distributed locks and leader election get their own pages in system design (Distributed Locking, Leader Election). Event loops and callbacks are on Control Flow & Event Handling; remote calls and partial failure on Distribution of Components.

Page map ​

If you are looking forGo to
Every term and hazard in a few tablesEverything in one minute
Why concurrency needs design, not just keywordsWhy concurrency design exists
Dijkstra, Hoare's CSP, actors, Pike, Schmidt's patterns, SWEBOKWhere it comes from
Concurrency vs parallelism, shared memory vs messages, races, deadlock, ABA, backpressure, idempotencyThe concepts, one by one
Worker pool, pipeline, futures, reactor/proactor, active object, monitor, read-write lock, double-checked locking, leader/followersThe pattern catalogue
The Go model, the PHP/Laravel model, locks across processes, Little's law, error messagesMechanics
Idiomatic codeGo, Laravel
Overselling, double-running jobs, leaking goroutines, Octane stateSolving the classic problems
Race detector, deterministic schedulers, property tests, leak checksTesting concurrent designs
Goroutine leaks, queue depth, lock waitsObservability
Which model for which workloadChoosing
Monolith → modular monolith → microservices → distributedIn architecture
Go worker pool with backpressure; Laravel overlap and lock demoLab
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concepts section.

TermIn plain wordsTiny exampleDesign question it raises
ConcurrencyStructuring a program as independent activitiesA server handles 1,000 open connectionsWhat can proceed independently?
ParallelismRunning computations at the same instant on several coresResize 8 images on 8 coresIs there CPU work worth splitting?
AsynchronyStarting work now and collecting the result laterDispatch a queued email, return 202Who waits for the result, and how long?
Shared memoryActivities read and write the same variablesTwo goroutines update one mapWho guards it, and with what lock?
Message passingActivities own their state and send copiesWorkers receive jobs over a channel or a queueWho owns the state now?
CSPHoare's model: sequential processes that communicate over channelsGo goroutines + channelsWhich channels, which direction, who closes?
ActorAn entity with a private mailbox and state; reacts to one message at a timeErlang process, Akka actorWhich messages, what happens on overload?
SynchronizationOrdering events between activitiesMutex, channel send/receive, WaitGroupWhat must happen before what?

The hazards.

HazardIn plain wordsTiny exampleDesign fix
Race conditionThe result depends on who runs firstTwo requests both see "1 seat left"Atomic operation, lock, or one owner
Data raceUnsynchronized access to the same memory, at least one writecounter++ from two goroutinesMutex, atomic, or confinement
Lost updateA read-modify-write erases another's writeTwo stock decrements, one survivesAtomic update, row lock, version check
DeadlockEveryone waits for someone else, foreverA holds X wants Y, B holds Y wants XOne global lock order, timeouts
LivelockEveryone keeps reacting and nobody progressesTwo retries that always collideRandomized backoff (jitter)
StarvationOne activity never gets its turnWriters starved by a stream of readersFair queueing, priorities, limits
Priority inversionA high-priority task waits on a low one that cannot runMars Pathfinder bus taskPriority inheritance, short critical sections
ABAA value changes A→B→A and a check believes nothing happenedLock-free stack popVersion counters, tagged pointers, GC

The patterns. Unpacked in the pattern catalogue.

PatternUse it whenGoLaravel / PHP
Worker pool / producer-consumerMany jobs, limited resourcesN goroutines reading one channelqueue:work processes, Horizon
PipelineWork flows through stagesStages joined by channelsJob chains, Bus::chain
Fan-out / fan-inIndependent calls, then combineerrgroup, merge functionConcurrency::run, Bus::batch
Future / promiseStart now, read laterA channel of one resultConcurrency::run, Guzzle promises
MonitorShared object, one caller at a timeStruct + sync.MutexRow lock with lockForUpdate
Read-write lockMany readers, rare writerssync.RWMutexsharedLock vs lockForUpdate
Immutability / copy-on-writeReaders must never blockatomic.Pointer to a frozen snapshotreadonly classes, value objects
Thread confinementOne owner per piece of stateOwner goroutineOne process per request (PHP-FPM)
Reactor / proactorMany connections, few threadsGo netpoller (hidden)Swoole, ReactPHP event loop

The design rules in one breath. Give every piece of mutable state exactly one owner; prefer immutable messages; bound every queue; put a timeout or cancellation on every wait; acquire locks in one global order; make every handler idempotent because at-least-once is the norm; measure queue depth and in-flight work.

Why concurrency design exists ​

A program that does one thing at a time is easy to reason about: every line runs after the previous one. Real systems are not like that. A web server waits for thousands of clients at once, a checkout calls a payment provider while the stock check runs, and a queue worker processes jobs while another worker on another machine processes the next one. As soon as two activities overlap in time, three questions appear that the sequential program never had to answer: what may run at the same time, who may touch which data while it does, and how do the activities wait for each other. Answering them in the code, one go statement or dispatch() at a time, produces races and deadlocks that show up only under load. Answering them in the design, before the code, produces a small set of rules that the code then follows.

Sequential designConcurrent design
One timeline, easy to read and debugMany timelines, bugs depend on timing
No shared-state questionsEvery mutable value needs an owner or a guard
Latency = sum of all waitsLatency = longest wait on the critical path
Uses one coreCan use all cores and overlap I/O
Overload makes it slowOverload without bounds makes it fall over (memory, connections)
Tests are deterministicTests must provoke interleavings (race detector, stress, deterministic schedulers)
Shared memory + lock (monitor)Message passing (CSP, confinement)goroutine Agoroutine Bgoroutine Cmu.Lock() / Unlock()shared mapevery access must locksender Asender Bsender Cchan Request (bounded)owner goroutineonly it touches the mapRisk: one forgotten lock = data raceRisk: owner is a bottleneck; full channel blocks

The picture shows the two ownership models this page keeps coming back to. On the left, three activities share one map and the design is correct only if every one of them remembers the lock. On the right, the map belongs to one owner and everyone else sends it messages: the race is impossible by construction, but the owner can become a bottleneck and its inbox must be bounded. Both are implemented in confinement/main.go.

The analogy we reuse on this page: a restaurant kitchen. Orders arrive at the pass (requests), cooks work at stations (workers), tickets hang on a rail (a queue), and there is one deep fryer (a shared resource). A good head chef does not hire more cooks and hope. They decide which dishes can be prepared independently (concurrency), how many cooks fit at the fryer (a semaphore), how many tickets the rail can hold before the front of house stops seating people (a bounded queue and backpressure), and that only the grill cook touches the grill (ownership). The kitchen deadlocks when the pastry cook holds the only mixer and waits for the oven while the baker holds the oven and waits for the mixer.

Three common misunderstandings, up front ​

  1. "Concurrency makes things faster." It makes waiting overlap. If the work is CPU-bound and there is one core, concurrent code is slower (it adds switching). If the bottleneck is one database, more workers only lengthen the database's queue.
  2. "PHP has no concurrency, so Laravel developers can skip this." Every PHP-FPM worker, queue worker, scheduler run and server is a concurrent activity. Two FPM workers processing two checkouts for the last item is a race, and it oversells exactly like two goroutines would.
  3. "Channels mean no races." Channels remove races on what you send. If you send a pointer to a map and both sides keep using it, the race is still there, it is just harder to see.

Where it comes from ​

Dijkstra, 1965 onwards. Edsger Dijkstra's work on cooperating sequential processes introduced the semaphore and the classic exercises (mutual exclusion, the dining philosophers). We did not read the original manuscripts for this page; SWEBOK V4 is the source we quote for the definitions of the primitives: a semaphore is "a protected variable or abstract data type that provides a simple but useful abstraction for controlling access to a common resource", and "A monitor is an abstract data type that presents a set of programmer-defined operations executed with mutual exclusion."

Hewitt, 1973: actors. The actor model, from Carl Hewitt, Peter Bishop and Richard Steiger's 1973 paper, treats every concurrent entity as an actor with a private state and a mailbox (secondary source: Wikipedia's Actor model article, which dates the model to 1973). Erlang processes and Akka actors follow it.

Hoare, 1978: CSP. Tony Hoare's Communicating Sequential Processes (Communications of the ACM, August 1978) put input and output at the centre:

"This paper suggests that input and output are basic primitives of programming and that parallel composition of communicating sequential processes is a fundamental program structuring method." — C. A. R. Hoare, Communicating Sequential Processes, CACM 21(8), 1978

In the paper, processes running in parallel "may not communicate with each other by updating global variables"; communication "occurs when one process names another as destination for output and the second process names the first as source for input", with no automatic buffering, and input commands may appear in guards, so a process can wait on whichever partner is ready first. Go's goroutines, unbuffered channels and select descend from this line of work (Go names channels rather than processes).

1990s–2000s: patterns. Douglas Schmidt and colleagues documented the server-side concurrency patterns that frameworks still implement: Reactor, Proactor, Active Object ("decouples method execution from method invocation to enhance concurrency and simplify synchronized access to an object that resides in its own thread of control") and Leader/Followers ("multiple threads take turns sharing a set of event sources in order to detect, demultiplex, dispatch, and process service requests"). Doug Lea's Concurrent Programming in Java (1996; 2nd ed. 1999) and Brian Goetz et al.'s Java Concurrency in Practice (2006) popularised the design vocabulary this page uses (thread confinement, immutability, safe publication, guarded by); we name them as secondary influences and quote neither. In the same period Bill Pugh and others published The "Double-Checked Locking is Broken" Declaration, showing that a popular lazy-initialization idiom "will not work reliably in a platform independent way when implemented in Java, without additional synchronization."

Go, 2009–2014. Go adopted CSP as its high-level model. Effective Go reduced it to a slogan:

"Do not communicate by sharing memory; instead, share memory by communicating." — Effective Go and Andrew Gerrand, Share Memory By Communicating, The Go Blog, 13 July 2010

Rob Pike's talk Concurrency is not Parallelism at Heroku's Waza conference (summarised on the Go blog on 16 January 2013) separated the two ideas for a generation of developers: "Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once." Sameer Ajmani's posts on pipelines and cancellation (13 March 2014) and on context (29 July 2014) set the idioms for stopping concurrent work.

PHP 8.1 and Laravel. PHP kept its shared-nothing, process-per-request model. PHP 8.1 added Fibers, which "represent full-stack, interruptible functions" (cooperative, single-threaded). Laravel added a Concurrency facade that runs closures in child PHP processes, alongside its long-standing queue workers, atomic locks and job middleware.

SWEBOK V4, 2024. The IEEE guide makes Concurrency the first of its Software Design Qualities (§3.1, quoted at the top), next to Control and Event Handling, Data Persistence and Distribution of Components, which are the sibling chapters of this group; the primitives themselves (semaphores, monitors, mutexes) are defined in the Software Construction KA, §4.10.

The concepts, one by one ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, and the design fix with code.

Concurrency, parallelism and asynchrony Must-know ​

In plain words: concurrency is how you structure a program (as independent activities); parallelism is how it runs (at the same instant on several cores); asynchrony is how you call something (start it, do not wait now, collect the result later).

Common misunderstanding: "Concurrent means parallel." One CPU core can run a perfectly concurrent server: while one request waits for the database, another runs. Conversely, a parallel numeric loop on eight cores has almost no concurrency design in it: no interaction, no shared state.

Definition: Pike, on the Go blog: "In programming, concurrency is the composition of independently executing processes, while parallelism is the simultaneous execution of (possibly related) computations." Asynchrony is a calling convention: the caller does not block on the callee's completion (callbacks, futures, queued jobs, events).

text
     time →        0ms        50ms       100ms      150ms
1    Sequential    [A cpu][A wait db.........][B cpu][B wait db.........]
2    Concurrent    [A cpu][A wait db.........]
     (1 core)             [B cpu][B wait db.........]        -- waits overlap
3    Parallel      [A cpu][A wait db.........]
     (2 cores)     [B cpu][B wait db.........]               -- CPU overlaps too
4    Asynchronous  [A: dispatch job → 202][..... worker runs A later .....]

Real scenarios: an API gateway that waits on 10,000 sockets on 4 cores (concurrency, little parallelism); image thumbnailing on a 16-core box (parallelism); "send the receipt email after checkout" as a queued job (asynchrony); a Laravel dashboard that runs three slow counts at once with Concurrency::run (concurrency that happens to be parallel because each closure runs in its own PHP process).

Design fix: decide per activity which of the three you need. Waiting on I/O → concurrency (goroutines, an event loop, more processes). CPU-heavy → parallelism bounded by core count (GOMAXPROCS, number of worker processes). Not needed for the response → asynchrony (a queue).

Shared memory vs message passing: CSP and actors Must-know ​

In plain words: either several activities touch the same data and take turns with a lock, or each piece of data has one owner and the others send it messages.

Common misunderstanding: "Message passing is always better." Effective Go itself says the slogan "can be taken too far. Reference counts may be best done by putting a mutex around an integer variable, for instance." A cache read by every request is usually best as shared memory behind an RWMutex or as an immutable snapshot, not as an owner goroutine answering a channel.

Definition: shared-memory concurrency synchronizes access to common variables with primitives (mutex, semaphore, monitor, atomic operations). Message-passing concurrency gives each process private state and communicates by sending values; in CSP the communication is synchronous over channels (or named processes), in the actor model it is asynchronous into a per-actor mailbox. Message passing across processes and machines is the only option there is: queues, brokers and HTTP are message passing.

text
     Shared memory (monitor)                    Message passing (owner)
1    A: mu.Lock(); m["x"]++; mu.Unlock()        A: inc <- "x"
2    B: mu.Lock() -- waits for A                B: inc <- "x"       -- buffered, no wait
3    B: m["x"]++; mu.Unlock()                   owner: m["x"]++ ; m["x"]++  -- one goroutine
4    C: m["x"]++   -- forgot the lock: DATA RACE   C cannot reach m at all: it is not in scope

Real scenarios: an in-process rate limiter (shared counter + mutex, fine); a chat room where one goroutine owns the member list and broadcasts (owner + channels); order processing across services (messages on RabbitMQ or Kafka: the only way); a Laravel app where "shared memory" is the database or Redis, and the row lock or Cache::lock is the mutex.

PropertyShared memory + locksCSP (channels)Actors (mailboxes)
Where state livesShared, guardedPrivate to a goroutinePrivate to an actor
CommunicationRead/write variablesSynchronous or buffered channelAsynchronous mailbox
Typical failureForgotten lock, deadlockGoroutine leak, blocked sendMailbox overflow, lost messages
Back-pressureLock contentionUnbuffered/bounded channel blocksMust be added (bounded mailbox)
ProductsGo sync, Java synchronized, database row locksGo, Clojure core.async, OccamErlang/Elixir, Akka, Orleans
Across machinesDistributed lock (hard)Broker queuesErlang distribution, Akka Cluster

Design fix: pick one model per piece of state and write it down next to the type ("owned by the dispatcher goroutine", "guarded by mu"). See both versions in confinement/main.go.

Identifying concurrency in a design Must-know ​

In plain words: look for work that does not depend on other work, for waits on slow things, and for many similar items. Those are the places where concurrency pays.

Common misunderstanding: "Add a goroutine (or a queued job) wherever something is slow." Concurrency added without an owner, a bound and a stop signal turns a slow feature into a flaky one.

Definition: a design has a concurrency opportunity where (1) activities are independent (no data dependency between them), (2) an activity spends most of its time waiting on I/O, or (3) the same operation applies to many items (data parallelism). For each opportunity the designer then chooses a unit of concurrency (goroutine, thread, process, job, service), the coordination (join, pipeline, pub/sub), and the limits (how many at once, how long).

text
     Checkout request, sequential                       After analysis
1    validate cart              5 ms                     validate cart            5 ms
2    price items (DB)          40 ms   ┐ independent     ┌ price items   40 ms ┐
3    fraud score (HTTP)       120 ms   ┤ of each other   ┤ fraud score  120 ms ├ fan-out, join, 2 s timeout
4    shipping quote (HTTP)     90 ms   ┘                 └ shipping      90 ms ┘
5    charge card (HTTP)       300 ms                     charge card            300 ms  (depends on 2-4)
6    send email                80 ms                     dispatch email job       1 ms  (async, after commit)
7    total                    635 ms                     total                  ≈ 426 ms

Real scenarios: a search page that queries products, facets and recommendations independently; a nightly export of a million rows (data parallelism, bounded workers); webhooks fanned out to 50 subscribers; a report that must not run twice at the same time (the opposite: preventing concurrency).

Design fix: draw the dependency graph of the use case. Everything on one path stays sequential; parallel branches become a fan-out with a join, a limit and a deadline; anything the user does not wait for becomes a job dispatched after the transaction commits.

Race condition and data race Must-know ​

In plain words: a race condition is a bug where the outcome depends on timing. A data race is the low-level version: two threads touch the same memory without synchronization and at least one writes.

Common misunderstanding: "No data race means no race condition." A program can use a mutex correctly on every access and still have a race condition at the design level: check "seat free?" under the lock, release it, then book under the lock again. Each access is safe; the check-then-act sequence is not.

Definition: the Go memory model: "A data race is defined as a write to a memory location happening concurrently with another read or write to that same location, unless all the accesses involved are atomic data accesses as provided by the sync/atomic package." A race condition is any situation where correctness depends on the relative order of events that the design does not control; it appears in memory, in databases, in caches and between services. The usual shapes are check-then-act and read-modify-write.

text
     Request 1 (FPM worker 1)                    Request 2 (FPM worker 2)
1    SELECT seats_left FROM shows WHERE id=7;    -- 1
2                                                SELECT seats_left FROM shows WHERE id=7;  -- 1
3    if 1 > 0: INSERT booking; UPDATE seats_left = 0
4                                                if 1 > 0: INSERT booking; UPDATE seats_left = 0
5    -- two bookings, one seat: a race condition with no data race in PHP at all

Real scenarios: overselling stock; two "welcome" emails because two workers saw welcomed_at IS NULL; a cache stampede where 500 requests recompute the same key at once; Go fatal error: concurrent map writes (the runtime catches some map races); a counter that loses increments under load.

Design fix: make check and act one atomic step: a conditional UPDATE ... WHERE seats_left > 0, a row lock, a unique constraint, a compare-and-swap, or a single owner. For data races in Go, run tests with -race (see Testing).

Lost update Must-know ​

In plain words: two activities read the same value, each computes a new one, and the second write silently erases the first.

Common misunderstanding: "My code runs inside a transaction, so it is safe." In PostgreSQL's default Read Committed (and with plain reads in MySQL InnoDB), a plain SELECT takes no lock; the read-modify-write in application code still loses updates. The isolation-level details are on Isolation Levels.

Definition: a read-modify-write cycle performed by two concurrent activities on the same item, where the modification happens outside the store, and the later write is based on a stale read.

text
     Worker A                         Worker B                         stock
1    read stock = 5                                                     5
2                                     read stock = 5                    5
3    write stock = 5 - 2 = 3                                            3
4                                     write stock = 5 - 1 = 4           4   -- A's decrement is lost

Real scenarios: stock counts, wallet balances, like counters, a JSON settings column edited by two admins, an in-memory struct copied, changed and stored back by two goroutines.

Design fix, in order of preference: (1) let the store do it atomically; (2) lock the row (pessimistic); (3) check a version on write (optimistic, retry on conflict).

sql
-- 1. Atomic and conditional: no read in the application at all.
UPDATE products SET stock = stock - 2 WHERE id = 42 AND stock >= 2;   -- 0 rows = not enough stock
-- 2. Pessimistic: hold the row until commit.
BEGIN; SELECT stock FROM products WHERE id = 42 FOR UPDATE; UPDATE products SET stock = 3 WHERE id = 42; COMMIT;
-- 3. Optimistic: succeed only if nobody wrote since we read version 7.
UPDATE products SET stock = 3, version = version + 1 WHERE id = 42 AND version = 7;   -- 0 rows = conflict, retry

The Laravel versions of all three are in ReserveStock.php; the Go compare-and-swap and version-column versions are in optimistic/main.go.

Deadlock Must-know ​

In plain words: two or more activities each hold something the other needs and wait for it forever.

Common misunderstanding: "Deadlocks only happen with mutexes." They happen with any blocking wait: two goroutines each waiting to send on an unbuffered channel the other should read, a worker pool whose jobs submit sub-jobs to the same full pool, two services that call each other synchronously with exhausted thread pools, two database transactions updating the same rows in opposite order.

Definition: a set of activities is deadlocked when each is waiting for an event that only another member of the set can cause. The four Coffman conditions (Coffman, Elphick and Shoshani, System Deadlocks, ACM Computing Surveys, 1971; cited here via Wikipedia's Deadlock article, a secondary source) must all hold: mutual exclusion (a resource has one holder), hold and wait (holders request more), no preemption (nobody can take a resource away), and circular wait (a cycle in the wait-for graph). Breaking any one prevents deadlock.

Deadlock: circular waitFix: one global lock orderworker 1worker 2lock Alock Bwaits forworker 1worker 2lock A (first)lock B (free)waits for A,holds nothingsolid arrow: holds dashed arrow: waits formutual exclusion + hold-and-wait + no preemption + circular waitworker 2 queues on A and holds nothing,so no cycle can close (Transfer in lockorder/main.go)
text
     Worker 1 (transfer A → B)          Worker 2 (transfer B → A)
1    lock(A)                            lock(B)
2    lock(B)   -- waits for worker 2    lock(A)   -- waits for worker 1
3    ... forever ...                    ... forever ...
     Go: if every goroutine is blocked: "fatal error: all goroutines are asleep - deadlock!"
     PostgreSQL: one transaction is aborted with SQLSTATE 40P01; MySQL InnoDB: error 1213

Real scenarios: money transfers between two accounts in opposite directions; a job that locks order then invoice while another locks invoice then order; an unbuffered result channel that nobody reads after the reader returned early on error (a partial deadlock, which Go reports only if all goroutines block, so in a server it is a silent leak).

Design fix: (1) lock ordering: always acquire in one global order (by ID, by table name) — the diagram's right half and lockorder/main.go; (2) hold at most one lock while calling out, never across I/O or a remote call; (3) put a timeout on every wait (context, Cache::lock(...)->block(5), lock_timeout) so a deadlock becomes an error you can retry; (4) let the database detect it and retry the transaction (DB::transaction(..., attempts: 3)). Database specifics are on Deadlocks.

Livelock, starvation and priority inversion Important ​

In plain words: the system is not stuck, but useful work does not get done: everybody politely retries at the same moment (livelock), one activity never wins (starvation), or an important task waits behind an unimportant one (priority inversion).

Common misunderstanding: "If there is no deadlock, the design is live." Safety (nothing bad happens) and liveness (something good eventually happens) are separate properties; locks and retries give you safety and can cost you liveness.

Definition: livelock: activities keep changing state in response to each other without progress (two workers that both release and retry a lock on a fixed 100 ms schedule). Starvation: an activity is perpetually denied a resource because others are always chosen (a writer under a continuous stream of readers, a low-priority queue that never gets a worker). Priority inversion: a high-priority task blocks on a resource held by a low-priority task, which in turn cannot run because medium-priority tasks preempt it. The best-known case is NASA's Mars Pathfinder (1997): as Glenn Reeves of JPL explained in the account relayed by Mike Jones, a high-priority bus management task waited on a mutex held by a low-priority meteorological task, the watchdog reset the system, and the fix was to enable priority inheritance on that mutex.

text
     Livelock (fixed retry)                       Fix (jittered retry)
1    A: try lock → busy → sleep 100 ms            A: busy → sleep 100 ms + rand(0..100)
2    B: try lock → busy → sleep 100 ms            B: busy → sleep 100 ms + rand(0..100)
3    A and B wake together, collide again ...     A wakes at 137 ms, wins; B wakes at 181 ms

Real scenarios: optimistic-locking retries that collide forever on a hot row; Laravel WithoutOverlapping jobs released with the same releaseAfter all waking together; Horizon's default queue starving reports because every worker is busy; a Go sync.RWMutex where long readers delay a writer (Go's implementation blocks new readers once a writer waits, precisely to avoid writer starvation, which is why recursive read locking can deadlock).

ProblemSymptomDesign fix
LivelockCPU busy, throughput zeroExponential backoff with jitter; cap retries
StarvationOne queue or tenant always waitsFair scheduling, per-queue minimum workers (Horizon minProcesses), per-tenant limits
Priority inversionUrgent task slow only when a slow task holds a shared lockPriority inheritance (RTOS), short critical sections, separate pools per priority

ABA problem Good to know ​

In plain words: you read a value A, someone changes it to B and back to A, and your later check "is it still A?" says yes although the world changed underneath.

Common misunderstanding: "Compare-and-swap is always safe because it checks the value." It checks the value, not the history.

Definition: Wikipedia (secondary): "the ABA problem occurs during synchronization, when a location is read twice, has the same value for both reads, and the read value being the same twice is used to conclude that nothing has happened in the interim." It is a classic hazard in lock-free data structures that reuse memory (a popped node is freed and a new node gets the same address).

text
     T1                                    T2
1    top = A, next = B   (plans CAS A→B)
2                                          pop A; pop B; push A   (B is gone, A is back)
3    CAS(top, A, B) succeeds               -- top now points at freed node B

Real scenarios: lock-free stacks and queues in C/C++; optimistic concurrency that compares a value (WHERE status = 'pending') instead of a version (an order went pending → paid → refunded → pending); cache entries compared by content.

Design fix: compare a monotonically increasing version, not the value (version column, tagged pointer, generation counter). In Go, garbage collection prevents the memory-reuse variant for pointers, but the value-level variant still applies to your own state machines.

Ownership, confinement and immutability Must-know ​

In plain words: the safest shared state is state that is not shared. Give each mutable thing one owner at a time; share only things that cannot change.

Common misunderstanding: "Immutability is about functional programming style." It is a concurrency tool: an object that never changes after it is published can be read by any number of goroutines or processes without a lock.

Definition: Ownership: at any moment exactly one activity may mutate a piece of state; ownership can be transferred (sending a value on a channel, dispatching a job with its data). Thread confinement: state reachable from only one thread/goroutine/process (local variables, the owner goroutine, a PHP-FPM request's memory). Immutability: state that cannot change after construction; safe publication of an immutable object makes it readable everywhere. Copy-on-write: writers build a new version and swap a reference atomically; readers keep the old snapshot.

text
     Ownership transfer through a channel
1    producer: buf := make([]byte, n); fill(buf)
2    producer: jobs <- buf          -- from here on, producer must not touch buf
3    worker:   b := <-jobs; process(b)   -- worker is the owner now
     Copy-on-write config
4    writer: next := clone(cur); next.limit = 200; ptr.Store(next)
5    reader: cfg := ptr.Load()      -- consistent snapshot, never locks

Real scenarios: HTTP handlers that keep request state in local variables (confined); a routing table or feature-flag set swapped atomically on reload (copy-on-write); Laravel jobs that carry IDs and immutable DTOs instead of live models; Go's strings (immutable) shared freely across goroutines.

Design fix: in Go, document ownership on every struct field that is shared, prefer passing values over pointers across goroutines, use atomic.Pointer[T] for snapshots and sync.Once for lazy init (immutable/main.go). In PHP, use readonly properties and classes for messages and DTOs, keep jobs' payload small and immutable, and never mutate static or singleton state under Octane.

Bounded queues, backpressure, timeouts and cancellation Must-know ​

In plain words: every place where work waits must have a size limit and a time limit, and every activity must be stoppable.

Common misunderstanding: "An unbounded queue absorbs spikes." It converts a spike into memory growth and latency that grows without limit; by the time the queue is drained the callers have timed out and retried, which makes the spike bigger.

Definition: a bounded queue has a fixed capacity. When it is full the producer must either wait (backpressure: slowness propagates upstream), be rejected (load shedding: HTTP 429/503, ErrQueueFull), or drop something (oldest, newest, lowest priority). A timeout bounds how long any wait may last. Cancellation propagates "stop" from the caller to every activity started on its behalf, so work whose result nobody wants is abandoned; in Go this is context.Context ("A Context carries a deadline, cancellation signal, and request-scoped values across API boundaries"). The full broker-level treatment is on Backpressure & Flow Control.

producerproducerbounded queue: cap = 6Submit blocks until ctx deadline= backpressure to the callerTrySubmit: queue fullreject now (load shedding, 429/503)worker 1worker 2worker 3worker 4metrics: queue depth,in-flight, done, failed
text
     Unbounded                                   Bounded (cap 6) + 2 s deadline
1    1,000 req/s arrive, 400 req/s processed     1,000 req/s arrive, 400 req/s processed
2    queue grows by 600/s; after 60 s: 36,000    queue full after a few ms
3    latency 90 s; clients time out at 30 s      producers wait ≤ 2 s, then 503
4    workers still process the 36,000 dead jobs  workers only process work someone still wants

Real scenarios: a Go service that spawns one goroutine per incoming message from Kafka (memory explosion during a replay); a Laravel queue whose backlog grows for hours while Horizon's wait-time alert is not configured; a RabbitMQ consumer without a prefetch limit (RabbitMQ documents basic.qos "to limit the number of unacknowledged messages on a channel"); an HTTP client without a timeout that pins a worker forever.

Design fix: a buffered channel or errgroup.SetLimit as the bound in Go; select on ctx.Done() in every blocking send and receive; queue:work --timeout below retry_after in Laravel; prefetch in RabbitMQ; partitions × consumers in Kafka; and the lab's worker pool that implements both Submit (wait until a deadline) and TrySubmit (shed now).

Idempotency Must-know ​

In plain words: doing the operation twice has the same effect as doing it once. When retries and duplicates are normal, idempotency is what makes them harmless.

Common misunderstanding: "We use locks, so duplicates cannot happen." Locks expire, workers crash after doing the work but before acknowledging it, clients retry after a timeout, and queues deliver at least once. Duplicates are a design input, not an edge case.

Definition: an operation f is idempotent if f(f(x)) = f(x). In concurrent and distributed designs it is achieved with an idempotency key (a client-supplied unique ID stored with the result under a unique constraint), with natural idempotency (set absolute values instead of increments: stock = 7 rather than stock = stock - 1), or with an inbox table of processed message IDs (Idempotent Consumers & the Inbox Pattern).

text
     Client                    API (no key)              API (Idempotency-Key: k1)
1    POST /pay  ──timeout──▶   charge #1 (succeeds)      insert k1, charge #1
2    POST /pay  (retry)        charge #2  -- double!     k1 exists → return result of #1

Real scenarios: payment and checkout endpoints; webhook receivers; queue consumers with at-least-once delivery; scheduled jobs that may run on two servers during a deploy.

Design fix: a unique index is the real guarantee; a short lock in front of it only reduces wasted work. See IdempotentCheckout.php.

The pattern catalogue ​

These are design-level patterns: each names a shape of concurrency, independent of the language. The table is the catalogue; the subsections below expand the ones you will use weekly.

PatternIntentWhenMain hazardGoLaravel / PHP
Producer/consumerDecouple the rate of producing from consuming via a queueBursty input, steady processingUnbounded queueBuffered channelQueue + queue:work
Worker poolFixed number of workers share a job queueLimit concurrency on a resourcePool deadlock on self-submissionN goroutines on one channelnumprocs, Horizon maxProcesses
PipelineStages connected by queues, each does one stepStreaming transformationLeaked stages on early exitChannels + ctx.Done()Job chains (Bus::chain)
Fan-out / fan-inSplit work across workers, then merge resultsIndependent sub-tasksUnbounded fan-outerrgroup, mergeConcurrency::run, Bus::batch
Future / promiseA placeholder for a result computed concurrentlyStart early, use laterNever-awaited futures, lost errorsChannel of one resultConcurrency::run, Guzzle promises
ReactorOne thread demultiplexes ready I/O events and dispatches handlersMany connections, short handlersA slow handler blocks everyoneGo netpoller (inside the runtime)ReactPHP, Swoole event loop
ProactorStart async operations; dispatch handlers on completionOS with completion-based I/O (IOCP, io_uring)Complex lifetimesHidden by the runtimeSwoole coroutines (similar effect)
Active objectMethod calls become requests queued to an object's own threadSerialize access without callers lockingQueue growthOwner goroutine + request channelA dedicated queue with one worker
MonitorObject whose methods run under one lock, with condition waitsShared object, simple invariantsCalling out while lockedStruct + sync.Mutex / sync.CondlockForUpdate on a row
Read-write lockMany readers or one writerRead-mostly dataWriter starvation, upgrade deadlocksync.RWMutexsharedLock / lockForUpdate
Double-checked lockingLazy init with a lock only on first useExpensive singletonBroken without memory barriersUse sync.Once insteadNot needed under FPM; container singletons
Immutability / copy-on-writeShare only frozen data; replace by swapping a pointerConfig, routing tablesWriters must serializeatomic.Pointer[T]readonly classes
Thread confinementState reachable from one thread onlyPer-request or per-owner stateLeaking a referenceLocal variables, owner goroutineRequest-per-process FPM
Leader/followersThreads take turns: one leader waits for events, hands off, becomes a followerHigh-performance servers, avoids handoff queuesComplexityRare (runtime scheduler)Not used directly
Thread-per-requestOne thread/process per requestSimple serversResource exhaustionOne goroutine per request (net/http)PHP-FPM pm.max_children
Semaphore / bulkheadCap concurrent use of a resourceProtect a DB or APIPermits never releasedsemaphore.Weighted, buffered channelCache::funnel, Redis::funnel

Worker pool and producer/consumer Must-know ​

A producer/consumer design puts a queue between the code that creates work and the code that does it, so each side runs at its own pace. A worker pool fixes the number of consumers, which caps the load on whatever the workers use (database connections, an API's rate limit, CPU). The pool's size is the most important number in the design: below the bottleneck's capacity, the pool is the limit; above it, you only move the queue into the bottleneck. In Go the queue is a buffered channel and the workers are goroutines (lab); in Laravel the queue is Redis/database/SQS and the workers are php artisan queue:work processes. Laravel's docs: "To assign multiple workers to a queue and process jobs concurrently, you should simply start multiple queue:work processes", e.g. Supervisor's numprocs=8. Horizon automates the count with its auto balancing strategy between minProcesses and maxProcesses.

Pool deadlock. A job that submits a sub-job to the same bounded pool and waits for it can deadlock once every worker is waiting for a sub-job that has no free worker. Fix: never block a worker on work in its own pool; use a separate pool, or continue asynchronously (chains, batches with callbacks).

Pipeline, fan-out and fan-in Must-know ​

The Go blog defines it informally: "a pipeline is a series of stages connected by channels, where each stage is a group of goroutines running the same function." Fan-out: "Multiple functions can read from the same channel until that channel is closed ... This provides a way to distribute work amongst a group of workers to parallelize CPU use and I/O." Fan-in: one function reads from several inputs and multiplexes them onto one output channel that is closed when all inputs are closed.

generatesource, closes outnormalize #1normalize #2normalize #3mergeWaitGroup, closesinkmay stop earlyfan-out: one channel, N readersfan-in: N channels, one writerctx.Done(): every send uses select { case out <- v: case <-ctx.Done(): return } so no stage leaks

Two design rules come from the same post. Stages close their outbound channels when they are done sending, and stages keep receiving until inbound channels close or the downstream signals cancellation; otherwise "This is a resource leak: goroutines consume memory and runtime resources ... Goroutines are not garbage collected; they must exit on their own." Ordering is lost after fan-out; if order matters, carry a sequence number and reorder at the sink, or partition by key so each key goes to one worker (the same idea as a Kafka partition). Code: pipeline/main.go, and for independent calls with a limit and first-error cancellation, fanout/main.go.

Futures and promises Important ​

A future (or promise) is a placeholder for a value that another activity is computing; the caller continues and later blocks on, or chains from, the future. Go has no future type: a goroutine writing into a channel of capacity one is a future, and errgroup is a group of futures with error propagation. PHP has promises in libraries (Guzzle's Utils::all, ReactPHP, Amp); in Laravel, Concurrency::run is a blocking "start all, wait for all" over child processes, and Http::pool runs concurrent HTTP requests. The design hazards are the same everywhere: a future nobody awaits hides its error and keeps its resources; a future without a deadline can wait forever.

Reactor, proactor and leader/followers Good to know ​

Schmidt's Reactor "handles service requests that are delivered concurrently to an application by one or more clients" with one event loop that waits for readiness (epoll, kqueue) and dispatches non-blocking handlers. Proactor "supports the demultiplexing and dispatching of multiple event handlers, which are triggered by the completion of asynchronous events": the OS performs the I/O and reports completion (Windows IOCP, Linux io_uring). Leader/Followers lets a pool of threads take turns: one leader waits on the event sources, and when an event arrives it promotes a follower to leader and processes the event itself, avoiding a handoff queue. You rarely write these by hand today. Go's runtime is a reactor (the netpoller) under a goroutine-per-connection programming model, so you write blocking code and get event-loop efficiency. Node.js, ReactPHP, Swoole and Nginx are reactors you program against directly, which is why a CPU-heavy handler on them stalls every other connection. Event-driven control flow is covered on Control Flow & Event Handling.

Active object and monitor Important ​

A monitor keeps the shared state private and runs every method under one lock (Go: a struct with an unexported mu sync.Mutex and methods that lock it; condition waits with sync.Cond). Its rule is: never call out (I/O, callbacks, another monitor) while holding the lock, or you invite deadlock and long waits. An active object goes further: callers do not lock at all; their calls become messages in the object's queue, and the object's own thread executes them in order, returning futures. The owner goroutine in confinement/main.go is an active object. In Laravel the equivalent is a dedicated queue with exactly one worker (--queue=ledger, numprocs=1), which serializes all ledger writes without any locks, at the price of throughput.

Read-write lock Good to know ​

A read-write lock lets many readers in at once or one writer alone. It only wins when reads dominate and critical sections are long enough for the extra bookkeeping to pay off; for short sections a plain sync.Mutex is often faster. Go's documentation warns that an RWMutex "should not be used for recursive read locking; a blocked Lock call excludes new readers from acquiring the lock". In SQL the same idea is FOR SHARE (Laravel sharedLock) versus FOR UPDATE (lockForUpdate). For read-mostly configuration, an immutable snapshot behind atomic.Pointer beats both: readers never wait.

Double-checked locking and safe lazy initialization Important ​

The idiom checks "is it initialized?" without a lock, then locks and checks again before creating. The Double-Checked Locking is Broken declaration explains why it fails without memory barriers: another thread can see the reference before it sees the fully constructed object, because compilers and CPUs reorder writes. In Go the unlocked first read is simply a data race. The design answer is to use the platform's primitive: sync.Once (or sync.OnceValue) in Go, a volatile/holder idiom in Java, and in Laravel a container singleton binding (safe under PHP-FPM because each process is single-threaded; under Octane, see the Octane hazard). Singleton design itself is on Creational Patterns.

Mechanics ​

The Go model Must-know ​

Go's unit of concurrency is the goroutine, a function running independently with a small growable stack, multiplexed by the runtime scheduler onto OS threads (GOMAXPROCS of them run Go code at once). Goroutines communicate through channels (unbuffered: send and receive meet; buffered: a bounded queue) and wait on several with select. Correctness rests on the Go memory model, whose advice is short: "Programs that modify data being simultaneously accessed by multiple goroutines must serialize such access. To serialize access, protect the data with channel operations or other synchronization primitives such as those in the sync and sync/atomic packages." Its other line is worth framing: "If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don't be clever." The ordering guarantees are expressed as happens-before edges: a send on a channel happens before the corresponding receive completes, an Unlock happens before a later Lock returns, and so on.

PrimitiveDesign roleTypical usePitfall
go f()Start an activityPer request, per workerNo owner → leak; no recover → crash
Unbuffered chan TSynchronous handoff (rendezvous)Ownership transfer, signalsBoth sides must be ready; easy partial deadlock
Buffered chan TBounded queueWorker pool input, semaphoreBuffer size is a design decision, not a tuning knob
close(ch)"No more values" broadcastEnd of a streamOnly the sender closes; send on closed channel panics
selectWait on several eventsSend-or-cancel, timeoutsdefault turns it non-blocking (busy loop risk)
context.ContextCancellation, deadlines, request valuesFirst parameter of every blocking callNot checking ctx.Done() in loops
sync.MutexMonitor lockGuard a few fieldsCopying a mutex; calling out while locked
sync.RWMutexRead-write lockRead-mostly mapsRecursive read locking
sync.WaitGroupJoin N activitiesWait for workers to finishAdd inside the goroutine (too late)
sync.OnceOne-time initLazy singletonsPanics inside Do are not retried
sync.CondWait for a condition under a monitorRare; channels are usually clearerMissed wake-ups without a loop
sync/atomicLock-free counters, flags, CAS, pointersMetrics, snapshotsABA, mixing atomic and plain access
errgroup.GroupFan-out with first-error cancel and a limitParallel I/O callsIgnoring the derived context
semaphore.WeightedWeighted permitsMemory- or cost-weighted workForgetting Release
-raceData race detectorCI, staging under loadFinds only executed races

Three details matter at design level. errgroup: "The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever occurs first", and SetLimit "limits the number of active goroutines in this group to at most n", which makes it the default fan-out tool. semaphore: "Weighted provides a way to bound concurrent access to a resource", with permits that can be weighted by cost. sync values: "Values containing the types defined in this package should not be copied", so a struct with a mutex is passed by pointer. Go 1.25 added sync.WaitGroup.Go and the testing/synctest package (first available in Go 1.24 behind GOEXPERIMENT=synctest); the snippets on this page target Go 1.24 and do not use them. Each primitive is taught in depth on the Go path: select, context, sync & atomic, race conditions & deadlocks, rate limiting.

The PHP and Laravel model Must-know ​

PHP's classic model is shared-nothing, request-per-process: PHP-FPM keeps a pool of worker processes (sized by pm.max_children; pm = static, dynamic or ondemand), each handles one request at a time, and nothing in PHP memory survives the request. That is thread confinement for free: there are no data races in PHP code under FPM. The races move to what the processes share: the database, Redis/cache, the filesystem and external APIs. Concurrency in a Laravel design is therefore about processes and shared stores:

Unit / toolWhat it isConcurrency roleKey knobs
PHP-FPM workerOne OS process per in-flight requestThread-per-request (process)pm, pm.max_children
Queue workerphp artisan queue:work processThe main unit of background concurrencySupervisor numprocs, --timeout, --max-jobs, retry_after
HorizonSupervisor of Redis queue workers with balancingWorker pool per queuebalance (auto, simple, false), minProcesses, maxProcesses, waits
Concurrency::runClosures run in child PHP processesFan-out / fan-in inside one request or commandDriver process (default), fork (CLI only), sync (tests); timeout
Concurrency::deferClosures run concurrently after the response is sentFire-and-forget fan-out—
Http::poolConcurrent HTTP requests via GuzzleI/O fan-outPer-request timeouts
Cache::lockAtomic lock in the cache storeMutex across processes and serversTTL, block, owner token, restoreLock, refresh
Cache::withoutOverlapping, Cache::funnelSingle-flight and N-at-a-time limitsMutex / semaphore across serverslockFor, waitFor, limit, releaseAfter, block
WithoutOverlapping job middlewareLock per key around a jobOne running job per resourcereleaseAfter, dontRelease, expireAfter, shared
ShouldBeUniqueLock taken at dispatchOne queued job per keyuniqueId, #[UniqueFor], uniqueVia, ShouldBeUniqueUntilProcessing
Scheduler withoutOverlapping, onOneServerLocks for scheduled tasksSingle-run cron across serversLock expiry (minutes)
lockForUpdate / sharedLockSELECT ... FOR UPDATE / FOR SHAREMonitor on a row, inside DB::transactionattempts for deadlock retry
RateLimiter, Redis::throttle, Redis::funnelRate and concurrency limitsProtect downstream APIsKeys, decay, limits
OctaneFrankenPHP, Swoole/Open Swoole or RoadRunner workers that keep the app in memoryLong-lived workers; Swoole task workers--workers, --task-workers, --max-requests
Fibers (PHP 8.1)Cooperative, single-threaded coroutinesBasis of async libraries (Revolt, Amp)No parallelism by themselves
pcntlUnix process control (fork, signals)CLI only; used by queue timeoutsMust not be enabled in a web server

Four documented constraints shape the design. Atomic locks need a shared store: Laravel's lock-based features require "the memcached, redis, dynamodb, database, file, or array cache driver", and "all servers must be communicating with the same central cache server" (file and array therefore work only on one machine). Timeouts must nest: "The --timeout value should always be at least several seconds shorter than your retry_after configuration value ... If your --timeout option is longer than your retry_after configuration value, your jobs may be processed twice." pcntl is CLI-only: the PHP manual says Process Control "should not be enabled within a web server environment", which is why the Concurrency fork driver "may only be used within PHP's CLI context". Fibers are not threads: they "represent full-stack, interruptible functions" that one thread switches between; they give concurrency for I/O (with an event loop) but no parallelism.

The Octane hazard. Octane "boots your application once and keeps it in memory", so the register and boot methods run once per worker. An object bound as a singleton that captured the request, the container or the config at boot "may have a stale version of the container or request on subsequent requests", and "adding data to a statically maintained array will result in a memory leak". The design rule is the same as in Go: state that outlives a request needs an explicit owner and lifetime. Use scoped bindings (flushed when "a Laravel Octane worker processes a new request or when a Laravel queue worker processes a new job"), pass request data as method arguments, and treat Swoole tables and the Octane cache as shared memory across workers.

Concurrency across processes and services Must-know ​

Once activities run in different processes or machines, in-memory mutexes are useless and the tools change:

NeedToolGuaranteeCaveat
One writer per rowSELECT ... FOR UPDATE (lockForUpdate)Held until commit by the databaseLock waits, deadlocks; keep transactions short
No lost updates without locksOptimistic concurrency: version column, WHERE version = ?, HTTP If-Match/ETagConflicts detected on writeRetries under contention; see Optimistic vs Pessimistic
One holder across serversDistributed lock (Cache::lock on Redis, Postgres advisory lock, etcd/ZooKeeper lease)Mutual exclusion while the lease is validLease can expire while the holder is paused
Safety even if the lease expiredFencing token checked by the storageStale holders' writes are rejectedStorage must check the token
Exactly one active instanceLeader election (etcd, ZooKeeper, Kubernetes Lease, DB row)One leader at a time (with fencing)See Leader Election
Duplicates are harmlessIdempotency keys, inbox table, unique constraintsEffect happens onceMust cover every side effect
Parallel consumers with orderKafka partitions; RabbitMQ single active consumerOrder per partition / per queueParallelism capped by partition count
Bounded consumer concurrencyRabbitMQ basic.qos prefetch, Kafka max.poll.records, worker countLimits unacknowledged workToo low wastes throughput, too high hides overload

Martin Kleppmann's How to do distributed locking (2016) gives the design question to ask first: is the lock for efficiency ("saves you from unnecessarily doing the same work twice") or for correctness ("prevents concurrent processes from stepping on each others' toes")? A Redis lock is fine for efficiency. For correctness, a lock with a timeout is not enough because "Client 1 acquires the lease and gets a token of 33, but then it goes into a long pause and the lease expires"; you need "a fencing token ... a number that increases ... every time a client acquires the lock" that the storage checks, or a design that does not need the lock at all (a unique constraint, a conditional update). The deep treatment is on Distributed Locking.

Consumer concurrency. On Kafka, the javadoc is explicit: "The Kafka consumer is NOT thread-safe", and the simplest model is "One Consumer Per Thread", which "makes in-order processing on a per-partition basis very easy to implement"; its listed drawback is that "The number of total threads across all processes will be limited by the total number of partitions", and max.poll.records limits how many records one poll returns. On RabbitMQ, concurrency is the number of consumers times the prefetch count; RabbitMQ applies the prefetch per consumer by default, slightly deviating from the AMQP 0-9-1 channel-level definition. Scaling consumers is covered on Competing Consumers.

Capacity and Little's law Important ​

Little's law (John Little, 1961; quoted here from Wikipedia, a secondary source) states that "the long-term average number of customers (L) in a stationary system is equal to the long-term average effective arrival rate (λ) multiplied by the average time that a customer spends in the system (W)": L = λW. It turns concurrency sizing into arithmetic:

QuestionFormulaExample
How many requests are in flight?L = λ × W400 req/s × 0.25 s = 100 concurrent requests
How many workers do I need?workers ≥ λ × service time50 jobs/s × 0.6 s = 30 workers (+ headroom)
What throughput can a pool give?λ_max = workers / W8 FPM children / 0.2 s = 40 req/s per server
How long will the backlog take?backlog / (λ_out − λ_in)36,000 jobs / (400 − 300)/s = 6 minutes
Connection pool size?≈ queries/s × query time2,000 q/s × 5 ms = 10 connections busy

If the measured in-flight count is far above λW, something is waiting that should not be (a lock, a slow dependency). Back-of-the-envelope estimation is taught on Capacity Estimation.

Errors and signals you will see Important ​

Message / codeWhereMeaningDesign response
fatal error: all goroutines are asleep - deadlock!Go runtimeEvery goroutine is blockedFix the protocol (who sends, who closes)
fatal error: concurrent map writesGo runtimeUnsynchronized map writes detectedMutex, sync.Map, or one owner
WARNING: DATA RACEGo race detector (-race)Two unsynchronized accesses, one a writeAdd synchronization or confine
context deadline exceeded / context canceledGo contextWait exceeded its deadline / caller cancelledExpected; return early, do not retry blindly
LockTimeoutExceptionLaravel Cache::lock(...)->block(), Cache::withoutOverlappingLock not acquired in timeRetry later, or skip
LimiterTimeoutExceptionLaravel Cache::funnel without failure closureNo slot within block secondsRelease the job, back off
MaxAttemptsExceededExceptionLaravel queueJob used all attempts (overlap releases count)Raise #[Tries], use retryUntil
TimeoutExceededExceptionLaravel queueJob ran longer than its timeoutShorter work units, higher timeout below retry_after
SQLSTATE 40P01PostgreSQLDeadlock detected, transaction abortedRetry the whole transaction; fix lock order
SQLSTATE 40001PostgreSQL, othersSerialization failureRetry the whole transaction
MySQL 1213 / 1205InnoDBDeadlock / lock wait timeoutRetry; shorten transactions

Go ​

All Go code lives in one module (docs/snippets/design/concurrency-design/go, go 1.24, only dependency golang.org/x/sync), passes gofmt -l . and go vet ./..., and every program runs clean under go run -race.

Example: monitor vs owner goroutine ​

The same counter twice: MonitorCounter is a monitor (private map, every method locks), OwnerCounter confines the map to one goroutine and exposes it through a single bounded request channel, so the owner applies requests in the order they were sent; ctx stops it. Output: monitor: 100 owner: 100.

go
// Package main shows the same counter designed two ways:
// a monitor (shared memory guarded by a mutex) and an owner goroutine
// (thread confinement plus message passing, CSP style).
package main

import (
	"context"
	"fmt"
	"sync"
)

// MonitorCounter is a monitor: private state, every method holds the lock.
type MonitorCounter struct {
	mu     sync.Mutex
	counts map[string]int
}

func NewMonitorCounter() *MonitorCounter {
	return &MonitorCounter{counts: make(map[string]int)}
}

func (c *MonitorCounter) Inc(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.counts[key]++
}

func (c *MonitorCounter) Get(key string) int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.counts[key]
}

// OwnerCounter confines the map to one goroutine. Other goroutines never
// touch the map; they send requests over ONE channel, so the owner handles
// them strictly in the order they were sent (an active object).
type OwnerCounter struct {
	reqs chan request
}

type request struct {
	key   string
	reply chan int // nil for an increment, set for a read
}

func NewOwnerCounter(ctx context.Context) *OwnerCounter {
	c := &OwnerCounter{reqs: make(chan request, 64)} // bounded inbox
	go c.loop(ctx)
	return c
}

func (c *OwnerCounter) loop(ctx context.Context) {
	counts := make(map[string]int) // owned by this goroutine only
	for {
		select {
		case r := <-c.reqs:
			if r.reply == nil {
				counts[r.key]++
				continue
			}
			r.reply <- counts[r.key]
		case <-ctx.Done():
			return
		}
	}
}

func (c *OwnerCounter) Inc(key string) { c.reqs <- request{key: key} }

func (c *OwnerCounter) Get(key string) int {
	reply := make(chan int, 1)
	c.reqs <- request{key: key, reply: reply}
	return <-reply
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	m := NewMonitorCounter()
	o := NewOwnerCounter(ctx)

	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			m.Inc("page:/home")
			o.Inc("page:/home")
		}()
	}
	wg.Wait()
	// Every Inc was sent on reqs before this Get, and one channel is FIFO,
	// so the owner has applied all of them when it answers.
	fmt.Println("monitor:", m.Get("page:/home"), "owner:", o.Get("page:/home"))
}

Example: pipeline with fan-out, fan-in and early exit ​

Every send is a select with ctx.Done(), every stage closes what it owns, and the consumer stops after three values; the deferred cancel() releases all upstream goroutines.

go
// Package main is a three-stage pipeline with fan-out and fan-in.
// Every stage stops when ctx is cancelled, so no goroutine leaks.
package main

import (
	"context"
	"fmt"
	"strings"
	"sync"
)

// generate is the source stage: it owns and closes its output channel.
func generate(ctx context.Context, lines ...string) <-chan string {
	out := make(chan string)
	go func() {
		defer close(out)
		for _, l := range lines {
			select {
			case out <- l:
			case <-ctx.Done():
				return
			}
		}
	}()
	return out
}

// normalize is a worker stage; several copies read the same input (fan-out).
func normalize(ctx context.Context, in <-chan string) <-chan string {
	out := make(chan string)
	go func() {
		defer close(out)
		for l := range in {
			select {
			case out <- strings.ToUpper(strings.TrimSpace(l)):
			case <-ctx.Done():
				return
			}
		}
	}()
	return out
}

// merge multiplexes many inputs onto one output (fan-in).
func merge(ctx context.Context, ins ...<-chan string) <-chan string {
	out := make(chan string)
	var wg sync.WaitGroup
	wg.Add(len(ins))
	for _, in := range ins {
		go func(c <-chan string) {
			defer wg.Done()
			for v := range c {
				select {
				case out <- v:
				case <-ctx.Done():
					return
				}
			}
		}(in)
	}
	go func() { wg.Wait(); close(out) }()
	return out
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel() // stops every stage if we return early

	src := generate(ctx, " a ", "b", " c", "d ", "e")
	w1, w2, w3 := normalize(ctx, src), normalize(ctx, src), normalize(ctx, src)

	n := 0
	for v := range merge(ctx, w1, w2, w3) {
		fmt.Println(v) // order is not guaranteed after fan-out
		n++
		if n == 3 {
			break // consumer stops early; deferred cancel releases upstream
		}
	}
}

Example: bounded fan-out with errgroup and a weighted semaphore ​

errgroup.WithContext + SetLimit(2): at most two calls in flight, the first error cancels the others, and each goroutine writes only its own slice index (confinement by index, so no lock is needed).

go
// Package main fans out independent I/O calls with errgroup: bounded
// concurrency, first error cancels the rest, results written by index.
package main

import (
	"context"
	"fmt"
	"time"

	"golang.org/x/sync/errgroup"
	"golang.org/x/sync/semaphore"
)

type Quote struct {
	Carrier string
	Cents   int
}

func fetchQuote(ctx context.Context, carrier string) (Quote, error) {
	select {
	case <-time.After(30 * time.Millisecond): // pretend HTTP call
		return Quote{Carrier: carrier, Cents: 500 + len(carrier)*10}, nil
	case <-ctx.Done():
		return Quote{}, ctx.Err()
	}
}

// AllQuotes calls every carrier with at most limit calls in flight.
func AllQuotes(ctx context.Context, carriers []string, limit int) ([]Quote, error) {
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
	defer cancel()

	g, ctx := errgroup.WithContext(ctx)
	g.SetLimit(limit)
	out := make([]Quote, len(carriers)) // each goroutine owns one index
	for i, c := range carriers {
		g.Go(func() error {
			q, err := fetchQuote(ctx, c)
			if err != nil {
				return fmt.Errorf("%s: %w", c, err)
			}
			out[i] = q
			return nil
		})
	}
	if err := g.Wait(); err != nil {
		return nil, err
	}
	return out, nil
}

// heavyReports shows a weighted semaphore: a big report takes 4 slots of 8.
func heavyReports(ctx context.Context, sizes []int64) error {
	sem := semaphore.NewWeighted(8)
	g, ctx := errgroup.WithContext(ctx)
	for _, w := range sizes {
		if err := sem.Acquire(ctx, w); err != nil {
			return err
		}
		g.Go(func() error {
			defer sem.Release(w)
			time.Sleep(time.Duration(w) * 5 * time.Millisecond)
			return nil
		})
	}
	return g.Wait()
}

func main() {
	qs, err := AllQuotes(context.Background(), []string{"dhl", "ups", "fedex", "post"}, 2)
	fmt.Println(qs, err)
	fmt.Println(heavyReports(context.Background(), []int64{1, 4, 2, 4, 1}))
}

Example: deadlock-free transfers with lock ordering ​

2,000 concurrent transfers in opposite directions. Locking the lower ID first removes the circular wait; the total stays 2000 and the program never hangs.

go
// Package main avoids deadlock in a two-account transfer by always
// locking accounts in a global order (by ID), which breaks circular wait.
package main

import (
	"errors"
	"fmt"
	"sync"
)

type Account struct {
	ID      int64
	mu      sync.Mutex
	balance int64
}

var ErrInsufficient = errors.New("insufficient funds")

// Transfer locks the lower ID first, whatever the direction of the transfer.
func Transfer(from, to *Account, amount int64) error {
	if from.ID == to.ID {
		return nil
	}
	first, second := from, to
	if to.ID < from.ID {
		first, second = to, from
	}
	first.mu.Lock()
	defer first.mu.Unlock()
	second.mu.Lock()
	defer second.mu.Unlock()

	if from.balance < amount {
		return ErrInsufficient
	}
	from.balance -= amount
	to.balance += amount
	return nil
}

func main() {
	a := &Account{ID: 1, balance: 1000}
	b := &Account{ID: 2, balance: 1000}

	var wg sync.WaitGroup
	for i := 0; i < 1000; i++ {
		wg.Add(2)
		go func() { defer wg.Done(); _ = Transfer(a, b, 1) }() // A -> B
		go func() { defer wg.Done(); _ = Transfer(b, a, 1) }() // B -> A
	}
	wg.Wait()
	fmt.Println("total:", a.balance+b.balance) // always 2000, never hangs
}

Example: sync.Once and immutable snapshots ​

No hand-written double-checked locking: sync.Once for lazy init, and an atomic.Pointer[Config] that readers load without locking while a single writer publishes copies.

go
// Package main replaces double-checked locking with sync.Once and
// publishes immutable config snapshots with atomic.Pointer (copy-on-write).
package main

import (
	"fmt"
	"maps"
	"sync"
	"sync/atomic"
)

// Config is never mutated after it is published.
type Config struct {
	Version int
	Limits  map[string]int
}

type ConfigStore struct {
	cur atomic.Pointer[Config]
	mu  sync.Mutex // serializes writers only; readers never lock
}

func (s *ConfigStore) Load() *Config { return s.cur.Load() }

// SetLimit copies the current snapshot, changes the copy, then swaps it in.
func (s *ConfigStore) SetLimit(key string, v int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	old := s.cur.Load()
	next := &Config{Version: old.Version + 1, Limits: maps.Clone(old.Limits)}
	next.Limits[key] = v
	s.cur.Store(next)
}

var (
	storeOnce sync.Once
	store     *ConfigStore
)

// Store is lazily initialized exactly once; no hand-written double check.
func Store() *ConfigStore {
	storeOnce.Do(func() {
		s := &ConfigStore{}
		s.cur.Store(&Config{Version: 1, Limits: map[string]int{"api": 100}})
		store = s
	})
	return store
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 8; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			cfg := Store().Load() // a consistent snapshot, safe to read freely
			_ = cfg.Limits["api"]
		}()
	}
	Store().SetLimit("api", 200)
	wg.Wait()
	fmt.Println("version:", Store().Load().Version, "api:", Store().Load().Limits["api"])
}

Example: optimistic concurrency in memory and in SQL ​

Reserve is a compare-and-swap loop (50 goroutines, 10 items: exactly 10 succeed). RenameProduct is the same idea across processes: a version column and RowsAffected() == 0 as the conflict signal.

go
// Package main shows optimistic concurrency twice: an in-memory
// compare-and-swap loop, and a version-column UPDATE across processes.
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"sync"
	"sync/atomic"
)

// Reserve decrements stock without a lock; it retries when another
// goroutine won the race between Load and CompareAndSwap.
func Reserve(stock *atomic.Int64, qty int64) bool {
	for {
		cur := stock.Load()
		if cur < qty {
			return false
		}
		if stock.CompareAndSwap(cur, cur-qty) {
			return true
		}
	}
}

var ErrConflict = errors.New("version conflict, reload and retry")

// RenameProduct is the same idea across processes: the UPDATE succeeds only
// if nobody changed the row since we read version.
func RenameProduct(ctx context.Context, db *sql.DB, id, version int64, name string) error {
	res, err := db.ExecContext(ctx,
		`UPDATE products SET name = $1, version = version + 1
		 WHERE id = $2 AND version = $3`, name, id, version)
	if err != nil {
		return err
	}
	n, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if n == 0 {
		return ErrConflict
	}
	return nil
}

func main() {
	var stock atomic.Int64
	stock.Store(10)
	var ok atomic.Int64
	var wg sync.WaitGroup
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if Reserve(&stock, 1) {
				ok.Add(1)
			}
		}()
	}
	wg.Wait()
	fmt.Println("reserved:", ok.Load(), "left:", stock.Load()) // reserved: 10 left: 0
}

The Go angle ​

  • Design the goroutine's whole life before writing go. Who starts it, what stops it (a closed channel or ctx.Done()), who waits for it (WaitGroup, errgroup), where its error goes. A goroutine without those four answers is a leak waiting for traffic.
  • Channels for ownership transfer and signalling, mutexes for guarding state. Effective Go: "using channels to control access makes it easier to write clear, correct programs", but a counter or a cache is simpler behind sync.Mutex.
  • Bound everything. A buffered channel's capacity, errgroup.SetLimit, semaphore.NewWeighted, http.Server timeouts, sql.DB.SetMaxOpenConns. net/http already runs one goroutine per connection; your handler should not add unbounded goroutines of its own.
  • context.Context is the cancellation tree. Pass it as the first argument of every function that blocks, derive timeouts per call, and check ctx.Done() in loops. The context chapter covers values and deadlines.
  • Rate is not concurrency. golang.org/x/time/rate ("A Limiter controls how frequently events are allowed to happen", a token bucket) limits rate; a semaphore limits how many at once. Protecting a downstream API usually needs both.
  • Ecosystem. golang.org/x/sync/singleflight collapses duplicate concurrent calls for the same key (cache stampede protection); go.uber.org/goleak fails a test that leaks goroutines; pgx pools, go-redis pools and the database/sql pool are themselves bounded worker pools, sized by connections.

Laravel ​

PHP files target Laravel 13 / PHP 8.4. PHP is not installed on the build machine, so they were reviewed twice by hand, not run; every API used is in the Laravel 13 docs linked in the references.

Example: fan-out inside a request with Concurrency::run ​

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Ticket;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Concurrency;

// Fan-out inside one request: three independent, slow queries run in
// child PHP processes (the default "process" driver) and are joined here.
final class DashboardController
{
    public function __invoke(): JsonResponse
    {
        $results = Concurrency::run([
            'users' => fn () => User::query()->where('created_at', '>=', now()->subDay())->count(),
            'revenue' => fn () => (int) Order::query()->where('status', 'paid')->sum('total_cents'),
            'tickets' => fn () => Ticket::query()->where('status', 'open')->count(),
        ], timeout: 5); // each child is killed after 5 seconds

        return response()->json($results);
    }
}

// Closures are serialized and run in another process: they must not rely on
// in-memory state of the parent (static arrays, singletons, open transactions).
// Each child opens its own database connection.

Example: unique and non-overlapping jobs ​

php
<?php

namespace App\Jobs;

use App\Models\Product;
use App\Services\SupplierClient;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\Middleware\WithoutOverlapping;

// Two different guarantees, combined on purpose:
// - ShouldBeUnique: at most one copy of this job per product is *queued*
//   (lock taken at dispatch, keyed by uniqueId, released when the job ends).
// - WithoutOverlapping: at most one copy per supplier is *running*
//   (lock taken by the worker, keyed by the middleware key).
#[Tries(5)]          // an overlapping release counts as an attempt
#[UniqueFor(600)]    // the unique lock expires after 10 minutes anyway
final class SyncSupplierStock implements ShouldQueue, ShouldBeUnique
{
    use Queueable;

    public function __construct(public Product $product) {}

    public function uniqueId(): string
    {
        return (string) $this->product->id;
    }

    /** @return array<int, object> */
    public function middleware(): array
    {
        return [
            (new WithoutOverlapping('supplier:'.$this->product->supplier_id))
                ->releaseAfter(30)   // try again in 30 s instead of failing
                ->expireAfter(180),  // lock dies 3 min after start if the worker crashes
        ];
    }

    public function handle(SupplierClient $supplier): void
    {
        $qty = $supplier->stockFor($this->product->sku); // one call per supplier at a time

        // Idempotent write: setting an absolute value is safe to repeat.
        $this->product->forceFill(['supplier_stock' => $qty])->save();
    }
}

Example: three ways to stop a lost update ​

php
<?php

namespace App\Actions;

use App\Models\Product;
use Illuminate\Support\Facades\DB;
use RuntimeException;

// Three ways to stop a lost update on stock, from simplest to most explicit.
final class ReserveStock
{
    // 1. Atomic conditional update: the database does read-check-write in one statement.
    public function atomic(int $productId, int $qty): bool
    {
        return DB::table('products')
            ->where('id', $productId)
            ->where('stock', '>=', $qty)
            ->decrement('stock', $qty) === 1;
    }

    // 2. Pessimistic: lock the row, decide in PHP, write, commit (lock released).
    public function pessimistic(int $productId, int $qty): void
    {
        DB::transaction(function () use ($productId, $qty) {
            $product = Product::query()->whereKey($productId)->lockForUpdate()->firstOrFail();

            if ($product->stock < $qty) {
                throw new RuntimeException('Out of stock');
            }

            $product->decrement('stock', $qty);
        }, attempts: 3); // retried when the database reports a deadlock
    }

    // 3. Optimistic: no lock; the write succeeds only if the version is unchanged.
    public function optimistic(int $productId, int $qty, int $maxRetries = 3): void
    {
        for ($try = 0; $try < $maxRetries; $try++) {
            $row = DB::table('products')->where('id', $productId)->first(['stock', 'version']);

            if ($row === null || $row->stock < $qty) {
                throw new RuntimeException('Out of stock');
            }

            $updated = DB::table('products')
                ->where('id', $productId)
                ->where('version', $row->version)
                ->update(['stock' => $row->stock - $qty, 'version' => $row->version + 1]);

            if ($updated === 1) {
                return;
            }
            usleep(random_int(5_000, 20_000)); // jitter before re-reading
        }

        throw new RuntimeException('Too much contention, try again');
    }
}

Example: an idempotent endpoint with a lock and a unique index ​

php
<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

// The client retries a POST (timeout, double click, mobile network).
// Two layers make the effect happen once: a short lock for the common race,
// and a unique index on idempotency_key as the real guarantee.
final class IdempotentCheckout
{
    public function __invoke(Request $request): JsonResponse
    {
        $key = $request->header('Idempotency-Key') ?? abort(400, 'Idempotency-Key required');

        return Cache::lock('checkout:'.$key, 30)->block(5, function () use ($request, $key) {
            if ($existing = Payment::query()->where('idempotency_key', $key)->first()) {
                return response()->json($existing, 200); // replay the first result
            }

            try {
                $payment = Payment::query()->create([
                    'idempotency_key' => $key, // UNIQUE index in the migration
                    'order_id' => $request->integer('order_id'),
                    'amount_cents' => $request->integer('amount_cents'),
                ]);
            } catch (UniqueConstraintViolationException) {
                // The lock expired and another process won: return its row.
                return response()->json(Payment::query()->where('idempotency_key', $key)->firstOrFail(), 200);
            }

            return response()->json($payment, 201);
        });
    }
}

Example: Octane-safe state ​

php
<?php

namespace App\Providers;

use App\Services\PriceFormatter;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

// Under Octane one worker process serves many requests, so state that
// survives a request is shared by every later request on that worker.
final class OctaneSafeServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Wrong under Octane: the singleton captures the FIRST request forever.
        // $this->app->singleton(PriceFormatter::class, fn (Application $app) =>
        //     new PriceFormatter($app['request']->header('Accept-Language')));

        // Right: resolve per request (scoped is flushed between Octane requests) ...
        $this->app->scoped(PriceFormatter::class, fn (Application $app) => new PriceFormatter(
            $app->make(Request::class)->header('Accept-Language', 'en'),
        ));
    }
}

final class LeakyController
{
    // Wrong under Octane: grows on every request until the worker restarts.
    private static array $seen = [];

    public function __invoke(Request $request): array
    {
        self::$seen[] = $request->ip();

        return ['count' => count(self::$seen)];
    }
}

The Laravel angle ​

  • The queue worker is the concurrency unit. Design background work as small, idempotent jobs; scale by adding worker processes (Supervisor numprocs, Horizon maxProcesses), not by forking inside a job. Separate queues by priority so a slow reports backlog cannot starve payments.
  • Pick the right lock for the guarantee. ShouldBeUnique = at most one queued; WithoutOverlapping = at most one running per key; Cache::funnel / Redis::funnel = at most N running; Schedule::...->withoutOverlapping()->onOneServer() = one cron run; lockForUpdate = one writer per row inside a transaction. They compose, as in SyncSupplierStock.
  • Mind the counters. "Releasing an overlapping job back onto the queue will still increment the job's total number of attempts", and Tries defaults to 1, so a WithoutOverlapping job without #[Tries] or retryUntil fails on its first overlap. Use expireAfter so a crashed worker does not hold the lock forever.
  • Dispatch after commit. A job dispatched inside a transaction can run before the commit is visible; use afterCommit() (or the after_commit queue option) so the worker reads committed data.
  • Concurrency::run is process-level fan-out. Closures are serialized and run in fresh PHP processes, so they cannot share in-memory state with the parent, they open their own DB connections, and the process driver's timeout is the cancellation mechanism. The sync driver turns it off in tests.
  • Octane changes the model. Long-lived workers make singletons and statics shared across requests. Treat them as the Go page treats package-level variables: immutable, or owned and reset per request (scoped).

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Oversold stock (lost update)Atomic conditional updateUPDATE ... SET stock = stock - ? WHERE stock >= ?No lock held in the app, one round tripLogic must fit in one statement
Oversold stock, complex rulesPessimistic row locklockForUpdate in DB::transactionSimple reasoningWaits, deadlocks under contention
Concurrent edits of a documentOptimistic concurrencyversion column or ETag + If-MatchNo waiting; works over HTTPRetries or user-visible conflicts
Same job runs twice at onceWithoutOverlapping / Cache::lockLock per resource keyCheap, cross-serverLock TTL vs job duration; needs idempotency anyway
Same job queued 1,000 timesShouldBeUniqueLock at dispatch by uniqueIdQueue stays smallDoes not stop overlapping runs by itself
Cron runs on every serveronOneServer() + withoutOverlapping()Cache lock per taskOne run per tickShared cache required
Slow API overwhelmed by fan-outSemaphore / funnelerrgroup.SetLimit, Cache::funnelProtects the dependencyAdds queueing latency
Unbounded backlogBounded queue + backpressure / sheddingBuffered channel, 429, Horizon wait alertsPredictable latency and memorySome work is rejected
Goroutine leakCancellation everywhereselect on ctx.Done(), close by ownerBounded resourcesDiscipline in every send/receive
Deadlock between locksGlobal lock order + timeoutsSort keys before locking; block(5)Removes circular waitMust know all locks up front
Duplicate side effect after retryIdempotency keyUnique index + stored resultSafe retriesStorage and key expiry policy
Cache stampedeSingle-flightsingleflight.Group, Cache::lock around recompute, Cache::flexibleOne recompute per keyWaiters share one failure

Overselling under concurrent checkouts ​

Two PHP-FPM workers or two goroutines are the same problem here. The atomic conditional update is the first choice; the row lock when the decision needs several reads; optimistic when conflicts are rare and you want no waiting.

sql
-- PostgreSQL / MySQL: the check and the write are one statement.
UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock >= 1;
-- affected rows = 1: reserved; 0: sold out. No application-side race window exists.

Jobs that must not run concurrently ​

Decide which guarantee you need: "not queued twice" (ShouldBeUnique), "not running twice for this key" (WithoutOverlapping), "not more than N" (Cache::funnel), or "only one server" (onOneServer). Then make the job idempotent anyway, because locks expire: the --timeout/retry_after rule above is the classic way a "unique" job runs twice.

Fan-out that takes a dependency down ​

Fan-out multiplies load. 200 requests/s × 10 parallel calls = 2,000 calls/s to a supplier that allows 100. Bound the fan-out per request (SetLimit), bound it globally (a shared semaphore, a Cache::funnel key, or a rate limiter in front of the client), and give every call a deadline shorter than the caller's.

Leaked goroutines and stuck workers ​

A goroutine blocked forever on a send nobody will receive is invisible until memory grows. Every blocking operation gets a select with ctx.Done(); every producer closes its channel; tests assert the goroutine count (lab, TestCancelStopsWorkers) or use goleak. The Laravel counterpart is a worker stuck on an HTTP call without a timeout: set client timeouts and queue:work --timeout.

Shared state under Octane ​

Replace singleton bindings that capture request, container or config with scoped bindings or resolver closures, remove static accumulators, and restart workers with --max-requests as a safety net, not a fix.

Testing concurrent designs ​

Concurrency bugs depend on interleavings that ordinary tests rarely produce. The design should make interleavings provokable and observable.

TechniqueToolWhat it findsLimit
Race detectiongo test -raceData races on executed paths"The race detector only finds races that happen at runtime, so it can't find races in code paths that are not executed"; "memory usage may increase by 5-10x and execution time by 2-20x"
Repetition / stressgo test -race -count=100, -cpu=1,4,8Rare interleavingsProbabilistic
Deterministic scheduling and fake timetesting/synctest (Go 1.25; experimental in 1.24)Timeouts, retries, tickers without real sleepsOnly goroutines inside the "bubble"
Leak checksgoleak.VerifyNone(t), runtime.NumGoroutine()Goroutines that never exitNeeds a quiescent end state
Property-based teststesting/quick, pgregory.net/rapidInvariants over random operation sequences (e.g. total balance constant)Needs good invariants
Linearizability / model checkingPorcupine (Go), Jepsen, TLA+Distributed protocol bugsExpensive; for core protocols
Two-process testsTwo artisan processes or two HTTP clientsLocks, unique jobs, row locks really holdNeeds real Redis/DB
FakesQueue::fake(), Bus::fake(), Concurrency sync driverDispatch logic, without concurrencyDoes not test races

testing/synctest deserves a note: its Test function runs the test in an isolated bubble; "Within a bubble, the time package uses a fake clock", and "Time in a bubble only advances when every goroutine in the bubble is durably blocked", which makes timeout logic deterministic. The race detector article itself recommends running "a binary built with -race under a realistic workload" when test coverage is incomplete.

text
     A property test for the transfer design (lockorder)
1    generate: 1,000 random transfers between 10 accounts, random amounts
2    run them on 8 goroutines under -race
3    assert: sum(balances) == initial sum           -- conservation invariant
4    assert: no balance < 0                         -- safety invariant
5    assert: test finishes within 5 s               -- liveness (no deadlock)

Observability ​

SignalGoLaravelAlarm when
Live goroutines / workersruntime.NumGoroutine(), pprof goroutine profileHorizon processes, Supervisor statusGrows without traffic growth (leak)
Queue depthlen(ch), pool Stats()Horizon dashboard, queue:monitorGrows for minutes (λ in > λ out)
Wait time / age of oldest jobTimestamp at enqueueHorizon waits thresholds and long-wait notificationsAbove the SLO
In-flight workAtomic gaugeRunning jobsNear the pool limit for long periods
Lock contentionpprof mutex and block profilesLock acquisition failures, LockTimeoutException rateRising waits or timeouts
Retries and conflictsCounter per error typeFailed jobs, MaxAttemptsExceededException, deadlock retriesSpikes after deploys
RejectionsErrQueueFull counter, HTTP 429/503Rate limiter hitsSustained shedding

The pprof profiles map directly onto the hazards: "goroutine - stack traces of all current goroutines" (leaks and partial deadlocks: thousands of goroutines parked on the same chan send), "block - stack traces that led to blocking on synchronization primitives" and "mutex - stack traces of holders of contended mutexes" (contention). For Laravel, Horizon's waits option sets, per connection and queue, how many seconds count as a long wait (60 by default), and Horizon notifies via mail, Slack or SMS.

Choosing ​

SituationRecommendationExtra techniqueReason
Several independent slow I/O calls in one requestFan-out / fan-in with a deadlineGo errgroup + SetLimit; Laravel Concurrency::run or Http::poolLatency = slowest call, not the sum
Work the user does not wait forAsynchrony via a queueDispatch after commit; idempotent jobShort responses, retries for free
CPU-heavy batchParallel worker pool sized to coresGOMAXPROCS workers; separate queue for heavy jobsMore workers than cores only adds switching
Read-mostly shared configImmutable snapshotatomic.Pointer, reload by swapReaders never block
Small shared counter or mapMonitorsync.Mutex; atomic for a single numberSimplest correct option
Complex state with many operationsOwner goroutine / active objectRequest channel, boundedInvariants live in one place
One running instance per resourcePer-key lockWithoutOverlapping, Cache::lock, FOR UPDATESerializes only what conflicts
Correctness-critical exclusion across serversAvoid the lock; or lease + fencingUnique constraints, conditional updates, fencing tokensLease expiry breaks plain locks
Contended hot rowAtomic update, or partition the counterSharded counters, append-only ledgerLocks serialize every writer
Ordered processing per keyPartition by keyKafka key → partition; one worker per key groupOrder and parallelism together
Bursty producer, steady consumerBounded producer/consumerBackpressure or shedding policyPredictable memory and latency
Many connections, small handlersEvent loop / goroutine-per-connectionGo net/http; Swoole/ReactPHP for PHPCheap waiting

In architecture: from a single process to a distributed system ​

The design questions stay the same at every scale: what runs independently, who owns which state, how is waiting bounded. What changes is the price of coordination: nanoseconds for a mutex, milliseconds for a row lock, tens of milliseconds and partial failure for a network lock.

Monolith: one process, one database ​

How it shows up: goroutines or FPM workers sharing one database. In Go, shared in-memory state (caches, counters) needs a monitor or an owner; in PHP, there is no in-memory sharing, and the database is the shared memory.

Simplest correct usage: keep request state confined; let the database arbitrate with atomic updates, unique constraints and short FOR UPDATE transactions; run background work in a worker pool with a bounded queue.

Example (everyday): a blog's "views" counter. Go: atomic.Int64 flushed every 10 s. Laravel: increment('views') (one atomic SQL statement), never $post->views++; $post->save().

Example (production): a ticketing monolith selling 5,000 seats in a flash sale. Seats are rows; reservation is UPDATE seats SET held_by = ?, held_until = now() + interval '10 minutes' WHERE id = ? AND held_by IS NULL; a scheduled job (onOneServer) releases expired holds; the payment callback is idempotent by order ID.

Modular monolith and multiple databases ​

How it shows up: modules own their tables and talk through in-process interfaces or an in-process event bus. Concurrency rules become module contracts: "only the Inventory module writes stock", "Billing receives OrderPlaced asynchronously".

Rules: one writer module per table (ownership at module level); cross-module calls never hold another module's locks; asynchronous module events go through a queue (or an outbox table) so a slow listener cannot block the caller's transaction; each module's jobs run on its own queue with its own worker count.

Example: Orders reserves stock by calling Inventory::reserve($sku, $qty) (atomic update inside Inventory) and dispatches SendOrderConfirmation after commit on the notifications queue, so a slow mail server never holds an orders transaction open.

Microservices: concurrency with a network in between ​

What survives: ownership (database per service), idempotency, bounded queues and timeouts. What does not: in-process locks and database transactions across services. Two services cannot share a mutex; "lock order" becomes "saga order", and a lost update across services becomes a conflicting event that must be reconciled.

text
     Checkout saga, every step idempotent and bounded
1    checkout-svc   POST /orders (Idempotency-Key: k1)   → order PENDING, outbox: OrderPlaced
2    inventory-svc  consume OrderPlaced (inbox dedupe)   → UPDATE stock ... WHERE stock >= qty → StockReserved | StockRejected
3    payment-svc    consume StockReserved                → charge with key order-123 (provider dedupes) → PaymentSucceeded
4    checkout-svc   consume PaymentSucceeded             → order CONFIRMED (UPDATE ... WHERE status = 'PENDING')
5    timeouts: each consumer has prefetch 20 and a 5 s call deadline; retries with jitter; DLQ after 5 attempts

Example: the flow above uses three concurrency tools per service: a conditional update for local state, an inbox table for duplicate messages, and consumer concurrency bounded by RabbitMQ prefetch or Kafka partitions. The saga itself is on Saga Pattern; the outbox on Transactional Outbox.

Distributed data: replicas, caches, locks and leaders ​

Where it breaks: reading from a replica after writing to the primary (stale read, then a lost update on write-back); a cache recomputed by 500 processes at once (stampede); a Redis lock that expires while the holder is in a GC pause; two nodes both believing they are the leader during a network partition; clocks used to order events across machines.

Countermeasures: read-modify-write against the primary only, with a version check; single-flight recompute (singleflight, Cache::lock, stale-while-revalidate); fencing tokens on every write guarded by a distributed lock; leader election through a consensus store (etcd, ZooKeeper, Kubernetes Lease) with fencing; logical versions instead of wall-clock timestamps for conflict detection. Details: Distributed Locking, Leader Election, Eventual Consistency.

Scaling path: 1×, 10×, 100× ​

ScaleConcurrency designTypical change
1× (one server)Goroutine/FPM per request, one worker pool, DB arbitratesAtomic updates and unique constraints; -race in CI
10× (several servers)Shared cache for locks, Horizon balancing, separate queues per priorityCache::lock/WithoutOverlapping need one central store; pool sizes from Little's law; queue-depth alerts
100× (many services, regions)Partitioned ownership, idempotent consumers, no correctness-critical distributed locksPartition by key (tenant, account); sharded counters; fencing; backpressure end to end

Lab ​

Two parts: a Go worker pool you can break and fix, and a Laravel demo of overlapping jobs and atomic locks. Part A runs offline; Part B needs a Laravel 13 app with Redis.

Part A: Go worker pool with backpressure and cancellation ​

Setup.

bash
cd docs/snippets/design/concurrency-design/go
gofmt -l . && go vet ./...        # no output, no errors
go
// Package main is the lab worker pool: a bounded queue gives backpressure,
// contexts give cancellation and per-job timeouts, Close drains gracefully.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"sync"
	"sync/atomic"
	"time"
)

type Job struct {
	ID int
}

type Handler func(ctx context.Context, j Job) error

var (
	ErrQueueFull = errors.New("queue full")
	ErrClosed    = errors.New("pool closed")
)

type Pool struct {
	jobs     chan Job        // bounded: its capacity is the backpressure limit
	stop     <-chan struct{} // closed when the pool's ctx is cancelled
	handle   Handler
	timeout  time.Duration
	wg       sync.WaitGroup
	mu       sync.RWMutex // guards closed and the send on jobs
	closed   bool
	inFlight atomic.Int64
	done     atomic.Int64
	failed   atomic.Int64
}

// New starts workers that stop when ctx is cancelled or the queue is closed.
func New(ctx context.Context, workers, queue int, timeout time.Duration, h Handler) *Pool {
	p := &Pool{jobs: make(chan Job, queue), stop: ctx.Done(), handle: h, timeout: timeout}
	for w := 0; w < workers; w++ {
		p.wg.Add(1)
		go p.worker(ctx)
	}
	return p
}

func (p *Pool) worker(ctx context.Context) {
	defer p.wg.Done()
	for {
		select {
		case <-ctx.Done():
			return // hard stop: abandon queued jobs
		case j, ok := <-p.jobs:
			if !ok {
				return // graceful stop: queue drained
			}
			p.run(ctx, j)
		}
	}
}

func (p *Pool) run(ctx context.Context, j Job) {
	p.inFlight.Add(1)
	defer p.inFlight.Add(-1)
	jctx, cancel := context.WithTimeout(ctx, p.timeout)
	defer cancel()
	if err := p.handle(jctx, j); err != nil {
		p.failed.Add(1)
		return
	}
	p.done.Add(1)
}

// Submit blocks while the queue is full until ctx expires: the caller slows
// down (backpressure) instead of the pool growing without limit.
func (p *Pool) Submit(ctx context.Context, j Job) error {
	p.mu.RLock()
	defer p.mu.RUnlock()
	if p.closed {
		return ErrClosed
	}
	select {
	case p.jobs <- j:
		return nil
	case <-ctx.Done(): // the caller gave up waiting
		return fmt.Errorf("submit job %d: %w", j.ID, ctx.Err())
	case <-p.stop: // the pool was cancelled; nobody will drain the queue
		return ErrClosed
	}
}

// TrySubmit never blocks: when the queue is full it sheds load at once.
func (p *Pool) TrySubmit(j Job) error {
	p.mu.RLock()
	defer p.mu.RUnlock()
	if p.closed {
		return ErrClosed
	}
	select {
	case p.jobs <- j:
		return nil
	default:
		return ErrQueueFull
	}
}

// Close stops intake, lets workers finish the queue, and waits for them.
func (p *Pool) Close() {
	p.mu.Lock()
	if !p.closed {
		p.closed = true
		close(p.jobs)
	}
	p.mu.Unlock()
	p.wg.Wait()
}

// Stats are the numbers to export as metrics: queue depth and in-flight work.
func (p *Pool) Stats() (queued, inFlight, done, failed int64) {
	return int64(len(p.jobs)), p.inFlight.Load(), p.done.Load(), p.failed.Load()
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	slow := func(ctx context.Context, j Job) error {
		select {
		case <-time.After(50 * time.Millisecond): // pretend I/O
			return nil
		case <-ctx.Done():
			return ctx.Err() // honour the per-job timeout and shutdown
		}
	}
	p := New(ctx, 4, 8, 200*time.Millisecond, slow)

	shed := 0
	for i := 1; i <= 40; i++ {
		if err := p.TrySubmit(Job{ID: i}); errors.Is(err, ErrQueueFull) {
			shed++
		}
	}
	q, f, _, _ := p.Stats()
	log.Printf("after burst: queued=%d inFlight=%d shed=%d", q, f, shed)

	sctx, scancel := context.WithTimeout(ctx, time.Second)
	defer scancel()
	for i := 41; i <= 60; i++ {
		if err := p.Submit(sctx, Job{ID: i}); err != nil { // waits for room
			log.Println(err)
		}
	}
	p.Close()
	_, _, done, failed := p.Stats()
	fmt.Printf("done=%d failed=%d shed=%d\n", done, failed, shed)
}

Step 1: see a data race first. Put this in a scratch directory and run it with the race detector. It is the design this page argues against: shared memory, no owner, no lock.

go
package main

import (
	"fmt"
	"sync"
)

func main() {
	hits := map[string]int{}
	var wg sync.WaitGroup
	for i := 0; i < 2; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			hits["/home"]++ // unsynchronized write from two goroutines
		}()
	}
	wg.Wait()
	fmt.Println(hits["/home"])
}
text
$ go run -race .
1    ==================
2    WARNING: DATA RACE
3    Read at 0x00c00008a0f0 by goroutine 7:
4      runtime.mapaccess1_faststr()
5    Previous write at 0x00c00008a0f0 by goroutine 6:
6      main.main.func1()   .../main.go:15
7    ...
8    Found 2 data race(s)   -- exit status 66

Step 2: run the pool.

bash
go run -race ./workerpool
# after burst: queued=8 inFlight=0 shed=32     (exact numbers vary with scheduling)
# done=28 failed=0 shed=32

The burst of 40 TrySubmit calls fills the queue (capacity 8) almost instantly; the rest are shed with ErrQueueFull. The next 20 Submit calls wait for room (backpressure) and all succeed within the 1 s deadline because 4 workers drain 4 jobs every 50 ms (80 jobs/s), so the last of the 28 accepted jobs finishes after roughly 350 ms. Close drains the queue and waits.

Step 3: break the backpressure. Change make(chan Job, queue) to make(chan Job, 100000) and re-run: nothing is shed, the queue absorbs everything, and the latency of the last job is the whole backlog. Now imagine the jobs arrive faster than they finish for an hour.

Step 4: watch timeouts work, then break them. In main, change the pool's timeout from 200*time.Millisecond to 10*time.Millisecond and run again. Every job now exceeds its deadline, and because slow selects on ctx.Done() it gives up:

bash
go run ./workerpool
# done=0 failed=28 shed=32

Now replace the select in slow with time.Sleep(50 * time.Millisecond); return nil and run once more: done=28 failed=0. The handler ignores its context, so the deadline exists on paper only: each worker stays busy for the full 50 ms whatever the caller wanted. Restore both changes.

Step 5: provoke a goroutine leak. The suite passes as shipped:

bash
go test -race -count=5 ./workerpool
# ok  academy/concurrency-design/workerpool  1.6s

Delete p.Close() from TestCancelStopsWorkers: it still passes, because cancel() reaches every worker through case <-ctx.Done(): return. Now also delete that case from worker. The workers can only stop when the queue is closed, nobody closes it, and the test fails:

text
1    main_test.go:62: goroutine leak: before=2 after=10
2    FAIL  academy/concurrency-design/workerpool

Step 6: size it with Little's law. With a handler time of 50 ms and 4 workers, the pool's maximum throughput is 4 / 0.05 = 80 jobs/s. Submit at 120 jobs/s for 5 s (a loop with time.Sleep(time.Second/120)) and confirm: the queue stays full and Submit waits; at 60 jobs/s it stays near empty.

Part B: Laravel overlapping jobs and atomic locks ​

Setup. A Laravel 13 app with CACHE_STORE=redis and QUEUE_CONNECTION=redis; copy LockDemo.php into app/Console/Commands, SyncSupplierStock.php into app/Jobs (with a stub SupplierClient whose stockFor() sleeps 10 s), and run a migration adding supplier_id and supplier_stock to products.

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;

// Lab command: run it in two or three terminals at the same time.
#[Signature('lab:lock {mode=block : block|try|funnel} {--seconds=5}')]
#[Description('Show what an atomic cache lock does under concurrency')]
final class LockDemo extends Command
{
    public function handle(): int
    {
        $pid = getmypid();
        $seconds = (int) $this->option('seconds');

        return match ($this->argument('mode')) {
            'try' => $this->tryOnce($pid, $seconds),
            'funnel' => $this->funnel($pid, $seconds),
            default => $this->block($pid, $seconds),
        };
    }

    // Non-blocking: the loser gives up at once (good for "skip if busy").
    private function tryOnce(int $pid, int $seconds): int
    {
        $lock = Cache::lock('lab:report', 30);

        if (! $lock->get()) {
            $this->warn("[$pid] busy, skipping");

            return self::SUCCESS;
        }

        try {
            $this->info("[$pid] got the lock, owner=".$lock->owner());
            sleep($seconds);
        } finally {
            $lock->release(); // only the owner token can release it
        }

        return self::SUCCESS;
    }

    // Blocking with a timeout: wait up to 3 s, then fail loudly.
    private function block(int $pid, int $seconds): int
    {
        try {
            Cache::lock('lab:report', 30)->block(3, function () use ($pid, $seconds) {
                $this->info("[$pid] working");
                sleep($seconds);
            });
        } catch (LockTimeoutException) {
            $this->error("[$pid] gave up after 3 s");

            return self::FAILURE;
        }

        return self::SUCCESS;
    }

    // Bounded parallelism: at most 2 holders at a time across all servers.
    private function funnel(int $pid, int $seconds): int
    {
        Cache::funnel('lab:exports')
            ->limit(2)
            ->releaseAfter(60)
            ->block(10)
            ->then(function () use ($pid, $seconds) {
                $this->info("[$pid] slot acquired");
                sleep($seconds);
            }, function () use ($pid) {
                $this->warn("[$pid] no slot within 10 s");
            });

        return self::SUCCESS;
    }
}

Step 1: a non-blocking lock. In two terminals within one second:

text
     Terminal 1                                  Terminal 2
1    php artisan lab:lock try --seconds=10
2    [4101] got the lock, owner=Fb8x...          php artisan lab:lock try
3                                                [4107] busy, skipping

Step 2: a blocking lock with a timeout. Run lab:lock block --seconds=10 in terminal 1 and lab:lock block in terminal 2. Expected: terminal 2 prints gave up after 3 s (a LockTimeoutException). Run it again with --seconds=2 in terminal 1: terminal 2 now waits about 2 s and then prints working.

Step 3: a funnel (semaphore). Start lab:lock funnel --seconds=8 in three terminals. Expected: two print slot acquired, the third waits and acquires a slot when one finishes (within its 10 s block).

Step 4: overlapping jobs. In Tinker, dispatch the same job three times for two products of the same supplier, then start two workers:

bash
php artisan tinker --execute="App\Jobs\SyncSupplierStock::dispatch(App\Models\Product::find(1)); App\Jobs\SyncSupplierStock::dispatch(App\Models\Product::find(1)); App\Jobs\SyncSupplierStock::dispatch(App\Models\Product::find(2));"
php artisan queue:work --timeout=60   # terminal 1
php artisan queue:work --timeout=60   # terminal 2

Expected: the second dispatch for product 1 is silently dropped by ShouldBeUnique (two jobs on the queue, not three). The two queued jobs share supplier:<id>, so one runs and the other is released by WithoutOverlapping and retried 30 s later; php artisan queue:failed stays empty because #[Tries(5)] leaves room for releases.

Step 5: the four documented traps. (1) Remove #[Tries(5)]: the released job fails immediately with MaxAttemptsExceededException, because an overlap release counts as an attempt and Tries defaults to 1. (2) Remove expireAfter(180) and kill a worker with kill -9 mid-job: the middleware's constructor defaults expiresAfter to 0 (no expiry, per the framework source), so the lock outlives the dead worker and every later job for that supplier is released until it runs out of attempts or you clear the lock. (3) Remove the WithoutOverlapping middleware, make the stub sleep 100 s, keep retry_after at 90 and start both workers with --timeout=120: after 90 s the second worker picks up the same job while the first is still running. Put the middleware back and the second copy is only released, which is why the overlap lock and the timeout rule are designed to work together. (4) Switch CACHE_STORE=file and run the workers on two machines (or containers with separate disks): neither uniqueness nor overlap is enforced, because "all servers must be communicating with the same central cache server".

Common misconceptions ​

BeliefReality
Concurrency means parallelismConcurrency is structure (independent activities); parallelism is simultaneous execution. One core can run concurrent code.
More workers always means more throughputOnly until the bottleneck saturates; after that, more workers lengthen its queue (Little's law).
PHP has no concurrency problemsEvery FPM worker, queue worker and server is concurrent; races move to the database, cache and APIs.
Channels make Go code race-freeOnly for values you transfer; shared pointers sent over channels still race.
A lock with a TTL guarantees mutual exclusionA paused holder can outlive its lease; correctness needs fencing tokens or a lock-free design.
An unbounded queue protects the systemIt converts overload into memory growth and unbounded latency.
Double-checked locking is a cheap optimizationWithout proper memory ordering it publishes half-built objects; use sync.Once.
Being inside a transaction prevents lost updatesPlain reads take no locks at the default levels; use atomic updates, FOR UPDATE or versions.
ShouldBeUnique stops a job from running twiceIt stops duplicate queueing; WithoutOverlapping stops concurrent runs; neither replaces idempotency.
No deadlock means the design is liveLivelock, starvation and priority inversion also stop progress.
The race detector proves there are no racesIt finds only races on paths executed during the run.
Octane is just a faster PHP-FPMIt keeps the app in memory; singletons and statics leak state across requests.

Cheat sheet ​

TopicWhat to remember
DefinitionsConcurrency = dealing with many things; parallelism = doing many things; asynchrony = not waiting now
First design stepDraw the dependency graph; parallelize independent branches only
OwnershipEvery mutable value has one owner or one guard; write it next to the field
PreferImmutable messages, confinement, atomic store operations
QueuesBounded, with a policy when full: wait (backpressure), reject (shed), or drop
WaitsEvery wait has a timeout or a cancellation (context, block(n), --timeout)
LocksShort, never across I/O, acquired in one global order
Lost updateAtomic update > FOR UPDATE > version check + retry
RetriesExponential backoff with jitter; capped; on idempotent operations only
Go fan-outerrgroup.WithContext + SetLimit; write results by index
Go lazy initsync.Once, never hand-written double-checked locking
Laravel concurrency unitThe queue worker process; scale with numprocs / Horizon
Laravel guaranteesShouldBeUnique (queued), WithoutOverlapping (running), funnel (N), onOneServer (cron)
Laravel timeouts--timeout < retry_after; Horizon timeout > job timeout
DistributedLock for efficiency is fine; for correctness add fencing or avoid the lock
SizingL = λW; workers ≥ arrival rate × service time
Testing-race, -count, synctest, goleak, property tests, two real processes
WatchGoroutine count, queue depth, oldest job age, lock waits, retries

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A dashboard makes three independent 300 ms queries. What is the latency with sequential code, and with fan-out/fan-in? Must-know ​

Answer

Answer: About 900 ms sequentially and about 300 ms (the slowest) with fan-out/fan-in, plus a little overhead. In Laravel, Concurrency::run adds process start-up cost; in Go, errgroup adds almost none.

2 — Your Go handler uses a mutex around every map access. Can it still have a race condition? Must-know ​

Answer

Answer: Yes: a check-then-act sequence split across two critical sections ("is it free?" then "book it") is a race condition without being a data race. Make the check and the act one critical section or one atomic store operation.

3 — Name the four Coffman conditions and the one that lock ordering breaks. Must-know ​

Answer

Answer: Mutual exclusion, hold and wait, no preemption, circular wait. A global lock order breaks circular wait.

4 — Two workers retry a lock every 100 ms and never succeed. What is this, and what fixes it? Important ​

Answer

Answer: Livelock. Randomized (jittered) exponential backoff, and a cap on retries.

5 — Why is a 100,000-slot buffered channel usually a design smell? Important ​

Answer

Answer: It is effectively unbounded: it hides overload, grows memory and latency, and removes backpressure. Choose a small bound and an explicit policy when full.

6 — What is the difference between ShouldBeUnique and WithoutOverlapping in Laravel? Important ​

Answer

Answer: ShouldBeUnique takes a lock at dispatch so a second copy is not queued; WithoutOverlapping takes a lock when the job runs so two copies for the same key do not run at once (the second is released back to the queue, which counts as an attempt).

7 — Why can a job run twice even with WithoutOverlapping? Important ​

Answer

Answer: The lock can expire (expireAfter, crashed worker), the job can be retried after a failure that happened after its side effect, or --timeout can exceed retry_after so the queue re-delivers it while it still runs. Hence idempotency.

8 — When is a Redis lock acceptable, and when do you need a fencing token? Good to know ​

Answer

Answer: Acceptable when the lock is for efficiency (avoiding duplicate work). For correctness (two holders would corrupt data), the storage must reject writes from a stale holder using a monotonically increasing fencing token, or the design should rely on a unique constraint or conditional update instead.

9 — A queue receives 50 jobs/s and each takes 0.4 s. How many workers do you need at minimum? Must-know ​

Answer

Answer: λ × W = 50 × 0.4 = 20 workers busy on average; provision more (for example 25–30) for variance and spikes.

10 — Why is a singleton that receives the Request in its constructor a bug under Octane but not under PHP-FPM? Important ​

Answer

Answer: Under FPM every request builds a new container, so the singleton is per request. Octane boots once per worker and reuses the container, so the singleton keeps the first request it saw. Use scoped or pass request data as method arguments.

11 — What does errgroup.WithContext do on the first error? Must-know ​

Answer

Answer: It cancels the derived context, so the other goroutines (which must observe ctx) stop early; Wait returns the first error.

12 — What can the race detector not tell you? Important ​

Answer

Answer: Races on code paths that did not execute, race conditions at the business level that involve no unsynchronized memory access (for example two processes and a database), and deadlocks or livelocks.

Glossary ​

TermMeaning
ConcurrencyStructuring a system as independently executing activities
ParallelismSimultaneous execution of computations on multiple processors
AsynchronyCalling style where the caller does not wait for completion
Process / thread / goroutineOS-isolated program instance / OS-scheduled flow sharing memory / Go runtime-scheduled lightweight flow
Shared memoryActivities communicate by reading and writing common variables
Message passingActivities communicate by sending values; state stays private
CSPCommunicating Sequential Processes, Hoare 1978: processes synchronizing through input/output
Actor modelHewitt 1973: actors with private state reacting to messages in a mailbox
ChannelGo's typed conduit between goroutines; unbuffered (rendezvous) or buffered (bounded queue)
selectGo statement that waits on several channel operations
context.ContextGo value carrying deadline, cancellation and request-scoped values
MutexLock allowing one holder at a time
SemaphoreCounter of permits limiting concurrent use of a resource
MonitorObject whose operations run with mutual exclusion, with condition waits
Read-write lockLock allowing many readers or one writer (sync.RWMutex, FOR SHARE)
Critical sectionCode that must not run concurrently with itself on the same data
Atomic operation / CASIndivisible operation; compare-and-swap writes only if the value is unchanged
Happens-beforeOrdering relation in a memory model that makes writes visible to reads
Race conditionCorrectness depends on uncontrolled timing
Data raceConcurrent unsynchronized access to the same memory, at least one write
Lost updateRead-modify-write that overwrites a concurrent update
DeadlockCycle of activities each waiting for another
Coffman conditionsMutual exclusion, hold and wait, no preemption, circular wait
LivelockActivities keep reacting without progress
StarvationAn activity never obtains a needed resource
Priority inversionHigh-priority task waits on a low-priority task's resource
Priority inheritanceLock holder temporarily gets the priority of its highest waiter
ABA problemA value returns to A after changes; a value comparison misses it
OwnershipExactly one activity may mutate a piece of state at a time
Thread confinementState reachable from only one thread or process
ImmutabilityState that cannot change after construction
Copy-on-writeWriters create a new version and swap a reference; readers keep snapshots
Producer/consumerQueue decoupling producers from consumers
Worker poolFixed number of workers sharing a job queue
PipelineStages connected by queues or channels
Fan-out / fan-inDistribute work to several workers / merge several results
Future / promisePlaceholder for a result computed concurrently
ReactorEvent loop dispatching handlers on I/O readiness
ProactorDispatching handlers on completion of asynchronous operations
Active objectObject with its own thread executing queued method requests
Leader/followersThreads take turns as the event-waiting leader
Double-checked lockingLazy-init idiom; broken without memory ordering; use sync.Once
Bounded queueQueue with a fixed capacity
BackpressureSlowing producers when consumers cannot keep up
Load sheddingRejecting work when overloaded (429, 503, ErrQueueFull)
Timeout / deadline / cancellationLimit on waiting / absolute end time / signal to stop work
Idempotency / idempotency keyRepeating an operation has no additional effect / client-supplied ID to dedupe
Optimistic concurrencyDetect conflicts on write with a version; retry
Pessimistic lockingLock before reading to prevent conflicts (FOR UPDATE)
Distributed lock / leaseLock held in a shared service / lock with an expiry time
Fencing tokenIncreasing number the storage checks to reject stale lock holders
Leader electionChoosing exactly one active node
Little's lawL = λW: in-flight = arrival rate × time in system
Goroutine leakGoroutine blocked forever, never collected
Queue depthNumber of jobs waiting
Race detectorGo's -race instrumentation that reports data races at runtime
testing/synctestGo package running tests in a bubble with a fake clock
errgroupgolang.org/x/sync/errgroup: goroutine group with error propagation, cancel and limit
singleflightGo package collapsing concurrent duplicate calls
PHP-FPMPHP FastCGI Process Manager: pool of worker processes, one request each
pm.max_childrenFPM's cap on worker processes
FibersPHP 8.1 interruptible functions for cooperative concurrency
pcntlPHP process-control extension (fork, signals); CLI only
Concurrency::runLaravel facade method running closures in child processes
Cache::lockLaravel atomic lock in the cache store, with owner token
Cache::funnelLaravel limiter allowing at most N concurrent holders
WithoutOverlappingLaravel job middleware: one running job per key
ShouldBeUniqueLaravel job contract: one queued job per unique ID
lockForUpdateLaravel query builder FOR UPDATE row lock
HorizonLaravel's Redis queue supervisor with balancing and metrics
OctaneLaravel's long-lived application server integration (FrankenPHP, Swoole, RoadRunner)
Prefetch (basic.qos)RabbitMQ limit on unacknowledged messages per consumer
Consumer group / partitionKafka unit of parallel consumption and ordering

References ​

Built by Morteza Negahi