Threads, Processes and Async: How Servers Handle Many Users
A web server that could only help one visitor at a time would be useless. Even a modest site may have dozens of people clicking at the same moment, and a busy one has thousands. Yet a computer has a limited number of processor cores, and each request may spend most of its life waiting on a disk or a database.
Servers solve this with three main tools: processes, threads and asynchronous programming. Each has strengths, costs and a typical home. Knowing the differences helps you read documentation, pick a framework and diagnose slow behavior.
The Basic Problem
Handling a request involves two kinds of time. Some of it is computation, where the processor is genuinely busy, such as rendering a template or checking a password hash. Most of it is waiting: for a database answer, a file to load or bytes to arrive over the network.
A naive server that handles one request from start to finish before touching the next wastes all that waiting time. The goal of concurrency is to make use of those idle moments, and when possible to use several cores at once.
Concurrency and parallelism are related but different. Concurrency means making progress on many tasks during the same period. Parallelism means literally running several tasks at the same instant on separate cores. A single core can be concurrent but not parallel.
Processes
A process is a running program with its own private memory. The operating system isolates processes from each other, so one cannot accidentally overwrite another's data.
Many classic servers use a pre-fork model: a main process starts a number of worker processes, and each worker handles one request at a time. Several popular Python and Ruby application servers work this way.
Benefits include strong isolation, since a crash in one worker does not take down the rest, and straightforward use of multiple cores. Drawbacks include higher memory use, because each process carries its own copy of the program, and extra effort when processes need to share data. They must communicate through files, sockets or a shared store instead of simple variables.
Threads
A thread is a lighter unit of execution that lives inside a process. Threads in the same process share memory, so they can read and write the same objects quickly.
A threaded server might create one thread per request or keep a pool of reusable threads. While one thread waits for the database, the operating system runs another. Threads are cheaper than processes, and they let several cores work on the same data.
The price is complexity. When two threads change the same piece of data, results depend on timing. This is a race condition, and it produces bugs that appear rarely and are hard to reproduce. Programmers use locks and other synchronization tools to prevent these problems, but locks add their own risks, such as deadlocks, where two threads wait on each other forever.
Some language runtimes also limit true parallelism. Python's standard implementation, for example, uses a global interpreter lock that lets only one thread run Python code at a time, although threads still help while waiting on input and output.
Asynchronous Programming
The asynchronous model takes a different path. Instead of giving each request its own thread, a single thread runs an event loop. When code needs to wait, it says so, usually with a keyword such as await, and the loop switches to another task that is ready. When the awaited result arrives, the first task resumes.
async def handle(request):
user = await database.fetch_user(request.user_id)
return render(user)
This is cooperative multitasking. Tasks hand control back voluntarily at each wait point. Because switching tasks is just a function call, one thread can juggle a very large number of mostly idle connections with modest memory.
The weakness is that a task which never yields, such as a long calculation, blocks every other task on that loop. Async shines for input and output heavy work and struggles with CPU heavy work.
Choosing and Combining
Real systems often mix the models.
- Many workers, each async: run one process per core, and let each process use an event loop. This gives parallelism across cores and cheap concurrency within each.
- Threads for blocking libraries: when a library offers no async version, push its calls onto a thread pool so the event loop stays responsive.
- Separate processes for heavy jobs: send image processing or report generation to a background worker, and keep the web process quick.
A rough guide follows.
- Mostly waiting on networks and databases: async or threads.
- Mostly computing: multiple processes, or native code that releases the interpreter lock.
- Need strong fault isolation: processes.
- Need shared in-memory state with low overhead: threads, handled carefully.
Signs You Picked Wrong
Symptoms give useful clues. If response times spike whenever one slow endpoint is called, a blocking call is probably stuck on a shared thread or loop. If memory climbs with each added worker, you may be paying for too many full processes. If rare, unexplained data corruption appears, look for unsynchronized threads.
Measure before changing anything. Load testing a realistic request mix tells you far more than theory.
Frequently Asked Questions
What is the difference between concurrency and parallelism?
Concurrency is about structuring work so many tasks can make progress in overlapping time, even on one core. Parallelism means tasks truly run at the same instant on different cores. A system can have one without the other.
Is async always faster than threads?
No. Async is efficient for large numbers of connections that mostly wait, but it gives no benefit for CPU-bound work and can be hurt by a single blocking call. Threads can be a simpler fit when your libraries are blocking.
Why do some servers run several worker processes?
Worker processes let a server use every processor core and isolate failures, since a crash affects only one worker. They also sidestep interpreter locks in languages that have them, at the cost of more memory.