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 for | Go to |
|---|---|
| Every term and hazard in a few tables | Everything in one minute |
| Why concurrency needs design, not just keywords | Why concurrency design exists |
| Dijkstra, Hoare's CSP, actors, Pike, Schmidt's patterns, SWEBOK | Where it comes from |
| Concurrency vs parallelism, shared memory vs messages, races, deadlock, ABA, backpressure, idempotency | The concepts, one by one |
| Worker pool, pipeline, futures, reactor/proactor, active object, monitor, read-write lock, double-checked locking, leader/followers | The pattern catalogue |
| The Go model, the PHP/Laravel model, locks across processes, Little's law, error messages | Mechanics |
| Idiomatic code | Go, Laravel |
| Overselling, double-running jobs, leaking goroutines, Octane state | Solving the classic problems |
| Race detector, deterministic schedulers, property tests, leak checks | Testing concurrent designs |
| Goroutine leaks, queue depth, lock waits | Observability |
| Which model for which workload | Choosing |
| Monolith → modular monolith → microservices → distributed | In architecture |
| Go worker pool with backpressure; Laravel overlap and lock demo | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concepts section.
| Term | In plain words | Tiny example | Design question it raises |
|---|---|---|---|
| Concurrency | Structuring a program as independent activities | A server handles 1,000 open connections | What can proceed independently? |
| Parallelism | Running computations at the same instant on several cores | Resize 8 images on 8 cores | Is there CPU work worth splitting? |
| Asynchrony | Starting work now and collecting the result later | Dispatch a queued email, return 202 | Who waits for the result, and how long? |
| Shared memory | Activities read and write the same variables | Two goroutines update one map | Who guards it, and with what lock? |
| Message passing | Activities own their state and send copies | Workers receive jobs over a channel or a queue | Who owns the state now? |
| CSP | Hoare's model: sequential processes that communicate over channels | Go goroutines + channels | Which channels, which direction, who closes? |
| Actor | An entity with a private mailbox and state; reacts to one message at a time | Erlang process, Akka actor | Which messages, what happens on overload? |
| Synchronization | Ordering events between activities | Mutex, channel send/receive, WaitGroup | What must happen before what? |
The hazards.
| Hazard | In plain words | Tiny example | Design fix |
|---|---|---|---|
| Race condition | The result depends on who runs first | Two requests both see "1 seat left" | Atomic operation, lock, or one owner |
| Data race | Unsynchronized access to the same memory, at least one write | counter++ from two goroutines | Mutex, atomic, or confinement |
| Lost update | A read-modify-write erases another's write | Two stock decrements, one survives | Atomic update, row lock, version check |
| Deadlock | Everyone waits for someone else, forever | A holds X wants Y, B holds Y wants X | One global lock order, timeouts |
| Livelock | Everyone keeps reacting and nobody progresses | Two retries that always collide | Randomized backoff (jitter) |
| Starvation | One activity never gets its turn | Writers starved by a stream of readers | Fair queueing, priorities, limits |
| Priority inversion | A high-priority task waits on a low one that cannot run | Mars Pathfinder bus task | Priority inheritance, short critical sections |
| ABA | A value changes A→B→A and a check believes nothing happened | Lock-free stack pop | Version counters, tagged pointers, GC |
The patterns. Unpacked in the pattern catalogue.
| Pattern | Use it when | Go | Laravel / PHP |
|---|---|---|---|
| Worker pool / producer-consumer | Many jobs, limited resources | N goroutines reading one channel | queue:work processes, Horizon |
| Pipeline | Work flows through stages | Stages joined by channels | Job chains, Bus::chain |
| Fan-out / fan-in | Independent calls, then combine | errgroup, merge function | Concurrency::run, Bus::batch |
| Future / promise | Start now, read later | A channel of one result | Concurrency::run, Guzzle promises |
| Monitor | Shared object, one caller at a time | Struct + sync.Mutex | Row lock with lockForUpdate |
| Read-write lock | Many readers, rare writers | sync.RWMutex | sharedLock vs lockForUpdate |
| Immutability / copy-on-write | Readers must never block | atomic.Pointer to a frozen snapshot | readonly classes, value objects |
| Thread confinement | One owner per piece of state | Owner goroutine | One process per request (PHP-FPM) |
| Reactor / proactor | Many connections, few threads | Go 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 design | Concurrent design |
|---|---|
| One timeline, easy to read and debug | Many timelines, bugs depend on timing |
| No shared-state questions | Every mutable value needs an owner or a guard |
| Latency = sum of all waits | Latency = longest wait on the critical path |
| Uses one core | Can use all cores and overlap I/O |
| Overload makes it slow | Overload without bounds makes it fall over (memory, connections) |
| Tests are deterministic | Tests must provoke interleavings (race detector, stress, deterministic schedulers) |
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
- "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.
- "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.
- "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).
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.
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 scopeReal 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.
| Property | Shared memory + locks | CSP (channels) | Actors (mailboxes) |
|---|---|---|---|
| Where state lives | Shared, guarded | Private to a goroutine | Private to an actor |
| Communication | Read/write variables | Synchronous or buffered channel | Asynchronous mailbox |
| Typical failure | Forgotten lock, deadlock | Goroutine leak, blocked send | Mailbox overflow, lost messages |
| Back-pressure | Lock contention | Unbuffered/bounded channel blocks | Must be added (bounded mailbox) |
| Products | Go sync, Java synchronized, database row locks | Go, Clojure core.async, Occam | Erlang/Elixir, Akka, Orleans |
| Across machines | Distributed lock (hard) | Broker queues | Erlang 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).
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 msReal 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.
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 allReal 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.
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 lostReal 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).
-- 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, retryThe 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.
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 1213Real 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.
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 msReal 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).
| Problem | Symptom | Design fix |
|---|---|---|
| Livelock | CPU busy, throughput zero | Exponential backoff with jitter; cap retries |
| Starvation | One queue or tenant always waits | Fair scheduling, per-queue minimum workers (Horizon minProcesses), per-tenant limits |
| Priority inversion | Urgent task slow only when a slow task holds a shared lock | Priority 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).
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 BReal 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.
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 locksReal 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.
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 wantsReal 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).
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 #1Real 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.
| Pattern | Intent | When | Main hazard | Go | Laravel / PHP |
|---|---|---|---|---|---|
| Producer/consumer | Decouple the rate of producing from consuming via a queue | Bursty input, steady processing | Unbounded queue | Buffered channel | Queue + queue:work |
| Worker pool | Fixed number of workers share a job queue | Limit concurrency on a resource | Pool deadlock on self-submission | N goroutines on one channel | numprocs, Horizon maxProcesses |
| Pipeline | Stages connected by queues, each does one step | Streaming transformation | Leaked stages on early exit | Channels + ctx.Done() | Job chains (Bus::chain) |
| Fan-out / fan-in | Split work across workers, then merge results | Independent sub-tasks | Unbounded fan-out | errgroup, merge | Concurrency::run, Bus::batch |
| Future / promise | A placeholder for a result computed concurrently | Start early, use later | Never-awaited futures, lost errors | Channel of one result | Concurrency::run, Guzzle promises |
| Reactor | One thread demultiplexes ready I/O events and dispatches handlers | Many connections, short handlers | A slow handler blocks everyone | Go netpoller (inside the runtime) | ReactPHP, Swoole event loop |
| Proactor | Start async operations; dispatch handlers on completion | OS with completion-based I/O (IOCP, io_uring) | Complex lifetimes | Hidden by the runtime | Swoole coroutines (similar effect) |
| Active object | Method calls become requests queued to an object's own thread | Serialize access without callers locking | Queue growth | Owner goroutine + request channel | A dedicated queue with one worker |
| Monitor | Object whose methods run under one lock, with condition waits | Shared object, simple invariants | Calling out while locked | Struct + sync.Mutex / sync.Cond | lockForUpdate on a row |
| Read-write lock | Many readers or one writer | Read-mostly data | Writer starvation, upgrade deadlock | sync.RWMutex | sharedLock / lockForUpdate |
| Double-checked locking | Lazy init with a lock only on first use | Expensive singleton | Broken without memory barriers | Use sync.Once instead | Not needed under FPM; container singletons |
| Immutability / copy-on-write | Share only frozen data; replace by swapping a pointer | Config, routing tables | Writers must serialize | atomic.Pointer[T] | readonly classes |
| Thread confinement | State reachable from one thread only | Per-request or per-owner state | Leaking a reference | Local variables, owner goroutine | Request-per-process FPM |
| Leader/followers | Threads take turns: one leader waits for events, hands off, becomes a follower | High-performance servers, avoids handoff queues | Complexity | Rare (runtime scheduler) | Not used directly |
| Thread-per-request | One thread/process per request | Simple servers | Resource exhaustion | One goroutine per request (net/http) | PHP-FPM pm.max_children |
| Semaphore / bulkhead | Cap concurrent use of a resource | Protect a DB or API | Permits never released | semaphore.Weighted, buffered channel | Cache::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.
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.
| Primitive | Design role | Typical use | Pitfall |
|---|---|---|---|
go f() | Start an activity | Per request, per worker | No owner → leak; no recover → crash |
Unbuffered chan T | Synchronous handoff (rendezvous) | Ownership transfer, signals | Both sides must be ready; easy partial deadlock |
Buffered chan T | Bounded queue | Worker pool input, semaphore | Buffer size is a design decision, not a tuning knob |
close(ch) | "No more values" broadcast | End of a stream | Only the sender closes; send on closed channel panics |
select | Wait on several events | Send-or-cancel, timeouts | default turns it non-blocking (busy loop risk) |
context.Context | Cancellation, deadlines, request values | First parameter of every blocking call | Not checking ctx.Done() in loops |
sync.Mutex | Monitor lock | Guard a few fields | Copying a mutex; calling out while locked |
sync.RWMutex | Read-write lock | Read-mostly maps | Recursive read locking |
sync.WaitGroup | Join N activities | Wait for workers to finish | Add inside the goroutine (too late) |
sync.Once | One-time init | Lazy singletons | Panics inside Do are not retried |
sync.Cond | Wait for a condition under a monitor | Rare; channels are usually clearer | Missed wake-ups without a loop |
sync/atomic | Lock-free counters, flags, CAS, pointers | Metrics, snapshots | ABA, mixing atomic and plain access |
errgroup.Group | Fan-out with first-error cancel and a limit | Parallel I/O calls | Ignoring the derived context |
semaphore.Weighted | Weighted permits | Memory- or cost-weighted work | Forgetting Release |
-race | Data race detector | CI, staging under load | Finds 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 / tool | What it is | Concurrency role | Key knobs |
|---|---|---|---|
| PHP-FPM worker | One OS process per in-flight request | Thread-per-request (process) | pm, pm.max_children |
| Queue worker | php artisan queue:work process | The main unit of background concurrency | Supervisor numprocs, --timeout, --max-jobs, retry_after |
| Horizon | Supervisor of Redis queue workers with balancing | Worker pool per queue | balance (auto, simple, false), minProcesses, maxProcesses, waits |
Concurrency::run | Closures run in child PHP processes | Fan-out / fan-in inside one request or command | Driver process (default), fork (CLI only), sync (tests); timeout |
Concurrency::defer | Closures run concurrently after the response is sent | Fire-and-forget fan-out | — |
Http::pool | Concurrent HTTP requests via Guzzle | I/O fan-out | Per-request timeouts |
Cache::lock | Atomic lock in the cache store | Mutex across processes and servers | TTL, block, owner token, restoreLock, refresh |
Cache::withoutOverlapping, Cache::funnel | Single-flight and N-at-a-time limits | Mutex / semaphore across servers | lockFor, waitFor, limit, releaseAfter, block |
WithoutOverlapping job middleware | Lock per key around a job | One running job per resource | releaseAfter, dontRelease, expireAfter, shared |
ShouldBeUnique | Lock taken at dispatch | One queued job per key | uniqueId, #[UniqueFor], uniqueVia, ShouldBeUniqueUntilProcessing |
Scheduler withoutOverlapping, onOneServer | Locks for scheduled tasks | Single-run cron across servers | Lock expiry (minutes) |
lockForUpdate / sharedLock | SELECT ... FOR UPDATE / FOR SHARE | Monitor on a row, inside DB::transaction | attempts for deadlock retry |
RateLimiter, Redis::throttle, Redis::funnel | Rate and concurrency limits | Protect downstream APIs | Keys, decay, limits |
| Octane | FrankenPHP, Swoole/Open Swoole or RoadRunner workers that keep the app in memory | Long-lived workers; Swoole task workers | --workers, --task-workers, --max-requests |
| Fibers (PHP 8.1) | Cooperative, single-threaded coroutines | Basis of async libraries (Revolt, Amp) | No parallelism by themselves |
pcntl | Unix process control (fork, signals) | CLI only; used by queue timeouts | Must 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:
| Need | Tool | Guarantee | Caveat |
|---|---|---|---|
| One writer per row | SELECT ... FOR UPDATE (lockForUpdate) | Held until commit by the database | Lock waits, deadlocks; keep transactions short |
| No lost updates without locks | Optimistic concurrency: version column, WHERE version = ?, HTTP If-Match/ETag | Conflicts detected on write | Retries under contention; see Optimistic vs Pessimistic |
| One holder across servers | Distributed lock (Cache::lock on Redis, Postgres advisory lock, etcd/ZooKeeper lease) | Mutual exclusion while the lease is valid | Lease can expire while the holder is paused |
| Safety even if the lease expired | Fencing token checked by the storage | Stale holders' writes are rejected | Storage must check the token |
| Exactly one active instance | Leader election (etcd, ZooKeeper, Kubernetes Lease, DB row) | One leader at a time (with fencing) | See Leader Election |
| Duplicates are harmless | Idempotency keys, inbox table, unique constraints | Effect happens once | Must cover every side effect |
| Parallel consumers with order | Kafka partitions; RabbitMQ single active consumer | Order per partition / per queue | Parallelism capped by partition count |
| Bounded consumer concurrency | RabbitMQ basic.qos prefetch, Kafka max.poll.records, worker count | Limits unacknowledged work | Too 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:
| Question | Formula | Example |
|---|---|---|
| How many requests are in flight? | L = λ × W | 400 req/s × 0.25 s = 100 concurrent requests |
| How many workers do I need? | workers ≥ λ × service time | 50 jobs/s × 0.6 s = 30 workers (+ headroom) |
| What throughput can a pool give? | λ_max = workers / W | 8 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 time | 2,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 / code | Where | Meaning | Design response |
|---|---|---|---|
fatal error: all goroutines are asleep - deadlock! | Go runtime | Every goroutine is blocked | Fix the protocol (who sends, who closes) |
fatal error: concurrent map writes | Go runtime | Unsynchronized map writes detected | Mutex, sync.Map, or one owner |
WARNING: DATA RACE | Go race detector (-race) | Two unsynchronized accesses, one a write | Add synchronization or confine |
context deadline exceeded / context canceled | Go context | Wait exceeded its deadline / caller cancelled | Expected; return early, do not retry blindly |
LockTimeoutException | Laravel Cache::lock(...)->block(), Cache::withoutOverlapping | Lock not acquired in time | Retry later, or skip |
LimiterTimeoutException | Laravel Cache::funnel without failure closure | No slot within block seconds | Release the job, back off |
MaxAttemptsExceededException | Laravel queue | Job used all attempts (overlap releases count) | Raise #[Tries], use retryUntil |
TimeoutExceededException | Laravel queue | Job ran longer than its timeout | Shorter work units, higher timeout below retry_after |
SQLSTATE 40P01 | PostgreSQL | Deadlock detected, transaction aborted | Retry the whole transaction; fix lock order |
SQLSTATE 40001 | PostgreSQL, others | Serialization failure | Retry the whole transaction |
MySQL 1213 / 1205 | InnoDB | Deadlock / lock wait timeout | Retry; 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.
// 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.
// 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).
// 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.
// 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.
// 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.
// 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 orctx.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.Servertimeouts,sql.DB.SetMaxOpenConns.net/httpalready runs one goroutine per connection; your handler should not add unbounded goroutines of its own. context.Contextis the cancellation tree. Pass it as the first argument of every function that blocks, derive timeouts per call, and checkctx.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/singleflightcollapses duplicate concurrent calls for the same key (cache stampede protection);go.uber.org/goleakfails a test that leaks goroutines;pgxpools,go-redispools and thedatabase/sqlpool 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
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
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
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
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
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, HorizonmaxProcesses), not by forking inside a job. Separate queues by priority so a slowreportsbacklog cannot starvepayments. - 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 inSyncSupplierStock. - Mind the counters. "Releasing an overlapping job back onto the queue will still increment the job's total number of attempts", and
Triesdefaults to 1, so aWithoutOverlappingjob without#[Tries]orretryUntilfails on its first overlap. UseexpireAfterso 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 theafter_commitqueue option) so the worker reads committed data. Concurrency::runis 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 theprocessdriver'stimeoutis the cancellation mechanism. Thesyncdriver 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
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Oversold stock (lost update) | Atomic conditional update | UPDATE ... SET stock = stock - ? WHERE stock >= ? | No lock held in the app, one round trip | Logic must fit in one statement |
| Oversold stock, complex rules | Pessimistic row lock | lockForUpdate in DB::transaction | Simple reasoning | Waits, deadlocks under contention |
| Concurrent edits of a document | Optimistic concurrency | version column or ETag + If-Match | No waiting; works over HTTP | Retries or user-visible conflicts |
| Same job runs twice at once | WithoutOverlapping / Cache::lock | Lock per resource key | Cheap, cross-server | Lock TTL vs job duration; needs idempotency anyway |
| Same job queued 1,000 times | ShouldBeUnique | Lock at dispatch by uniqueId | Queue stays small | Does not stop overlapping runs by itself |
| Cron runs on every server | onOneServer() + withoutOverlapping() | Cache lock per task | One run per tick | Shared cache required |
| Slow API overwhelmed by fan-out | Semaphore / funnel | errgroup.SetLimit, Cache::funnel | Protects the dependency | Adds queueing latency |
| Unbounded backlog | Bounded queue + backpressure / shedding | Buffered channel, 429, Horizon wait alerts | Predictable latency and memory | Some work is rejected |
| Goroutine leak | Cancellation everywhere | select on ctx.Done(), close by owner | Bounded resources | Discipline in every send/receive |
| Deadlock between locks | Global lock order + timeouts | Sort keys before locking; block(5) | Removes circular wait | Must know all locks up front |
| Duplicate side effect after retry | Idempotency key | Unique index + stored result | Safe retries | Storage and key expiry policy |
| Cache stampede | Single-flight | singleflight.Group, Cache::lock around recompute, Cache::flexible | One recompute per key | Waiters 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.
-- 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.
| Technique | Tool | What it finds | Limit |
|---|---|---|---|
| Race detection | go test -race | Data 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 / stress | go test -race -count=100, -cpu=1,4,8 | Rare interleavings | Probabilistic |
| Deterministic scheduling and fake time | testing/synctest (Go 1.25; experimental in 1.24) | Timeouts, retries, tickers without real sleeps | Only goroutines inside the "bubble" |
| Leak checks | goleak.VerifyNone(t), runtime.NumGoroutine() | Goroutines that never exit | Needs a quiescent end state |
| Property-based tests | testing/quick, pgregory.net/rapid | Invariants over random operation sequences (e.g. total balance constant) | Needs good invariants |
| Linearizability / model checking | Porcupine (Go), Jepsen, TLA+ | Distributed protocol bugs | Expensive; for core protocols |
| Two-process tests | Two artisan processes or two HTTP clients | Locks, unique jobs, row locks really hold | Needs real Redis/DB |
| Fakes | Queue::fake(), Bus::fake(), Concurrency sync driver | Dispatch logic, without concurrency | Does 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.
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
| Signal | Go | Laravel | Alarm when |
|---|---|---|---|
| Live goroutines / workers | runtime.NumGoroutine(), pprof goroutine profile | Horizon processes, Supervisor status | Grows without traffic growth (leak) |
| Queue depth | len(ch), pool Stats() | Horizon dashboard, queue:monitor | Grows for minutes (λ in > λ out) |
| Wait time / age of oldest job | Timestamp at enqueue | Horizon waits thresholds and long-wait notifications | Above the SLO |
| In-flight work | Atomic gauge | Running jobs | Near the pool limit for long periods |
| Lock contention | pprof mutex and block profiles | Lock acquisition failures, LockTimeoutException rate | Rising waits or timeouts |
| Retries and conflicts | Counter per error type | Failed jobs, MaxAttemptsExceededException, deadlock retries | Spikes after deploys |
| Rejections | ErrQueueFull counter, HTTP 429/503 | Rate limiter hits | Sustained 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Several independent slow I/O calls in one request | Fan-out / fan-in with a deadline | Go errgroup + SetLimit; Laravel Concurrency::run or Http::pool | Latency = slowest call, not the sum |
| Work the user does not wait for | Asynchrony via a queue | Dispatch after commit; idempotent job | Short responses, retries for free |
| CPU-heavy batch | Parallel worker pool sized to cores | GOMAXPROCS workers; separate queue for heavy jobs | More workers than cores only adds switching |
| Read-mostly shared config | Immutable snapshot | atomic.Pointer, reload by swap | Readers never block |
| Small shared counter or map | Monitor | sync.Mutex; atomic for a single number | Simplest correct option |
| Complex state with many operations | Owner goroutine / active object | Request channel, bounded | Invariants live in one place |
| One running instance per resource | Per-key lock | WithoutOverlapping, Cache::lock, FOR UPDATE | Serializes only what conflicts |
| Correctness-critical exclusion across servers | Avoid the lock; or lease + fencing | Unique constraints, conditional updates, fencing tokens | Lease expiry breaks plain locks |
| Contended hot row | Atomic update, or partition the counter | Sharded counters, append-only ledger | Locks serialize every writer |
| Ordered processing per key | Partition by key | Kafka key → partition; one worker per key group | Order and parallelism together |
| Bursty producer, steady consumer | Bounded producer/consumer | Backpressure or shedding policy | Predictable memory and latency |
| Many connections, small handlers | Event loop / goroutine-per-connection | Go net/http; Swoole/ReactPHP for PHP | Cheap 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.
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 attemptsExample: 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×
| Scale | Concurrency design | Typical change |
|---|---|---|
| 1× (one server) | Goroutine/FPM per request, one worker pool, DB arbitrates | Atomic updates and unique constraints; -race in CI |
| 10× (several servers) | Shared cache for locks, Horizon balancing, separate queues per priority | Cache::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 locks | Partition 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.
cd docs/snippets/design/concurrency-design/go
gofmt -l . && go vet ./... # no output, no errors// 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.
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"])
}$ 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 66Step 2: run the pool.
go run -race ./workerpool
# after burst: queued=8 inFlight=0 shed=32 (exact numbers vary with scheduling)
# done=28 failed=0 shed=32The 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:
go run ./workerpool
# done=0 failed=28 shed=32Now 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:
go test -race -count=5 ./workerpool
# ok academy/concurrency-design/workerpool 1.6sDelete 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:
1 main_test.go:62: goroutine leak: before=2 after=10
2 FAIL academy/concurrency-design/workerpoolStep 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
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:
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, skippingStep 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:
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 2Expected: 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
| Belief | Reality |
|---|---|
| Concurrency means parallelism | Concurrency is structure (independent activities); parallelism is simultaneous execution. One core can run concurrent code. |
| More workers always means more throughput | Only until the bottleneck saturates; after that, more workers lengthen its queue (Little's law). |
| PHP has no concurrency problems | Every FPM worker, queue worker and server is concurrent; races move to the database, cache and APIs. |
| Channels make Go code race-free | Only for values you transfer; shared pointers sent over channels still race. |
| A lock with a TTL guarantees mutual exclusion | A paused holder can outlive its lease; correctness needs fencing tokens or a lock-free design. |
| An unbounded queue protects the system | It converts overload into memory growth and unbounded latency. |
| Double-checked locking is a cheap optimization | Without proper memory ordering it publishes half-built objects; use sync.Once. |
| Being inside a transaction prevents lost updates | Plain reads take no locks at the default levels; use atomic updates, FOR UPDATE or versions. |
ShouldBeUnique stops a job from running twice | It stops duplicate queueing; WithoutOverlapping stops concurrent runs; neither replaces idempotency. |
| No deadlock means the design is live | Livelock, starvation and priority inversion also stop progress. |
| The race detector proves there are no races | It finds only races on paths executed during the run. |
| Octane is just a faster PHP-FPM | It keeps the app in memory; singletons and statics leak state across requests. |
Cheat sheet
| Topic | What to remember |
|---|---|
| Definitions | Concurrency = dealing with many things; parallelism = doing many things; asynchrony = not waiting now |
| First design step | Draw the dependency graph; parallelize independent branches only |
| Ownership | Every mutable value has one owner or one guard; write it next to the field |
| Prefer | Immutable messages, confinement, atomic store operations |
| Queues | Bounded, with a policy when full: wait (backpressure), reject (shed), or drop |
| Waits | Every wait has a timeout or a cancellation (context, block(n), --timeout) |
| Locks | Short, never across I/O, acquired in one global order |
| Lost update | Atomic update > FOR UPDATE > version check + retry |
| Retries | Exponential backoff with jitter; capped; on idempotent operations only |
| Go fan-out | errgroup.WithContext + SetLimit; write results by index |
| Go lazy init | sync.Once, never hand-written double-checked locking |
| Laravel concurrency unit | The queue worker process; scale with numprocs / Horizon |
| Laravel guarantees | ShouldBeUnique (queued), WithoutOverlapping (running), funnel (N), onOneServer (cron) |
| Laravel timeouts | --timeout < retry_after; Horizon timeout > job timeout |
| Distributed | Lock for efficiency is fine; for correctness add fencing or avoid the lock |
| Sizing | L = λW; workers ≥ arrival rate × service time |
| Testing | -race, -count, synctest, goleak, property tests, two real processes |
| Watch | Goroutine count, queue depth, oldest job age, lock waits, retries |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Concurrency | Structuring a system as independently executing activities |
| Parallelism | Simultaneous execution of computations on multiple processors |
| Asynchrony | Calling style where the caller does not wait for completion |
| Process / thread / goroutine | OS-isolated program instance / OS-scheduled flow sharing memory / Go runtime-scheduled lightweight flow |
| Shared memory | Activities communicate by reading and writing common variables |
| Message passing | Activities communicate by sending values; state stays private |
| CSP | Communicating Sequential Processes, Hoare 1978: processes synchronizing through input/output |
| Actor model | Hewitt 1973: actors with private state reacting to messages in a mailbox |
| Channel | Go's typed conduit between goroutines; unbuffered (rendezvous) or buffered (bounded queue) |
select | Go statement that waits on several channel operations |
context.Context | Go value carrying deadline, cancellation and request-scoped values |
| Mutex | Lock allowing one holder at a time |
| Semaphore | Counter of permits limiting concurrent use of a resource |
| Monitor | Object whose operations run with mutual exclusion, with condition waits |
| Read-write lock | Lock allowing many readers or one writer (sync.RWMutex, FOR SHARE) |
| Critical section | Code that must not run concurrently with itself on the same data |
| Atomic operation / CAS | Indivisible operation; compare-and-swap writes only if the value is unchanged |
| Happens-before | Ordering relation in a memory model that makes writes visible to reads |
| Race condition | Correctness depends on uncontrolled timing |
| Data race | Concurrent unsynchronized access to the same memory, at least one write |
| Lost update | Read-modify-write that overwrites a concurrent update |
| Deadlock | Cycle of activities each waiting for another |
| Coffman conditions | Mutual exclusion, hold and wait, no preemption, circular wait |
| Livelock | Activities keep reacting without progress |
| Starvation | An activity never obtains a needed resource |
| Priority inversion | High-priority task waits on a low-priority task's resource |
| Priority inheritance | Lock holder temporarily gets the priority of its highest waiter |
| ABA problem | A value returns to A after changes; a value comparison misses it |
| Ownership | Exactly one activity may mutate a piece of state at a time |
| Thread confinement | State reachable from only one thread or process |
| Immutability | State that cannot change after construction |
| Copy-on-write | Writers create a new version and swap a reference; readers keep snapshots |
| Producer/consumer | Queue decoupling producers from consumers |
| Worker pool | Fixed number of workers sharing a job queue |
| Pipeline | Stages connected by queues or channels |
| Fan-out / fan-in | Distribute work to several workers / merge several results |
| Future / promise | Placeholder for a result computed concurrently |
| Reactor | Event loop dispatching handlers on I/O readiness |
| Proactor | Dispatching handlers on completion of asynchronous operations |
| Active object | Object with its own thread executing queued method requests |
| Leader/followers | Threads take turns as the event-waiting leader |
| Double-checked locking | Lazy-init idiom; broken without memory ordering; use sync.Once |
| Bounded queue | Queue with a fixed capacity |
| Backpressure | Slowing producers when consumers cannot keep up |
| Load shedding | Rejecting work when overloaded (429, 503, ErrQueueFull) |
| Timeout / deadline / cancellation | Limit on waiting / absolute end time / signal to stop work |
| Idempotency / idempotency key | Repeating an operation has no additional effect / client-supplied ID to dedupe |
| Optimistic concurrency | Detect conflicts on write with a version; retry |
| Pessimistic locking | Lock before reading to prevent conflicts (FOR UPDATE) |
| Distributed lock / lease | Lock held in a shared service / lock with an expiry time |
| Fencing token | Increasing number the storage checks to reject stale lock holders |
| Leader election | Choosing exactly one active node |
| Little's law | L = λW: in-flight = arrival rate × time in system |
| Goroutine leak | Goroutine blocked forever, never collected |
| Queue depth | Number of jobs waiting |
| Race detector | Go's -race instrumentation that reports data races at runtime |
testing/synctest | Go package running tests in a bubble with a fake clock |
| errgroup | golang.org/x/sync/errgroup: goroutine group with error propagation, cancel and limit |
singleflight | Go package collapsing concurrent duplicate calls |
| PHP-FPM | PHP FastCGI Process Manager: pool of worker processes, one request each |
pm.max_children | FPM's cap on worker processes |
| Fibers | PHP 8.1 interruptible functions for cooperative concurrency |
| pcntl | PHP process-control extension (fork, signals); CLI only |
Concurrency::run | Laravel facade method running closures in child processes |
Cache::lock | Laravel atomic lock in the cache store, with owner token |
Cache::funnel | Laravel limiter allowing at most N concurrent holders |
WithoutOverlapping | Laravel job middleware: one running job per key |
ShouldBeUnique | Laravel job contract: one queued job per unique ID |
lockForUpdate | Laravel query builder FOR UPDATE row lock |
| Horizon | Laravel's Redis queue supervisor with balancing and metrics |
| Octane | Laravel's long-lived application server integration (FrankenPHP, Swoole, RoadRunner) |
Prefetch (basic.qos) | RabbitMQ limit on unacknowledged messages per consumer |
| Consumer group / partition | Kafka unit of parallel consumption and ordering |
References
- IEEE Computer Society, Guide to the Software Engineering Body of Knowledge (SWEBOK) V4.0, 2024, Software Design KA §3.1 Concurrency and Software Construction KA §4.10 Concurrency Primitives. PDF
- C. A. R. Hoare, "Communicating Sequential Processes", Communications of the ACM 21(8), August 1978. PDF (CMU course copy)
- The Go Memory Model, version of June 6, 2022. go.dev/ref/mem
- Effective Go, Concurrency section. go.dev/doc/effective_go
- Andrew Gerrand, "Share Memory By Communicating", The Go Blog, 13 July 2010. go.dev/blog/codelab-share
- Andrew Gerrand, "Concurrency is not parallelism" (Rob Pike's Waza talk), The Go Blog, 16 January 2013. go.dev/blog/waza-talk; slides: go.dev/talks/2012/waza.slide
- Sameer Ajmani, "Go Concurrency Patterns: Pipelines and cancellation", The Go Blog, 13 March 2014. go.dev/blog/pipelines
- Sameer Ajmani, "Go Concurrency Patterns: Context", The Go Blog, 29 July 2014. go.dev/blog/context
- Dmitry Vyukov and Andrew Gerrand, "Introducing the Go Race Detector", The Go Blog, 26 June 2013. go.dev/blog/race-detector; Data Race Detector
- Go packages: sync, sync/atomic, errgroup, semaphore, x/time/rate, testing/synctest, runtime/pprof, goleak; Go 1.25 release notes
- D. C. Schmidt, "Reactor", "Proactor" (with Harrison, Pyarali, Jordan) and "Active Object" (with Lavender) pattern papers; Schmidt, O'Ryan, Kircher, Pyarali, Buschmann, "Leader/Followers", 2000. Reactor, Proactor, Active Object, Leader/Followers
- D. Bacon, J. Bloch, J. Bogda, et al., "The 'Double-Checked Locking is Broken' Declaration". cs.umd.edu/~pugh
- Mike Jones (relaying Glenn Reeves, JPL), "What really happened on Mars Rover Pathfinder", 1997. cs.cornell.edu
- Martin Kleppmann, "How to do distributed locking", 8 February 2016. martin.kleppmann.com
- Doug Lea, Concurrent Programming in Java (2nd ed., 1999) and Brian Goetz et al., Java Concurrency in Practice (2006): named as secondary influences, not quoted.
- PHP manual: Fibers, Process Control (pcntl), FPM, FPM configuration
- Laravel 13: Concurrency, Queues, Cache: atomic locks, Horizon, Octane, Rate Limiting, Query Builder: pessimistic locking, Database: deadlocks, Task Scheduling, Service Container: scoped, HTTP Client: concurrent requests, Artisan. Framework source: WithoutOverlapping, Redis Connection (
funnel,throttle) - RabbitMQ: Consumer Prefetch, Consumers. Apache Kafka: KafkaConsumer javadoc, Multi-threaded Processing
- Wikipedia (secondary): Actor model, Little's law, ABA problem, Deadlock (Coffman conditions)