SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • What is System Design?
  • High-Level Design (HLD)
  • Low-Level Design (LLD)
  • Functional vs Non-Functional Requirements
  • Back-of-the-Envelope Estimation
  • Numbers Every Engineer Should Know
  • SLA, SLO and SLI
  • Basic OS: Process, Thread, Memory
  • 30 Must-Know Concepts
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/Introduction

Basic OS: Process, Thread, Memory

What a running program really is: processes, threads and the memory they use.

⏱ 14 min readBeginnerMust KnowHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Every server you design runs on an operating system (OS). A few OS ideas explain a lot of system design: what a process is, what a thread is, and how memory is used.

  • A process is a running program with its own private memory.
  • A thread is a line of work inside a process. Threads of one process share its memory.
  • Memory is split into code, heap (shared, grows as needed) and stack (one per thread).
  • Sharing is fast but risky: two threads changing the same data can cause bugs called race conditions.

02Concept: What is it?

A program is a file on disk. When you start it, the OS creates a process: a running copy with its own memory space, its own open files, and at least one thread.

A thread is the smallest unit of work the OS can schedule on a CPU core. A process can have one thread or thousands. Threads of the same process see the same heap, but each has its own stack for its function calls and local variables.

What is inside a process
1Codethe instructions of the program (shared, read only)
2Heapobjects and data made at run time, shared by all threads
3Stack of each threadfunction calls and local variables, one stack per thread
Memory layout is simplified. Real systems have more regions, but these three are the ones to remember.
Process vs thread
Process A
🧵Thread 1
🧵Thread 2
🧠Shared heap
Process B
🧵Thread 1
🧠Own heap
Processes are walled off from each other. Threads live together inside one wall.
🧠One sentence to keep
Processes isolate (safer, heavier). Threads share (faster, riskier).

03Real-Life Example

🍵Restaurants and cooks
Think of a restaurant as a process. It has its own kitchen (memory), its own fridge and its own recipe book (code). The cooks are threads. They all work in the same kitchen and share the same fridge. This is fast, but if two cooks reach for the last egg at the same time, there is trouble. A different restaurant across the street (another process) has its own kitchen. Its cooks cannot take your eggs, but you also cannot just grab theirs. You must phone them (inter-process communication).
Restaurant
Operating system
A restaurant
A process
A cook
A thread
The shared kitchen and fridge
The heap, shared by all threads
A cook’s own notepad
A thread’s stack
The recipe book
The code
Two cooks grabbing the last egg
A race condition
A sign: “only one cook at the stove”
A lock (mutex)
Phoning the other restaurant
Inter-process communication

04Why Do We Need It?

🧠Understand your server
Web servers, databases and caches are all processes with threads. Knowing this explains their limits.
⚡Use all CPU cores
One thread uses one core at a time. To use many cores you need many threads or processes.
🛡️Isolation
A crash in one process does not take down another. That is why browsers and servers use many processes.
💾Memory is limited
Each thread has a stack, and each process has overhead. Too many can use all the memory.
🐛Avoid nasty bugs
Races and deadlocks come from shared memory. They are hard to see and hard to repeat.
📈Scale choices
“More threads or more processes or more machines?” is a basic design choice.
Before you scale out to many machines, know what one machine does: processes, threads and memory.

05Where Do We Use It?

🌐Web servers
Some use a thread per request, some use several processes, and some use one thread with an event loop.
🗄️Databases
PostgreSQL commonly runs a process per connection. MySQL commonly runs a thread per connection.
🧭Browsers
Modern browsers run tabs and plugins in separate processes, so one bad page cannot crash everything.
🐳Containers
A container is, at heart, one or more processes with limits on CPU, memory and what they can see.
🧰Worker pools
Thread pools and process pools reuse workers instead of creating new ones for each job.
🐍Language runtimes
Some runtimes limit threads running at once (for example CPython’s global interpreter lock), so people use processes instead.

06Types / Parts / How It Works

Process vs thread

ProcessThread
MemoryIts own private address spaceShares the heap of its process; has its own stack
Cost to createHeavierLighter
Cost to switchHigher (new address space)Lower (same address space)
Talking to each otherNeeds IPC: pipes, sockets, shared memoryJust read and write shared variables
If one crashesOthers usually surviveCan take down the whole process
Main riskOverhead and slow sharingRace conditions and deadlocks

The main memory regions

RegionWhat lives thereWho sees itHow it fails
CodeProgram instructionsAll threadsRarely changes
HeapObjects and data created at run timeAll threads of the processLeaks (never freed), fragmentation, races
StackFunction calls and local variablesOne thread onlyStack overflow from very deep recursion

Process states

A process or thread moves between states
🆕Readywaiting for a CPU
→↓scheduled
⚙️Runningon a core
→↓waits for I/O
⏳Blockedwaiting for disk or network
Ready Running Blocked
The scheduler picks who runs next. A context switch saves one and loads another.
VisualizerTwo workers and one shared counterRun two threads without a lock and step through: both read the same value, so one update is lost. Then add the lock, or switch to two processes with separate memory.
Two workers run as
Protect the counter?
Memory layout (one process, two threads)
Process (one address space)
Code
Heap (shared)counter = 0
Stack of thread Atmp = 0
Stack of thread Btmp = 0
Operations in order (step 0 of 12). Each add is: read the counter, then write back value + 1.
A.read
B.read
A.write
B.write
A.read
B.read
A.write
B.write
A.read
B.read
A.write
B.write
Counter
0
one shared value
Should be
6
if no update is lost
Lost updates
–
after the last step
Switch cost
Lower
same address space
Memory used
1 copy
of code and heap
No lock. Watch for both threads reading the same value, then both writing back old value + 1. One update disappears.

A teaching model with a fixed order of operations (no random numbers). The real CPU can switch between threads at almost any instruction, and the exact costs depend on the OS and hardware, so only the comparison (lower or higher) is shown here.

07How to Use It / Steps / Implementation

Working safely with threads and memory

  1. 1
    Prefer not to share
    The safest shared data is data you do not share. Give each thread its own copy, or pass messages instead.
  2. 2
    Protect what you do share
    Use a lock (mutex) around the code that changes shared data, so only one thread is inside at a time.
  3. 3
    Keep locks short
    Hold a lock only for the few lines that need it. Long locks make other threads wait.
  4. 4
    Take locks in one order
    If two threads take lock A and B in different orders, they can wait for each other forever (deadlock). Always take them in the same order.
  5. 5
    Use a pool
    Create a fixed set of workers once and reuse them. Do not create a new thread for every request.
  6. 6
    Watch memory
    Track how much memory each process uses. A slow growth that never stops is usually a leak.
  7. 7
    Pick processes for isolation
    When a failure must not spread, or the language limits threads, use separate processes.
💡I/O-heavy vs CPU-heavy
If your work mostly waits for the network or disk, many threads (or an event loop) help, because waiting costs almost no CPU. If your work is heavy calculation, you need as many workers as CPU cores, and not many more.
⚠️Do not guess about the “last write wins”
Without a lock, you cannot predict which thread’s change survives. A program that works 999 times and fails once is still broken.

08Key Terms to Know

TermMeaning in easy words
ProgramA file of instructions on disk. It is not running yet.
ProcessA running program, with its own memory and resources
ThreadA line of execution inside a process. Threads share the process’s heap.
HeapMemory for data created at run time, shared by the threads of a process
StackMemory for function calls and local variables. Each thread has its own.
Context switchThe OS pauses one thread or process and starts another. It costs a little time.
SchedulerThe part of the OS that decides what runs on which core, and when
Virtual memoryEach process sees its own private memory. The OS maps it to real RAM.
Race conditionA bug where the result depends on the exact timing of threads
Mutex (lock)A tool that lets only one thread into a section of code at a time
IPCInter-process communication: ways for processes to exchange data (pipes, sockets, shared memory)

09Pros, Cons and Trade-offs

✅ Pros
  • Threads share data cheaply and switch fast
  • Processes isolate faults and are safer
  • More workers use more CPU cores
  • Pools reuse workers and save start-up time
  • The OS handles scheduling for you
⚠️ Cons
  • Shared memory brings races and deadlocks
  • Too many threads waste memory and switch time
  • Processes are heavier and talk slowly
  • A thread crash can bring down the whole process
  • Bugs are hard to repeat and debug

Trade-offs

ChoiceWe gainWe lose
ThreadsFast sharing, low overheadRisk of races, one crash can kill all
ProcessesIsolation and safetyMore memory, slow sharing
Few workersLow memory and little switchingCPU idle while others wait
Many workersHide waiting on I/OMore memory and context switching
LocksCorrect shared dataWaiting, and a risk of deadlock
No sharing (message passing)Fewer racesCopying data and a different design

10Common Problems and Mistakes

Common mistakes

  1. Sharing without a lock. Two threads change one value and an update is lost.
  2. Locks in different orders. Thread 1 holds A and wants B, thread 2 holds B and wants A. Both wait forever (deadlock).
  3. One thread per request without a limit. A traffic spike creates thousands of threads and uses all the memory.
  4. Memory leaks. Data is created and never released. The process grows until the OS kills it.
  5. Holding a lock while waiting on the network. Every other thread queues behind a slow call.
  6. Thinking more threads always means faster. Past the number of cores, CPU-heavy work only adds switching cost.
  7. Deep recursion. It can overflow the stack of a thread.

Things to watch

🧯Out of memory
The OS or container may kill the biggest process. Set memory limits and watch the trend.
🔁Thrashing
When memory is short and the OS keeps swapping to disk, everything becomes very slow.
🧟Zombie and orphan processes
Finished or abandoned processes that are not cleaned up still use table entries.
🔒Lock contention
Many threads fighting for one lock. Throughput stops growing even with more cores.

11Real-World Examples

🐘PostgreSQL
Starts a process per connection. This is one reason a connection pool in front of it helps.
🐬MySQL
Commonly uses a thread per connection, which is lighter than a process.
🧭Web browsers
Tabs are isolated in separate processes so a crash or a malicious page has a smaller reach.
🟢Node.js
Runs your JavaScript on one main thread with an event loop. For many cores you run several processes.
☕Java servers
Many Java servers use a thread pool, with a limit on how many requests run at once.
🐳Containers and Kubernetes
Each container is a set of isolated processes with CPU and memory limits.
📝Note
Defaults differ between products and versions. Check the documentation of the one you use.
Mini case: why a pool in front of a database
🖥️Many app threads
→↓hundreds
🧱Pooler
→↓few
🐘DB processes
Each connection is a heavy process, so a pooler reuses a few of them.

12Related Topics to Read Next

Concurrency vs Parallelism→

The next step: how threads and processes run together.

Connection Pooling→

A pool shares few heavy connections between many threads.

Ports and Sockets→

How processes talk over the network.

Scalability→

More workers, more cores, more machines.

Stateless vs Stateful→

What a server keeps in its memory between requests.

Latency vs Throughput vs Bandwidth→

Why waiting and switching affect speed.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Process: a running program with its own private memory.
  • ✔Thread: a line of work inside a process. Shares the heap, has its own stack.
  • ✔Memory: code (instructions), heap (shared data), stack (per thread).
  • ✔Process vs thread: isolate vs share. Safer and heavier vs faster and riskier.
  • ✔Race condition: unlocked shared data, lost updates. Deadlock: waiting for each other forever.
  • ✔Cures: share less, lock briefly, take locks in the same order.
  • ✔Sizing: CPU-heavy means about the cores. I/O-heavy means more. Always use a pool with a limit.
  • ✔One line: “Processes keep things apart, threads share things, and sharing needs care.”
← Previous
SLA, SLO and SLI
Next →
30 Must-Know Concepts