System Design
Learn System Design
Introduction to System Design
How to Learn System Design?
Network Essentials
HTTP vs. HTTPS
TCP vs. UDP
HTTP: 1.0 vs. 1.1 vs 2.0 vs. 3.0
URL vs. URI vs. URN
What Happens When You Type a URL into the Browser
Flashcards Review
Chapter Assessment
Long-Polling vs. WebSockets vs. Server-Sent Events
Introduction to Real-Time Communication
What is Long-Polling?
What is WebSocket?
What are Server-Sent Events?
Difference Between Long-Polling, WebSockets, and Server-Sent Events
Flashcards Review
Chapter Assessment
Domain Name System (DNS)
Introduction to DNS
DNS Resolution Process
DNS Load Balancing and High Availability
Flashcards Review
Chapter Assessment
Proxies
What is a Proxy Server?
Uses of Proxies
VPN vs. Proxy Server
Flashcards Review
Chapter Assessment
Load Balancing
Introduction to Load Balancing
Load Balancing Algorithms
Uses of Load Balancing
Load Balancer Types
Stateless vs. Stateful Load Balancing
High Availability and Fault Tolerance
Scalability and Performance
Challenges of Load Balancers
Flashcards Review
Chapter Assessment
API Gateway
Introduction to API Gateway
Usage of API gateway
Advantages and disadvantages of using API gateway
Flashcards Review
Chapter Assessment
API Design
What Is an API?
What Are REST APIs?
Resources, Not Actions
HTTP Methods and Their Semantics
URL Design
Request and Response Shapes
Status Codes and Error Design
Pagination from the Consumer's View
Idempotency Keys
Versioning and Backward Compatibility
Concurrency and Conditional Requests
REST vs gRPC vs GraphQL
Flashcards Review
Chapter Assessment
Rate Limiting and Throttling
What Is Rate Limiting
Rate Limiting Algorithms
Distributed Rate Limiting
Rate Limiting in Practice
Flashcards Review
Chapter Assessment
Caching
Introduction to Caching
Why is Caching Important?
Types of Caching
Cache Replacement Policies
Cache Invalidation
Cache Read Strategies
Cache Coherence and Consistency Models
Caching Challenges
Cache Performance Metrics
Flashcards Review
Chapter Assessment
CDN
What is CDN?
Origin Server vs. Edge Server
CDN Architecture
Push CDN vs. Pull CDN
Flashcards Review
Chapter Assessment
Data Partitioning
Introduction to Data Partitioning
Partitioning Methods
Data Sharding Techniques
Benefits of Data Partitioning
Common Problems Associated with Data Partitioning
Flashcards Review
Chapter Assessment
Redundancy and Replication
What is Redundancy?
What is Replication?
Replication Methods
Data Backup vs. Disaster Recovery
Flashcards Review
Chapter Assessment
CAP & PACELC Theorems
Introduction to CAP Theorem
Components of CAP Theorem
Trade-offs in CAP Theorem
Examples of CAP Theorem in Practice
Beyond CAP Theorem
System Design Trade-offs in Interviews
Flashcards Review
Chapter Assessment
Databases (SQL vs. NoSQL)
Introduction to Databases
SQL Databases
NoSQL Databases
SQL vs. NoSQL
ACID vs BASE Properties
Real-World Examples and Case Studies
SQL Normalization and Denormalization
In-Memory Database vs. On-Disk Database
Data Replication vs. Data Mirroring
Database Federation
Flashcards Review
Chapter Assessment
Indexes
What are Indexes?
How a B-Tree Index Works
Types of Indexes
B-Tree vs. LSM Tree
Indexes in Distributed Systems
Flashcards Review
Chapter Assessment
Bloom Filters
Introduction to Bloom Filters
Benefits & Limitations of Bloom Filters
Variants and Extensions of Bloom Filters
Applications of Bloom Filters
Flashcards Review
Chapter Assessment
Quorum
Why Quorum?
What is Quorum?
Flashcards Review
Chapter Assessment
Leader and Follower
What is Leader and Follower Pattern?
Flashcards Review
Chapter Assessment
Heartbeat
What is Heartbeat?
Flashcards Review
Chapter Assessment
Checksum
What is Checksum?
Uses of Checksum
Flashcards Review
Chapter Assessment
Distributed Messaging System
Introduction to Messaging System
Introduction to Kafka
Messaging patterns
Popular Messaging Queue Systems
RabbitMQ vs. Kafka vs. ActiveMQ
Scalability and Performance
Flashcards Review
Chapter Assessment
Distributed File Systems
What is a Distributed File System?
Architecture of a Distributed File System
Key Components of a DFS
Flashcards Review
Chapter Assessment
Security
What is Security and Privacy?
What is Authentication?
What is Authorization?
Authentication vs. Authorization
OAuth vs. JWT for Authentication
What is Encryption?
What are DDoS Attacks?
Flashcards Review
Chapter Assessment
Misc Concepts
Batch Processing vs. Stream Processing
XML vs. JSON
Synchronous vs. Asynchronous Communication
Push vs. Pull Notification Systems
Microservices vs. Serverless Architecture
Message Queues vs. Service Bus
Stateful vs. Stateless Architecture
Event-Driven vs. Polling Architecture
Flashcards Review
Chapter Assessment
Quiz - System Design Fundamentals
Quiz
System Design Trade-offs
Importance of Discussing Trade-offs
Strong vs Eventual Consistency
Latency vs Throughput
ACID vs BASE Properties in Databases
Read-Through vs Write-Through Cache
Batch Processing vs Stream Processing
Load Balancer vs. API Gateway
API Gateway vs Direct Service Exposure
Proxy vs. Reverse Proxy
API Gateway vs. Reverse Proxy
SQL vs. NoSQL
Primary-Replica vs Peer-to-Peer Replication
Data Compression vs Data Deduplication
Server-Side Caching vs Client-Side Caching
REST vs RPC
Polling vs. Long-Polling vs. WebSockets vs. Webhooks
CDN Usage vs Direct Server Serving
Serverless Architecture vs Traditional Server-based
Stateful vs Stateless Architecture
Hybrid Cloud Storage vs All-Cloud Storage
Token Bucket vs Leaky Bucket
Read Heavy vs Write Heavy System
Quiz
How to Approach a System Design Interview
System Design Interviews - A step by step guide
Functional vs. Non-functional Requirements
What are Back-of-the-Envelope Estimations?
Things to Avoid During System Design Interview
System Design Master Template
System Design Master Template
Quiz
Designing a URL Shortening Service like TinyURL
Designing a URL Shortening Service like TinyURL
Quiz - Designing URL Shortner
Designing Pastebin
Designing Pastebin
Quiz - Designing Pastebin
Designing Instagram
Designing Instagram
Quiz - Designing Instagram
Designing Dropbox
Designing Dropbox
Quiz - Designing Dropbox
Designing Facebook Messenger
Designing Facebook Messenger
Quiz - Designing Facebook Messenger
Designing Twitter
Designing Twitter
Quiz - Designing Twitter
Designing Youtube or Netflix
Designing Youtube or Netflix
Quiz - Designing Youtube
Designing Typeahead Suggestion
Designing Typeahead Suggestion
Quiz - Designing Typeahead Suggestion
Designing an API Rate Limiter
Designing an API Rate Limiter
Quiz - Designing an API Rate Limiter
Designing Twitter Search
Designing Twitter Search
Quiz - Designing Twitter Search
Designing a Web Crawler
Designing a Web Crawler
Quiz - Designing a Web Crawler
Designing Facebook’s Newsfeed
Designing Facebook’s Newsfeed
Quiz - Designing Facebook’s Newsfeed
Designing Yelp or Nearby Friends
Designing Yelp or Nearby Friends
Quiz - Designing Yelp or Nearby Friends
Designing Uber backend
Designing Uber backend
Quiz - Designing Uber backend
Designing Ticketmaster
Designing Ticketmaster
Quiz - Designing Ticketmaster
Dynamo: How to design a key value store?
Dynamo: Introduction
High-Level Architecture
Data Partitioning
Replication
Vector Clocks and Conflicting Data
The Life of Dynamo’s put() & get() Operations
Anti-entropy Through Merkle Trees
Gossip Protocol
Dynamo Characteristics and Criticism
Summary: Dynamo
Quiz: Dynamo
Mock Interview: Dynamo
Designing YouTube Likes Counter (medium)
YouTube Likes Counter
Quiz
Cassandra: How to Design a Wide-column NoSQL Database?
Cassandra: Introduction
High-level Architecture
Replication
Cassandra Consistency Levels
Gossiper
Anatomy of Cassandra's Write Operation
Anatomy of Cassandra's Read Operation
Compaction
Tombstones
Summary: Cassandra
Quiz: Cassandra
Mock Interview: Cassandra
Kafka: How to Design a Distributed Messaging System?
Messaging Systems: Introduction
Kafka: Introduction
High-level Architecture
Kafka: Deep Dive
Consumer Groups
Kafka Workflow
Role of ZooKeeper
Controller Broker
Kafka Delivery Semantics
Kafka Characteristics
Summary: Kafka
Quiz: Kafka
Mock Interview: Kafka
Chubby: How to Design a Distributed Locking Service?
Chubby: Introduction
High-level Architecture
Design Rationale
How Chubby Works
File, Directories, and Handles
Locks, Sequencers, and Lock-delays
Sessions and Events
Master Election and Chubby Events
Caching
Database
Scaling Chubby
Summary: Chubby
Quiz: Chubby
Mock Interview: Chubby
HDFS: How to Design File Storage System?
Hadoop Distributed File System: Introduction
High-level Architecture
Deep Dive
Anatomy of a Read Operation
Anatomy of a Write Operation
Data Integrity & Caching
Fault Tolerance
HDFS High Availability (HA)
HDFS Characteristics
Summary: HDFS
Quiz: HDFS
Mock Interview: HDFS
GFS: How to Design a Distributed File System Storage?
Google File System: Introduction
High-level Architecture
Single Master and Large Chunk Size
Metadata
Master Operations
Anatomy of a Read Operation
Anatomy of a Write Operation
Anatomy of an Append Operation
GFS Consistency Model and Snapshotting
Fault Tolerance, High Availability, and Data Integrity
Garbage Collection
Criticism on GFS
Summary: GFS
Quiz: GFS
Mock Interview: GFS
BigTable: How to Design a Wide Column Storage System?
BigTable: Introduction
BigTable Data Model
System APIs
Partitioning and High-level Architecture
SSTable
GFS and Chubby
Bigtable Components
Working with Tablets
The Life of BigTable's Read & Write Operations
Fault Tolerance and Compaction
BigTable Refinements
BigTable Characteristics
Summary: BigTable
Quiz: BigTable
Mock Interview: BigTable
Designing Reddit (medium)
Design Reddit
Quiz
Designing Notification Service (medium)
Designing a Notification System
Quiz
Design Google Calendar (medium)
Design Google calendar (Medium)
Quiz
Design a Recommendation System (medium)
Design a Recommendation System for Netflix
Quiz
Designing Gmail (medium)
Design Gmail
Quiz
Designing Google News (medium)
Design Google News, a Global News Aggregator System (Medium)
Quiz
Designing Unique ID Generator (medium)
Design Unique ID Generator (Easy)
Quiz
Designing Code Judging System (medium)
Design Code Judging System like LeetCode (Medium)
Quiz
Designing Payment System (hard)
Design Payment System
Quiz
Designing Flash Sale System (hard)
Design a Flash Sale for an E-commerce Site (Hard)
Quiz
Designing Reminder Alert System (hard)
Design a Reminder Alert System
Quiz
System Design Patterns
Introduction: System Design Patterns
1. Bloom Filters
2. Consistent Hashing
3. Quorum
4. Leader and Follower
5. Write-ahead Log
6. Segmented Log
7. High-Water Mark
8. Lease
9. Heartbeat
10. Gossip Protocol
11. Phi Accrual Failure Detection
12. Split Brain
13. Fencing
14. Checksum
15. Vector Clocks
16. CAP Theorem
17. PACELC Theorem
18. Hinted Handoff
19. Read Repair
20. Merkle Trees
Quiz
Monitoring and Observability
observability
monitoring
distributed systems
distributed tracing
At 2 PM, the support team gets messages from users: "Checkout is not working." The engineers look at their servers. All 40 servers are running, and CPU use looks normal.
So where do they start? One request passes through many services on many machines. No single machine has all the information.
This lesson answers two questions. How does a team learn that something is wrong? And how does it find out why?
Monitoring and Observability
The two words are often used as if they mean the same thing. They do not.
Monitoring means watching predefined metrics and limits, so the team learns that something is wrong. For example, the error rate went above a limit, or a disk is almost full. Monitoring answers the questions the team knew to ask in advance.
Observability is a property of the system. It describes how well the system's outputs let you explain a problem that nobody expected. Those outputs are mainly metrics, logs, and traces.
Here is the difference in one example. A monitored system tells you that 6 percent of checkouts are failing. An observable system also lets you follow one failing request, step by step, and find out why it failed.
Monitoring is something you do. Observability is something the system has. Metrics and alerts give you monitoring. Adding traces and central logs gives you observability: the ability to ask new questions without writing and deploying new code first.
The work splits into five parts. Three of them are signals that the system produces. The other two are tools that use those signals.
Metrics
Metrics are numbers that measure the performance, health, and behavior of a system. The most common ones are latency, throughput, error rate, and resource use, like CPU and memory.
A metric is stored as a time series, which is the same measurement recorded again and again over time. For example, the system records the checkout error rate every 10 seconds. Graphs of these values show trends, like errors slowly rising after a release.
There are three common types of metrics.
- Counter. A number that only goes up, like the total number of requests since the service started. The rate of change gives useful values, like requests per second.
- Gauge. A number that goes up and down, like memory in use or the number of jobs waiting in a queue.
- Histogram. A count of values in ranges, like how many requests took 0 to 100 ms, 100 to 250 ms, and so on. A histogram lets you calculate percentiles, like the p99 latency.
A useful starting set is called the four golden signals. It comes from Google's guidance on running large systems.
- Latency. How long requests take.
- Traffic. How many requests arrive, for example per second.
- Errors. How many requests fail.
- Saturation. How full the system is, like CPU at 90 percent or a queue that keeps growing.
Common tools to collect, store, and query metrics are Prometheus, Graphite, and InfluxDB.
Metrics show how the system is doing, but not why. A metric is a summary of many requests. It tells you the error rate went up. It does not tell you which request failed, or what happened inside it.
One warning about metrics: do not add a label (a tag attached to each measurement) with too many values, like a user ID. Each label value creates a separate time series. A metric labeled with 10 million user IDs becomes 10 million time series, and the metrics system can slow down or fail.
Logging
Logs are records of events that the parts of a system write while they run. They give a detailed view of what actually happened.
Each log line usually has a time, a log level, and a message. The level shows how important the event is, like DEBUG, INFO, WARN, or ERROR.
Logs are much easier to search when they are structured. This means each line is written as fields, often in JSON, instead of free text. Here is an example.
{"time": "14:02:17", "level": "ERROR", "service": "payment", "trace_id": "a1b2c3", "message": "card provider timeout", "duration_ms": 5003}
With fields like service and trace_id, an engineer can search for every error from the payment service, or every line that belongs to one request.
Logs are useful only when they are collected in one place. Logs spread across 50 machines are almost impossible to search during a problem. Centralized logging sends every log line to one system, where engineers can search all of them at once. Common tools are the ELK stack (Elasticsearch, Logstash, and Kibana) and Graylog.
Logs have costs too. A busy system writes a very large amount of log data, and storing it costs money. So teams keep detailed logs for a limited time, like 14 days. Also, never write passwords, card numbers, or other private data into logs.
Distributed Tracing
Distributed tracing tracks a request as it moves through a distributed system. It shows the end-to-end performance of the request, and it shows which part caused a problem.
Here is how it works.
- When a request enters the system, it gets a unique trace ID.
- Every service passes the trace ID to the next service, usually in a request header.
- Each service records a span, which is one timed step of work. A span has the service name, a start time, and a duration.
- A tracing system collects all the spans with the same trace ID and shows them together as one trace.
Here is an example. A checkout request takes 2,300 ms in total. The trace shows these spans.
- The order service takes 40 ms.
- The payment service takes 2,200 ms. Inside it, the call to the card provider takes 2,150 ms.
- The email service takes 30 ms.
The trace answers the question quickly: the card provider call is slow. A metric would only show that checkout is slow on average. With logs alone, an engineer would have to match lines from every service by hand.
When an engineer needs to see the path of one slow request across many services, tracing is the right tool. It follows that single request across all services and shows the slow part.
Common tracing tools are Jaeger, Zipkin, and OpenTelemetry. OpenTelemetry is also a standard way to produce metrics, logs, and traces from your code.
Busy systems often keep only a sample of traces, like 1 in 100 requests, because storing every trace costs too much. Many systems also keep every trace for requests that failed or were very slow.
Alerting and Anomaly Detection
Alerting watches the system for unusual behavior or performance problems, and it notifies the right team when one happens. The goal is to act before users are affected.
Alerts are created in two ways.
- Predefined thresholds. A person sets a rule in advance. For example, send an alert when the error rate stays above 2 percent for 5 minutes. Thresholds catch the problems you expected.
- Anomaly detection. A machine learning model learns the normal pattern of a metric, like traffic that rises every weekday morning. It sends an alert when the metric moves far from that pattern. Anomaly detection can catch problems you did not expect.
Common tools are Grafana, PagerDuty, and Sensu. The engineer on duty usually receives the alert as a phone notification, a call, or a chat message.
Good alerts follow a few rules.
- Alert on what users feel. High error rates and slow responses hurt users. High CPU alone may not, so it is often better on a dashboard than in an alert.
- Every alert should need action. An alert that goes away on its own a minute later only interrupts people for no reason.
- Add a time window. "Above 2 percent for 5 minutes" avoids alerts for a short spike that disappears on its own.
When a team receives too many alerts that need no action, engineers start to ignore all alerts. This is called alert fatigue, and it causes teams to miss real problems.
Visualization and Dashboards
Dashboards combine metrics, logs, and traces into graphs and tables on one screen. They show the current state of the system, so a team can decide quickly what to do. Common tools are Grafana, Kibana, and Datadog.
A good dashboard is simple. The top row shows what users feel: traffic, error rate, and latency. Lower rows show the parts that affect those numbers, like each service, the database, and the queues. A good dashboard also marks events like new releases, because many problems start right after a change.
Using the Signals Together
Each signal answers a different question. A real investigation often uses all of them, one after another. Here is the checkout problem from the start of this lesson.
- The alert. The team gets an alert: the checkout error rate is 6 percent, and it is normally 0.2 percent.
- The dashboard. Errors started at 14:00. Only checkout is affected, and its p99 latency rose from 400 ms to 5 seconds.
- The traces. Traces of failed requests show that the payment service waits 5 seconds and then times out.
- The logs. The payment service logs for those trace IDs say "connection pool exhausted". A release at 13:58 made the pool of database connections smaller.
- The fix. The team rolls back, which means it returns to the previous release. The error rate drops back to 0.2 percent.
The alert and the dashboard told the team that something was wrong. The traces and logs told the team why. That second part is what observability gives you.
| Component | Question it answers | Use it when |
|---|---|---|
| Metrics | How is the system doing? | You want trends and totals |
| Logs | What exactly happened? | You need the details of one event |
| Tracing | What happened to this one request? | One request is slow, and you do not know where |
| Alerting | When should someone look? | You want to know before users tell you |
| Dashboards | What is the state of everything now? | You want one place to see the system |
Key Takeaways
- Monitoring tells you that something is wrong, using signals chosen in advance. Observability is how well the system's outputs let you explain why.
- Metrics are numbers like latency, throughput, error rate, and resource use. Tools include Prometheus, Graphite, and InfluxDB.
- Logs record detailed events. Structure them as fields, and collect them in one place with tools like the ELK stack or Graylog.
- Distributed tracing follows one request across services with a trace ID and spans. It is the right tool for finding where one slow request spent its time. Tools include Jaeger, Zipkin, and OpenTelemetry.
- Alerting uses predefined thresholds or machine-learning anomaly detection, so the team can act before users are affected. Alert on what users feel, and avoid alert fatigue.
- Dashboards like Grafana, Kibana, and Datadog show the whole system in one place.
A system that runs on many machines will have problems that nobody predicted. The team that can see inside the system finds and fixes them in minutes instead of hours. The next lesson, Resilience and Error Handling, covers what a system should do when something breaks.
Practice Questions
Try each question first, then open the answer.
1. The p50 latency of checkout is 120 ms and has not changed. But some users say their checkout took 8 seconds, and the average latency graph looks normal. Which tool helps most, and why?
<details> <summary>Show answer</summary>Distributed tracing. The average and the p50 hide a small number of slow requests. Traces of the slow requests show every service each request passed through, and how long each step took. That shows exactly which part is slow. A p99 latency graph could also show the problem, but only a trace shows where the time went.
</details>2. Which type of metric fits each value? (a) Total orders since the service started. (b) Jobs waiting in a queue right now. (c) Response times, used to calculate the p99.
<details> <summary>Show answer</summary>(a) Counter, (b) gauge, (c) histogram. The total number of orders only goes up, so it is a counter. The queue length goes up and down, so it is a gauge. Response times are counted in ranges, and a histogram of those ranges lets you calculate percentiles like the p99.
</details>3. A team receives 200 alerts a day. Most are about high CPU, and they go away on their own. Engineers now ignore alerts, and last week they missed a real outage. What went wrong, and what should the team change?
<details> <summary>Show answer</summary>This is alert fatigue. Too many alerts need no action, so people stop reading them. The team should alert on what users feel, like error rate and latency, and add time windows like "for 5 minutes". Alerts that never need action should be removed or moved to a dashboard.
</details>4. A food delivery app is usually busiest at 7 PM on Friday. This Friday, orders at 7 PM drop by 60 percent, but there are no errors, so no error-rate alert is sent. What kind of alerting would catch this?
<details> <summary>Show answer</summary>Anomaly detection. A model that has learned the normal traffic pattern knows that 7 PM on Friday should be busy. A 60 percent drop is far from that pattern, so it sends an alert. A threshold on errors cannot catch it, because nothing is returning errors. For example, a broken release may have hidden the order button.
</details>5. Fifty servers each write logs to their own disk. An engineer needs every log line for one failed request. What two changes would make this easy?
<details> <summary>Show answer</summary>Centralized logging and a trace ID in every log line. Centralized logging, with a tool like the ELK stack or Graylog, puts the logs from all 50 servers in one searchable place. The trace ID should also be a field in every structured log line. Then one search finds all the lines for that request.
</details>Discussion
On This Page