Chapter 10 — System Design Interview Questions (40+ Questions)
System Design interviews evaluate your ability to design large-scale, reliable, maintainable software systems.
For Senior Full Stack / Team Lead roles, interviewers expect you to discuss:
- scalability
- availability
- performance
- security
- data storage
- architecture trade-offs
1. How do you approach a system design interview?
Interview Answer
I start by understanding requirements, defining the system boundaries, estimating scale, and then designing the architecture.
Step 1 — Clarify Requirements
Ask:
Functional requirements
What should the system do?
Example:
For an online shopping system:
- users browse products
- add items to cart
- place orders
- make payments
Non-functional requirements
How should the system behave?
Examples:
- response time
- availability
- scalability
- security
Step 2 — Estimate Scale
Understand:
- number of users
- requests per second
- data size
- traffic patterns
Example:
Users:
10 million
Requests:
50,000 per second
Step 3 — Design High-Level Architecture
Example:
Users
|
Load Balancer
|
Web/API Servers
|
Business Services
|
Database
Step 4 — Identify Bottlenecks
Ask:
- Where can it fail?
- What becomes slow under load?
- How do we scale?
Senior Answer
I approach system design by first clarifying requirements, estimating scale, designing a high-level architecture, then refining areas such as data storage, scalability, reliability, and security.
2. What are the main characteristics of a scalable system?
Interview Answer
A scalable system can handle increasing workload by adding resources without significant performance degradation.
Main characteristics:
1. Horizontal Scaling
Adding more servers.
Example:
Before:
Application Server
After:
Load Balancer
/ | \
Server Server Server
2. Stateless Services
Servers should not store user session data locally.
Bad:
User Session
|
Server A Memory
Problem:
If Server A fails:
Session Lost
Better:
Server
|
Redis / Database
3. Caching
Reduce database load.
Example:
User Request
|
Cache
|
Database (only if needed)
4. Database Scaling
Options:
- indexing
- replication
- partitioning
- sharding
5. Asynchronous Processing
Move slow operations to background workers.
Example:
Instead of:
Upload File
|
Process Immediately
|
Return Response
Use:
Upload File
|
Queue
|
Background Worker
Senior Answer
A scalable system uses stateless services, horizontal scaling, caching, asynchronous processing, and scalable data storage strategies.
3. Explain the difference between vertical and horizontal scaling.
Interview Answer
Scaling can be achieved by increasing the capacity of one machine or adding more machines.
Vertical Scaling (Scale Up)
Increase server power.
Example:
Before:
4 CPU
16 GB RAM
After:
32 CPU
128 GB RAM
Advantages:
- simple
- fewer application changes
Disadvantages:
- hardware limits
- expensive
- single point of failure
Horizontal Scaling (Scale Out)
Add more servers.
Example:
Before:
One Server
After:
Load Balancer
/ | \
Server Server Server
Advantages:
- better availability
- unlimited growth potential
- fault tolerant
Disadvantages:
- more complexity
- requires distributed architecture
Senior Answer
Vertical scaling increases the capacity of an existing server, while horizontal scaling adds more servers. Modern cloud applications usually prefer horizontal scaling because it improves availability and elasticity.
4. What is load balancing?
Interview Answer
A load balancer distributes incoming traffic across multiple servers to improve availability and performance.
Architecture:
Users
|
Load Balancer
/ | \
Server Server Server
Responsibilities
Traffic Distribution
Example:
Request 1 → Server A
Request 2 → Server B
Request 3 → Server C
Health Checks
The load balancer removes unhealthy servers.
Example:
Server A ❌
Removed from pool
SSL Termination
The load balancer can handle HTTPS encryption.
Client
HTTPS
|
Load Balancer
HTTP
|
Application
Load Balancing Algorithms
Round Robin
Requests distributed sequentially.
A → B → C → A
Least Connections
Send traffic to server with fewer active requests.
IP Hash
Same client goes to same server.
Examples
Cloud:
- AWS Elastic Load Balancer
- Azure Load Balancer
- Azure Application Gateway
Senior Answer
A load balancer improves system availability by distributing traffic across healthy servers and providing features such as health monitoring, SSL termination, and traffic routing.
5. What is caching and why is it important?
Interview Answer
Caching stores frequently accessed data in faster storage to reduce latency and database load.
Without Cache:
User Request
|
Application
|
Database
|
Response
With Cache:
User Request
|
Cache
|
Response
Types of Cache
1. Client-Side Cache
Stored in browser.
Examples:
- images
- JavaScript files
- CSS
2. Application Cache
Stored in application memory.
Example:
.NET MemoryCache
3. Distributed Cache
Shared between servers.
Examples:
- Redis
- Memcached
Architecture:
Server A
|
Server B
|
Redis Cache
Cache Strategies
Cache Aside
Application checks cache first.
Flow:
Request
|
Cache
|
Miss
|
Database
|
Update Cache
Write Through
Data written to cache and database together.
Write Behind
Write to cache first, database later.
Senior Answer
Caching improves performance by reducing database access and response times. In distributed systems I usually prefer a distributed cache such as Redis.
6. What is Redis and when would you use it?
Interview Answer
Redis is an in-memory data store commonly used as a cache, session store, message broker, and fast database.
Architecture:
Application
|
Redis
|
Database
Common Uses
1. Application Cache
Example:
Product catalog:
Product Data
|
Redis
|
Database
2. Session Storage
Example:
User Login
|
Redis Session
Useful when multiple servers exist.
3. Distributed Locking
Example:
Prevent two processes updating the same resource.
4. Real-Time Data
Examples:
- leaderboards
- counters
- notifications
.NET Example
IDistributedCache cache;
Senior Answer
Redis is useful for low-latency data access scenarios such as caching, session management, distributed locks, and real-time counters.
7. What is database replication?
Interview Answer
Database replication creates copies of data on multiple database servers.
Architecture:
Application
|
Primary DB
/ \
Replica DB Replica DB
Benefits
Read Scaling
Heavy reads go to replicas.
Example:
Write
|
Primary DB
Read
|
Replica DB
High Availability
If primary fails:
Replica
|
Become Primary
Types
Synchronous Replication
Data copied immediately.
Advantages:
- no data loss
Disadvantages:
- slower
Asynchronous Replication
Copy happens later.
Advantages:
- faster
Disadvantage:
- possible data loss
Examples
AWS:
- RDS Read Replicas
Azure:
- SQL Database Replication
Senior Answer
Database replication improves availability and read scalability by maintaining synchronized copies of data across multiple database instances.
8. What is database partitioning?
Interview Answer
Database partitioning divides a large table into smaller logical pieces while keeping it as one database object.
Example:
Large Orders table:
Orders
100 million rows
Partition by year:
Orders_2024
Orders_2025
Orders_2026
Benefits
- faster queries
- easier maintenance
- better data management
Types
Horizontal Partitioning
Split rows.
Example:
Customer ID
1-1M
1M-2M
Vertical Partitioning
Split columns.
Example:
Customer table:
Before:
Customer
ID
Name
Address
Photo
After:
Customer
ID
Name
CustomerDetails
Address
Photo
Senior Answer
Partitioning improves database performance and manageability by dividing large datasets into smaller, more efficient structures.
9. What is database sharding?
Interview Answer
Sharding is a database scaling technique where data is distributed across multiple independent databases.
Example:
Before:
One Database
1 billion users
After:
Shard 1
Users 1-10M
Shard 2
Users 10M-20M
Shard 3
Users 20M-30M
Sharding Key
Determines where data goes.
Example:
UserId % 3
Result:
User 1 → Shard 1
User 2 → Shard 2
User 3 → Shard 3
Advantages
- unlimited scaling
- distributed load
Challenges
- joins become difficult
- data balancing
- transactions across shards
Senior Answer
Sharding horizontally distributes data across multiple database instances. It provides massive scalability but introduces complexity around transactions and data distribution.
10. What is a CDN?
Interview Answer
A Content Delivery Network (CDN) is a distributed network of servers that delivers static content from locations closer to users.
Without CDN:
User Canada
|
Server USA
|
Image
With CDN:
User Canada
|
CDN Canada Edge Server
|
Image
CDN Stores
- images
- videos
- JavaScript files
- CSS
- static files
Benefits
- lower latency
- reduced server load
- better global performance
Examples:
- CloudFront (AWS)
- Azure Front Door
- Cloudflare
Senior Answer
A CDN improves performance by caching static content closer to users and reducing latency between clients and origin servers.
11. What is an API Gateway?
Interview Answer
An API Gateway is a single entry point between clients and backend services.
It handles:
- routing
- authentication
- authorization
- rate limiting
- logging
- request transformation
Without API Gateway:
id="api1"
Client
|
+---- Service A
|
+---- Service B
|
+---- Service C
Problems:
- client knows all services
- duplicated security logic
- difficult maintenance
With API Gateway:
id="api2"
Client
|
API Gateway
/ | \
Service A Service B Service C
Responsibilities
Routing
Example:
/api/orders
|
Order Service
/api/users
|
User Service
Authentication
Example:
Request
|
Validate JWT Token
|
Forward Request
Rate Limiting
Example:
User
|
100 requests/minute allowed
|
Block excess requests
Response Aggregation
Example:
Mobile app needs:
- user information
- orders
- recommendations
Instead of:
Mobile
|
|
Service A
|
Service B
|
Service C
Gateway combines responses:
Mobile
|
API Gateway
|
Combined Response
Examples
AWS:
- API Gateway
Azure:
- API Management
Enterprise:
- Kong
- Ocelot (.NET)
Senior Answer
An API Gateway provides a centralized entry point for client applications and handles cross-cutting concerns such as authentication, routing, rate limiting, and monitoring.
12. What is microservice architecture?
Interview Answer
Microservice architecture divides an application into small, independently deployable services that communicate through APIs or messaging systems.
Monolith:
id="mono1"
Application
+----------------+
| User Module |
| Order Module |
| Payment Module |
| Reporting |
+----------------+
Microservices:
id="micro1"
API Gateway
|
+-------------+-------------+
User Order Payment
Service Service Service
+-------------+-------------+
|
Databases
Characteristics
Independent Deployment
Each service can be deployed separately.
Example:
Order Service v2
without deploying
Payment Service
Independent Scaling
Example:
Order Service
100 servers
User Service
10 servers
Separate Data Ownership
Example:
Order Service
Order Database
User Service
User Database
Benefits
- scalability
- independent teams
- fault isolation
- technology flexibility
Challenges
- distributed complexity
- network failures
- monitoring
- data consistency
Senior Answer
Microservices allow teams to build independently deployable services with clear boundaries. They improve scalability and team autonomy but require strong practices around communication, monitoring, and data management.
13. How do microservices communicate?
Interview Answer
Microservices communicate using synchronous or asynchronous communication.
1. Synchronous Communication
Usually HTTP/REST or gRPC.
Example:
id="sync1"
Order Service
|
HTTP Request
|
Payment Service
Example:
Create order:
Order Service
|
Payment API
|
Payment Result
Advantages:
- simple
- immediate response
Disadvantages:
- tight coupling
- failures propagate
2. Asynchronous Communication
Using message brokers.
Example:
id="async1"
Order Service
|
Message Queue
|
Notification Service
Examples:
- RabbitMQ
- Kafka
- AWS SQS
- Azure Service Bus
Advantages:
- loose coupling
- better resilience
- handles traffic spikes
Senior Answer
I choose synchronous communication when immediate responses are required and asynchronous messaging when I need loose coupling, reliability, and independent processing.
14. What is a message queue?
Interview Answer
A message queue is a system that allows applications to communicate asynchronously by sending and receiving messages.
Architecture:
id="queue1"
Producer
|
Message Queue
|
Consumer
Example:
Order processing:
Customer places order
|
Order Service
|
Queue
|
Inventory Service
|
Email Service
Benefits
Decoupling
Services do not directly depend on each other.
Reliability
Messages remain available if consumer is temporarily down.
Load Handling
Queue absorbs traffic spikes.
Example:
10,000 requests
|
Queue
|
Workers process gradually
Examples
AWS:
- SQS
Azure:
- Service Bus
Open Source:
- RabbitMQ
Senior Answer
Message queues improve system reliability by allowing asynchronous processing and reducing direct dependencies between services.
15. Explain RabbitMQ.
Interview Answer
RabbitMQ is a message broker that implements Advanced Message Queuing Protocol (AMQP).
It routes messages between producers and consumers.
Architecture:
id="rabbit1"
Producer
|
Exchange
|
Queue
|
Consumer
Components
Producer
Creates messages.
Example:
Order Created Event
Exchange
Receives messages and routes them.
Types:
- Direct
- Topic
- Fanout
- Headers
Queue
Stores messages.
Consumer
Processes messages.
Example:
Order system:
Order Service
creates:
OrderCreated Event
|
RabbitMQ
|
Email Service
Features
- acknowledgments
- retries
- dead-letter queues
- routing rules
Senior Answer
RabbitMQ is suitable for reliable asynchronous communication where message routing, delivery guarantees, and task processing are important.
16. Kafka vs RabbitMQ. What is the difference?
Interview Answer
Both are messaging systems, but they are designed for different scenarios.
Kafka | RabbitMQ |
Event streaming platform | Message broker |
Very high throughput | Traditional messaging |
Stores events | Usually removes messages after processing |
Log-based | Queue-based |
Analytics and streaming | Task processing |
Kafka:
id="kafka1"
Producer
|
Topic
|
Consumers
Messages remain:
Event 1
Event 2
Event 3
RabbitMQ:
id="rabbit2"
Producer
|
Queue
|
Consumer
After processing:
Message Removed
Kafka Use Cases
- financial transactions
- analytics pipelines
- event sourcing
- IoT data
RabbitMQ Use Cases
- background jobs
- notifications
- order processing
Senior Answer
Kafka is better for high-volume event streaming and data pipelines, while RabbitMQ is often better for traditional asynchronous task processing and message routing.
17. What is event-driven architecture?
Interview Answer
Event-driven architecture is a design pattern where services communicate through events instead of direct calls.
Traditional:
id="event1"
Order Service
|
Payment Service
|
Notification Service
Services are coupled.
Event-driven:
id="event2"
Order Service
|
OrderCreated Event
|
+-------------+-------------+
Payment Notification Inventory
Example Event:
{
"eventType":"OrderCreated",
"orderId":123,
"timestamp":"2026-07-25"
}
Benefits
- loose coupling
- scalability
- easier integration
Challenges
- debugging complexity
- eventual consistency
- event versioning
Senior Answer
Event-driven architecture allows services to react to business events independently, improving scalability and reducing coupling between components.
18. What is eventual consistency?
Interview Answer
Eventual consistency means that distributed systems may temporarily have different data states, but eventually all replicas become consistent.
Example:
Bank transfer:
Account A
-$100
|
Event
|
Account B
+$100
There may be a short delay before both systems reflect the final state.
Strong consistency:
Write
|
All systems updated immediately
Eventual consistency:
Write
|
Update asynchronously
|
Eventually synchronized
Common in:
- microservices
- distributed databases
- cloud systems
Example
Order system:
Order Service
Order Created
|
Message Queue
|
Inventory Updated
Inventory may update a few seconds later.
Senior Answer
Eventual consistency is a trade-off used in distributed systems to achieve scalability and availability while allowing temporary data differences between services.
19. What is rate limiting?
Interview Answer
Rate limiting controls how many requests a client can make within a specific time period.
Purpose:
- prevent abuse
- protect services
- control costs
- avoid overload
Example:
User:
100 API calls/minute
Allowed:
100
Blocked:
101+
Architecture:
id="rate1"
Client
|
API Gateway
|
Rate Limiter
|
Backend
Algorithms
Fixed Window
Example:
100 requests per minute
Sliding Window
More accurate:
Last 60 seconds
Token Bucket
Tokens are generated over time.
Example:
Bucket:
100 tokens
Each request:
Consumes 1 token
Implementation
Possible locations:
- API Gateway
- Redis
- Load Balancer
Senior Answer
Rate limiting protects APIs from excessive usage and is usually implemented at the gateway layer using techniques such as token bucket or sliding window algorithms.
20. Design a notification system.
Interview Answer
A notification system should support sending:
- SMS
- push notifications
- in-app messages
while handling high volume reliably.
High-Level Design
id="notif1"
Application
|
Notification Service
|
Message Queue
|
+-------------+-------------+
Email SMS Push
Service Service Service
Flow
Example:
User receives order confirmation.
Order Created
|
Notification Event
|
Queue
|
Email Worker
|
Send Email
Components
Notification API
Receives requests.
Queue
Handles spikes.
Workers
Process messages.
Templates
Store message formats.
Example:
Order {id} shipped
User Preferences
Store:
- email enabled
- SMS enabled
- language
Scaling
Use:
- multiple workers
- queues
- retries
- dead-letter queues
Senior Answer
I would design a notification system using asynchronous processing with queues, independent notification workers, retry mechanisms, and user preference management to support scalability and reliability.
21. Design a URL Shortener (like Bitly)
Interview Answer
A URL shortener converts long URLs into short unique URLs and redirects users back to the original URL.
Examples:
Long URL:
https://www.example.com/products/category/item?id=123456
Short URL:
https://short.ly/aB91x
Requirements
Functional
- Create short URL
- Redirect short URL
- Track clicks
- Expiration support
Non-functional
- Low latency
- High availability
- Scalable storage
High-Level Architecture
User
|
Load Balancer
|
URL Service
|
+--------------+
| |
Database Cache
Data Model
Table:
UrlMapping
Id
ShortCode
OriginalUrl
CreatedDate
ExpirationDate
ClickCount
Example:
ShortCode | Original URL |
aB91x |
Creating Short URL
Algorithm:
- Generate unique ID
- Convert ID to Base62
- Store mapping
Example:
Database ID:
123456
Base62:
aB91x
Redirect Flow
User opens:
short.ly/aB91x
Flow:
Browser
|
URL Service
|
Cache
|
Database
|
Original URL
Scaling
Use:
- Redis cache for popular URLs
- database indexing on ShortCode
- CDN for global access
Senior Answer
I would design a URL shortener using a stateless URL service, a distributed database for mappings, Redis caching for frequent redirects, and a Base62 encoding strategy to generate compact unique identifiers.
22. Design a File Storage System (like Google Drive)
Interview Answer
A file storage system allows users to upload, store, retrieve, and share files.
Requirements
Functional:
- Upload files
- Download files
- Delete files
- Share files
- Version files
Non-functional:
- Large storage capacity
- High availability
- Secure access
Architecture
Client
|
File Service
|
+---------------+
| |
Metadata DB Object Storage
Components
Metadata Database
Stores:
FileId
Name
Owner
Size
Location
CreatedDate
Object Storage
Stores actual files.
Examples:
- AWS S3
- Azure Blob Storage
Architecture:
Upload File
|
File Service
|
Object Storage
|
Save Metadata
Large File Upload
Use:
Chunk Upload
Split file:
Large File
|
+----+----+----+
Part 1 Part 2 Part 3
Upload separately.
Security
Use:
- authentication
- authorization
- encryption
- signed URLs
Senior Answer
I would separate metadata management from file storage. Metadata belongs in a database, while large binary objects should be stored in scalable object storage such as S3 or Azure Blob Storage.
23. Design a Chat Application (like WhatsApp)
Interview Answer
A chat system requires real-time communication, message persistence, and delivery tracking.
Requirements
Functional:
- Send messages
- Receive messages
- Online status
- Message history
Architecture
Client
|
WebSocket Server
|
Message Service
|
Message Database
Real-Time Communication
Use:
- WebSockets
- SignalR
- Socket.IO
Flow:
User A
|
WebSocket
|
Chat Server
|
WebSocket
|
User B
Message Storage
Example:
Messages
Id
SenderId
ReceiverId
Text
Timestamp
Status
Handling Offline Users
Use queue:
Message
|
Queue
|
Store
|
Deliver when online
Scaling
Use:
- multiple WebSocket servers
- Redis pub/sub
- message queues
Senior Answer
I would use WebSockets for real-time communication, a message service for processing, persistent storage for history, and queues for handling offline users and reliability.
24. Design a Stock Trading Platform
Interview Answer
A trading platform requires real-time market data, low latency, security, and reliable transaction processing.
Architecture
Users
|
Trading API
|
+----------------+
| |
Order Service Market Data Service
| |
Database WebSocket Server
Components
Market Data Service
Receives:
- stock prices
- volume
- trades
Example:
AAPL
Price:
$215.50
Volume:
1,000,000
Order Service
Handles:
- buy orders
- sell orders
- validation
- execution
Database
Stores:
Orders
Id
UserId
Symbol
Quantity
Price
Status
Real-Time Updates
Use:
Market Feed
|
WebSocket
|
Browser
Important Design Points
Low Latency
Use:
- caching
- asynchronous processing
- optimized databases
Reliability
Use:
- message queues
- transaction logging
- audit trails
Security
Use:
- MFA
- encryption
- authorization
Senior Answer
For a trading platform I would separate order processing from market data streaming. I would use WebSockets for real-time prices, reliable order services, event-driven processing, and strong auditing because financial systems require accuracy and traceability.
25. Design a Search System (like Google Search)
Interview Answer
A search system indexes data and allows users to quickly find relevant information.
Architecture
Documents
|
Crawler
|
Indexer
|
Search Index
|
Query API
|
User
Components
Crawler
Collects documents.
Indexer
Creates searchable structures.
Example:
Word:
database
Documents:
1,5,10,20
Search Engine
Processes queries.
Examples:
- Elasticsearch
- Apache Solr
Search Optimization
Use:
- inverted indexes
- ranking algorithms
- caching
Example
User searches:
"ASP.NET Core authentication"
System:
Query
|
Search Index
|
Rank Results
|
Return Results
Senior Answer
A scalable search system uses crawlers, indexing pipelines, and search engines such as Elasticsearch. The key design challenge is building efficient indexes and ranking relevant results quickly.
26. Design an Authentication System
Interview Answer
An authentication system verifies user identity and manages access.
Architecture
User
|
Authentication API
|
User Database
|
Token Service
Login Flow
User enters credentials
|
Validate password
|
Generate JWT token
|
Return token
JWT Structure
Example:
{
"sub":"123",
"role":"Admin",
"exp":123456789
}
Components
User Store
Stores:
- username
- password hash
- roles
Token Service
Creates:
- access tokens
- refresh tokens
Authorization
Checks:
User Role
|
Permission
|
Allow / Deny
Security
Use:
- password hashing
- MFA
- HTTPS
- token expiration
Senior Answer
I design authentication systems using secure password storage, JWT or OAuth2 tokens, refresh token management, and role-based authorization.
27. Explain OAuth 2.0.
Interview Answer
OAuth 2.0 is an authorization framework that allows applications to access resources on behalf of users without sharing passwords.
Example:
"Login with Google"
Flow:
Application
|
Google Authorization Server
|
User Login
|
Access Token
|
Application
Components
Resource Owner
User.
Client
Application requesting access.
Authorization Server
Issues tokens.
Example:
- Microsoft Identity Platform
- Google Identity
Resource Server
API protecting data.
Common Flow
Authorization Code Flow:
User Login
|
Authorization Code
|
Exchange Code
|
Access Token
|
Call API
Senior Answer
OAuth2 separates authentication and authorization by allowing applications to obtain limited access tokens instead of handling user credentials directly.
28. What is JWT and how does it work?
Interview Answer
JWT (JSON Web Token) is a compact token format used for securely transmitting claims between parties.
Structure:
Header.Payload.Signature
Example:
xxxxx.yyyyy.zzzzz
Flow
User Login
|
Server validates credentials
|
Creates JWT
|
Client stores token
|
Send token with requests
Request:
Authorization:
Bearer eyJhbGci...
Advantages
- stateless authentication
- scalable
- works across services
Disadvantages
- difficult to revoke
- token size
- requires expiration strategy
Senior Answer
JWT enables stateless authentication by carrying user claims inside signed tokens. In production systems I combine JWT with expiration, refresh tokens, and secure storage.
29. What are distributed transactions?
Interview Answer
Distributed transactions occur when a single business operation involves multiple independent services or databases.
Example:
Order creation:
Order Service
+
Payment Service
+
Inventory Service
Problem:
Payment succeeds:
Payment completed
Inventory fails:
Stock update failed
System becomes inconsistent.
Traditional Solution
Two-Phase Commit (2PC)
Prepare Phase
|
Commit Phase
Problems:
- slow
- difficult across services
Modern Solution
Use:
- Saga Pattern
- Event-driven architecture
Senior Answer
In microservice systems I avoid traditional distributed transactions when possible and use patterns such as Saga with compensating actions.
30. Explain the Saga Pattern.
Interview Answer
Saga is a pattern for managing distributed transactions using a sequence of local transactions with compensation actions.
Example:
Order process:
Create Order
|
Reserve Inventory
|
Process Payment
|
Send Confirmation
If payment fails:
Compensating actions:
Cancel Order
|
Release Inventory
Architecture:
Order Service
|
Event
|
Inventory Service
|
Event
|
Payment Service
Types
Choreography
Services react to events.
Service A
|
Event
|
Service B
|
Event
|
Service C
Orchestration
Central coordinator controls flow.
Saga Coordinator
|
Service A
|
Service B
|
Service C
Senior Answer
Saga provides a way to maintain consistency across microservices by using local transactions and compensating actions instead of distributed database transactions.
31. What is CQRS (Command Query Responsibility Segregation)?
Interview Answer
CQRS is a design pattern that separates operations that change data (commands) from operations that read data (queries).
Instead of using one model for everything, we use separate models optimized for different purposes.
Traditional CRUD:
Application
|
Single Database Model
|
Read + Write
CQRS:
Application
|
+---------+---------+
| |
Command Side Query Side
| |
Write Database Read Database
Command Side
Handles:
- Create
- Update
- Delete
Example:
CreateOrderCommand
{
CustomerId = 10,
ProductId = 100
}
Query Side
Handles:
- Reading data
- Reporting
- Searching
Example:
GetCustomerOrdersQuery
Why use CQRS?
Different Optimization
Write model:
- transactions
- validation
- consistency
Read model:
- fast queries
- denormalized data
- reporting
Example:
Trading platform:
Command:
Buy Stock
|
Order Service
|
Trading Database
Query:
Show Portfolio
|
Read Database
|
Fast Response
Benefits
- scalable reads
- cleaner business logic
- independent optimization
Challenges
- more complexity
- data synchronization
- eventual consistency
Senior Answer
CQRS separates write operations from read operations, allowing each side to be optimized independently. I use it when systems have very different read and write workloads, such as financial or reporting applications.
32. What is Event Sourcing?
Interview Answer
Event sourcing stores the sequence of events that changed the state instead of storing only the current state.
Traditional database:
Account
Id:
100
Balance:
500
Only the final state is stored.
Event sourcing:
Account Events
Created
Deposit +1000
Withdraw -500
Deposit +200
Current balance is calculated from events.
Architecture
Command
|
Application
|
Event Store
|
Events
|
Build Current State
Example:
Bank Account:
Events:
AccountCreated
DepositMade(1000)
PaymentMade(300)
PaymentMade(200)
Current state:
Balance = 500
Benefits
Complete History
You know:
- what happened
- when
- who did it
Auditability
Useful for:
- banking
- trading
- insurance
Challenges
- complex queries
- event versioning
- storage growth
Senior Answer
Event sourcing stores business events as the source of truth. It is useful in systems where audit history and traceability are critical, such as financial systems.
33. Design an E-commerce Platform (Amazon-like)
Interview Answer
An e-commerce system requires product management, shopping cart, orders, payments, and inventory.
High-Level Architecture
Users
|
API Gateway
|
+-----------+-----------+-----------+
Product Cart Order Payment
Service Service Service Service
|
Databases
Main Services
Product Service
Handles:
- catalog
- categories
- pricing
Database:
Products
Id
Name
Price
Category
Cart Service
Stores:
- user cart
- selected items
Order Service
Handles:
- order creation
- status tracking
Example:
Created
|
Paid
|
Shipped
|
Delivered
Payment Service
Integrates with:
- payment providers
- fraud detection
Inventory Service
Tracks:
- available quantity
- reservations
Scaling
Use:
- Redis for product cache
- queues for order processing
- search engine for products
Senior Answer
I would design an e-commerce platform using separate services for catalog, cart, order, payment, and inventory. I would use asynchronous messaging between services to handle high traffic and maintain reliability.
34. Design an Uber-like Ride Sharing System
Interview Answer
A ride-sharing system requires real-time location tracking, matching drivers with passengers, and trip management.
Architecture
Passenger App
|
Ride Service
|
Matching Engine
|
Driver Service
|
Location Service
Components
Location Service
Receives GPS updates:
Driver:
Latitude
Longitude
Speed
Matching Engine
Finds nearby drivers.
Example:
Passenger Request
|
Search radius 5 km
|
Available Driver
Real-Time Communication
Use:
- WebSockets
- SignalR
For:
- driver location
- trip status
Database
Stores:
Trips:
TripId
DriverId
PassengerId
Start
End
Status
Challenges
- millions of locations
- real-time updates
- geographic search
Technologies
Possible:
- Redis Geo
- Elasticsearch
- Kafka
- WebSockets
Senior Answer
A ride-sharing system requires a real-time location service, matching engine, and event-driven architecture. Geographic indexing and WebSocket communication are key for scalability.
35. Design a Payment System
Interview Answer
Payment systems require high reliability, security, and transaction consistency.
Architecture
Client
|
Payment API
|
Payment Service
|
+--------------+
| |
Bank Gateway Transaction DB
Components
Payment Service
Handles:
- payment requests
- validation
- processing
Transaction Database
Stores:
Transaction
Id
UserId
Amount
Status
Date
Payment States
Example:
Created
|
Processing
|
Completed
|
Failed
Important Features
Idempotency
Prevents duplicate payments.
Example:
User clicks Pay twice.
System should create:
One Transaction
not:
Two Charges
Audit Logs
Every transaction recorded.
Security
Use:
- encryption
- tokenization
- PCI compliance
Senior Answer
Payment systems require strong consistency, idempotent operations, audit logging, and security controls. I would design them with transactional storage and reliable event processing.
36. Design a Reporting System
Interview Answer
Reporting systems usually separate transactional workloads from analytical workloads.
Problem
Production database:
Orders
Users
Payments
Heavy reports slow down applications.
Solution
Create reporting pipeline:
Production DB
|
ETL Pipeline
|
Data Warehouse
|
Reporting System
Components
Data Extraction
Collect data from:
- SQL databases
- APIs
- logs
Data Warehouse
Optimized for analytics.
Examples:
- Snowflake
- Redshift
- Azure Synapse
Reporting Layer
Examples:
- Power BI
- QuickSight
- SSRS
Example
Daily sales report:
Orders Database
|
Nightly ETL
|
Data Warehouse
|
Dashboard
Senior Answer
I separate reporting workloads from transactional systems using ETL pipelines and analytical databases to prevent performance impact on operational applications.
37. What is a multi-tenant SaaS architecture?
Interview Answer
Multi-tenancy allows multiple customers to use the same application infrastructure while keeping their data isolated.
Example:
SaaS application:
Application
|
+-----------+-----------+
Company A Company B
Data Data
Common Models
1. Shared Database, Shared Tables
Example:
Customers Table
TenantId
UserId
Name
Data:
TenantId=1
TenantId=2
2. Shared Database, Separate Schemas
Database
|
+-- CompanyA Schema
|
+-- CompanyB Schema
3. Separate Database
Tenant A DB
Tenant B DB
Tenant C DB
Considerations
- security isolation
- scalability
- cost
- backup strategy
Senior Answer
Multi-tenant systems require strong tenant isolation, security controls, and a database strategy that balances scalability, maintenance, and cost.
38. Explain cloud architecture best practices.
Interview Answer
Cloud architecture should focus on scalability, reliability, security, and cost optimization.
Key Principles
1. Design for Failure
Assume components fail.
Example:
Server Failure
|
Automatic Recovery
2. Use Managed Services
Examples:
AWS:
- RDS
- S3
- Lambda
Azure:
- SQL Database
- Blob Storage
- Functions
3. Automate Deployment
Use:
- CI/CD
- Infrastructure as Code
Examples:
- Terraform
- CloudFormation
- Bicep
4. Monitor Everything
Collect:
- metrics
- logs
- traces
Senior Answer
Good cloud architecture uses managed services, automation, observability, security controls, and designs for failure rather than assuming infrastructure will always be available.
39. What is disaster recovery (DR)?
Interview Answer
Disaster recovery defines how a system recovers after major failures.
Important metrics:
RTO (Recovery Time Objective)
How quickly must the system recover?
Example:
RTO = 1 hour
RPO (Recovery Point Objective)
How much data loss is acceptable?
Example:
RPO = 5 minutes
Meaning:
Maximum 5 minutes of data loss.
DR Strategies
Backup and Restore
Cheapest.
Pilot Light
Minimal infrastructure running.
Warm Standby
Partially running environment.
Active-Active
Multiple regions serving traffic.
Region A
|
Users
|
Region B
Senior Answer
Disaster recovery planning defines recovery objectives, backup strategies, and failover mechanisms to minimize downtime and data loss.
40. What is observability?
Interview Answer
Observability is the ability to understand the internal state of a system by analyzing telemetry data.
The three main pillars are:
1. Logs
Detailed events.
Example:
User login failed
UserId=123
Time=10:05
2. Metrics
Numerical measurements.
Examples:
- CPU usage
- response time
- requests per second
3. Traces
Follow a request across services.
Example:
API Gateway
|
Order Service
|
Payment Service
|
Database
Tools
Examples:
- Application Insights
- CloudWatch
- Grafana
- Prometheus
- ELK Stack
Senior Answer
Observability allows teams to diagnose production problems using logs, metrics, and distributed tracing. For microservice systems it is essential for troubleshooting and performance monitoring.
Final section of System Design.
41. Design a Notification Platform at Scale
Interview Answer
A large notification platform must support millions of notifications through multiple channels:
- SMS
- Push notifications
- In-app messages
The main challenges are scalability, reliability, retries, and delivery tracking.
High-Level Architecture
Applications
|
Notification API
|
Message Queue
|
Notification Workers
/ | \
Email SMS Push
Service Service Service
|
Delivery Tracking DB
Components
Notification API
Receives requests:
Example:
{
"userId":123,
"type":"ORDER_CREATED",
"channel":"EMAIL"
}
Message Queue
Examples:
- RabbitMQ
- Kafka
- AWS SQS
- Azure Service Bus
Purpose:
- absorb traffic spikes
- decouple services
Example:
1 million notifications
|
Queue
|
Workers process gradually
Worker Services
Responsible for:
- sending messages
- retries
- failures
Example:
Send Email
|
Failed
|
Retry after 5 minutes
Delivery Database
Stores:
Notification
Id
UserId
Channel
Status
CreatedDate
SentDate
Scaling Strategies
Use:
- multiple workers
- partitioned queues
- batch processing
- rate limiting
Senior Answer
I would design a notification platform using asynchronous processing with queues, independent workers for each channel, retry mechanisms, and delivery tracking to achieve scalability and reliability.
42. Design a Stock Market Data Pipeline
Interview Answer
A stock market data system must process high-volume real-time market events with very low latency.
Architecture
Market Data Providers
|
Data Ingestion
|
Message Streaming Platform
|
+---------------+---------------+
Real-Time API Storage
|
WebSocket Servers
|
Trading Clients
Components
Data Ingestion Service
Receives:
- price updates
- trades
- volume
- order book changes
Example:
{
"symbol":"AAPL",
"price":215.50,
"volume":1000
}
Streaming Layer
Examples:
- Kafka
- AWS Kinesis
- Azure Event Hubs
Purpose:
- high throughput
- ordered events
- replay capability
Real-Time Service
Uses:
- WebSockets
- SignalR
Example:
Market Update
|
WebSocket
|
Browser Dashboard
Storage
Different storage for different needs:
Time-series database
For:
- historical prices
- charts
Examples:
- InfluxDB
- TimescaleDB
Relational Database
For:
- accounts
- orders
- transactions
Senior Answer
A market data platform should separate ingestion, streaming, real-time delivery, and historical storage. Event streaming platforms such as Kafka help process large volumes of market events reliably.
43. Design a Document Management System
Interview Answer
A document management system stores, searches, secures, and manages business documents.
Examples:
- contracts
- invoices
- reports
Architecture
User
|
Document Service
|
+----------------+
| |
Metadata DB Object Storage
|
File Content
Components
Metadata Database
Stores:
Document
Id
Name
Owner
Version
CreatedDate
Location
Object Storage
Stores actual files.
Examples:
- AWS S3
- Azure Blob Storage
Features
Version Control
Example:
Contract.doc
Version 1
Version 2
Version 3
Access Control
Example:
Manager
Can Edit
Employee
Read Only
Search
Use:
- Elasticsearch
- Azure Cognitive Search
Security
Use:
- encryption
- access policies
- audit logging
Senior Answer
I would separate document metadata from binary storage, using databases for metadata and object storage for files. Security, versioning, and audit history are critical parts of the design.
44. Design a Centralized Logging System
Interview Answer
A centralized logging system collects logs from many applications and makes them searchable.
Architecture
Applications
|
Log Collectors
|
Message Queue
|
Log Processing
|
Search Storage
|
Dashboard
Components
Log Collectors
Collect logs from:
- applications
- servers
- containers
Examples:
- Fluent Bit
- Logstash
Processing
Responsibilities:
- parsing
- filtering
- enrichment
Example:
Add:
Application Name
Environment
Timestamp
Storage
Examples:
- Elasticsearch
- OpenSearch
- Splunk
Visualization
Examples:
- Kibana
- Grafana
Example Log
{
"level":"ERROR",
"service":"OrderAPI",
"message":"Payment failed"
}
Senior Answer
A centralized logging platform collects logs through agents, processes them, stores them in searchable systems, and provides dashboards for troubleshooting and operational visibility.
45. Design a Monitoring Platform
Interview Answer
A monitoring platform collects system health information and alerts teams about problems.
Architecture
Services
|
Metrics Collectors
|
Time-Series Database
|
Alert Engine
|
Dashboard
Metrics Examples
Application:
- response time
- errors
- requests/sec
Infrastructure:
- CPU
- memory
- disk
Database:
- connections
- query performance
Alert Example
CPU > 90%
for 10 minutes
|
Send Alert
|
Team Notification
Tools
Examples:
- Prometheus
- Grafana
- Azure Monitor
- AWS CloudWatch
Senior Answer
Monitoring systems collect metrics, analyze system health, and provide alerts. A good monitoring strategy combines infrastructure metrics, application metrics, logs, and distributed tracing.
46. What is API versioning and why is it important?
Interview Answer
API versioning allows APIs to evolve without breaking existing clients.
Example:
Version 1:
GET /api/v1/users
Version 2:
GET /api/v2/users
Common Approaches
URL Versioning
Example:
/api/v1/orders
Header Versioning
Example:
Accept-Version:2
Query Parameter
Example:
/api/orders?version=2
Why Needed?
Because clients may:
- update slowly
- depend on old contracts
- require migration time
Best Practices
- maintain backward compatibility
- document changes
- deprecate old versions gradually
Senior Answer
API versioning allows systems to evolve while maintaining compatibility with existing consumers. I prefer clear versioning strategies and gradual migration paths.
47. Explain security architecture in a modern application.
Interview Answer
Security should be designed at every layer:
- frontend
- API
- database
- infrastructure
Typical Architecture
User
|
Identity Provider
|
API Gateway
|
Application Services
|
Database
Authentication
Answers:
"Who are you?"
Technologies:
- OAuth2
- OpenID Connect
- JWT
Authorization
Answers:
"What can you do?"
Examples:
Admin
Create/Delete Users
Employee
Read Data
Data Security
Use:
- encryption at rest
- encryption in transit
- secrets management
Infrastructure Security
Use:
- firewalls
- private networks
- security groups
Senior Answer
Modern security architecture uses defense in depth, combining authentication, authorization, encryption, secure networking, and continuous monitoring.
48. How do you handle data consistency in distributed systems?
Interview Answer
Distributed systems require balancing consistency, availability, and performance.
Strategies
Strong Consistency
All nodes see the same data immediately.
Example:
Bank balance.
Eventual Consistency
Systems become consistent over time.
Example:
Social media likes.
Techniques
Transactions
For single database operations.
Distributed Locks
Prevent conflicting updates.
Example:
Only one process updates inventory
Event-driven Updates
Example:
Order Created
|
Inventory Updated
|
Notification Sent
Saga Pattern
Uses compensation.
Senior Answer
I choose consistency strategies based on business requirements. Financial transactions may require strong consistency, while large-scale systems often use eventual consistency with event-driven patterns.
49. Explain architecture trade-offs.
Interview Answer
Every architecture decision involves balancing competing goals.
Common trade-offs:
Performance vs Cost
Example:
More servers:
Higher performance
Higher cost
Consistency vs Availability
Example:
Distributed databases:
Strong consistency
slower
Eventual consistency
faster
Simplicity vs Scalability
Monolith:
Simple
Less scalable
Microservices:
Complex
Highly scalable
Speed of Development vs Flexibility
Example:
Framework with conventions:
- faster initially
- less customization
Senior Answer
Good architecture decisions are based on business requirements. I evaluate scalability, reliability, cost, complexity, and maintainability before choosing a solution.
50. Describe a senior architect-level system design scenario.
Interview Answer
A senior engineer should demonstrate:
- requirement analysis
- architecture decisions
- technical trade-offs
- operational awareness
Example:
"Design a global banking platform."
Approach
Step 1: Requirements
Functional:
- accounts
- transfers
- payments
- reports
Non-functional:
- security
- availability
- compliance
Step 2: Architecture
Users
|
API Gateway
|
Microservices
|
Databases + Events
|
Monitoring
Step 3: Important Decisions
Use:
- microservices for domains
- queues for async processing
- databases with replication
- encryption
- audit logs
Step 4: Failure Handling
Plan:
- backups
- disaster recovery
- retries
- monitoring
Senior Answer
At a senior level, I focus not only on designing components but also on operational concerns such as reliability, security, scalability, deployment, monitoring, and future growth.
Chapter 10 — System Design Completed ✅
Total:
50 System Design Interview Questions
Covered:
✅ Scalability
✅ Load Balancing
✅ Caching
✅ Databases
✅ Microservices Architecture
✅ API Gateway
✅ Messaging
✅ Kafka/RabbitMQ
✅ Event Driven Design
✅ CQRS
✅ Event Sourcing
✅ Cloud Architecture
✅ Security
✅ Disaster Recovery
✅ Observability
✅ Real-world system designs