Skip to content
System Design Interview0%

System Design Interview Framework

System design interviews test your ability to architect large-scale distributed systems under ambiguity. This guide provides a repeatable framework, estimation cheat sheets, and links to detailed walkthroughs for the most commonly asked problems.

The Structured Framework

Every system design interview should follow a disciplined structure. Rushing into diagrams without clarifying requirements is the single most common reason candidates fail.

Step 1: Requirements Gathering (3-5 minutes)

Before touching the whiteboard, ask clarifying questions. Split requirements into two categories:

Functional Requirements — What the system does:

  • Core features (the "must haves")
  • User-facing APIs
  • Data inputs and outputs
  • Edge cases and error handling

Non-Functional Requirements — How the system behaves:

  • Scale (users, QPS, data volume)
  • Latency (p50, p99 targets)
  • Availability (99.9% = 8.7 hours downtime/year)
  • Consistency model (strong, eventual, causal)
  • Durability (zero data loss?)
  • Security and compliance

Interview Tip

Always ask: "Who are the users?", "What is the expected scale?", and "What are the most important quality attributes?" This shows maturity and prevents wasted effort on irrelevant components.

Step 2: Back-of-Envelope Estimation (3-5 minutes)

Estimations ground your design in reality. Interviewers want to see you think quantitatively.

Step 3: High-Level Design (10-15 minutes)

Draw the 30,000-foot architecture:

  • Client types (web, mobile, API)
  • Load balancers
  • Application servers
  • Databases (SQL vs NoSQL)
  • Caches
  • Message queues
  • CDNs
  • Third-party services

Step 4: Detailed Component Design (10-15 minutes)

Deep-dive into 2-3 critical components. The interviewer will guide you toward what interests them most.

Step 5: Scaling & Trade-offs (5-10 minutes)

Discuss bottlenecks, failure modes, and how to scale each layer.


Estimation Cheat Sheet

These reference numbers let you do quick back-of-envelope math in any interview.

Power of Two Reference

PowerExact ValueApproxBytes
2101,0241 Thousand1 KB
2201,048,5761 Million1 MB
2301,073,741,8241 Billion1 GB
2401,099,511,627,7761 Trillion1 TB
2501 Quadrillion1 PB

Latency Numbers Every Engineer Should Know

OperationLatency
L1 cache reference0.5 ns
Branch mispredict5 ns
L2 cache reference7 ns
Mutex lock/unlock25 ns
Main memory reference100 ns
Compress 1KB with Zippy3 us
Send 1KB over 1 Gbps network10 us
Read 4KB randomly from SSD150 us
Read 1MB sequentially from memory250 us
Round trip within same datacenter500 us
Read 1MB sequentially from SSD1 ms
HDD seek10 ms
Read 1MB sequentially from HDD20 ms
Send packet CA -> Netherlands -> CA150 ms

QPS Estimation Formulas

Daily Active Users (DAU) to QPS:

QPS=DAU×actions per user per day86400Peak QPS2×QPS(general rule)Peak QPS3-5×QPS(social/viral apps)

Example: 100M DAU, 10 actions/day:

QPS=100M×108640011,57412KPeak QPS24K-60K

Storage Estimation Formulas

Text storage:

Daily storage=DAU×posts per user×avg post size

Media storage:

Daily storage=uploads per day×avg file size

5-year projection:

Total=Daily storage×365×5

Bandwidth Estimation

Ingress=Daily data in86400Egress=Daily data out86400

Quick Reference

  • 1 day = 86,400 seconds (round to 105 for easy math)
  • 1 month ~ 2.5M seconds
  • 1 year ~ 30M seconds
  • A single server can handle ~10K-50K concurrent connections
  • A single PostgreSQL instance handles ~10K-50K QPS (depending on query complexity)
  • Redis handles ~100K-500K QPS per instance
  • A single Kafka broker handles ~100K-1M messages/sec

Availability Math

AvailabilityDowntime/YearDowntime/Month
99% (two 9s)3.65 days7.3 hours
99.9% (three 9s)8.77 hours43.8 minutes
99.99% (four 9s)52.6 minutes4.38 minutes
99.999% (five 9s)5.26 minutes26.3 seconds

Combined availability of components in series:

Atotal=A1×A2××An

Example: Three components each at 99.9%:

A=0.9993=0.99799.7%

Common Patterns Reference

These patterns appear repeatedly across system design problems. Mastering them lets you quickly assemble solutions.

1. Consistent Hashing

Problem: Distributing data across N nodes where N changes over time.

Solution: Hash both keys and nodes onto a ring. Each key is assigned to the next node clockwise.

Used in: URL Shortener, Dropbox, distributed caches

2. Fan-Out on Write vs Fan-Out on Read

Fan-Out on Write (Push Model):

  • Pre-compute results when data changes
  • Fast reads, slow writes
  • Works for users with bounded follower counts
  • Used by: Instagram Feed, Twitter Feed

Fan-Out on Read (Pull Model):

  • Compute results at read time
  • Slow reads, fast writes
  • Better for users with millions of followers (celebrity problem)

3. Write-Ahead Log (WAL)

Problem: Ensuring durability without flushing every write to disk.

Solution: Append every mutation to a sequential log before applying it. On crash, replay the log.

Used in: Chat System, databases, message queues

4. Event Sourcing / CQRS

Problem: Complex read and write patterns that don't fit a single model.

Solution: Separate the write model (event log) from the read model (materialized views). Events are immutable; views are derived.

Used in: Notification System, Twitter Feed

5. Blob Storage + Metadata DB

Problem: Storing large binary objects alongside structured metadata.

Solution: Store blobs in object storage (S3), metadata in a database. Reference blobs by URL/key.

Used in: Instagram, YouTube, Dropbox

6. Message Queues for Async Processing

Problem: Decoupling producers from consumers; handling bursty traffic.

Solution: Kafka, RabbitMQ, or SQS between services. Producers enqueue; consumers process at their own pace.

Used in: YouTube transcoding, Web Crawler, Notification System

7. Rate Limiting

Problem: Preventing abuse and protecting downstream services.

Algorithms:

  • Token Bucket — smooth rate, allows bursts
  • Sliding Window — precise, memory-intensive
  • Leaky Bucket — fixed output rate

Used in: Notification System, URL Shortener, API gateways

8. Geospatial Indexing

Problem: Finding nearby entities efficiently.

Solutions:

  • Geohash — encode lat/long into string, prefix matching for proximity
  • Quadtree — recursive spatial subdivision
  • R-tree — bounding rectangle hierarchy
  • S2 geometry — map sphere to cube faces, Hilbert curve indexing

Used in: Uber, location-based services

9. CDN (Content Delivery Network)

Problem: Serving static content to globally distributed users with low latency.

Solution: Cache content at edge servers worldwide. Pull or push model.

Used in: Instagram, YouTube, Dropbox

10. Database Sharding Strategies

Strategies:

  • Range-based — simple but hotspots
  • Hash-based — even distribution but range queries are hard
  • Directory-based — flexible but single point of failure
  • Geographic — data locality for compliance

11. Leader-Follower Replication

Problem: Scaling reads and providing fault tolerance.

Solution: One leader handles writes; followers replicate and serve reads.

12. Bloom Filters

Problem: Quickly checking if an element is NOT in a set, without storing the full set.

Solution: Probabilistic data structure. False positives possible, false negatives impossible.

Used in: Web Crawler (duplicate URL detection), cache lookups


API Design Principles

When designing APIs in an interview:

  1. Use RESTful conventions for CRUD operations
  2. Use WebSockets for real-time bidirectional communication
  3. Use Server-Sent Events for one-way real-time updates
  4. Include pagination for list endpoints (cursor-based preferred)
  5. Version your APIs (/api/v1/...)
  6. Include rate limiting headers in responses
typescript
// Cursor-based pagination example
interface PaginatedResponse<T> {
  data: T[];
  cursor: string | null;  // null means no more pages
  hasMore: boolean;
}

// API endpoint
// GET /api/v1/feed?cursor=abc123&limit=20

Database Selection Guide

RequirementChooseExamples
ACID transactionsRelational DBPostgreSQL, MySQL
Flexible schemaDocument DBMongoDB, DynamoDB
High write throughputLSM-tree DBCassandra, RocksDB
Graph relationshipsGraph DBNeo4j, Neptune
Caching / sessionsIn-memoryRedis, Memcached
Full-text searchSearch engineElasticsearch, Solr
Time-series dataTSDBInfluxDB, TimescaleDB
File/blob storageObject storeS3, GCS, Azure Blob

Walkthrough Index

Each walkthrough follows the framework above. Ordered by complexity — start from the top if you're new, jump in anywhere if you're not.

Tier 1 — Core Primitives

Master these first. Every other system reuses these concepts.

ProblemKey ConceptsDifficulty
URL ShortenerHashing, Base62, read-heavy caching, analytics pipelineMedium
Key-Value StoreConsistent hashing, LSM trees, replication, gossip protocolMedium
Rate LimiterToken bucket, sliding window, Redis atomics, distributed enforcementMedium
Distributed CacheConsistent hashing, LRU/LFU eviction, hot keys, cluster topologyMedium

Tier 2 — Storage & Media

Adds blob storage, CDN, and file pipelines.

ProblemKey ConceptsDifficulty
Dropbox / Google DriveFile chunking, deduplication, delta sync, conflict resolutionMedium-Hard
InstagramImage storage, CDN, news feed, fan-out, celebrity problemMedium-Hard
YouTubeVideo transcoding, adaptive bitrate (DASH), CDN distributionHard
NetflixStreaming, recommendation engine, Open Connect CDNHard
SpotifyAudio streaming, offline sync, playlist managementHard

Tier 3 — Social & Real-Time

Adds WebSockets, fan-out, and message delivery semantics.

ProblemKey ConceptsDifficulty
Chat System (WhatsApp)WebSockets, message delivery receipts, group chat, E2E encryptionHard
SlackChannels, presence, search, workspace isolationHard
Twitter FeedFan-out-on-write vs read, timelines, trending topicsHard
RedditVoting, ranking algorithms, comment trees, federationMedium-Hard
LinkedInSocial graph, feed ranking, job matching, InMailHard
Notification SystemMulti-channel (push/SMS/email), priority queues, rate limitingMedium

Tier 4 — Search & Crawling

Adds inverted indexes, ranking, and large-scale crawling.

ProblemKey ConceptsDifficulty
Typeahead / AutocompleteTrie, prefix search, ranking, real-time updatesMedium
Search AutocompleteDistributed trie, top-K, personalizationMedium-Hard
Web CrawlerURL frontier, Bloom filter, politeness, distributed BFSMedium-Hard
Search EngineInverted index, PageRank, crawl + index + serve pipelineHard
Twitter SearchReal-time indexing, inverted index on tweets, rankingHard
Search RankingRelevance scoring, ML ranking models, A/B testingHard

Tier 5 — Location & Matching

Adds geospatial indexing and real-time matching.

ProblemKey ConceptsDifficulty
Uber / LyftGeospatial index (H3/Quadtree), real-time matching, surge pricingHard
Google MapsGraph shortest path, tile rendering, ETA, map updatesHard
TinderGeospatial filtering, swipe matching, recommendationMedium-Hard
Food DeliveryReal-time tracking, order routing, driver dispatchHard

Tier 6 — Booking & Transactions

Adds distributed transactions, inventory, and payment flows.

ProblemKey ConceptsDifficulty
Ticket Booking (Ticketmaster)Seat locking, distributed transactions, flash salesHard
Hotel Booking (Airbnb)Inventory, double-booking prevention, calendar syncHard
E-CommerceProduct catalog, cart, inventory, order managementHard
Payment SystemIdempotency, double-spend prevention, reconciliationHard
Stock ExchangeOrder book, matching engine, low-latency, market dataExpert

Tier 7 — Developer & Infra Tools

Complex internal systems requiring deep infra knowledge.

ProblemKey ConceptsDifficulty
API GatewayAuth, rate limiting, routing, observabilityMedium
CDNPoPs, cache hierarchy, origin offload, anycast routingMedium-Hard
GitHubGit object store, distributed VCS, PR workflow, CI/CD hooksHard
Google DocsOperational transformation, CRDT, conflict-free collaborationExpert
ZoomWebRTC, SFU vs MCU, bandwidth adaptation, recordingExpert
Live StreamingRTMP ingest, HLS/DASH output, low-latency edge deliveryHard

Tier 8 — Advanced & Specialized

Niche but frequently asked at senior/staff levels.

ProblemKey ConceptsDifficulty
News AggregatorFeed aggregation, deduplication, rankingMedium
Email ServiceSMTP, deliverability, spam filtering, inbox storageMedium-Hard
LeaderboardRedis sorted sets, real-time ranking, time-windowed boardsMedium
Ad PlatformBidding, targeting, impression tracking, fraud detectionExpert
Recommendation EngineCollaborative filtering, embeddings, real-time servingExpert
Fraud DetectionRule engines, ML scoring, graph analysis, real-time decisionsExpert
Content ModerationML classifiers, human review queues, appeal workflowsHard
Social Network (General)Graph storage, feed, privacy model, growth mechanicsHard
Parking LotOOP design, slot allocation, pricing engineMedium

Tier 9 — AI Systems

Emerging category — increasingly asked at top companies.

ProblemKey ConceptsDifficulty
ChatGPT / LLM ServiceInference serving, token streaming, context management, costExpert
GitHub CopilotCode completion, low-latency inference, context window, IDE integrationExpert

The Interview Checklist

Use this checklist during your practice sessions:

Before Drawing Anything

  • [ ] Clarified functional requirements (3-5 core features)
  • [ ] Clarified non-functional requirements (scale, latency, availability)
  • [ ] Asked about constraints (budget, team size, timeline)
  • [ ] Estimated QPS, storage, bandwidth

During High-Level Design

  • [ ] Drew client -> LB -> app server -> DB flow
  • [ ] Identified read vs write paths
  • [ ] Chose appropriate database(s)
  • [ ] Added caching where read-heavy
  • [ ] Added message queues where async processing needed
  • [ ] Added CDN for static content

During Detailed Design

  • [ ] Defined API endpoints with request/response
  • [ ] Designed database schema with indexes
  • [ ] Addressed the "hard part" of the problem
  • [ ] Drew sequence diagrams for critical flows

During Scaling Discussion

  • [ ] Identified the bottleneck
  • [ ] Discussed horizontal scaling strategy
  • [ ] Addressed single points of failure
  • [ ] Mentioned monitoring and alerting

Common Mistakes to Avoid

Common Pitfalls

  1. Jumping to solutions — Always gather requirements first
  2. Over-engineering — Start simple, add complexity when justified
  3. Ignoring non-functional requirements — Scale and latency matter
  4. Not doing estimations — Numbers ground your design in reality
  5. Monologue mode — System design is a conversation, not a lecture
  6. Ignoring trade-offs — Every decision has pros and cons
  7. No diagrams — Always draw; visual communication is essential
  8. Premature optimization — Solve the core problem first

Scaling Playbook

When the interviewer asks "how would you scale this?", use this playbook:

Tier 1: Single Server Optimizations

  • Add indexes to database queries
  • Implement application-level caching (Redis)
  • Optimize N+1 queries
  • Connection pooling

Tier 2: Vertical Scaling

  • Bigger machines (more CPU, RAM, SSD)
  • Read replicas for database
  • Separate read and write paths (CQRS)

Tier 3: Horizontal Scaling

  • Stateless application servers behind load balancer
  • Database sharding
  • Distributed caching (Redis Cluster)
  • CDN for static assets

Tier 4: Global Scale

  • Multi-region deployment
  • Global load balancing (GeoDNS)
  • Data replication across regions
  • Edge computing

CAP Theorem Quick Reference

In the presence of a network Partition, you must choose between:

  • CP (Consistency + Partition Tolerance): Every read receives the most recent write or an error. Examples: ZooKeeper, HBase, MongoDB (with majority reads)
  • AP (Availability + Partition Tolerance): Every request receives a response (possibly stale). Examples: Cassandra, DynamoDB, CouchDB

Real-World Note

In practice, most systems are not purely CP or AP. They offer tunable consistency (e.g., Cassandra's consistency levels). The CAP theorem is a starting point for discussion, not a rigid classification.


Consistency Models

ModelGuaranteeLatencyUse Case
StrongRead sees latest writeHighBanking, inventory
LinearizableStrong + real-time orderingHighestDistributed locks
CausalRespects cause-effectMediumSocial feeds, chat
EventualWill converge eventuallyLowDNS, CDN caches
Read-your-writesSee your own writesMediumUser profiles

Load Balancing Algorithms

AlgorithmDescriptionBest For
Round RobinRotate through serversEqual-capacity servers
Weighted Round RobinWeight by capacityMixed-capacity servers
Least ConnectionsRoute to least busyVariable request duration
IP HashHash client IPSession stickiness
Consistent HashingMinimal redistributionCaches, sharding

Caching Strategies

Cache-Aside (Lazy Loading)

Read: Check cache -> miss -> read DB -> populate cache -> return
Write: Write DB -> invalidate cache
  • Most common pattern
  • Cache only what's needed
  • Risk: cache stampede on cold start

Write-Through

Write: Write cache + DB simultaneously
Read: Always from cache
  • No stale data
  • Higher write latency
  • Cache may hold unused data

Write-Behind (Write-Back)

Write: Write cache -> async write DB
Read: Always from cache
  • Low write latency
  • Risk: data loss if cache dies before DB write

Read-Through

Read: Cache handles DB read on miss
Write: Write directly to DB
  • Cache acts as main data source for reads
  • Simplifies application logic

Monitoring and Observability

Always mention monitoring in your design:

The Four Golden Signals

  1. Latency — Time to serve a request (p50, p95, p99)
  2. Traffic — Requests per second
  3. Errors — Rate of failed requests (5xx, timeouts)
  4. Saturation — How "full" the system is (CPU, memory, disk, queue depth)

Observability Stack

  • Metrics: Prometheus + Grafana
  • Logs: ELK Stack (Elasticsearch, Logstash, Kibana)
  • Traces: Jaeger or Zipkin (distributed tracing)
  • Alerts: PagerDuty, OpsGenie

Further Reading

  • Start with the individual walkthroughs linked in the Walkthrough Index
  • Each walkthrough includes production-grade code examples, detailed diagrams, and interview tips specific to that problem
  • Practice by time-boxing yourself to 45 minutes per problem
  • Focus on communication and trade-off discussion, not just technical correctness

The Golden Rule

A good system design answer is not about finding THE correct answer — it is about demonstrating a structured thought process, making reasonable trade-offs, and communicating clearly.

"What I cannot create, I do not understand." — Richard Feynman