CodeNFacts
CodeHub
Home

All Categories


Sign In
Course notes

System Design,
sketched out.

A field guide to the concepts behind WhatsApp, Instagram, YouTube, and every other system built to survive millions of users - diagrams, trade-offs, cheat sheets, and the questions interviewers actually ask.

Fundamentals
01

What is System Design?

System design is the process of designing scalable, reliable, efficient, and maintainable software systems that can handle millions of users.

Reference systems
  • WhatsApp
  • Instagram
  • YouTube
  • Netflix
  • Amazon
  • Google Search
What every good system aims for
  • Scalable
  • Reliable
  • Available
  • Secure
  • Fast
  • Cost-effective
  • Easy to maintain
02

Functional vs Non-Functional Requirements

Functional — what the system should do (e.g. Instagram)
  • User registration
  • Login
  • Upload photos
  • Like posts
  • Comment
  • Follow users
Non-functional — how well it performs
  • Handle 10 million users
  • Response time under 200 ms
  • 99.99% availability
  • Secure authentication
  • Data backup
Scalability & Performance
03

Scalability

Scalability means handling increased traffic without a drop in performance. There are two directions to scale in.

Fig — Vertical scaling
  4 GB RAM  ──────▶  32 GB RAM

  (one server, more power)
Advantages
  • + Easy to do
  • + No code changes needed
Trade-offs
  • Hits a hardware ceiling
  • Gets expensive fast
Fig — Horizontal scaling
        User Requests
              |
              V
        Load Balancer
         /    |    \
        S1    S2    S3
Advantages
  • + Grows without a hard limit
  • + Fault tolerant
Trade-offs
  • More operational complexity
04

Load Balancer

A load balancer distributes incoming requests across multiple servers so no single machine gets overwhelmed.

Fig — Traffic distribution
   1000 Requests
         |
         V
   Load Balancer
    /    |     \
   S1    S2    S3
Benefits
  • Prevents server overload
  • High availability
  • Better overall performance
Popular tools
  • Nginx
  • HAProxy
  • AWS ELB
05

Caching

A cache stores frequently accessed data so repeat requests never have to hit the database.

Fig — Without a cache
  Client
    |
  Server
    |
 Database
Fig — With a cache
  Client
    |
  Server
    |
  Redis
    |
 Database
Benefits
  • Faster response times
  • Reduced database load
Common tools
  • Redis
  • Memcached
Data Layer
06

SQL vs NoSQL Databases

SQLNoSQL
ExamplesMySQL, PostgreSQL, OracleMongoDB, Cassandra, DynamoDB
FeaturesACID, relationships, transactionsFlexible schema, horizontal scaling
Good forBanking, ecommerce, ERPSocial media, big data, chat apps
07

Database Replication

Replication copies data from one database to another so reads can be served from copies while writes stay centralized.

Fig — Master → replicas
         Master
       /       \
  Replica1   Replica2
Roles
  • Master handles writes
  • Replicas handle reads
Benefits
  • Faster reads
  • Built-in backup
  • Higher availability
08

Database Sharding

Sharding splits data across multiple databases so each one only holds a slice of the total.

Fig — Sharding by key range
  Shard 1        Shard 2        Shard 3
  Users A–F      Users G–N      Users O–Z
Benefits
  • Better scalability
  • Faster queries per shard
09

CAP Theorem

A distributed system can't guarantee Consistency, Availability, and Partition tolerance all at once — you get to pick two.

LetterMeaning
CConsistency — every read gets the latest write
AAvailability — every request gets a response
PPartition tolerance — keeps working despite network splits
System typeTypical choice
BankingCP — consistency over availability
Social mediaAP — availability over strict consistency
10

ACID Properties

Used in SQL databases
  • Atomicity — all or nothing
  • Consistency — valid state to valid state
  • Isolation — concurrent transactions don't interfere
  • Durability — committed data survives a crash
11

BASE Properties

Used in NoSQL databases
  • Basically Available — the system responds, even if degraded
  • Soft State — state may change over time without input
  • Eventual Consistency — replicas converge given enough time
29

Common Databases at a Glance

SQLNoSQL
MySQLMongoDB
PostgreSQLCassandra
SQL ServerDynamoDB
Redis (key-value)
Architecture Patterns
12

CDN (Content Delivery Network)

A CDN caches content in edge locations physically closer to users, so it doesn't have to travel all the way to the origin server.

Fig — Edge delivery
  User (India)
       |
  Nearest CDN Edge
       |
  Origin Server (USA)
Examples
  • Cloudflare
  • Akamai
  • AWS CloudFront
Benefits
  • Faster page loads
  • Lower latency
13

Reverse Proxy

A reverse proxy sits in front of your servers and mediates every request that reaches them.

Fig — Request path
  Users
    |
  Reverse Proxy
    |
  App Servers
Examples
  • Nginx
  • Apache
Benefits
  • Security
  • SSL termination
  • Load balancing
  • Caching
14

API Gateway

An API gateway is the single front door that manages every incoming API request before it reaches your services.

Fig — Routing through the gateway
  Client
    |
  API Gateway
    |
  Microservices
Responsibilities
  • Authentication
  • Rate limiting
  • Logging
  • Routing
15

Monolith Architecture

Everything — every feature and module — lives inside one deployable application.

Fig — Single application
  Application
  ├── Login
  ├── Orders
  ├── Payments
  └── Inventory
Advantages
  • + Easy to develop initially
  • + Simple deployment
Trade-offs
  • Hard to scale parts independently
  • Codebase grows large and tangled
16

Microservices

The application is split into independent services, each owning a single responsibility.

Fig — Independent services
  Login Service     Order Service
  Payment Service    Notification Service
Advantages
  • + Independent deployment
  • + Scales piece by piece
  • + Fault isolation
Trade-offs
  • Complex inter-service communication
  • Harder to monitor
17

Message Queue

A message queue lets services communicate asynchronously — the sender doesn't wait for the receiver.

Fig — Producer → consumer
  Producer
     |
   Queue
     |
  Consumer
Examples
  • RabbitMQ
  • Apache Kafka
  • Amazon SQS
Benefits
  • Decoupling
  • Reliability
  • Automatic retry handling
18

Event-Driven Architecture

Services react to events instead of calling each other directly, which keeps them loosely coupled.

Fig — An order's event chain
  Order Created
        ↓
  Inventory Updated
        ↓
  Payment Processed
        ↓
  Email Sent
Security
19

Rate Limiting

Rate limiting restricts how many requests a client can make in a given window, protecting the system from abuse and overload.

Fig — Example limit
  100 requests / minute / client
Common techniques
  • Token Bucket
  • Leaky Bucket
  • Fixed Window
  • Sliding Window
20

Authentication vs Authorization

AuthenticationAuthorization
Who are you?What can you access?
Login, OTP, passwordAdmin, user, moderator
21

JWT (JSON Web Token)

Fig — Token flow
  Client Login
       ↓
    Server
       ↓
  JWT Token
       ↓
  Client stores token
       ↓
  Sent with API requests
Benefits
  • Stateless
  • Fast to verify
  • Widely supported
22

OAuth 2.0

OAuth lets users log in with an identity they already have, instead of creating a new password for every app.

Common providers
  • Google
  • GitHub
  • Facebook
Fig — Authorization flow
  User → Provider (e.g. Google)
         → Authorization
         → Access Token
         → Application
23

HTTPS

HTTPS wraps HTTP traffic in SSL/TLS encryption so data can't be read or tampered with in transit.

Benefits
  • Secure communication
  • Data privacy
  • Server authentication
Reliability & Advanced
24

Consistent Hashing

Consistent hashing distributes data evenly across servers, so adding or removing a server only reshuffles a small slice of the data.

Benefits
  • Easy horizontal scaling
  • Minimal data movement on resize
  • Backbone of most caching systems
25

Bloom Filter

A bloom filter is a fast, space-efficient probabilistic structure that tells you an item is definitely absent, or possibly present.

Use cases
  • Cache lookups
  • Database optimization
  • Web crawlers
26

Distributed Lock

A distributed lock ensures only one server processes a critical task at a time, even across a fleet of machines.

Use cases
  • Preventing double payment
  • Inventory reservation
Tools
  • Redis
  • ZooKeeper
27

Circuit Breaker

A circuit breaker stops calls to a failing dependency so one broken service doesn't cascade into a full outage.

Fig — States
  Closed  ──failure──▶  Open  ──timeout──▶  Half-Open
    ▲                                          |
    └──────────────success───────────────────┘
Libraries
  • Resilience4j
  • Hystrix (legacy)
28

Monitoring & Logging

Monitoring tracks
  • CPU
  • Memory
  • Requests per second
  • Latency
  • Error rate
Logging captures
  • Application logs
  • Access logs
  • Error logs
Tools
  • Prometheus
  • Grafana
  • ELK Stack
Interview Prep
30

Common System Design Interview Questions

  • Design WhatsApp
  • Design Instagram
  • Design YouTube
  • Design Uber
  • Design Netflix
  • Design Twitter / X
  • Design a URL Shortener
  • Design Google Drive
  • Design Dropbox
  • Design Amazon
31

Typical Interview Approach

  • Clarify requirements
  • Estimate scale — users, requests, storage
  • Define APIs and the data model
  • Draw the high-level architecture
  • Identify bottlenecks
  • Add scalability — load balancers, caching, sharding
  • Address reliability — replication, failover
  • Discuss security, monitoring, and trade-offs
32

Common Technologies Reference

CategoryExamples
Web ServerNginx, Apache
Load BalancerHAProxy, AWS ELB
CacheRedis, Memcached
Message QueueKafka, RabbitMQ, SQS
SQL DatabaseMySQL, PostgreSQL
NoSQL DatabaseMongoDB, Cassandra
MonitoringPrometheus, Grafana
LoggingELK Stack, Loki
ContainerizationDocker
OrchestrationKubernetes
33

Learning Roadmap

  • Computer Networks — HTTP, TCP/IP, DNS
  • Operating Systems — processes, threads, memory
  • Databases — SQL and NoSQL
  • Caching — Redis
  • Load Balancing
  • CAP Theorem, ACID, BASE
  • Distributed Systems
  • Message Queues — Kafka, RabbitMQ
  • Microservices
  • Cloud Platforms — AWS, Azure, GCP
  • Docker and Kubernetes
  • Practice real-world designs — YouTube, WhatsApp, Uber, Netflix
Cheat sheets
Scaling, at a glance
StrategyWhat it meansProsCons
VerticalAdd power to one boxSimple, no code changeHardware ceiling, costly
HorizontalAdd more boxesGrows without limit, fault tolerantNeeds a load balancer, more moving parts
CAP cheat sheet
ChoiceWhen to reach for itExample domain
CPPick when correctness matters more than uptimeBanking, payments
APPick when uptime matters more than perfect freshnessSocial feeds, shopping carts
SQL vs NoSQL, in one line
TypeStrengthReach for it when…
SQLStructured, relational, transactionalBanking, ecommerce, ERP
NoSQLFlexible schema, scales horizontallySocial media, big data, chat
The big picture

Most large-scale designs are a remix of the pieces above. Here's roughly how they stack.

Fig — a request's full journey
  Client
     |
  CDN (static assets)
     |
  Load Balancer
     |
  API Gateway  ── auth, rate limiting
     |
  Microservices ── message queue between them
    /        \
  Cache      Database (replicated + sharded)
Important things to keep in mind
01

Always clarify requirements before drawing a single box — an elegant answer to the wrong problem is still wrong.

02

State your assumptions out loud. Interviewers care more about your reasoning than a 'correct' final diagram.

03

Estimate scale early: back-of-envelope numbers for users, QPS, and storage steer every later decision.

04

There is no perfect design, only trade-offs. Naming the trade-off you're making is more valuable than avoiding one.

05

Start simple, then scale. A single server with a database is a legitimate first draft — add complexity only as bottlenecks appear.

06

Bottlenecks usually hide in three places: the database, a single point of failure, and unbounded growth of one resource.

07

Caching solves read-heavy problems; sharding and queues solve write-heavy problems. Reach for the tool that matches the pattern.

08

Security, monitoring, and failure handling are not optional extras — bring them up even if the interviewer doesn't ask.

33 topics · fundamentals through interview prep — revisit the diagrams before your next system design round.