π§ Definition
System design is the process of defining the architecture, components, modules, interfaces, and data flow of a system to meet specific requirements β such as scalability, reliability, availability, and performance.
In simple terms:
π§© Purpose of System Design
The goal is to build a system that is:
ποΈ What It Includes
A good system design discussion usually includes:
βοΈ Example (Quick Illustration)
If the interviewer says: βDesign Instagram,β
Youβd think about:
π― Interview Tip
When asked this question, wrap up with a crisp line like:
βSystem design is all about translating product requirements into a scalable and reliable architecture that works efficiently at scale.β
βοΈ Definition
CAP Theorem (also called Brewerβs Theorem) states that a distributed system can provide only two out of three guarantees at any given time:
π The Core Idea
In a distributed system, network partitions are inevitable (servers can fail or disconnect).
So, when a partition happens, you must choose between:
Thatβs why you can only have two of the three at the same time.
π CAP Combinations
| Type | Guarantees | Example |
|---|---|---|
| CA (Consistency + Availability) | Works only when thereβs no partition (theoretical, not practical in distributed systems). | Traditional RDBMS on a single node |
| CP (Consistency + Partition tolerance) | Prioritizes data accuracy over availability. | HBase, MongoDB (in some configs), BigTable |
| AP (Availability + Partition tolerance) | Prioritizes serving users over data accuracy. | Cassandra, DynamoDB, CouchDB |
π― Real-World Analogy
Imagine you have two servers replicating user data across a network:
If the connection between them breaks (partition):
π¬ Interview-Style Summary Answer
βCAP Theorem states that in a distributed system, we can only guarantee two of the three: Consistency, Availability, and Partition Tolerance. Since network partitions are unavoidable, we often design systems to choose between Consistency and Availability based on the use case β for example, banking systems prefer consistency, while social media prefers availability.β
βοΈ Definition
Scaling means increasing a systemβs capacity to handle more load β users, requests, or data.
There are two main types of scaling:
You increase the capacity of a single machine β add more CPU, RAM, storage, etc.
Example:
Upgrading your database server from:
You add more machines (nodes/servers) to share the load.
Example:
Instead of one powerful database, you use multiple servers working together β each handling part of the traffic.
βοΈ Quick Comparison Table
| Feature | Vertical Scaling | Horizontal Scaling |
|---|---|---|
| Method | Add more power (CPU, RAM) to one machine | Add more machines |
| Complexity | Simple | Complex |
| Cost | Expensive at high-end | Scales with cheaper hardware |
| Fault Tolerance | Low | High |
| Example | Upgrading a single MySQL server | Adding more servers behind a load balancer |
π§ Example (How to Use in Interviews)
βVertical scaling means making one machine stronger β itβs simpler but limited.
Horizontal scaling means adding more machines β itβs complex but highly scalable and fault-tolerant.
Most large-scale systems like Google or Netflix use horizontal scaling to handle millions of users.β
βοΈ Definition
Load Balancing is the process of distributing incoming network traffic or requests across multiple servers to ensure no single server becomes overloaded and the system remains fast, reliable, and available.
Think of it as a traffic police officer that directs vehicles (requests) to different lanes (servers) so that no lane gets jammed.
π§© Why Itβs Important in System Design
π§ Types of Load Balancing Algorithms
| Algorithm | Description | Example Use |
|---|---|---|
| Round Robin | Sends requests to servers one by one in order. | Simple, equal load |
| Least Connections | Sends request to the server with the fewest active connections. | When requests vary in time |
| IP Hash | Uses client IP to decide which server handles the request. | Session consistency |
| Weighted Round Robin | Some servers get more traffic based on their capacity. | Heterogeneous servers |
ποΈ Where It Fits in Architecture
Typical system design:
Clients (Users)
β
Load Balancer
β
Multiple Application Servers
β
Database / Cache Layer
Tools/Services commonly used:
π― Example Answer (Interview Style)
βLoad balancing is the technique of distributing incoming traffic across multiple servers to ensure no single machine is overloaded. Itβs critical for scalability, fault tolerance, and high availability.
For example, in a web app with millions of users, a load balancer ensures requests are spread evenly across servers and automatically rerouted if a server fails, keeping the app fast and reliable.β
βοΈ 1. Latency
Definition:
The time taken to process a single request β from when itβs sent by the client until the response is received.
In simpler terms:
β±οΈ Latency = delay per request
Example:
If a user clicks βSendβ on WhatsApp and the message takes 200 ms to deliver β latency is 200 ms.
Goal:
Lower latency = faster system response.
Measured in: milliseconds (ms) or microseconds (Β΅s).
βοΈ 2. Throughput
Definition:
The number of requests or operations a system can handle in a given time period.
π‘ It measures capacity, not delay.
Example:
A web server handling 10,000 requests per second (RPS) has high throughput.
Goal:
Higher throughput = system can handle more users simultaneously.
Measured in: requests/sec, transactions/sec, or MB/sec.
βοΈ 3. Availability
Definition:
The percentage of time the system is operational and accessible to users.
Formula:
Availability = (Uptime / Total Time) Γ 100
Example:
If a system is down for 1 hour in a 1000 hour period:
β Availability = (999 / 1000) Γ 100 = 99.9% uptime
This is known as βthree ninesβ availability β common in production systems.
Cloud providers often target:
π§ Putting It All Together
| Metric | Meaning | Ideal Goal | Example |
|---|---|---|---|
| Latency | Time per request | Low | 100 ms API response |
| Throughput | Requests handled per second | High | 50k RPS |
| Availability | System uptime | High | 99.99% uptime |
π§© Trade-offs
You need to balance all three based on your system goals.
π― Sample Interview Answer
βLatency is the delay in processing a single request, throughput is the total number of requests handled per second, and availability is the percentage of time the system is up and running.
In simple terms β latency measures speed, throughput measures capacity, and availability measures reliability.
A well-designed system aims for low latency, high throughput, and high availability.β
βοΈ Definition
Sharding is the process of splitting a large database into smaller, faster, more manageable pieces called shards, which are distributed across multiple servers.
Each shard holds a subset of the data, and together they make up the entire dataset.
π§© Why Sharding Is Needed
As data grows, a single database server:
π Sharding helps by horizontally scaling the database β spreading the load across multiple machines.
π§ How It Works
Imagine a users table with 100 million records.
Instead of storing all users on one server, you can split (shard) them like this:
| Shard | Data Range | Server |
|---|---|---|
| Shard 1 | Users with ID 1β10M | Server A |
| Shard 2 | Users with ID 10Mβ20M | Server B |
| Shard 3 | Users with ID 20Mβ30M | Server C |
Each shard handles queries for its own subset of users.
ποΈ Sharding Key
The sharding key determines how data is divided.
Itβs usually a column like:
Choosing a good sharding key is crucial β it ensures even data distribution and avoids hotspots.
βοΈ Types of Sharding
| Type | Description | Example |
|---|---|---|
| Range-based Sharding | Divide by range of values (e.g., user IDs 1β1000, 1001β2000) | Simple, but can create uneven load |
| Hash-based Sharding | Apply a hash function to the key (e.g., hash(user_id) % N) | Ensures even data spread |
| Directory-based Sharding | Use a lookup table to map keys to shards | Flexible, but adds lookup overhead |
π― Benefits
β Challenges
ποΈ Real-World Example
π£οΈ Interview-Ready Answer
βSharding is a database scaling technique that divides a large dataset into smaller parts called shards, each stored on separate servers.
It helps improve performance and scalability by distributing load.
For example, if we have millions of users, we can shard data by user ID so each server handles a specific range of users.
The main challenge is choosing the right sharding key and handling cross-shard queries efficiently.β
βοΈ Definition
Store data in tables (rows and columns) with a fixed schema and use Structured Query Language (SQL) to manage and query data.
π Example: MySQL, PostgreSQL, Oracle, SQL Server
Store data in flexible, schema-less formats like documents, key-value pairs, graphs, or wide-columns.
π Example: MongoDB, Cassandra, Redis, DynamoDB, Neo4j
π Key Differences
| Feature | SQL (Relational) | NoSQL (Non-Relational) |
|---|---|---|
| Data Model | Tables with rows & columns | Key-Value, Document, Graph, or Column-based |
| Schema | Fixed and predefined | Dynamic / flexible schema |
| Scalability | Vertical Scaling (scale up) | Horizontal Scaling (scale out) |
| Query Language | SQL (structured, powerful joins) | Unstructured queries, API-based (JSON, etc.) |
| Transactions | ACID (Atomicity, Consistency, Isolation, Durability) | BASE (Basically Available, Soft state, Eventually consistent) |
| Joins | Supported | Generally not supported |
| Consistency | Strong consistency | Often eventual consistency (for performance) |
| Use Case | Complex queries, strict data integrity | Large-scale data, high velocity, flexible structure |
| Examples | MySQL, PostgreSQL, Oracle | MongoDB, Cassandra, DynamoDB, Redis, Neo4j |
π§ Understanding ACID vs BASE
π§© When to Use Which
| Scenario | Choose |
|---|---|
| Need strict consistency & complex relationships | β SQL |
| Need high scalability, flexible schema, or fast reads/writes | β NoSQL |
| Example: Banking, ERP | SQL |
| Example: Social media feed, IoT, caching | NoSQL |
ποΈ Real-World Example
π― Sample Interview Answer
βSQL databases store structured data with predefined schemas and support ACID transactions β ideal for use cases like banking or accounting systems.
NoSQL databases are schema-less and designed for scalability and flexibility, often trading strict consistency for performance and availability.
For example, MongoDB stores data as JSON documents, which makes it great for dynamic and rapidly changing data structures.β
βοΈ Short Answer
Partitioning is the logical division of data within a database.
Sharding is the physical distribution of those partitions across multiple machines or servers.
π§© Detailed Explanation
Both sharding and partitioning involve splitting data into smaller chunks, but they differ mainly in scope and purpose:
| Feature | Partitioning | Sharding |
|---|---|---|
| Definition | Dividing a database/table into smaller parts (partitions) for better manageability and performance | Distributing those partitions across multiple servers or nodes |
| Scope | Happens within a single database or server | Happens across multiple databases or servers |
| Goal | Improve query performance and manageability | Improve scalability and handle large-scale data |
| Storage | All partitions still reside on the same machine | Shards are stored on different machines |
| Management | Managed by the database engine (e.g., MySQL partitioning) | Managed at application or cluster level (e.g., MongoDB, Cassandra) |
| Example | Partitioning orders by date inside one PostgreSQL database | Sharding users by user_id across multiple MongoDB servers |
π§ Analogy
Imagine a library π:
You organize all the books in one building by genre (Science, History, Fiction).
β Still one library, just organized better.
You build multiple library branches, each holding books of a specific genre.
β Data is physically spread across multiple locations.
ποΈ Real-World Example
A MySQL table is partitioned by date β Jan data in one partition, Feb in another β but all partitions live on the same server.
A MongoDB cluster shards users based on their user_id across multiple servers, each handling a portion of users.
π― Interview-Ready Answer
βPartitioning is about dividing data logically within the same database to improve performance, while sharding is about distributing those partitions physically across multiple servers to improve scalability and fault tolerance.
In short, all sharding involves partitioning, but not all partitioning involves sharding.β
βοΈ Definitions
Performance refers to how fast a system responds to a single request or operation.
π§© In short β Speed per user/request.
π Measured by:
Scalability refers to how well a system can handle increased load (users, traffic, or data) by adding more resources (servers, CPUs, etc.).
π§© In short β Capacity to grow.
π Measured by:
π Relationship Between Performance and Scalability
Performance and scalability are related but not the same:
| Concept | Description |
|---|---|
| Performance | Measures speed β how fast the system works for one user. |
| Scalability | Measures growth β how well performance holds up as users increase. |
| Relationship | A system must be scalable to maintain good performance under heavy load. |
π In other words:
βPerformance is about how fast; scalability is about how fast you stay when users grow.β
π§ Example
Suppose your web app handles 100 users with 200 ms latency (good performance).
Now, 10,000 users join:
β Good scalability ensures performance remains stable as traffic increases.
βοΈ How They Work Together
| Situation | Performance | Scalability | Example |
|---|---|---|---|
| Optimize code | β Improves | β Not affected much | Faster queries |
| Add more servers | β Same per-user speed | β Improves | Load balancing |
| Poor database indexing | β Slow | β Degrades with load | Unoptimized DB queries |
π― Interview-Ready Answer
βPerformance measures how efficiently a system handles individual requests, while scalability measures how well that performance is maintained as the load increases.
A system with good performance may not scale well, but a scalable system ensures consistent performance as demand grows.
In short β performance is speed; scalability is sustainable speed under load.β
β
What is Caching?
Caching is the technique of storing frequently accessed data in a fast storage layer (like Redis, Memcached, in-memory caches) so that future requests can be served much faster without hitting the slow backend/database.
π In simple words:
Caching reduces latency, improves throughput, and reduces load on the database.
β Why Cache?
Examples:
β
Cache Update / Cache Write Strategies
There are four main cache update strategies you MUST know for interviews:
Most common strategy.
How it works:
How it works:
How it works:
How it works:
β Bonus: Eviction Policies (Mention briefly if asked)
These decide which item to remove when cache is full.
β
Interview-Ready Summary Answer
βCaching is storing frequently accessed data in a fast storage layer like Redis to reduce latency and database load. The main cache update strategies are:
Each strategy balances performance, consistency, and complexity differently.β
βοΈ What is Consistency in System Design?
Consistency refers to how up-to-date and synchronized the data is across all replicas (databases, caches, or services) in a distributed system.
When multiple copies of data exist (for scaling and fault tolerance), consistency patterns define how quickly and reliably changes made to one copy are reflected in others.
π§© Main Consistency Patterns
After a write operation, all reads will return the latest updated value.
The system behaves like a single machine β once data is written, every node immediately reflects the change.
Achieved by synchronous replication.
π§ Example:
Bank transactions β after transferring βΉ500, your account balance must instantly reflect the change.
Updates will propagate gradually β all replicas will eventually become consistent, but temporary stale reads are possible.
Common in distributed, high-availability systems.
π§ Example:
Social media feed β when you post a photo, some users may see it instantly, others after a few seconds.
Ensures that causally related operations are seen by all nodes in the same order, but independent operations may be seen in a different order.
π§ Example:
If you βlikeβ a post after commenting on it, all users will see your comment before your like β maintaining logical order.
A client will always see their own writes immediately, even if other clients might see stale data.
Very common in user-centric applications.
π§ Example:
When you upload your profile picture, you instantly see the change β others might see it after some delay.
Once a client has read a value, it will never see an older value on subsequent reads.
π§ Example:
In a messaging app, youβll never see a message disappear and then reappear β it always moves forward in time.
Ensures that writes from a single client are applied in order.
Prevents older writes from overwriting newer ones.
π§ Example:
In document editing, your latest edit should never be replaced by an earlier version.
π Summary Table
| Consistency Type | Description | Example Use Case |
|---|---|---|
| Strong | Always up-to-date | Banking |
| Eventual | Becomes consistent over time | Social media |
| Causal | Maintains cause-effect order | Comments & Likes |
| Read-after-write | User sees their own writes immediately | Profile updates |
| Monotonic Read | Never see older data after new | Chat apps |
| Monotonic Write | Writes applied in correct order | Collaborative editing |
Would you like me to show you how to explain this in a 60-second interview-style answer (clear and crisp version)?
βοΈ Definition
A Content Delivery Network (CDN) is a geographically distributed network of servers that store and deliver static content (like images, videos, CSS, JavaScript, etc.) to users from the nearest server location β improving speed, reliability, and performance.
π How It Works
When a user requests content (say an image or video),
π Why Itβs Important in System Design
π¦ Common CDN Providers
π§ Example (Real World)
When you open YouTube, the video you watch is served from a CDN edge server near your location β not from Googleβs central data center.
Thatβs why videos start instantly, even for millions of users at once.
π£οΈ Interview-Style Answer (60 seconds)
βA CDN or Content Delivery Network is a globally distributed system of servers that cache and deliver content from locations closer to the user.
It helps reduce latency, improves load times, and takes pressure off the origin servers.
CDNs are critical in system design for scalability, availability, and performance β especially for static assets like images, videos, and scripts.β
ποΈ Request Flow in a Scalable System with CDN
User (Browser / App)
β
βΌ
ββββββββββββββββββββββ
β DNS Resolution β
β (maps domain to β
β nearest CDN node) β
ββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββ
β CDN Edge Server β
β (serves static β
β cached content) β
ββββββββββββββββββββββ
β
(If cache miss)
β
βΌ
ββββββββββββββββββββββ
β Load Balancer β
β (distributes to β
β multiple servers) β
ββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββ
β Application β
β Servers (API) β
ββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββ
β Database β
β (SQL/NoSQL) β
ββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββ
β Object Storage β
β (e.g., S3 for β
β images/videos) β
ββββββββββββββββββββββ
βοΈ Step-by-Step Explanation
π Where the CDN Helps
| Type of Content | Delivered By | Example |
|---|---|---|
| Static (Images, CSS, JS, Videos) | CDN | Profile pictures, thumbnails |
| Dynamic (User feed, search results) | Origin servers | Personalized dashboard |
| Cached API responses | CDN or Redis | Frequently accessed public data |
π‘ Bonus Tip for Interview
When you mention CDN in your design, say something like:
βTo reduce latency and offload static traffic, Iβll integrate a CDN like Cloudflare or AWS CloudFront between users and our origin servers. This ensures faster global delivery and improves fault tolerance.β
βοΈ Definition
Leader Election is the process of selecting one node (server or process) among a group of distributed nodes to act as the coordinator or βleaderβ for managing specific tasks β such as updates, synchronization, or decision-making.
The leader coordinates work, while the others (followers) wait for instructions or updates.
π§© Why Leader Election Is Needed
In distributed systems, multiple nodes often run in parallel for fault tolerance.
If they all try to make decisions simultaneously, conflicts or inconsistencies can occur.
A leader helps by:
π‘ Example Scenario
Letβs say you have 3 replicas of a database for reliability:
π§ Popular Leader Election Algorithms
ποΈ Real-World Use Cases
| System | Where Leader Election Is Used |
|---|---|
| Apache Kafka | Each partition has one broker as leader for reads/writes |
| MongoDB | Replica sets elect a primary (leader) node |
| Kubernetes (K8s) | Controller manager uses leader election for failover |
| Zookeeper | Uses ZAB protocol to elect a leader |
βοΈ Advantages
β οΈ Challenges
π£οΈ Interview-Style 1-Minute Answer
βLeader Election is a process in distributed systems where one node is chosen as the coordinator or leader to manage operations like writes, synchronization, or coordination among nodes.
It ensures consistency and avoids conflicts. If the leader fails, a new one is elected automatically using algorithms like Raft or Bully. Systems like Kafka, MongoDB, and Kubernetes use leader election for reliability and fault tolerance.β
βοΈ Definition
A Distributed System is a collection of independent computers (nodes or servers) that appear to the users as a single coherent system.
While they offer scalability, fault tolerance, and performance, they also introduce design challenges due to network communication and coordination complexity.
π§© Key Design Issues in Distributed Systems
Letβs break them down category-wise π
Distributed systems should hide complexity from users, including:
π§± Summary Table
| Issue | Description | Example |
|---|---|---|
| Communication | Reliable message passing | Network latency handling |
| Consistency | Keeping replicas in sync | CAP trade-off |
| Fault Tolerance | Handle node failures | Leader re-election |
| Clock Synchronization | Order of events | Timestamps in logs |
| Load Balancing | Distribute load | Round-robin, consistent hashing |
| Security | Protect data and nodes | SSL, authentication |
| Partitioning | Split data | User ID sharding |
| Replication | Data copies and updates | Primary-replica setup |
| Scalability | Handle growth | Horizontal scaling |
| Transparency | Hide system complexity | User-friendly access |
π£οΈ Interview-Ready 60-Second Answer
βIn distributed systems, several design issues arise due to coordination among multiple nodes β such as ensuring consistency, handling node failures, managing replication and synchronization, maintaining clock order, balancing load, and achieving fault tolerance.
These challenges make distributed systems complex but also enable scalability and reliability when designed carefully.β
π¬ Example 1: Netflix Distributed System
Netflix runs a global streaming platform that serves millions of users watching videos simultaneously β a textbook distributed system.
Hereβs how the design issues actually appear π
| Design Issue | How Netflix Faces It | Solution Netflix Uses |
|---|---|---|
| Communication | Microservices (hundreds) must talk to each other efficiently. | Uses gRPC and REST APIs with service discovery. |
| Consistency | User watch progress, likes, or recommendations must be synced across regions. | Uses eventual consistency (via Cassandra, Kafka) β minor delay acceptable. |
| Fault Tolerance | Any server, region, or data center can fail anytime. | Uses Chaos Monkey to simulate failures and auto-recovery mechanisms. |
| Load Balancing | Millions of users watching at different times cause uneven traffic. | Uses Elastic Load Balancers (AWS ELB) + Global DNS load balancing. |
| Replication | Videos and metadata replicated globally. | Uses Amazon S3 + CDN (Akamai, CloudFront) for static content. |
| Clock Synchronization | Logs and metrics must be time-aligned for debugging. | Uses NTP servers and logical timestamps. |
| Security | Each device request must be authorized. | Uses OAuth tokens, TLS encryption, and API Gateway security layers. |
| Scalability | Traffic spikes during releases. | Uses Auto-scaling on AWS and microservice scaling independently. |
| Transparency | Users should never see failures. | Global fallback logic β redirects users to nearby healthy region. |
π§ Key Insight:
Netflix trades strong consistency for availability and fault tolerance, following the AP model of the CAP theorem.
π Example 2: Amazon (E-commerce Platform)
Amazonβs system handles millions of transactions per second β everything from searching, ordering, payments, to delivery tracking.
| Design Issue | How Amazon Faces It | Solution Amazon Uses |
|---|---|---|
| Communication | Thousands of microservices (catalog, cart, orders, payments). | Uses service mesh, API Gateway, and asynchronous queues (SQS). |
| Consistency | Product inventory must remain correct even under high traffic. | Uses eventual consistency with idempotent operations and DynamoDB. |
| Fault Tolerance | Data center or network failures must not stop transactions. | Multi-region replication + failover routing (Route 53). |
| Clock Synchronization | Payment logs must match across services. | Uses global time synchronization with vector clocks. |
| Scalability | Black Friday traffic spikes 10x normal load. | Auto-scaling groups + partitioned databases. |
| Security | Sensitive data (payments, user info). | End-to-end encryption, IAM roles, tokenized data. |
| Load Balancing | Billions of product page requests. | Elastic Load Balancers + CDN (CloudFront). |
| Replication | Search indexes and product data replicated globally. | Uses DynamoDB Global Tables. |
π§ Key Insight:
Amazon prioritizes Availability and Partition tolerance β it prefers to stay up and handle temporary data staleness rather than go offline.
π§ Interview-Style Wrap-Up Answer
βIn real-world systems like Netflix or Amazon, distributed system design issues appear everywhere β from ensuring consistent data across global replicas to handling failures gracefully.
Netflix uses eventual consistency and CDNs to deliver streaming content globally, while Amazon uses partitioned databases and message queues for scalability and fault tolerance.
Both systems prioritize availability and resilience over strict consistency, following the CAP theorem trade-offs.β