Concurrency models: processes vs threads
System DesignModel answerLast updated
Contrast processes and threads as concurrency primitives, covering isolation, memory models, IPC vs shared memory, and when to choose each.
Concurrency models: processes vs threads
You're designing a backend service that needs to handle work concurrently. Explain how processes and threads differ as concurrency primitives.
Your answer should cover:
- Core definitions: what each primitive represents at the OS level
- Memory model: how each manages address space and data visibility
- Communication: how units coordinate and share information
- Performance characteristics: creation cost, context switching, CPU-bound vs I/O-bound workloads
- Fault isolation: what happens when one unit fails
- Practical examples: describe 1–2 scenarios where you'd pick one over the other
Be concrete. Mention specific mechanisms (like copy-on-write, the GIL, or cache coherence) where relevant.
Hints
Hint 1
Think about what resources each primitive owns versus shares with others
Hint 2
Consider the trade-off between isolation and communication overhead
Hint 3
The Python GIL changes the calculus for CPU-bound work—why?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Core definitions
A process is the operating system's abstraction for a running program. It owns a virtual address space, file descriptors, security credentials, and at least one thread of execution. The OS schedules processes independently and enforces boundaries between them.
A thread is a schedulable unit of execution within a process. Threads share their parent process's address space, open files, and other resources, but each has its own stack, register state, and instruction pointer.
In one line: processes provide isolation; threads provide cheap sharing.
Memory model
Processes have isolated address spaces. Process A cannot read or write Process B's memory without explicit setup. When you fork a process, the child gets a logical copy of the parent's memory, but the OS uses copy-on-write: physical pages are shared until either side modifies them. To share data deliberately, processes use mechanisms like mmap(MAP_SHARED) or System V shared memory.
Threads share everything except their stacks. All threads in a process see the same heap, globals, and code segment. A pointer to a heap object works identically across all threads. Each thread's stack lives in the shared address space, so technically one thread could access another's stack variables if it had the address—though this is rarely safe.
This shared-memory model makes communication trivial but introduces data races. Without synchronization (mutexes, atomics, memory barriers), concurrent reads and writes produce undefined behavior.
Communication patterns
Threads communicate via shared memory:
- Read and write shared variables directly
- Synchronize with mutexes, condition variables, semaphores, or lock-free atomics
- Common bugs: race conditions, deadlocks, priority inversion, and visibility issues (one thread's write not seen by another due to CPU caching)
Processes communicate via inter-process communication (IPC):
- Pipes, Unix domain sockets, or TCP sockets
- Message queues (POSIX or System V)
- Signals for simple notifications
- Shared memory segments paired with a cross-process lock (semaphore or file lock)
Message-passing IPC forces explicit serialization. In Python, this means pickling objects; in other languages, you might use Protocol Buffers or JSON. This overhead is real, but the explicit message boundaries make systems easier to reason about and naturally extend to distributed environments (multiple machines).
Performance characteristics
Creation cost:
- Processes are heavier. Forking duplicates page tables, file descriptor tables, and sets up a new PID namespace. Modern kernels mitigate this with copy-on-write, but it's still more expensive than threads.
- Threads are cheaper. The kernel allocates a stack (typically 2–8 MB of virtual memory) and a thread control block, but reuses the existing address space.
Context switching:
- Switching processes changes the address space, flushing the TLB (translation lookaside buffer) and polluting CPU caches. This adds microseconds of overhead.
- Switching threads within the same process keeps the address space intact, so TLB and cache remain warm. Context switches cost tens of nanoseconds on modern hardware.
CPU-bound workloads (computation-heavy):
- In languages like C, C++, Rust, Java, or Go, threads scale across multiple cores. All threads can execute simultaneously.
- In CPython, the Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time. CPU-bound threads serialize, gaining no speedup. Use multiprocessing instead, or call into native code (like NumPy) that releases the GIL. Python 3.13 introduced an experimental free-threaded build, but the default still has the GIL.
I/O-bound workloads (network, disk, database):
- Threads excel here. Even in Python, blocking I/O releases the GIL, so threads overlap wait time efficiently.
- Processes would waste memory for no gain.
- At extreme concurrency (tens of thousands of connections), async I/O or event loops (like
asyncio,libuv) often outperform both.
Memory overhead:
- Each process duplicates code, heap, and ancillary structures. A thousand worker processes consume gigabytes.
- Threads share the heap and code, so memory scales much better for high concurrency.
Fault isolation
Thread failures propagate to the entire process:
- A segfault, null pointer dereference, or stack overflow in any thread crashes the whole process.
- In Python, an unhandled exception terminates only that thread, but it may leave shared state corrupted or locks permanently held.
Process failures are contained:
- A worker process crash is visible to the parent (via
wait()orSIGCHLD). The parent can restart the worker. - This is why Chrome isolates renderer processes per tab, why nginx and Gunicorn use worker processes, and why PostgreSQL spawns one backend process per connection.
Security boundaries align with process boundaries. Sandboxing, privilege separation, and running untrusted code all require separate processes.
When to choose each
Choose threads when:
-
I/O-bound fanout. A request triggers 20 downstream API calls. A thread pool overlaps the waits and shares a single connection pool and cache. No serialization overhead.
-
Low-latency responsiveness. A desktop application offloads file parsing to a background thread so the UI remains interactive. Both threads share application state without copying.
Choose processes when:
-
CPU-bound parallelism in Python. Training a model, batch-processing images, or running heavy simulations. Processes sidestep the GIL and utilize all cores. PyTorch
DataLoaderworkers andmultiprocessing.Poolboth use this pattern. -
Fault isolation and robustness. Running plugin code, user-submitted scripts, or web scraping tasks that might crash. A worker pool where each process handles N tasks, then exits to release leaked resources. The supervisor restarts crashed workers without affecting others.
Common pitfalls
Forking multithreaded programs: only the thread that calls fork() survives in the child. Locks held by other threads remain locked forever, causing deadlocks. Use the spawn start method in Python's multiprocessing, or fork before creating threads.
Pickling limitations: Python's multiprocessing serializes arguments and return values. Lambdas, open file handles, and sockets cannot be pickled. Workaround: use multiprocessing.Manager or shared memory for large data.
Thread stack exhaustion: each thread reserves virtual memory for its stack (often 8 MB). Creating 10,000 threads consumes 80 GB of address space, even if most is unused. Use a thread pool sized to available cores for CPU work, or switch to async I/O for high concurrency.
False sharing: independent variables on the same cache line (64 bytes on x86) cause cache thrashing when updated by different threads. Pad hot variables or use thread-local storage.
Python code example
import time
from threading import Thread, Lock
from multiprocessing import Process
shared_counter = 0
lock = Lock()
def increment_with_lock(iterations: int) -> None:
global shared_counter
for _ in range(iterations):
with lock:
shared_counter += 1
def cpu_work(n: int) -> int:
"""Simulates CPU-bound computation."""
total = 0
for i in range(n):
total += i * i
return total
def io_work(delay: float) -> None:
"""Simulates I/O-bound work."""
time.sleep(delay) # Releases GIL during sleep
# Threads share memory
shared_counter = 0
threads = [Thread(target=increment_with_lock, args=(50_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Threads: shared_counter = {shared_counter}") # 200,000
# Processes have isolated memory
shared_counter = 0
processes = [Process(target=increment_with_lock, args=(50_000,)) for _ in range(4)]
for p in processes:
p.start()
for p in processes:
p.join()
print(f"Processes: parent's shared_counter = {shared_counter}") # Still 0
Key takeaway: threads see one shared shared_counter; processes each modify their own private copy, leaving the parent's untouched.