SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • Scalability
  • Availability
  • Reliability
  • Single Point of Failure (SPOF)
  • Latency vs Throughput vs Bandwidth
  • Consistent Hashing
  • CAP Theorem
  • Fault Tolerance and Redundancy
  • Failover
  • Stateless vs Stateful
  • Concurrency vs Parallelism
  • Capacity Planning
  • Back Pressure
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Core Concepts

Concurrency vs Parallelism

Juggling many tasks versus doing many at once, and the bugs it brings: race conditions and deadlock.

⏱ 15 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Concurrency is dealing with many tasks at once, by switching between them. Parallelism is running many tasks at the same instant on different CPU cores.

  • One cook switching between three pots is concurrent. Three cooks, one pot each, is parallel.
  • When tasks share data, concurrency brings bugs: a race condition (the result depends on timing) and a deadlock (everyone waits for everyone).
  • The cures: locks used with care, a fixed lock order, timeouts, and sharing as little as possible.

02Concept: What is it?

A computer with a single core can still "do many things at once". It runs one task for a very short time, then switches to another, and so on, so fast that all of them seem to move together. This is concurrency: a way to structure a program as several tasks in progress. With several cores, tasks can truly run at the same moment. That is parallelism: a way to make the work faster by doing parts simultaneously.

You can have concurrency without parallelism (one core, many tasks), parallelism without much concurrency (one big job split into equal pieces), or both. A server that handles thousands of requests with a few threads that wait for the network (I/O) is concurrent. A video encoder that uses all 8 cores is parallel.

Concurrent vs parallel
Concurrent (1 core)
⚙️Core 1A, B, C, A, B, C ...
↓switches quickly
⏱️Total time = A + B + C
Parallel (3 cores)
⚙️Core 1A
⚙️Core 2B
⚙️Core 3C
⏱️Total time = the longest one
Same three tasks. One core switches between them, three cores run them side by side.
🧠The danger is shared data
If tasks never touch the same data, concurrency is easy. The trouble starts when two tasks read and change the same thing, and the final answer depends on who moved first.

03Real-Life Example

🍵Two Cooks and One Recipe Board
A kitchen has a whiteboard that shows "eggs left: 10". Cook A reads the board (10), walks to the fridge, takes 1 egg and plans to write 9. At the same moment cook B reads the board (still 10), takes 1 egg and also plans to write 9. Both write 9. Two eggs were used, but the board says 9 instead of 8. That is a race condition. Now picture two cooks who each hold one knife and one board, and each needs the other's tool to finish. Both wait politely forever. That is a deadlock.
Kitchen
Concurrency
One cook, three pots, switching
Concurrency on one core
Three cooks, one pot each
Parallelism on many cores
The shared whiteboard
Shared data (a variable, a row)
Read the board, think, then write
Read, modify, write (not atomic)
Only one cook may hold the marker
A lock (mutex)
Each waits for the tool the other holds
Deadlock
A rule: always take the knife first, then the board
Lock ordering
A lost update
🅰️A reads 5
→↓
🅱️B reads 5
→↓
🅰️A writes 6
→↓
🅱️B writes 6should be 7
Two workers read the same value, so one increment disappears.

04Why Do We Need It?

⏳Do not waste waiting time
While one task waits for a disk or the network, another task can use the CPU.
🚀Use every core
Modern machines have many cores. Without parallelism most of them stay idle.
👥Serve many users
A server must handle thousands of requests at the same time.
🐞Avoid nasty bugs
Race conditions and deadlocks pass most tests and then fail in production, rarely and without a clear cause.
🧮Know the limits
Some work cannot be split. More cores do not make that part faster.
🎙️Talk about it in interviews
Locks, threads, atomic operations and deadlocks are standard system design topics.
Concurrency is about structure, parallelism is about speed, and shared data is where the bugs live.

05Where Do We Use It?

🌐Web servers
Many requests are in progress at once, handled by threads or an event loop.
🗄️Databases
Many transactions run together. Locks and isolation levels keep them from clashing.
🎞️Video and image work
A big job is split into pieces and processed on several cores or machines.
🧠Machine learning
Matrix maths runs in parallel on GPUs.
🧰Thread pools and queues
A fixed set of workers takes tasks from a queue.
🔁Counters and caches
Shared counters and caches need atomic updates or locks.

06Types / Parts / How It Works

Concurrency vs parallelism

ConcurrencyParallelism
IdeaMany tasks in progress, taking turnsMany tasks running at the same instant
Needs several cores?NoYes
Main goalHandle many things, hide waitingFinish one big job faster
Good forI/O-heavy work (network, disk)CPU-heavy work (encoding, maths)
Typical toolsThreads, async/await, event loopsMultiple processes, thread pools on many cores, GPUs
Main riskRaces and deadlocks on shared dataThe same risks, plus limits from the part that cannot be split

The two classic bugs

BugWhat happensTypical cures
Race conditionThe result depends on the order of steps. A read-modify-write is cut in the middle, so an update is lostA lock around the whole step, an atomic operation (atomic increment, compare-and-swap), or avoid sharing
DeadlockTasks wait in a circle for locks that others hold, and none can moveTake locks in one fixed order, hold fewer locks, use timeouts, or avoid nested locks
StarvationA task never gets its turn because others keep winningFair locks, queues, priorities that age

The four conditions for a deadlock (all must be true)

  • Mutual exclusion: a resource can be held by only one task at a time.
  • Hold and wait: a task holds one resource while waiting for another.
  • No taking away: a held resource cannot be forced out of the holder's hands.
  • Circular wait: there is a loop of tasks, each waiting for the next one's resource.
💡Break one condition, and deadlock is impossible
A fixed lock order breaks the circular wait. A timeout breaks hold-and-wait. Taking all locks at once breaks hold-and-wait too.
VisualizerRace condition, deadlock, and one core vs manyRun the race without a lock and press Play. Then add the lock. Switch to deadlock, then fix the lock order. Finally compare one core with several.
What do you want to see?
Who moves next?
Protection
🔢Shared counter = 0lock: free
🧑‍💻Worker Aholds nothing
read counteradd 1write counter
🧑‍💻Worker Bholds nothing
read counteradd 1write counter
Step 1 of 7
Start
Two workers are ready. Each one runs its small steps, one at a time. We choose which worker moves next.
Expected
2
increments done
Final counter
1
at the last step
Lost updates
1
overwritten
Final counter 1, but 2 increments were done. Updates were lost. Both workers read the same old value, so the second write erased the first. Press Play and watch the “holds” number.

Simplified and deterministic. The order of steps is chosen by the buttons, not at random. Real schedulers can pick any order, which is why these bugs appear only sometimes. Each task is a made-up 4 units of work.

07How to Use It / Steps / Implementation

Writing safe concurrent code

  1. 1
    Share as little as you can
    Pass messages, give each task its own copy, or use immutable data. No shared data means no race.
  2. 2
    Find the critical section
    A critical section is a piece of code that touches shared data. Make it short and protect the whole of it.
  3. 3
    Protect it
    Use a lock (mutex), or an atomic operation for simple counters and flags. Protect the read, the change and the write together.
  4. 4
    Fix a lock order
    If you need several locks, always take them in the same order, everywhere in the code.
  5. 5
    Do not hold locks while waiting
    Never call the network, the disk or unknown code while holding a lock. It stalls others and invites deadlock.
  6. 6
    Use timeouts
    Waiting for a lock or a result with a timeout turns a hang into an error you can handle.
  7. 7
    Prefer safe building blocks
    Thread-safe queues, concurrent maps, thread pools and actors are better than inventing your own locking.
  8. 8
    Test under stress
    Run many threads, add random delays, use race detectors (for example the thread sanitizer or Go's race detector). Bugs hide in the rare timing.
⚠️Locks have a cost
Too many locks, or one big lock, makes everything wait in line. Then a program with 8 cores runs as if it had 1. Lock only what you must, for as short a time as you can.
📝Across machines
The same ideas return in distributed systems, where there is no shared memory. You then need distributed locks, versions on records, or idempotent operations.

08Key Terms to Know

TermMeaning in easy words
ConcurrencySeveral tasks in progress at the same time, usually by taking turns
ParallelismSeveral tasks running at the very same moment on different cores
ProcessA running program with its own memory
ThreadA unit of work inside a process. Threads of one process share its memory
Race conditionA bug where the result depends on the timing of tasks
Critical sectionCode that touches shared data and must not be interrupted by others
Lock / mutexA key that only one task can hold, to protect a critical section
Atomic operationOne step that cannot be cut in the middle (such as an atomic increment)
DeadlockTasks wait for each other in a circle, and none can continue
StarvationA task never gets its turn
Context switchThe CPU stops one task and starts another. It has a small cost

09Pros, Cons and Trade-offs

✅ Pros
  • Hides waiting time and keeps the CPU busy
  • Lets one server handle many users
  • Parallelism can speed up big jobs a lot
  • Makes programs responsive (the screen does not freeze)
  • Maps well to multi-core hardware
⚠️ Cons
  • Races and deadlocks are hard to see and to repeat
  • Locks add waiting and complexity
  • Context switches cost time
  • Not every job can be split, so more cores may not help
  • Code is harder to test and to reason about

Trade-offs

ChoiceWe gainWe lose
One big lockSimple and safeLittle parallelism, everyone waits
Many small locksMore work in parallelMore chance of deadlock and mistakes
Atomic operationsFast, no waiting for simple updatesOnly fit simple cases
Message passing, no shared dataNo races on shared memoryCopying data and a different style of design
More threadsMore work in progressMore switching and memory, and diminishing returns
Optimistic updates with retryNo waiting when conflicts are rareWasted work when conflicts are common

10Common Problems and Mistakes

Common mistakes

  1. Checking and then acting. "If the seat is free, book it" is a race if another task can book it between the check and the action.
  2. Forgetting the lock on one path. A single unprotected access breaks the whole protection.
  3. Different lock orders. One function locks A then B, another locks B then A. That is a deadlock waiting to happen.
  4. Holding a lock during slow work. A network call under a lock blocks everyone else.
  5. Believing a test that passed. Timing bugs may pass a thousand runs and fail on the next one.
  6. Too many threads. Thousands of threads waste memory and time on switching.
  7. Assuming a read-modify-write is atomic. count++ is read, add, write: three steps.

Things to watch

🎲Heisenbugs
Bugs that vanish when you add logging, because timing changes. Use race detectors.
🪢Lock contention
Many threads fight for one lock. Measure wait time and split the lock or the data.
🧊Hung threads
A deadlock shows as work that never ends. Use thread dumps and timeouts to find it.
🧮Amdahl's limit
The part of a job that must run in order limits the speed-up, however many cores you add.

11Real-World Examples

🟦Node.js
One thread with an event loop handles many connections concurrently, and worker threads or processes add parallelism.
🐹Go
Goroutines and channels make concurrency easy, and a race detector helps find races.
☕Java
Thread pools, ExecutorService and concurrent collections, with synchronized blocks and locks.
🗄️Database transactions
Locks, versions and isolation levels let many transactions run without lost updates.
🏦Bank transfers
Moving money between two accounts takes two locks. A fixed order (for example lower account id first) avoids deadlock.
🎟️Ticket booking
Two people click the last seat at the same moment. A lock, a unique constraint or a version check decides who wins.
📝Note
Language and library details change between versions. Treat the names as examples and check your language's documentation.
Mini case: a transfer between two accounts
🧑Transfer 1X → Y
→↓lock lower id first
🔒Lock X, then Y
←same order
🧑Transfer 2Y → X
Same lock order
Take the locks in one fixed order, and the circle cannot form.

12Related Topics to Read Next

Basic OS: Process, Thread, Memory→

The building blocks that concurrency uses.

ACID Transactions→

Databases solve races between many users with isolation.

Distributed Locks→

The same problem across many machines.

Idempotency→

Makes repeated or overlapping work safe.

Connection Pooling→

A pool shares a few connections between many tasks.

Back Pressure→

What to do when work arrives faster than it can be done.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Concurrency: many tasks in progress, taking turns. Parallelism: many tasks at the same instant.
  • ✔Race condition: result depends on timing. Typical: read, add, write on a shared counter.
  • ✔Fix a race: avoid sharing, use a lock, or use an atomic operation.
  • ✔Deadlock: a circle of waiting. Needs mutual exclusion, hold and wait, no preemption, circular wait.
  • ✔Avoid deadlock: one lock order everywhere, short locks, timeouts.
  • ✔Never: hold a lock while doing slow I/O or calling unknown code.
  • ✔Limit: the part that cannot be split caps the speed-up (Amdahl).
  • ✔One line: “Share less, lock the whole step, and always lock in the same order.”
← Previous
Stateless vs Stateful
Next →
Capacity Planning