System Design
Learn System Design
Introduction to System Design
How to Learn System Design?
Key Characteristics of Distributed Systems
Scalability
Availability
Latency and Performance
Concurrency and Coordination
Monitoring and Observability
Resilience and Error Handling
Fault Tolerance vs. High Availability
Flashcards Review
Chapter Assessment
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
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
What are Indexes?
database design
data modeling
performance
databases
+2
A shopping website has a users table with 10 million rows. When a user logs in, the database must find the one row with that user's email address.
Without any help, the database starts at the first row and checks every row until it has read all 10 million. On a busy website, this can take seconds, and it happens on every login.
With the right help, the same search reads only a few small blocks of data and finishes in a few milliseconds. That help is called an index. This lesson explains what an index is, how it makes queries faster, when it does not help, and what it costs.
What an Index Is
An index is a data structure that makes it faster to find rows in a database table. It works like the table of contents of a book. It points to where the actual row data is stored.
An index stores the values of one or more columns in sorted order. Next to each value, it stores a pointer to the full row. A pointer is the location of the row, so the database can go directly to it.
The main goal of an index is to make searching a table faster. The database can find the rows it needs without reading the whole table.
A Library Catalog
A library shows the idea well. A library catalog is a list of all the books in a library. It works like a database table with four columns: book title, writer, subject, and date of publication.
Most libraries keep two catalogs:
- One catalog is sorted by title. It helps when you already know the name of the book.
- One catalog is sorted by writer. It helps when you want to find books by a writer you like.
Each catalog entry tells you where the book sits on the shelves. So you can find a book whether you start from its title or from its writer.
These two catalogs are indexes for the library's books. Each one is a sorted list that is easy to search by one piece of information. The books themselves never move.
What an Index Stores
When you create an index on a column, the database stores two things for every row:
- The value in that column.
- A pointer to the full row.
Suppose a Books table has a title, a writer, and a subject. The rows are stored in no particular order.
| Row | Title | Writer | Subject |
|---|---|---|---|
| 1 | Networks | Lee | Computing |
| 2 | Algorithms | Garcia | Mathematics |
| 3 | Databases | Rossi | Computing |
An index on the Title column keeps only the titles, in alphabetical order, with a pointer to each row.
| Title (sorted) | Points to |
|---|---|
| Algorithms | Row 2 |
| Databases | Row 3 |
| Networks | Row 1 |
The index is much smaller than the table. It holds one column and a pointer, not every column. A small, sorted structure is fast to search.
How an Index Makes a Query Faster
Here is a common query and the index that helps it.
CREATE INDEX idx_users_email ON users (email); SELECT * FROM users WHERE email = 'maria@example.com';
Without an index, the database must read every row and check its email. Reading every row of a table is called a full table scan. For 10 million rows, the database reads 10 million rows to return one.
With an index, the database searches the small sorted index, finds the matching email, and follows the pointer directly to the row.
Most databases store an index as a B-tree, which is a tree structure that stays balanced as data is added. Even for a table with 100 million rows, a B-tree is only about three levels deep. So a lookup needs only a few steps. The How a B-Tree Index Works lesson explains this structure.
An index improves queries in two ways:
- Fewer disk reads. The database reads a few small blocks of the index and one row, not the entire table. Disk reads are usually the slowest part of a query.
- Sorting is already done. The index is already in order. So a query that sorts results by the indexed column can often skip the sorting step.
Selectivity: When an Index Helps
An index does not help every query equally. The key idea is selectivity.
Selectivity measures how well an index filters rows. An index has high selectivity when it filters out a large number of rows, and leaves only a few to check. This reduces the work for each query.
Here are three columns in the same users table of 10 million rows:
email: every user has a different email. One value matches one row. This is very high selectivity.country: about 200 different values. One value matches about 50,000 rows on average. This is medium selectivity.status: only two values,activeandinactive. One value can match 5 million rows. This is very low selectivity.
An index on status does not help much. Each matching row needs a separate jump from the index to the table. Doing 5 million separate jumps is slower than reading the table from start to end. The query planner is the part of the database that decides how to run a query. It often ignores such an index and scans the table instead.
A good index is on a column you filter by, where the filter removes most of the rows.
Indexes for Very Large Datasets
Indexes matter even more as data grows. Suppose a dataset is 1 terabyte, and each record is about 1 kilobyte. That is about one billion records.
Reading one billion records for each search would take far too long. At this size, an index is not an optional speed-up. It is a requirement.
A dataset this large is also usually spread across several machines. The system needs a way to know which machine holds the record you want. An index is the usual answer. The Indexes in Distributed Systems lesson covers how this works.
The Cost: Slower Writes and More Storage
An index is an extra copy of some of your data. The database must keep that copy up to date.
Every time a row is inserted, the database writes the row and then updates every index on the table. Updates and deletes can also change the indexes. So indexes make INSERT, UPDATE, and DELETE operations slower.
For example, suppose the users table has three indexes, on email, name, and created_at. Then one insert becomes four writes: the row, plus one update for each index.
Indexes also use storage space. On a table with many indexes, the indexes can take more space than the data itself.
So an index is a trade-off:
- Reads become faster, for queries that filter or sort on the indexed column.
- Writes become slower, and storage use grows.
Adding indexes is probably not worth it for a table that is written very often but read rarely. A raw event log is a common example. It receives many writes every second, but it is read only for an occasional report.
Different Kinds of Indexes
There are several kinds of indexes, each built for a different kind of query. Some examples:
- A unique index does not allow two rows to have the same value.
- A composite index covers more than one column, like
(customer_id, order_date). - A full-text index helps search for words inside long text.
- A hash index is fast for finding one exact value.
The Types of Indexes lesson explains each kind and when to use it.
When to Add an Index
Before adding an index, check these points:
- Is the column used to filter, join, or sort in common queries? Add indexes for the queries you actually run.
- Is the column selective? The filter should remove most of the rows.
- How often is the table written to? A table with many writes pays a higher cost for each index.
- Is the index still used? Remove indexes that no longer help any query.
For example, users are looked up by email on every login, and each email is unique. A new user row is written once, at signup, but it is read on every login. So an index on email is a good choice.
Quick Reference
| Question | Answer |
|---|---|
| What is an index? | A sorted data structure that stores column values and a pointer to each full row |
| What problem does it solve? | It avoids a full table scan, so the database does not read every row |
| What does it cost? | Extra storage, and extra work on every insert, update, and delete |
| When does it help most? | On selective columns used to filter, join, or sort |
| When does it help least? | On tables with many writes and few reads, and on columns with very few distinct values |
Key Takeaways
- An index is a data structure that works like a table of contents. It points to where the actual row data is stored.
- An index stores the values of a column in sorted order, together with a pointer to each full row.
- The main goal of an index is faster searching. It lets the database avoid a full table scan.
- An index with high selectivity filters out most rows. An index on a column with very few distinct values helps little.
- Indexes slow down inserts, updates, and deletes, because every write must also update each index. They also use extra storage.
- For very large datasets spread across machines, indexes are a requirement, not an option.
An index trades some write speed and storage for much faster reads. The next lesson, How a B-Tree Index Works, looks inside the structure that most database indexes use.
Practice Questions
Try each question first, then open the answer.
1. A customers table has 20 million rows, and there is no index on phone. A query runs WHERE phone = '555-0142'. What does the database do, and how does an index on phone change it?
Without an index, the database does a full table scan. It reads all 20 million rows and checks each phone number. With an index on phone, it searches the small sorted index and finds the value in a few steps. Then it follows the pointer straight to the row.
2. A users table has 50 million rows. Which column is best to index for filters: country (about 200 values), phone_number (unique for each user), or is_verified (true or false)?
phone_number, because it has the highest selectivity. Each value matches one row, so the index filters out almost all rows. country matches about 250,000 rows per value on average. is_verified can match about 25 million rows, so the query planner would often ignore that index and scan the table.
3. A table has four indexes and receives 1,000 inserts per second. How many writes per second does the database perform for these inserts?
<details> <summary>Show answer</summary>About 5,000 writes per second. Each insert writes the row once, and then updates each of the four indexes. So each insert becomes 1 + 4 = 5 writes, and 1,000 inserts become 5,000 writes. This is why each extra index slows down writes.
</details>4. An event log receives 50,000 writes per second, and it is read only once a day for a report. A developer wants to add six indexes to make the report faster. What is the problem?
<details> <summary>Show answer</summary>The cost of the indexes would be much larger than the benefit. Each insert would become 1 + 6 = 7 writes, so 50,000 inserts would become 350,000 writes per second. The indexes would also use a lot of storage. The benefit is only one faster report per day, so it is better to keep few or no indexes on this table.
</details>5. A Books table has 1,000,000 rows, and each row uses about 1 KB. An index on Title uses about 50 bytes per entry. About how large are the table and the index?
The table is about 1 GB, and the index is about 50 MB. The table is 1,000,000 x 1 KB, which is about 1,000,000,000 bytes, or 1 GB. The index is 1,000,000 x 50 bytes, which is 50,000,000 bytes, or 50 MB. The index is about 20 times smaller, and it is sorted, which is why it is much faster to search.
</details>Discussion
On This Page