Understanding Backend Concurrency: Threads, Event Loops, and Virtual Threads
How modern systems handle thousands of requests efficiently and the trade-offs behind the most common concurrency models.
Mechanics of Backend Concurrency: Threads, Event Loops
Every backend system must handle multiple requests simultaneously. If a web server processes only one request at a time, all other users are forced to wait or receive an error.
Understanding how your operating system and programming runtime handle multiple tasks shapes your mental model, helps you debug latency issues, and informs your architectural decisions. Most developers learn to use keywords like async, await, or go to make things run concurrently. But understanding the mechanical differences between these models separates engineers who just write code from those who design high-performance systems.
#The I/O Bottleneck
When a client sends a request, your server parses the JSON, queries a database, and returns a response.
Parsing JSON takes CPU cycles. Querying a database takes network I/O. On a local network, a database query might take 1 to 2 milliseconds. In a cross-availability zone production environment, it might take 20 to 30 milliseconds. In a cross-region setup, it might take 90 to 100 milliseconds.
During those 100 milliseconds, your CPU is completely idle regarding that specific request. It is waiting for network packets to arrive. A modern CPU can execute roughly 3 billion instructions per second, which equals 3 million instructions per millisecond. If your server waits 100 milliseconds for a database response, it could have executed 300 million instructions. If your server processes requests synchronously, those 300 million instructions are wasted.
A typical API call involves multiple network operations: 3 to 5 database queries, plus 1 or 2 external calls to services like Redis or an email provider. If each of these 5 operations takes 50 milliseconds, your server spends 250 milliseconds waiting for I/O. The actual CPU computation might only take 10 milliseconds.
Your hardware resources are idle 95% of the time. Concurrency solves this by allowing the CPU to perform other tasks while waiting for I/O operations to complete.
#Concurrency vs. Parallelism
These terms are often used interchangeably, but they mean different things mechanically.
Parallelism is executing multiple instructions at the exact same moment. This requires hardware support. If you have two CPU cores, you can execute two instructions simultaneously. One CPU core can only execute one instruction at a time.
Concurrency is structuring a program to start, pause, and resume multiple tasks. It gives the illusion of doing multiple things at once, even if you only have a single CPU core.
Parallelism is about doing multiple things at once. Concurrency is about dealing with multiple things at once. From the client's perspective, both Request A and Request B are in progress. But at any exact millisecond, only one request is using the CPU.
#I/O Bound vs. CPU Bound
To choose the right concurrency model, you must classify your workload.
| Workload Type | Primary Bottleneck | Examples | Required Model |
|---|---|---|---|
| I/O Bound | Waiting for external resources (network, disk) | Database queries, HTTP API calls, file reads | High Concurrency |
| CPU Bound | Executing instructions (crunching numbers) | Bcrypt hashing, image resizing, complex JSON parsing | High Parallelism |
Most backend applications are heavily I/O bound. The bottleneck is almost always the network, not the CPU. However, if your backend is performing heavy cryptographic operations, video encoding, or processing large media files, it becomes CPU bound, and the rules change.
#Model 1: OS Threads
The traditional approach to concurrency is using operating system threads. A thread is an independent unit of execution managed directly by the OS kernel.
When the OS creates a thread, it allocates a stack to track function calls and local variables. On Linux, this default stack size is often 8MB. While much of this is virtual memory backed by physical pages only when used, it still represents a significant memory footprint. The OS also creates an instruction pointer to track exactly where the thread is in its execution workflow.
The OS uses a preemptive scheduler. It assigns each thread a time slice, usually measured in milliseconds. When the time slice expires, a hardware timer interrupt forces the CPU to pause the thread, save its CPU registers to memory, and switch to the next thread.
The Overhead of Threads
Threads are powerful, but they are expensive.
- Memory: Each thread requires its own stack. If your server creates a new thread for every incoming request, 10,000 concurrent requests will consume gigabytes of RAM just for thread stacks.
- Creation: Creating a thread requires a system call to the kernel. The kernel must allocate memory, set up data structures, and add it to the scheduler. This takes microseconds to milliseconds.
- Context Switching: Switching between threads requires saving and restoring CPU registers and updating kernel bookkeeping. This takes 1 to 10 microseconds. If you have hundreds of threads, the CPU spends a significant amount of time just switching contexts instead of executing your code.
Threads in the same process share memory. This allows fast communication via shared variables, but it introduces the risk of race conditions.
Blocking I/O in Threads
When a thread hits a blocking I/O operation, like reading from a database socket, the CPU cannot do anything. The thread tells the OS scheduler it is blocked. The OS marks the thread as blocked, saves its state, and switches to another thread. When the database returns the response, the OS marks the original thread as runnable, and the scheduler eventually picks it up again.
Here is what this looks like in a synchronous, threading-based language like Python:
def handle_request(request):
# CPU work: parsing request
user_id = parse_json(request)
# I/O work: blocks the entire thread
user = db.query("SELECT * FROM users WHERE id = %s", user_id)
# CPU work: serializing response
return serialize_json(user)To the human reading the code, it looks sequential. But behind the scenes, while db.query is waiting for network packets, the OS pauses this thread and executes other requests.
#Model 2: The Event Loop
The event loop model uses a single thread to handle multiple requests. Instead of pausing and switching threads, the single thread registers callbacks for I/O operations and moves on to the next task.
The golden rule of the event loop is that you must never block it. If you run a heavy CPU-bound task on the main thread, the entire event loop stops. No other requests can be processed, and no I/O callbacks can fire until the blocking task finishes.
The event loop relies on OS-level I/O multiplexing APIs like epoll (Linux) or kqueue (macOS). These APIs allow the OS to monitor thousands of network sockets simultaneously. The OS notifies the application only when a socket is ready to read or write.
Async/Await as a State Machine
Modern languages use async and await to make event loop programming readable. Under the hood, the compiler transforms an async function into a state machine.
Consider this JavaScript function:
async function fetchUserData(userId) {
const user = await db.getUser(userId);
const orders = await db.getOrders(userId);
return { user, orders };
}
The runtime rewrites this conceptually into a state machine that interacts with the event loop:
When the runtime hits an await keyword, it pauses the current state, registers a callback for the I/O operation, and returns control to the event loop. When the I/O completes, the event loop resumes the function at the next state.
This explains two common questions about async/await:
- Why can we only use
awaitinsideasyncfunctions? Because the function must be transformed into a state machine to handle the yielding and resuming. - Why is blocking the event loop so bad? Because the state machine will never get to advance to the next state.
Before async/await, developers had to write nested callbacks, leading to deeply indented code. async/await is syntactic sugar that allows you to write concurrent code that looks sequential, while the runtime handles the state transitions behind the scenes.
#Model 3: Virtual Threads (Goroutines)
Languages like Go use a hybrid approach called virtual threads or Goroutines.
Goroutines are not managed by the operating system. They are managed by the language's runtime scheduler. The Go runtime creates a small pool of actual OS threads (usually matching the number of CPU cores) and maps thousands of Goroutines onto them. This is known as M:N scheduling.
When a Goroutine hits a blocking I/O operation, the Go runtime scheduler pauses that specific Goroutine and swaps in another Goroutine to run on the same OS thread.
Why Goroutines are Lightweight
- Tiny Initial Stack: A Goroutine stack starts at just 2KB and grows dynamically as needed. You can spawn millions of them before exhausting memory.
- User-Space Context Switching: Switching between Goroutines does not require a kernel system call. It only requires swapping a few pointers in user space. This takes nanoseconds, compared to the microseconds required for an OS thread context switch.
Because they are so cheap, the Go standard library creates a new Goroutine for every incoming HTTP request. You write synchronous, blocking code, and the runtime handles the concurrency transparently.
func handleRequest(w http.ResponseWriter, r *http.Request) {
// CPU work
userID := parseJSON(r)
// I/O work: blocks only this Goroutine, not the OS thread
user := db.Query("SELECT * FROM users WHERE id = ?", userID)
// CPU work
writeJSON(w, user)
}#The Concurrency Trap: Race Conditions
Whenever multiple tasks share state, you risk race conditions. The root cause of almost all concurrency bugs is shared memory.
The Lost Update Problem
Consider a simple counter. To increment it, a thread must perform three steps: read the value, add one, and write the new value.
If two threads try to increment the counter at the exact same time:
- Millisecond 1: Thread A reads the counter (value is 0).
- Millisecond 2: Thread B reads the counter (value is 0).
- Millisecond 3: Thread A adds 1 to its register (value is 1).
- Millisecond 4: Thread B adds 1 to its register (value is 1).
- Millisecond 5: Thread A writes 1 back to the counter.
- Millisecond 6: Thread B writes 1 back to the counter.
The final value is 1, not 2. Thread A's increment was completely lost. This is a classic race condition caused by shared memory.
Race Conditions in Single-Threaded Async
A common misconception is that single-threaded event loops are immune to race conditions. They are not. Any await keyword creates a yield point where other tasks can execute and mutate shared state.
Consider a bank withdrawal function:
let balance = 100;
async function withdraw(amount) {
if (balance >= amount) {
await processWithdrawal(); // Yields control to event loop
balance = balance - amount;
}
}If you call withdraw(100) twice concurrently when the balance is 100:
- Task A checks the balance (
100 >= 100). It enters the block and hitsawait. Control is yielded to the event loop. - Task B starts executing. It checks the balance (
100 >= 100). It enters the block and hitsawait. Control is yielded. - Task A's I/O completes. It resumes and sets
balance = 100 - 100(0). - Task B's I/O completes. It resumes and sets
balance = 0 - 100(-100).
The final balance is -100. The check passed for both tasks because the state was evaluated before either task yielded control. Single-threaded async code is highly susceptible to race conditions if shared state is modified after an await.
#Solving Shared State Issues
To prevent race conditions, you must control access to shared state.
Mutexes and Locks
A mutex (mutual exclusion) ensures that only one task can execute a specific block of code at a time. If Task A acquires the lock, Task B must wait until Task A releases it. This serializes access to the shared variable, preventing interleaved operations.
import threading
lock = threading.Lock()
counter = 0
def increment():
global counter
with lock:
current = counter
counter = current + 1Message Passing via Channels
Instead of sharing memory, tasks can communicate by passing messages. This is the core philosophy of Go's channels. By ensuring that only one specific Goroutine is responsible for updating a piece of state, and having all other Goroutines send requests to it via a channel, you eliminate shared memory mutations entirely. The state is isolated, and concurrency bugs disappear.
#Choosing the Right Model
Backend systems spend the majority of their time waiting for I/O. Concurrency allows your application to remain productive during these wait times by switching to other tasks.
- Use OS threads when you need true parallelism for CPU-bound workloads, but be mindful of memory and context-switching overhead.
- Use the event loop for highly concurrent, I/O-bound workloads, but ensure your callbacks and async functions remain non-blocking.
- Use virtual threads when you want the ergonomic, synchronous code style of threads with the lightweight efficiency of an event loop.
Regardless of the model you choose, shared state is the enemy. Design your systems to minimize shared memory, use locks when mutation is unavoidable, and never block the thread responsible for handling your I/O.