Guide / System design Fundamentals
Concurrency and connection pool basics
Threads vs async, locks and deadlocks, race conditions, thread and connection pool sizing, and how single-machine concurrency ideas map to distributed systems.
Many system design and LLD questions hide a concurrency question: two requests, one resource. This page gives you the vocabulary and the numbers.
Fundamentals#
C.1 Processes, threads, async#
| Model | How | Good for | Cost |
|---|---|---|---|
| Multi-process | Separate memory (Python workers, Nginx) | Isolation, CPU parallelism without GIL | Memory, IPC |
| Threads | Shared memory, OS scheduled | CPU and blocking I/O in one process | Race conditions, context switches, ~1 MB stack each |
| Async / event loop (Node, asyncio, Netty, Go goroutines scheduled by the runtime) | One thread multiplexes thousands of I/O waits | I/O-bound servers (10K+ connections) | A CPU-bound task blocks the loop; callbacks/await complexity |
Rule: I/O-bound → async or many threads; CPU-bound → processes or a pool sized to cores. Never block an event loop with CPU work or synchronous I/O.
C.2 Race conditions and synchronisation#
A race condition is a bug whose outcome depends on timing. Classic: if (balance >= x) balance -= x run twice concurrently. Tools:
- Mutex/lock: one thread at a time; keep critical sections tiny.
- Read-write lock: many readers or one writer.
- Atomic operations / CAS (compare-and-swap): lock-free counters and updates.
- Semaphore: limit concurrent access to N resources (a pool).
- Immutability and message passing: avoid shared state (actors, channels).
- Thread-safe structures:
ConcurrentHashMap, queues.
Deadlock needs four conditions: mutual exclusion, hold-and-wait, no preemption, circular wait. Break one: acquire locks in a global order, use timeouts (tryLock), or avoid nested locks. Livelock: threads keep reacting without progress. Starvation: a thread never gets the lock (use fair locks). Priority inversion: a low-priority thread holds a lock the high-priority one needs.
C.3 Pool sizing#
Thread pool for CPU work: cores (or cores + 1). For blocking I/O: cores × (1 + wait_time / compute_time): a request that computes 10 ms and waits 90 ms on a DB needs ~10 threads per core to keep a core busy.
Little’s Law: concurrency = throughput × latency. To serve 500 req/s at 200 ms you need ~100 requests in flight.
DB connection pool: more connections is not faster. A rule of thumb for the database side is about 2 × cores + effective_spindles active queries. A pool of 10–30 per app instance is typical; total across all instances must stay under the DB’s limit (use PgBouncer/RDS Proxy when instances multiply). Pool exhaustion shows as threads waiting for a connection: set a checkout timeout and alert on wait time. Never hold a connection while calling a slow external service.
Queues: bound every queue; an unbounded queue turns overload into out-of-memory and endless latency. Choose a rejection policy (fail fast, caller-runs, drop oldest).
C.4 From single machine to distributed#
| Single machine | Distributed equivalent | Note |
|---|---|---|
| Mutex | Distributed lock (Redis, ZooKeeper, DB row lock) | Needs fencing tokens; prefer constraints and conditional updates (Distributed systems) |
| Atomic CAS | Conditional write (WHERE version=?, DynamoDB condition expression) | The workhorse |
| Thread-safe queue | Kafka, SQS | At-least-once, idempotent consumers |
| Semaphore | Rate/concurrency limiter | Rate limiting |
| Memory barrier / visibility | Replication lag and consistency models | |
| Deadlock | Distributed deadlock: lock ordering and timeouts |
C.5 Concurrency patterns for LLD rounds#
Producer-consumer with a bounded blocking queue; worker pool with a job queue; read-through cache with per-key locks (single-flight); rate limiter with atomic token buckets; seat booking with hold + expiry and atomic state transitions; debounce and throttle; and idempotent handlers for retries. See LLD solutions.
Most asked questions#
1. Thread vs process vs async? Isolation vs shared memory vs cooperative multiplexing; choose by workload type (CPU vs I/O).
2. What is a deadlock and how do you prevent it? Circular wait on locks; consistent lock ordering, timeouts, fewer nested locks.
3. How do you size a thread pool? CPU-bound: ~cores; I/O-bound: cores × (1 + wait/compute); verify under load.
4. How do you prevent two requests from booking the same seat? Atomic conditional update or a unique constraint; hold with expiry; not check-then-act in application code.
5. Optimistic vs pessimistic locking? Optimistic: version check at write, retry on conflict (low contention). Pessimistic: lock first (high contention, short transactions).
6. What is the difference between concurrency and parallelism? Concurrency is structuring work as independent tasks interleaved; parallelism is executing simultaneously on multiple cores.
Senior-level questions#
1. “Latency spikes every few minutes on an async server.” A blocking call or CPU burst on the event loop, GC pauses, DNS resolution blocking, or a synchronous log write; use loop-lag metrics and profiling, move work to a pool.
2. “The service falls over at 100 users yet CPU is 10%.” Thread or connection pool exhaustion, a lock bottleneck, or a downstream limit; check pool wait times and thread dumps.
3. “Our retry logic created duplicate work under concurrency.” Make handlers idempotent and guard with unique constraints; use single-flight for identical in-flight work.
4. “Explain the cost of a lock under contention.” Context switches, cache-line bouncing and serialisation (Amdahl): throughput stops scaling; use sharded locks, lock-free structures or reduce shared state.
5. “How do you reason about memory visibility?” Without synchronisation, writes may not be visible to other threads; use volatile/atomics/locks (happens-before), or immutable data.
Quiz#
1. A request spends 5 ms on CPU and 45 ms waiting on I/O. Threads per core to saturate it?
1 + 45/5 = 10 threads per core.
2. Name the four deadlock conditions.
Mutual exclusion, hold and wait, no preemption, circular wait.
3. Why is a 500-connection pool per instance usually harmful?
The database cannot execute that many queries efficiently; contention rises, total connections across instances exceed limits, and latency worsens. Use a small pool and a proxy.
4. What does CAS stand for and use?
Compare-and-swap: atomically update a value only if it still equals the expected one; basis of lock-free structures and optimistic version checks.
5. Why should queues be bounded?
To apply backpressure; unbounded queues hide overload and consume memory until failure.