Compute and traffic antipatterns: blocking, per-request clients, noisy neighbors, retry storms
Recognise synchronous I/O, improper instantiation, a busy front end, noisy neighbours and retry storms from their signatures, and fix them with non-blocking calls, shared clients and pools, offloading, isolation and retry budgets.
Contentsand lesson path
On this page
- Why it matters
- Synchronous I/O: waiting instead of working
- Improper instantiation: creating what should be shared
- Busy front ends and noisy neighbours: competing for shared capacity
- Retry storms: clients that make an outage worse
- Check your understanding
- Apply it
- Review prompt
Lessons of Performance Antipatterns
- From symptom to cause: a method for slow systems Concept · 15 min
- Data-access antipatterns: chatty, over-fetching, busy and uncached Concept · 25 min
- Compute and traffic antipatterns: blocking, per-request clients, noisy neighbors, retry storms Concept · 25 min
- Fixing a slow endpoint under load, one antipattern at a time Lab · 30 min
- Antipattern diagnosis check Knowledge check · 6 questions
What you will learn
- Recognize compute and traffic antipatterns (synchronous I/O, improper instantiation, busy front end, noisy neighbor, retry storm) and fix them with non-blocking calls, shared clients and pools, offloading to workers, resource isolation and retry budgets.
01. Why it matters
The antipatterns in this lesson make healthy hardware look overloaded. CPUs sit half idle while requests queue, connections run out while the database is quiet, and a short slowdown in one service becomes an outage for its callers.
One warning first. You will find fixed limits quoted online, such as "a server can run about 5,000 threads" or "an event loop can serve 100,000 connections". Such numbers depend on the runtime, the memory per thread, how often the work blocks and what each request does, and an open connection is not a request served. Measure them on your own system instead of designing around them.
02. Synchronous I/O: waiting instead of working
Synchronous I/O means a thread or an event loop waits for input or output, such as a network reply or a disk read, when it could be doing other work. In a thread-per-request server every waiting thread still holds a worker slot, so capacity is the number of workers divided by how long each request holds one (sizing a tier shows the arithmetic). In an asyncio service it is worse: one blocking call inside an async def handler stops every request on that event loop until the call returns, as the async Python lab demonstrates.
The signature: throughput stops growing while CPU stays low; latency rises steeply with load; loop lag grows; and a sampling profiler that includes waiting samples, such as py-spy with --idle, shows request code sitting in a socket read. The fixes are non-blocking clients (an async database driver, an async HTTP client), asyncio.to_thread for a blocking library that has no async version, or moving the slow call out of the request altogether, for example into a queue.
Be careful to separate waiting from computing. to_thread helps when the thread waits, because a waiting thread releases Python's global interpreter lock (GIL). It does not help when the work is pure-Python computation, because in the standard CPython build only one thread runs Python code at a time. Free-threaded builds without the GIL exist from Python 3.13, but they are an optional install, not the default. The script below runs the same CPU-bound function eight times in three ways:
"""Does asyncio.to_thread make CPU-bound Python faster? Compare it with processes."""
import asyncio
import os
import time
from concurrent.futures import ProcessPoolExecutor
N = 1_500_000
def score(n: int) -> int: # pure-Python arithmetic: CPU-bound, no I/O at all
total = 0
for i in range(n):
total += i * i % 7
return total
async def timed(label: str, make_call) -> None:
best = float('inf')
for _ in range(3): # best of three runs, to reduce noise from other programs
start = time.perf_counter()
await asyncio.gather(*(make_call() for _ in range(8)))
best = min(best, time.perf_counter() - start)
print(f'{label:<32} {best:5.2f} s (best of 3)')
async def main() -> None:
print(f'8 calls of score(); this machine has {os.cpu_count()} CPUs')
async def on_loop() -> int:
return score(N) # no await inside: the loop runs one call after another
await timed('on the event loop', on_loop)
await timed('asyncio.to_thread', lambda: asyncio.to_thread(score, N))
loop = asyncio.get_running_loop()
with ProcessPoolExecutor(max_workers=4) as pool:
await timed('ProcessPoolExecutor, 4 workers',
lambda: loop.run_in_executor(pool, score, N))
if __name__ == '__main__':
asyncio.run(main())8 calls of score(); this machine has 8 CPUs
on the event loop 1.13 s (best of 3)
asyncio.to_thread 1.27 s (best of 3)
ProcessPoolExecutor, 4 workers 0.49 s (best of 3)With threads, the eight calls take about as long as running them one after another on the loop, and on some machines longer, because the threads take turns holding the GIL. Separate processes each have their own interpreter and run on separate cores, so four workers finish well ahead. For CPU-heavy Python work in a web service, that means more worker processes, a process pool, or a separate worker tier.
03. Improper instantiation: creating what should be shared
Improper instantiation means creating, for every request, an object that is designed to be created once and shared. HTTP clients, database engines and connection pools, cloud SDK clients, gRPC channels, TLS contexts and loaded machine-learning models are all expensive to build because they hold connections or large state. A new database connection, for example, costs a TCP handshake, often a TLS handshake, a password check (SCRAM, a challenge-and-response exchange, by default in current PostgreSQL) and, in PostgreSQL, a new server process: PostgreSQL starts one backend process for every connection. Each closed TCP connection also leaves a socket waiting in the TIME_WAIT state for a while, on the side that closed it first.
The standard library is enough to see the difference. This script runs a small HTTP server that counts TCP connections, then sends 200 requests with a new client each time and 200 with one shared client:
"""Count TCP connections: a new HTTP client per request versus one shared client."""
import http.client
import http.server
import threading
connections = 0
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1' # keep each connection open for more requests
def setup(self) -> None:
global connections
connections += 1 # runs once per TCP connection, not once per request
super().setup()
def do_GET(self) -> None:
body = b'{"rate": 0.92}'
self.send_response(200)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args) -> None: # keep the output quiet
pass
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
PORT = server.server_address[1]
def new_client_per_request(n: int) -> None:
for _ in range(n):
client = http.client.HTTPConnection('127.0.0.1', PORT) # created every time
client.request('GET', '/rate')
client.getresponse().read()
client.close()
def one_shared_client(n: int) -> None:
client = http.client.HTTPConnection('127.0.0.1', PORT) # created once
for _ in range(n):
client.request('GET', '/rate')
client.getresponse().read()
client.close()
for fn in (new_client_per_request, one_shared_client):
connections = 0
fn(200)
print(f'{fn.__name__:<24} 200 requests, {connections:>3} TCP connections')
server.shutdown()new_client_per_request 200 requests, 200 TCP connections
one_shared_client 200 requests, 1 TCP connectionsThe signature: connection counters that grow with the request count, such as the sessions column of PostgreSQL's pg_stat_database view rising by about one per request, or a log line per connection with log_connections on; thousands of sockets in TIME_WAIT; profiles in which connect and handshake code takes a visible share; a connect span on every request in the traces. Note what is not a signature: a pooled application normally keeps a steady set of idle connections open, so idle connections in pg_stat_activity are expected.
The fix is to create the object once per process, at start-up, and share it: in FastAPI, in the lifespan function. Size connection pools from measured load with Little's law and add headroom. Three cautions. Only share objects that are safe to use concurrently; most clients and pools are, but check. Create them in each worker process after the process starts, not before a fork. And a scarce resource such as a database connection should be borrowed from a pool for as short a time as possible, not held for a whole request that also waits on other services.
04. Busy front ends and noisy neighbours: competing for shared capacity
Busy front end means resource-heavy work runs in the tier that serves interactive requests: resizing images on upload, building exports and reports, parsing large files, or running model inference on the web servers. The heavy requests take workers and CPU from the light ones, so a page that normally answers in 30 ms waits behind a 20-second export. This waiting behind slower work is called head-of-line blocking.
The signature: the latency of light endpoints rises whenever a heavy endpoint is busy, which you see by putting the RED metrics of different endpoints side by side; front-end CPU or the worker pool is saturated while the database is not. The fix is to move the heavy work out of the request path: put a job on a queue, return 202 Accepted with a status URL, and let a separate pool of workers process jobs (background jobs covers the mechanics). Where the work must stay synchronous, give the heavy endpoint its own deployment and scaling, and cap how many heavy requests run at once. The cost: queued work needs retries, idempotency and backlog monitoring, and results arrive later.
A noisy neighbour is a consumer of a shared resource whose demand degrades everyone else: one tenant's bulk import in a shared database, a batch job filling a shared cache, a container without limits on a shared node. Microsoft's description adds a less obvious case: many tenants that each use a little can still peak together and exceed the capacity they share.
The signature: many tenants or workloads slow down together while one of them shows a spike in usage, and the same requests succeed at quieter times. Only per-tenant measurements show it, such as requests and database time per tenant, tagged through application_name in PostgreSQL or a tenant attribute in traces. Keep such labels bounded, for example the top 20 tenants plus one group for the rest, because one metric label per tenant can explode the number of time series.
The fixes are forms of resource governance: per-tenant quotas and rate limits, separate pools or queues per workload class, container CPU and memory limits, a separate shard or deployment for a large tenant, and bulk work run off-peak. Isolation has a price: reserved capacity sits idle when its workload is quiet.
05. Retry storms: clients that make an outage worse
A retry storm happens when retries add load to a dependency that is already struggling, so it cannot recover. Typical causes: a timeout shorter than the dependency's latency under load, so requests that are still running get sent again; retries at several layers, which multiply; immediate retries without any wait; and retries of errors that cannot succeed, such as 400 Bad Request.
The signature: the request rate arriving at the dependency climbs while the traffic users generate at the edge stays flat; the ratio of attempts to original requests rises above one, which you can see only if each call records its attempt number; and the service struggles to recover after the original fault is fixed.
The fixes: retry at one layer only; wait between attempts with capped exponential backoff plus jitter (a random extra delay, so clients do not retry in step); give each client a retry budget. The Google SRE book describes a per-request limit of three attempts and a per-client rule that allows retries only while they stay below 10% of requests. Add circuit breakers, let overloaded servers shed load and send Retry-After, and never retry errors that will fail again. The resilience patterns skill covers them in depth.
06. Check your understanding
07. Apply it
Continue the practice task. The sample service in the lab hides one synchronous call to a slow dependency and one object created per request. Before you open the lab's steps, read its app.py and write down, for each antipattern of this lesson, whether it is present, the line where it lives, and the measurement that would confirm it: a profile with --idle, the sessions counter, or a per-request dependency count. Then check your guesses against the lab.
08. Review prompt
Without looking back: explain why a blocking call hurts an event loop more than a thread pool, and why to_thread fixes waiting but not computing; list what a new database connection costs and how you would prove that a service creates one per request; describe how a busy front end and a noisy neighbour show up in per-endpoint and per-tenant metrics; and explain how retry storms form, how to detect one, and three ways to prevent it.
References
- Synchronous I/O antipattern (Azure Architecture Center)
- Improper Instantiation antipattern (Azure Architecture Center)
- Busy Front End antipattern (Azure Architecture Center)
- Noisy Neighbor antipattern (Azure Architecture Center)
- Retry Storm antipattern (Azure Architecture Center)
- Google SRE book: Handling Overload (retry budgets)
- Python documentation: Coroutines and Tasks (asyncio.to_thread)
- Python documentation: Python support for free threading
- PostgreSQL 17 documentation: how connections are established
- PostgreSQL 17 documentation: the cumulative statistics system (pg_stat_database)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.