0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Concurrency Patterns
Timeouts, Rate Limits and Bulkheads
Concurrent systems rarely fail because one request is slow. They fail because slowness spreads: queues grow, resources are held longer, retries add load, and a small problem in one dependency turns into an outage everywhere. This section explains the mechanics of overload, using queueing intuition and Little law, so the protective patterns in the rest of the lesson make sense.
Little law and concurrency
Little law states that the average number of requests in a system equals the arrival rate multiplied by the average time each request spends inside: L equals lambda times W. It holds for any stable system regardless of distribution, and it is the most useful single equation for reasoning about concurrency. A service receiving 1000 requests per second, each taking 50 milliseconds, has on average 50 requests in flight. If a dependency slows so that each request takes 500 milliseconds, the same traffic now means 500 requests in flight, ten times as many threads, connections and memory, even though the request rate has not changed at all. This is why latency problems turn into resource problems: every slowdown multiplies the concurrency a service must hold, and when that concurrency exceeds a limit such as a thread pool, a connection pool or file descriptors, requests start to queue or fail.
Queueing and the knee of the curve
When a server is busy part of the time, arriving requests sometimes wait in a queue. Queueing theory shows that waiting time stays small at low utilization but grows sharply as utilization approaches 100 percent: in the simplest model, average time in the system is the service time divided by one minus utilization, so at 50 percent utilization requests take twice their service time, at 90 percent ten times, and at 99 percent a hundred times. This knee in the curve means a system that is comfortable at 70 percent can become unusable after a modest traffic increase or a small slowdown. Variability in arrival and service times makes it worse. Capacity planning therefore targets utilization well below saturation, and protective mechanisms aim to keep each component on the flat part of the curve even when demand exceeds supply.
Congestion collapse
Under overload, systems can do something worse than slowing down: their useful throughput can fall. If clients time out after two seconds but requests are queued for three, the server spends all of its capacity on work whose results nobody will receive, and its goodput, the rate of useful completed requests, drops toward zero even while it is fully busy. Retries make this worse, since each timed out request comes back as a new one, increasing load further. Garbage collection pauses under memory pressure, lock contention among many threads and context switching overhead add their own drops in efficiency. The result is a metastable failure: once the system enters this state, it can stay there even after the original trigger disappears, because the retry traffic and backlog alone keep it overloaded, until operators intervene by shedding load or restarting.
Cascading failure
In a service graph, overload spreads along dependencies. When a database slows, the services calling it hold their requests longer, so by Little law they need more threads and connections; their own callers then see them slow down and hold their requests longer too, and so on up to the edge. Shared resources make the spread wider: if one thread pool serves calls to both a slow dependency and a healthy one, the slow calls fill the pool and the healthy ones fail too. Without protection, a single slow component can take down every service that depends on it directly or indirectly, along with unrelated features that happen to share pools with them. The patterns in this lesson, timeouts, rate limits, concurrency limits, bulkheads, circuit breakers and load shedding, each interrupt this spread at a different point.
Timeouts as the first line of defence
Every call that crosses a process boundary needs a timeout, because without one a single hung connection can hold a thread, a connection and memory forever. Many client libraries ship with no timeout or an absurdly long one by default: some HTTP clients wait indefinitely for a response, and some database drivers wait minutes for a connection from the pool. A good timeout has several parts. A connect timeout bounds how long establishing a connection may take, and it can be short, often 100 to 500 milliseconds inside a data centre, since a healthy host accepts connections quickly. A read or request timeout bounds how long the call may take once connected, and it should be set from the measured latency of the dependency, typically a little above its p99 or p99.9, so that normal slow requests succeed while truly stuck ones are abandoned. A pool acquisition timeout bounds how long a caller may wait for a free connection, which matters because waiting for a pool is exactly how overload shows up first. Setting each of these explicitly, rather than trusting defaults, is the cheapest resilience work a team can do.
Choosing timeout values from data
Timeouts that are too long protect nothing, because by the time they fire the caller has already exhausted its threads; timeouts that are too short cause failures during ordinary variation and trigger retries that add load. The right value comes from the latency distribution of the dependency under normal conditions. If a service has a p50 of 20 milliseconds, a p99 of 80 and a p99.9 of 150, a timeout of around 200 milliseconds abandons only requests that are far outside normal behaviour. The value should also fit the budget of the caller: if the caller must answer within 500 milliseconds and makes three sequential calls, each call cannot have a 400 millisecond timeout. Teams should review timeouts when latency profiles change, such as after a migration or a large traffic increase, and record the reasoning next to the configuration so that future readers know why a number was chosen. Metrics that count timeouts per dependency show when a value has drifted away from reality.
Measuring overload before it happens
The signals that predict overload are visible well before failures begin. In flight request counts, pool utilization, queue lengths and queueing delay rise as a system approaches its limits, while error rates often stay flat until the last moment. Dashboards should therefore show saturation alongside latency and errors, as the four golden signals in Google SRE guidance recommend: latency, traffic, errors and saturation. Latency should be shown as percentiles rather than averages, since the average hides the tail where overload first appears. Alerting on saturation, for example when a connection pool stays above 80 percent busy for several minutes, gives operators time to scale or shed load before users see errors. Load tests that find the knee of the curve for each service, and capacity plans that keep normal peaks well below it, turn these measurements into decisions about how much headroom to keep.
A worked overload example
Consider an API service with 16 worker threads per instance, each request taking 40 milliseconds of work, so each instance can complete about 400 requests per second at full utilization. Running at 280 requests per second puts it at 70 percent, where queueing adds modest delay. A marketing email arrives and traffic jumps to 380 requests per second, 95 percent utilization, and queueing delay multiplies, so the p99 rises from 120 milliseconds to over a second. Clients with a one second timeout begin to give up and retry, so the arrival rate rises to 450, beyond capacity, and the queue now grows without limit. Every request is served late, goodput falls, and the instance appears busy and broken at the same time. Autoscaling might add instances, but new instances take minutes to start, and the retries keep arriving. A concurrency limit of around 20 per instance with fast rejection, a retry budget on clients and load shedding of low priority endpoints would have kept the service at capacity, serving most requests on time while the extra instances started.
In flight work equals arrival rate times latency, so every slowdown multiplies the threads, connections and memory a service needs. Latency rises steeply near full utilization, retries and timeouts can collapse goodput, and shared pools let one slow dependency take down unrelated features. Protective patterns exist to break each of these links.