System Design

Learn System Design

How to Learn System Design?

Scalability

Availability

Latency and Performance

Concurrency and Coordination

Monitoring and Observability

Resilience and Error Handling

Fault Tolerance vs. High Availability

Flashcards Review

Chapter Assessment

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

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

Introduction to DNS

DNS Resolution Process

DNS Load Balancing and High Availability

Flashcards Review

Chapter Assessment

What is a Proxy Server?

Uses of Proxies

VPN vs. Proxy Server

Flashcards Review

Chapter Assessment

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

Introduction to API Gateway

Usage of API gateway

Advantages and disadvantages of using API gateway

Flashcards Review

Chapter Assessment

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

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

What is CDN?

Origin Server vs. Edge Server

CDN Architecture

Push CDN vs. Pull CDN

Flashcards Review

Chapter Assessment

Introduction to Data Partitioning

Partitioning Methods

Data Sharding Techniques

Benefits of Data Partitioning

Common Problems Associated with Data Partitioning

Flashcards Review

Chapter Assessment

What is Redundancy?

What is Replication?

Replication Methods

Data Backup vs. Disaster Recovery

Flashcards Review

Chapter Assessment

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

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

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

Introduction to Bloom Filters

Benefits & Limitations of Bloom Filters

Variants and Extensions of Bloom Filters

Applications of Bloom Filters

Flashcards Review

Chapter Assessment

Why Quorum?

What is Quorum?

Flashcards Review

Chapter Assessment

What is Leader and Follower Pattern?

Flashcards Review

Chapter Assessment

What is Heartbeat?

Flashcards Review

Chapter Assessment

What is Checksum?

Uses of Checksum

Flashcards Review

Chapter Assessment

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

What is a Distributed File System?

Architecture of a Distributed File System

Key Components of a DFS

Flashcards Review

Chapter Assessment

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

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

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

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

Quiz

Designing a URL Shortening Service like TinyURL

Quiz - Designing URL Shortner

Designing Pastebin

Quiz - Designing Pastebin

Designing Instagram

Quiz - Designing Instagram

Designing Dropbox

Quiz - Designing Dropbox

Designing Facebook Messenger

Quiz - Designing Facebook Messenger

Designing Twitter

Quiz - Designing Twitter

Designing Youtube or Netflix

Quiz - Designing Youtube

Designing Typeahead Suggestion

Quiz - Designing Typeahead Suggestion

Designing an API Rate Limiter

Quiz - Designing an API Rate Limiter

Designing Twitter Search

Quiz - Designing Twitter Search

Designing a Web Crawler

Quiz - Designing a Web Crawler

Designing Facebook’s Newsfeed

Quiz - Designing Facebook’s Newsfeed

Designing Yelp or Nearby Friends

Quiz - Designing Yelp or Nearby Friends

Designing Uber backend

Quiz - Designing Uber backend

Designing Ticketmaster

Quiz - Designing Ticketmaster

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

YouTube Likes Counter

Quiz

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

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: 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

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

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: 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

Design Reddit

Quiz

Designing a Notification System

Quiz

Design Google calendar (Medium)

Quiz

Design a Recommendation System for Netflix

Quiz

Design Gmail

Quiz

Design Google News, a Global News Aggregator System (Medium)

Quiz

Design Unique ID Generator (Easy)

Quiz

Design Code Judging System like LeetCode (Medium)

Quiz

Design Payment System

Quiz

Design a Flash Sale for an E-commerce Site (Hard)

Quiz

Design a Reminder Alert System

Quiz

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

Introduction to Caching

Introduction to Caching

caching

data storage

latency reduction

cdn

+1

medium
·
5 min
·Updated Jan 2025·Credit: System Design Fundamentals

An online store has one very popular product. Its page is viewed 10,000 times every minute. Each view runs the same database query to load the product's name, price, and description, and each query takes 50 ms.

The product details almost never change. But the database repeats the same work 10,000 times a minute, and it slows down for every other request too.

The fix is to keep a copy of the answer somewhere much faster and reuse it. This lesson explains what that fast storage is, how it works, the terms used to describe it, and what it costs.

What Caching Is

A cache is a high-speed storage layer that sits between the application and the original source of the data. The original source can be a database, a file system, or a remote web service.

A cache holds temporary copies of data or computation results. It is designed for fast access and retrieval. Caching is the practice of storing those copies so that later requests can be answered from the cache instead of the slower source.

The goal of caching is to reduce how many times data must be fetched from its original source. This makes processing faster and reduces latency.

Why Caching Works

Two facts make caching useful in almost every large system.

  • Memory is much faster than disk or the network. Reading from memory takes about 100 nanoseconds. Reading from an SSD takes about 100 microseconds, and a round trip inside one data center takes about half a millisecond. The numbers you should know lesson lists these values.
  • Many requests ask for the same data. Often a small share of items, like popular products or trending posts, receives most of the requests. A cache that holds just those items can answer most requests.

How a Cache Works

When the application needs data, it follows the same steps every time.

  1. Check the cache first.
  2. If the data is found in the cache, return it to the application.
  3. If the data is not found, fetch it from the original source. Store a copy in the cache for future use, and return the data to the application.
Image
The application checks the cache first, returns the copy when it is found, and otherwise reads the original source and stores a copy for next time

Here is the same logic as simple code.

function getProduct(id):
    product = cache.get("product:" + id)
    if product is found:
        return product                       # cache hit
    product = database.findProduct(id)       # cache miss
    cache.set("product:" + id, product, ttl = 300 seconds)
    return product

This common pattern, where the application checks the cache and fills it on a miss, is called cache-aside. The cache read strategies lesson compares it with other patterns.

Key Terms

Cache. A temporary storage location for data or computation results, designed for fast access and retrieval.

Cache hit. A cache hit happens when the requested data or computation result is found in the cache.

Cache miss. A cache miss happens when the requested data is not found in the cache. It must then be fetched from the original data source or calculated again.

Hit rate. The share of requests that are cache hits. For example, if 900 of 1,000 requests are hits, the hit rate is 90 percent.

Cache eviction. Eviction is the process of removing data from the cache. It usually happens to make room for new data. A rule called an eviction policy decides which items to remove. For example, a common policy removes the item that was used least recently. The cache replacement policies lesson covers the common policies.

Cache staleness. Staleness means the data in the cache is outdated compared with the original data source. For example, a price changed in the database, but the cache still holds the old price.

TTL (time to live). A time limit set on a cached item. After the TTL passes, the item is treated as stale and must be fetched again. The cache invalidation lesson explains how systems keep cached data fresh.

Image
A cache hit finds the data in the cache, a cache miss fetches it from the source, eviction removes data to make room, and staleness means the copy is older than the source

The Effect in Numbers

Consider the popular product page again. It gets 10,000 views per minute, and the database query takes 50 ms. A cache read takes about 1 ms.

Without a cache, the database runs 10,000 queries every minute, and each view waits about 50 ms for the data.

With a cache and a 90 percent hit rate:

  • 9,000 views are cache hits. Each one takes about 1 ms.
  • 1,000 views are cache misses. Each one checks the cache (1 ms), then queries the database (50 ms), for about 51 ms.
  • The average time is 0.9 x 1 + 0.1 x 51 = 0.9 + 5.1, which is about 6 ms, instead of 50 ms.
  • The database now runs only 1,000 queries per minute, instead of 10,000.
Image
Without a cache the database answers all 10,000 views, while with a 90 percent hit rate it answers only the 1,000 misses and the average time falls to about 6 ms

The cache made the page about 8 times faster, and it removed 90 percent of the load from the database. Lower load also means the database can serve more users before it needs more hardware.

What Gets Cached, and Where

Caching can be used for many kinds of data.

  • Web pages and parts of pages.
  • Database query results, like the product details above.
  • API responses from internal or external services.
  • Images, videos, stylesheets, and scripts.
  • Computation results, like a recommendation list that took seconds to calculate.

Caches also exist at many places along the path of a request, from the user's device to the database.

  • Browser cache. The user's browser keeps copies of images, stylesheets, and scripts, so a repeat visit downloads less.
  • CDN cache. A content delivery network stores copies of files on servers near users, which reduces latency for people far from the origin server. The CDN chapter covers this.
  • Application cache. The application keeps data in memory, either in its own process or in a shared cache server, like Redis or Memcached.
  • Database cache. The database itself keeps recently used data in memory, so repeated reads avoid the disk.
  • Disk cache. Data can also be cached on local disk. Disk is slower than memory, but faster than fetching data from a remote source.
Image
Caches sit at many layers of a request: the browser, the CDN edge, the application, and the database, in front of the original data on disk

A cache hit closer to the user saves more time, because the request travels a shorter distance. The types of caching lesson covers each kind in more detail.

The Costs of Caching

A cache also has costs. It brings new problems that a system must handle.

  • Stale data. Users may see old data until the cached copy expires or is removed. The system must decide how old is acceptable for each kind of data.
  • Limited space. Memory is expensive, so a cache cannot hold everything. It must evict some items, and the wrong choice lowers the hit rate.
  • A cold cache. After a restart, the cache is empty, so every request is a miss until the cache fills again. The sudden load on the database can cause problems.
  • More complexity. The cache is one more system to run, monitor, and scale.

Not all data should be cached. Data that changes on every request is a poor fit, because the cached copy is almost always stale. Data that must be exactly correct at a specific moment, like the stock count when a customer pays, should be read from the source. The caching challenges lesson covers the common problems and their fixes.

Key Takeaways

  • A cache is a high-speed storage layer that sits between the application and the original data source. The source can be a database, a file system, or a remote web service.
  • The application checks the cache first. If the data is found, it is returned. If not, it is fetched from the source, stored in the cache, and returned.
  • A cache hit means the data was found in the cache. A cache miss means it was not found and had to be fetched from the source.
  • Cache eviction removes data from the cache, usually to make room. Cache staleness means the cached data is outdated compared with the source.
  • Caching reduces latency and database load. With a 90 percent hit rate, a 50 ms query can become an average of about 6 ms.
  • Caches exist in browsers, CDNs, applications, and databases. They bring costs, like stale data, limited space, and extra complexity.

A cache uses some extra memory and accepts slightly older data to give much faster answers and much less work at the source. The next lesson, Why is Caching Important?, explains the main benefits of caching in more detail.

Practice Questions

Try each question first, then open the answer.

1. A cache receives 1,000 requests, and 850 of them are served from the cache. What is the hit rate, and how many requests must read the original source?

<details> <summary>Show answer</summary>

The hit rate is 85 percent, and 150 requests read the source. 850 of 1,000 requests are cache hits, so the hit rate is 850 / 1,000 = 85 percent. The other 150 requests are cache misses. Each of them must fetch the data from the original source.

</details>

2. A database query takes 80 ms, and a cache read takes 2 ms. The hit rate is 75 percent. What is the average time to get the data?

<details> <summary>Show answer</summary>

About 22 ms. A hit takes 2 ms. A miss checks the cache first and then queries the database, so it takes 2 + 80 = 82 ms. The average is 0.75 x 2 + 0.25 x 82 = 1.5 + 20.5 = 22 ms. That is almost 4 times faster than 80 ms.

</details>

3. A product's price changes in the database, but the product page keeps showing the old price for 5 minutes. What is this called, and what decides how long it lasts?

<details> <summary>Show answer</summary>

This is cache staleness. The cached copy is outdated compared with the database. How long it lasts depends on the TTL of the cached item, here about 5 minutes. The system can shorten it with a shorter TTL, or by removing the cached copy when the price changes.

</details>

4. The cache is full, and a new item must be stored. What happens, and what decides which item is removed?

<details> <summary>Show answer</summary>

The cache evicts an item to make room. An eviction policy decides which item is removed. For example, a least recently used policy removes the item that has not been used for the longest time. A good policy keeps popular items in the cache, which keeps the hit rate high.

</details>

5. Which of these is a poor fit for caching? (a) A product's description. (b) The exact stock count checked when a customer pays. (c) The website's logo.

<details> <summary>Show answer</summary>

(b) the exact stock count at payment time. It changes often, and it must be exactly correct at that moment, so it should be read from the source. A product description and a logo change rarely and are read very often, so they are good fits for caching.

</details>
Discussion
Have a question or insight about this topic? Share it with the community.
Reading Progress
0%

On This Page