0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Synchronization
Concurrency Patterns
Asynchronous I/O
Why Concurrency Is Hard
Almost every program that matters today does several things at once. A web server handles thousands of connections, a database runs many transactions, a phone app downloads images while the user scrolls, and a data pipeline spreads work across every core of a machine. Doing several things at once is what makes these systems fast and responsive, and it is also the source of the strangest bugs in software. This section separates two ideas that are often confused, concurrency and parallelism, and explains why modern programs cannot avoid either.
Two different ideas
Concurrency is about structure: a program is concurrent when it is organized as several independent activities whose lifetimes overlap. Parallelism is about execution: a program runs in parallel when some of those activities literally execute at the same instant on different processors. A single core machine can run a concurrent program by switching between activities many times per second, so their lifetimes overlap even though only one instruction runs at a time. A machine with sixteen cores can run the same program in parallel, with sixteen activities making progress at the same moment.
The distinction matters because the two solve different problems. Concurrency is a way to deal with many things at once, such as many clients, many timers and many outstanding requests. Parallelism is a way to do one large thing faster by splitting it across processors. A chat server is mostly concurrent: it spends nearly all its time waiting for messages and very little computing. A video encoder is mostly parallel: it has one job and wants every core working on it. Many real systems need both.
Why programs became concurrent
For decades, programs got faster for free because each new processor ran a single thread faster. Around 2005 that stopped: clock speeds stalled because of power and heat, and chip makers spent their growing transistor budgets on more cores instead. A program that uses one thread on a 64 core server today leaves 63 cores idle. Speed now comes from doing work in parallel, which forces programs to be concurrent.
The second driver is latency. A modern processor executes billions of instructions per second, while a disk read takes tens of microseconds to milliseconds and a network round trip across a region takes a millisecond or more. A program that waits for each I/O operation before starting the next spends almost all of its time idle. Overlapping waits, so that while one request waits for the database another is parsed and a third is sending its response, turns idle time into throughput. This kind of concurrency helps even on a single core.
Processes, threads and tasks
Operating systems offer two basic units of concurrency. A process has its own address space, file descriptors and resources; processes are isolated, so a bug in one cannot corrupt the memory of another, but sharing data between them requires explicit channels such as pipes, sockets or shared memory segments. A thread is a unit of execution inside a process; all threads of a process share its memory, which makes communication cheap and also makes accidental interference easy.
On top of these, languages and runtimes provide lighter units: coroutines, green threads, goroutines, virtual threads, async tasks and actors. These are scheduled by the runtime rather than the kernel and cost far less memory, so a program can have hundreds of thousands of them. They still run on top of a few operating system threads, and they still face the same fundamental problems when they share mutable state. Later lessons look at each model in depth; for now the important point is that all of them create activities whose steps can interleave.
Shared state is the root of the difficulty
Concurrency itself is not hard. Independent activities that never touch the same data, such as two processes compressing two different files, cannot interfere with each other. Difficulty arises when concurrent activities share mutable state: a counter, a cache, a list of connections, a bank balance or a file. Whenever two activities can read and write the same data and their steps can interleave in different orders, the result can depend on timing. The rest of this course is largely about controlling that dependence: avoiding sharing where possible, and coordinating access where sharing is necessary.
A short history of the concurrency problem
Concurrency is older than multicore hardware. Operating systems in the 1960s already ran several programs at once on a single processor, switching between them when one waited for a tape drive or a terminal, because idle processors were expensive. The engineers who built those systems ran into every problem in this course: two programs updating the same table, a printer driver and a spooler waiting on each other forever, an interrupt handler seeing a half written data structure. Dijkstra introduced semaphores in 1965, Hoare and Brinch Hansen described monitors in the early 1970s, and Lamport formalized what it means for concurrent operations to be ordered in 1978. Most of the tools developers use today are direct descendants of that work.
What changed in the multicore era is who has to care. For decades, concurrency was the concern of kernel developers, database engineers and a few specialists who wrote servers. Everyone else wrote sequential programs that ran faster every year. Today every application developer writes concurrent code, whether they choose to or not: a browser tab runs JavaScript alongside network callbacks, a mobile app must keep its interface thread free while it fetches data, and a backend service built on any modern framework handles requests concurrently by default. Frameworks hide much of the machinery, but they cannot hide shared state that the application itself creates.
Throughput, latency and responsiveness
Concurrency serves three related goals, and it helps to know which one a design is optimizing. Throughput is how much work finishes per unit of time, such as requests per second or rows processed per minute. Concurrency raises throughput by keeping every resource busy: while the processor parses one request, the network card receives another and the disk reads a third. Latency is how long one unit of work takes from start to finish. Parallelism can lower latency by splitting one request across cores, and concurrency can lower it by fetching independent pieces of data at the same time instead of one after another.
Responsiveness is the ability to react quickly to new events while long running work continues. A desktop application that freezes while saving a file has a responsiveness problem, not a throughput problem. The fix is to move the save to a background activity so the interface thread keeps handling clicks and repaints. Games, user interfaces and control systems often care more about responsiveness than raw speed. The three goals sometimes conflict. Batching work raises throughput but adds latency, and giving interactive work priority improves responsiveness at the cost of background throughput. Naming the goal first prevents a common mistake: adding threads to a system whose real problem is a slow downstream dependency, which raises contention without improving anything the users notice.
The cost of getting it wrong
Concurrency bugs are expensive out of proportion to their size. The Therac 25 radiation therapy machine delivered massive overdoses in the 1980s partly because of a race between operator input and the setup of the beam. The 2003 Northeast blackout in North America was made worse by a race condition in alarm software that silently stopped alerting operators. In everyday systems, races corrupt caches, double charge customers, leak connections and produce reports with numbers that are almost right. Because they appear rarely and disappear under observation, teams can spend weeks chasing a single one. Investing in a correct mental model up front is far cheaper than debugging by trial and error later.
Concurrency is about overlapping lifetimes and parallelism is about simultaneous execution. Most systems need concurrency to hide I/O latency and parallelism to use many cores. The danger comes from mutable state shared between activities, so the first design question is always what is shared and whether it needs to be.
When two activities run concurrently, their individual steps are merged into one timeline in some order, an interleaving. The program text fixes the order of steps within each activity, but not how steps of different activities alternate. The scheduler, the hardware and the timing of I/O decide that, and they decide differently on every run. This section shows how a few lines of innocent code can produce wrong results under some interleavings, and why the number of possible interleavings makes testing so unreliable.
Steps that look atomic but are not
Consider a counter shared by two threads, each of which executes count = count + 1. In source code this looks like a single action. The processor executes it as three: load the current value of count into a register, add one to the register, and store the register back to memory. Between any two of these steps, the scheduler may switch to the other thread, or the other thread may run the same steps at the same time on another core.
The unit that cannot be interrupted is called an atomic step. Single loads and stores of aligned machine words are usually atomic on modern hardware, but read, modify, write sequences are not, unless special instructions are used. Almost every operation in a high level language, including incrementing a field, appending to a list, inserting into a hash map or checking a value and then acting on it, is several steps underneath.
The lost update
Suppose count starts at 0 and two threads each increment it once. If thread A completes all three steps before thread B starts, count ends at 2. But if A loads 0, then B loads 0, then A stores 1, then B stores 1, count ends at 1. One increment is lost, and nothing failed: no exception, no crash, just a wrong number. Run a million increments on each of two threads, and the final count typically lands somewhere well below two million, different on every run.
Loading problem...
How many interleavings are there
Two threads of three steps each can interleave in 20 different orders. In general, if thread one has m steps and thread two has n steps, there are (m + n)! / (m! n!) interleavings. Two threads of 10 steps produce 184,756 orders; three threads of 10 steps produce more than five trillion. Real programs have threads with thousands of steps, and the space is astronomically large. Only a tiny fraction of interleavings may be wrong, and the scheduler may almost never pick them in a test environment, while under production load with different timing they appear regularly.
Check then act
The lost update is one instance of a broader pattern: a decision is made based on a value that may change before the decision is acted on. Check then act bugs appear everywhere. Code checks whether a file exists and then creates it, but another process creates it in between. Code checks that a balance covers a withdrawal and then subtracts, but another withdrawal runs in between, and the account goes negative. Code checks a cache, misses, computes the value and stores it, while ten other threads do the same expensive computation at the same time. The check and the act must happen as one atomic unit, or the program must tolerate the value changing between them.
Why the bug hides
Interleaving bugs share an unpleasant property: the probability of hitting them depends on timing. On a developer laptop with little load, a thread usually finishes its three steps before being interrupted, so lost updates are rare. In production, with many cores, heavy contention and preemption, the window between read and write is hit far more often. Adding a log statement or a debugger breakpoint changes the timing and often makes the bug disappear, which is why these are sometimes called heisenbugs. The next section looks at the sources of this nondeterminism and how to make it visible.
The same bug in many disguises
The lost update shows up far beyond counters. Two threads append to the same dynamic array: both read the current length, both write their element into the same slot, and both increment the length, so one element vanishes and the array may contain garbage at the end. Two requests update the same user profile: each reads the whole profile, changes one field and writes the whole profile back, so the second write erases the change made by the first. Two processes rotate the same log file: both see that it is too large, both rename it, and one rename overwrites the archive the other just created. In each case the pattern is identical: read shared state, compute a new value privately, and write it back as if nothing changed in between.
Data structures make the damage worse than a wrong number. A hash map in the middle of resizing has two tables and a partially moved set of entries. If another thread inserts during the resize, an entry can land in the old table after it has already been copied and silently disappear, or the internal linked lists can form a cycle so that later lookups loop forever. This has happened in production with unsynchronized maps in Java, Go and other languages, and it is why the documentation for most standard collections warns that they are not safe for concurrent modification. Go detects some of these cases at runtime and crashes the program on purpose with a fatal concurrent map writes error, because a crash is better than silent corruption.
Interleavings across processes and machines
Interleavings are not limited to threads in one process. Two processes sharing a file, two services writing to the same database row, and two replicas of a cache all face exactly the same problems at a coarser grain and with longer windows. A read modify write that spans a network call to a database can have a race window of several milliseconds instead of a few nanoseconds, which makes lost updates far more likely. The tools change, from mutexes and atomics to row locks, conditional updates and version numbers, but the reasoning is identical: identify the shared state, find the steps that must be atomic, and make sure no other activity can slip between them. Many lessons in this course apply directly to distributed systems for this reason.
Reasoning about a schedule by hand
A useful exercise when reviewing concurrent code is to write out a schedule explicitly. List the atomic steps of each activity in a column, then pick an interleaving that seems dangerous and walk through it, tracking the value of every shared variable after each step. For the counter, write A load, B load, A store, B store, and observe the result. Doing this for two or three adversarial schedules catches most atomicity bugs in a code review. The adversary mindset helps: imagine that the scheduler is actively trying to break your code and will pause any thread at the worst possible moment. Code that survives that adversary is correct under every interleaving.
The judged problem in this section asks you to do exactly this by machine: given the sequence of load and store steps two or more threads perform, simulate the shared variable and report how many increments were lost.
Statements that look atomic in source code are usually several machine steps. When two activities share data, any interleaving of those steps can happen, and the number of interleavings is far too large to test exhaustively. Look for read modify write and check then act patterns on shared data and make them atomic by design.
A sequential program given the same input produces the same output every time. A concurrent program does not have that guarantee: the same input can produce different outputs, or the same output in different ways, depending on timing outside the control of the program. This section looks at where that nondeterminism comes from, why it makes concurrency bugs so hard to reproduce, and the techniques engineers use to bring rare interleavings into view.
Sources of nondeterminism
Several layers contribute. The operating system scheduler decides when to preempt a thread and which thread runs next, based on time slices, priorities, interrupts and the other processes on the machine. Multiple cores run threads truly simultaneously, so the relative speed of two threads depends on cache misses, branch prediction and frequency scaling. I/O completes after variable delays, so the order in which network responses arrive changes run to run. Garbage collection pauses stop threads at unpredictable points. Even the hardware may reorder memory operations, a topic for the lesson on memory models. Each source alone is enough to change the interleaving.
Heisenbugs
A heisenbug is a bug that changes or disappears when you try to observe it. Concurrency bugs are the classic example. Attaching a debugger stops threads at breakpoints, serializing what used to run in parallel. Adding print statements adds I/O and locks inside the logging library, which shifts timing and sometimes adds accidental synchronization. Building with optimizations off changes which values live in registers. The bug occurs once in a million requests in production and never on the machine of the engineer trying to fix it.
This makes reasoning more valuable than testing for concurrent code. A test that passes a thousand times proves little if the failing interleaving has a probability of one in a million per run. Code that is correct by construction, with invariants that hold under every interleaving, is far more reliable than code that has merely not failed yet.
Making rare interleavings common
Engineers still need ways to find these bugs. Stress testing runs the concurrent code with many more threads than cores, many iterations and random delays, increasing the number of interleavings explored. Injecting a short sleep or yield at a suspicious point, such as between a check and an act, widens the race window so a bug that happened once a day happens on every run. Tools such as ThreadSanitizer instrument memory accesses and report data races even when the run happens to produce the right answer. Deterministic simulation runs all threads under a controlled scheduler that chooses interleavings systematically or from a seed, so any failure can be replayed exactly. Model checkers explore all interleavings of a small model of the algorithm.
Invariants as the unit of reasoning
The most useful mental tool for concurrent code is the invariant: a property of shared state that must always hold whenever no activity is in the middle of an update. For a bank, the sum of all balances equals total deposits minus withdrawals. For a queue, the size field equals the number of linked nodes. Each operation may break the invariant temporarily while it runs, and the job of synchronization is to make sure no other activity can observe that intermediate state. Thinking in invariants turns an infinite space of interleavings into a finite question: can any other activity see the state while the invariant is broken?
Observing interleavings in practice
One of the most illuminating experiments a developer can run takes only a few minutes. Start two threads that each increment a shared integer ten million times, print the result, and repeat the run five times. On most machines the results differ every run and fall well short of twenty million. Then wrap the increment in a mutex and run again: the result is exactly twenty million every time, and the program is noticeably slower. Then replace the mutex with an atomic increment: the result is still exact and the program is faster than the mutex version but slower than the broken one. Those three runs teach the core trade offs of the course: unsynchronized code is fast and wrong, and correct code pays for coordination.
In Python the experiment needs care, because the global interpreter lock makes many single bytecode operations effectively atomic, and the race appears only for operations that span several bytecodes, such as an increment of an attribute. That surprises many developers: the GIL does not make Python code thread safe. It protects the interpreter itself, not the invariants of the program. A later lesson covers the GIL in detail, and the first notebook of the course measures the race directly.
Why code review misses races
Concurrency bugs often survive careful code review because each function looks correct in isolation. A method that reads a field, computes and writes it back is perfectly correct in a sequential program, and the reviewer has to know that another thread may call the same method or a different method on the same object at the same time. That knowledge usually lives outside the code being reviewed, in how the object is shared. Documenting thread safety explicitly helps a great deal: annotate each class as immutable, thread safe or not thread safe, and annotate fields with the lock that guards them. Java has annotations such as GuardedBy for this purpose, and the Clang compiler can check similar annotations in C++ at compile time.
A second reason is that concurrency is a property of a whole program, not a function. A change in one module, such as moving a callback to a background thread for performance, can make a previously safe piece of code unsafe in a module the author never touched. Reviews that focus on diffs struggle with that. Teams that handle concurrency well keep the shared state concentrated in a few well known places so that any change touching them gets extra scrutiny.
The cost of nondeterminism in operations
Nondeterminism also hurts operations, not just development. A deployment that triggers a rare race may roll out successfully to ten percent of servers and fail only when traffic peaks hours later. Rollbacks may not help if the race corrupted persistent data. Incident timelines become hard to reconstruct because log lines from different threads interleave and timestamps from different machines disagree by milliseconds. Good concurrent systems add structure that makes behavior observable: request identifiers carried through every thread and task, metrics on queue depths and lock wait times, and logs that record which thread or task produced each line.
Deterministic by design
Some systems remove nondeterminism at the architecture level instead of fighting it in tests. FoundationDB famously runs its entire distributed database inside a single threaded deterministic simulator during testing, with simulated networks, disks and clocks, so that any failure found among millions of simulated runs can be replayed exactly from its seed. Game engines often run their simulation step on one thread with a fixed time step so that replays and network synchronization are exact. Event sourcing systems record every input in order so that state can be rebuilt deterministically. These designs accept a constraint, such as a single writer per piece of state or a controlled scheduler, in exchange for behavior that can be reproduced. Even when a full deterministic design is out of reach, isolating the nondeterministic parts, such as the network and the clock, behind interfaces that tests can control brings much of the same benefit.
Concurrent programs are nondeterministic because the scheduler, hardware, I/O and runtime all change timing. Bugs that depend on rare interleavings vanish under debuggers and logging, so tests that pass prove little. Define invariants on shared state, make sure no one sees them broken, and use stress tests, injected delays, race detectors and deterministic schedulers to surface rare failures.
A sequential program is correct when it produces the right output. For a concurrent program, correctness has more dimensions: nothing bad may ever happen, something good must eventually happen, and the results must make sense with respect to the real time order in which operations ran. This section introduces the vocabulary used throughout the course, safety and liveness, the three classic hazards of atomicity, visibility and ordering, and the idea of linearizability as the gold standard for concurrent objects.
Safety and liveness
A safety property says that nothing bad ever happens: two threads are never inside the same critical section, the counter never loses an increment, the account balance never goes negative. A safety violation is a finite event; you can point at the moment it happened. A liveness property says that something good eventually happens: every request eventually gets a response, every thread waiting for a lock eventually gets it. A liveness violation is an infinite event; a deadlocked program never fails, it simply never makes progress.
The two pull in opposite directions. The easiest way to guarantee safety is to do nothing, and a program that holds one global lock forever is perfectly safe and completely useless. The easiest way to guarantee liveness is to skip coordination, which breaks safety. Every concurrency design balances the two, and every bug can be classified as a violation of one or the other.
Atomicity, visibility and ordering
Concurrency bugs fall into three families. Atomicity bugs happen when a sequence that must appear indivisible, such as read modify write or check then act, is interleaved with another activity; the lost update is the canonical example. Visibility bugs happen when one thread writes a value and another thread does not see it, because the value sits in a register or a store buffer, or because the compiler hoisted a read out of a loop. A thread spinning on a done flag may spin forever even after another thread set the flag. Ordering bugs happen when operations become visible to another thread in a different order than written: a thread initializes an object and then publishes a pointer to it, and another thread sees the pointer before it sees the initialized fields.
Locks solve all three at once, which is why they are the default tool. Atomic variables solve visibility and ordering for single variables and atomicity for single operations on them. Understanding which family a bug belongs to tells you which tool fixes it and which merely hides it.
Linearizability
How should a concurrent object such as a queue or a counter behave? The standard answer is linearizability: every operation appears to take effect instantaneously at some single point between its invocation and its response, and the resulting sequence of operations is a legal sequential history. If a push completed before a pop started, the pop must see that push. Linearizability lets you reason about a concurrent object as if it were sequential, with operations ordered consistently with real time. Locks give linearizability easily; lock free structures must be designed carefully to provide it. Weaker guarantees, such as eventual consistency for replicated data, trade this simplicity for availability or speed.
Progress guarantees
Liveness has degrees. A blocking algorithm, one that uses locks, can stall every thread if one thread holding a lock is descheduled or crashes. A lock free algorithm guarantees that some thread always makes progress, even if others are delayed indefinitely, although an individual thread may starve. A wait free algorithm guarantees that every thread completes its operation in a bounded number of its own steps. Wait free algorithms are the strongest and hardest to build; lock free ones are common in high performance runtimes; blocking ones are the everyday default because they are simple and, with good design, fast enough.
Fairness
Fairness is a liveness property about how evenly waiting activities are served. A lock is fair if threads acquire it in roughly the order they asked for it; an unfair lock lets a newly arriving thread grab it ahead of threads that have waited a long time. Unfair locks are often faster, because the thread that just released the lock is likely still running with warm caches and can reacquire it without a context switch. The cost is that some threads may wait far longer than others, and in extreme cases starve. Most standard library mutexes are unfair by default for throughput, and offer a fair mode or a separate fair lock for cases where bounded waiting matters, such as request handling where tail latency is the metric.
Fairness also matters at higher levels: a thread pool that always picks the newest task may leave old tasks waiting forever, and a reader writer lock that always admits new readers may never let a writer in. Each of these is a design choice with a trade off between throughput and predictability, and later lessons return to them.
Sequential consistency as a mental baseline
When reasoning about interleavings, developers naturally imagine sequential consistency: all operations of all threads happen in some single global order, and each thread sees the operations of the others in that order, consistent with the order in its own program. Under that model, the lost update is the only kind of bug, and interleaving schedules tell the whole story. Real hardware and compilers do not guarantee sequential consistency for ordinary memory accesses, because reordering loads and stores makes programs much faster. That is where visibility and ordering bugs come from. Languages restore sequential consistency for programs that are free of data races, as long as all shared accesses are protected by locks or declared as atomic. This bargain, called sequential consistency for data race free programs, is the foundation of the Java, C++, Go and Rust memory models, and the lesson on memory models explains it in detail.
Composability
A final correctness concern is composition. Two thread safe operations combined are not necessarily thread safe. A concurrent map offers a safe get and a safe put, but calling get, checking the result and then calling put is a check then act race, even though each call alone is safe. Moving money between two thread safe accounts with a withdraw on one and a deposit on the other exposes an intermediate state where the money exists in neither. Composing operations safely requires either a larger lock that covers both, an API that provides the combined operation atomically, such as putIfAbsent or computeIfAbsent, or a transaction mechanism. When designing a concurrent API, provide the compound operations your callers will need, because they cannot build them correctly from the primitives.
Correctness is checked against a specification
All of these properties require a clear statement of what the code is supposed to do. A specification for a concurrent component lists its operations, the invariants on its state, the safety properties it guarantees and the progress it promises, for example that every enqueue eventually becomes visible to some dequeue. Formal tools such as TLA+ let engineers write such a specification and check it against every interleaving of a small model, and teams at Amazon, Microsoft and elsewhere have used it to find subtle bugs in designs before any code existed. Even without formal tools, writing the specification in plain language, in a comment at the top of the class, forces the author to decide what concurrent callers may observe, which is often the step that reveals the bug.
Concurrent correctness means safety, nothing bad ever happens, and liveness, something good eventually happens. Safety bugs come from atomicity, visibility or ordering hazards. Linearizability makes concurrent objects behave like sequential ones ordered by real time, and progress guarantees range from blocking to lock free to wait free.
Concurrency cannot be avoided, but its difficulty can be managed. Experienced engineers rarely start by sprinkling locks over shared data. They start by reducing what is shared, then choose a coordination model that fits the problem, and only then decide where precise synchronization is needed. This section surveys the main strategies, the limits that Amdahl law places on parallel speedup, and how to choose the granularity of concurrency.
Do not share: confinement and immutability
The simplest way to avoid races is for data not to be shared. Thread confinement keeps each piece of mutable data owned by exactly one activity: each request handler has its own buffers, each worker has its own partial result, and results are combined at the end. Immutability makes shared data safe by construction: an object that never changes after creation can be read by any number of threads without coordination. Many functional languages and modern libraries lean on immutable collections and copy on write for exactly this reason.
Share by communicating
When activities must cooperate, they can pass messages instead of sharing memory. A producer sends work items through a queue, and the consumer owns each item once received. Actors encapsulate state and process one message at a time, so their state is never accessed concurrently. Go summarizes the idea as do not communicate by sharing memory; instead, share memory by communicating. Message passing does not eliminate concurrency bugs, since deadlocks and ordering surprises remain, but it eliminates data races on the state that each owner keeps private.
Synchronize what remains
Some state must be shared and mutable: a connection pool, a cache, a rate limiter, an in memory index. For that state, synchronization tools make operations atomic and visible: mutexes and read write locks for critical sections, condition variables and semaphores for waiting, atomic variables and compare and swap for single word updates, and concurrent collections built from these. The rest of the synchronization section of this course covers each. A good rule is to keep the synchronized region small and well defined, often wrapped in a single class or module whose methods are the only way to touch the shared data.
Amdahl law
Parallelism has a hard limit. If a fraction s of a job is inherently sequential and the rest can be spread across N processors, the best speedup is 1 / (s + (1 - s) / N). With 5 percent sequential work, 8 cores give a speedup of about 5.9, 64 cores about 15.4, and infinitely many cores at most 20. Every lock that serializes work, every shared counter that all threads update, and every single threaded phase of a pipeline adds to s. This is why reducing contention matters as much as adding threads, and why the shape of the speedup curve flattens so quickly.
Choosing granularity
Concurrency has overhead: creating threads, switching contexts, acquiring locks and passing messages all cost time. Splitting work into pieces too small wastes more on coordination than it gains from parallelism, while pieces too large leave cores idle at the end and limit how well load balances. The right granularity depends on the cost of the coordination mechanism. An operating system thread costs microseconds to switch and kilobytes to megabytes of memory, so it suits tasks of milliseconds or more. A goroutine or async task costs far less, so it suits finer tasks. Measuring is the only reliable way to find the sweet spot, and the remaining lessons give the numbers needed to make a first estimate.
Gustafson and the case for scaling the problem
Amdahl law assumes a fixed problem size. In practice, when engineers get more cores, they often solve bigger problems in the same time: a weather model runs on a finer grid, a search engine indexes more pages, an analytics job processes a full month instead of a sample. Gustafson law captures this view. If the parallel part grows with the number of processors while the sequential part stays fixed, the scaled speedup is roughly N minus s times (N minus 1), which keeps growing almost linearly. Both laws are true; they answer different questions. Amdahl tells you how much faster a fixed job can get, and Gustafson tells you how much more work you can do in a fixed time. For a latency sensitive request, Amdahl is the right lens. For a batch system whose input keeps growing, Gustafson often is.
Contention and coherence costs
Amdahl law treats the parallel part as perfectly divisible, but real parallel work also pays for coordination that grows with the number of participants. When many cores write the same cache line, the hardware coherence protocol moves that line between cores on every write, and each move costs tens to hundreds of nanoseconds. When many threads compete for one lock, they spend time queueing and switching. The universal scalability law adds a coherence term to Amdahl: beyond some point, adding processors makes the system slower, not just less efficiently faster. Many teams discover this the hard way when a service scaled from 16 to 64 threads gets worse throughput. The cure is almost always to remove the shared hot spot: shard the data, keep per core or per thread state, or batch updates.
A practical checklist
When starting a concurrent design, a short checklist covers most of the ground. First, list the shared mutable state and who touches it. Second, for each piece, decide whether it can be confined to one owner, made immutable, or replaced by messages. Third, for what remains, write down the invariants and choose the synchronization that protects them, preferring coarse and simple over fine and clever until measurements show contention. Fourth, decide how activities are started, stopped and cancelled, so no work is orphaned. Fifth, plan how the system will be tested under concurrency and how contention will be observed in production. The remaining four sections of this course give the tools for each step, starting with how threads are scheduled by the operating system.
Choosing the model for the workload
Workloads fall broadly into two kinds. CPU bound work, such as compression, image processing or numerical computation, benefits from parallelism and wants roughly one busy thread per core; more threads than cores only add switching overhead. I/O bound work, such as serving requests that call databases and other services, benefits from concurrency and wants many activities in flight per core, since each spends most of its time waiting. For I/O bound work, the question is how cheaply each waiting activity can be represented: an operating system thread, a green thread or an async task. Many real services mix both and isolate them, running CPU heavy steps on a dedicated pool so they do not starve the activities handling I/O. The final lesson of the course returns to this choice with the full set of tools in hand.
Start simple and measure
The most common failure in concurrent design is premature cleverness: fine grained locking, lock free structures or elaborate async pipelines added before anyone measured a problem. These designs are harder to get right and harder to change, and they often deliver less speedup than expected because the bottleneck was elsewhere. A better path is to start with the simplest correct design, often one lock around a small piece of shared state or a single owner thread, measure it under realistic load, and only then refine the specific parts that show contention. Profilers that report lock wait time, scheduler latency and queue depth make the case for each refinement concrete, and a simple design that is fast enough is almost always better than a fast design that is subtly wrong.
A junior engineer knows that shared mutable data needs synchronization and recognizes the lost update. A mid level engineer spots read modify write and check then act patterns, writes code with clear ownership of data, and uses locks or atomics correctly around what is shared. A senior engineer designs systems that minimize sharing through confinement, immutability and message passing, reasons with invariants, safety and liveness, predicts scaling limits with Amdahl law, and builds stress tests and race detection into the development process.