System Design, Scalability & Distributed Systems Master Interview Bank
CAP Theorem, PACELC, consistent hashing, database sharding, distributed transactions (2PC, SAGA), rate limiters, message brokers, caching patterns, and load balancing.
Curriculum Roadmap & Learning Path
5 StagesPart 1: Foundational Distributed Systems Concepts & Trade-offs (1 - 10)
10 QuestionsWhat is System Design and What is the Standard 4-Step Framework for Technical Interviews?
System Design is the process of defining the architecture, components, modules, interfaces, and data for a system to satisfy specified business and technical requirements at scale.
Horizontal vs Vertical Scaling: Architectural Trade-offs and Bottlenecks.
Vertical Scaling (Scale-Up): Adding more CPU, RAM, or NVMe disk capacity to a single physical or virtual machine • Horizontal Scaling (Scale-Out): Adding more discrete commodity instances into a distributed pool behind a load balancer.
The CAP Theorem & PACELC Theorem Deep-Dive.
The CAP Theorem states that a distributed data store can guarantee at most two of three characteristics simultaneously in the presence of a network partition: Consistency (C): Every read receives the most recent write or an error.
Distributed Consistency Models: Strong, Eventual, Causal, and Read-Your-Writes.
Consistency models define the contract between a distributed storage system and its applications regarding the order and freshness of observed data across multiple nodes: Strong (Linearizable) Consistency: Once a write completes, all subsequent reads across all nodes immediately return that value or newer.
Load Balancing Algorithms and Layer 4 vs Layer 7 Reverse Proxies.
A Load Balancer (LB) distributes incoming network traffic across a cluster of backend servers to ensure high throughput, fault tolerance, and zero-downtime deployments.: Layer 4 Load Balancing (Transport Layer - TCP/UDP) • Operates on IP address and port numbers without inspecting application payload.
Consistent Hashing and Virtual Nodes: Mitigating Hot-Spots and Rebalancing.
In standard modulo hashing (hash(key) % N), adding or removing a single server forces almost 100% of keys to be relocated to new servers, causing catastrophic cache stampedes and database overloads. Consistent Hashing maps both servers and data keys onto a circular 2^{32}-1 hash ring.
Caching Strategies: Cache-Aside, Write-Through, Write-Behind, and Write-Around.
Caching reduces latency and offloads database IOPS by storing hot data in ultra-fast RAM (Redis/Memcached). The choice of caching pattern defines how reads and writes interact.
Cache Stampede, Thundering Herd, and Cache Invalidation Strategies.
Cache Stampede (Thundering Herd): When a heavily requested hot cache key expires (e.g. homepage top stories or flash sale product), thousands of • Cache Penetration: Malicious or buggy clients query keys that exist neither in cache nor in the database (e.g. id = -9999), constantly hitting the DB.
Message Brokers vs Event Streaming: RabbitMQ vs Apache Kafka.
Message Broker (RabbitMQ) • Smart broker, dumb consumer model • Messages are pushed to consumers via AMQP • Once acknowledged (ACK), messages are deleted from the broker.
Database Sharding Strategies: Range, Hash, and Directory-Based Partitioning.
Sharding is the horizontal partitioning of a large database across multiple independent physical database instances (shards) when a single database exceeds memory, storage, or connection limits.
Part 2: Real-World High-Scale Architecture Problems (11 - 25)
15 QuestionsDesign a Distributed URL Shortener (TinyURL / Bit.ly).
Design a scalable service that converts long URLs (e.g. 150 characters) into concise aliases (e.g. https://tiny.cc/a8X9k2) and redirects users with sub-15ms latency.
Design a Distributed Rate Limiter.
Protect backend microservices from DDoS attacks, brute-force bots, and resource starvation by enforcing request quota policies (e.g. 100 requests per minute per IP or API key). Algorithm Comparison: Token Bucket (Optimal): Tokens are added to a bucket at a constant refill rate.
Design a Real-Time Chat System (WhatsApp / Slack / Discord).
Support 1-on-1 private messaging, group channels, persistent chat history, and online status with end-to-end delivery guarantees. Core Components: Connection Handshake: Client connects via HTTP/HTTPS, authenticates, and upgrades connection to bidirectional WebSocket.
Design Twitter / Social Media Feed System (Fan-Out on Write vs Fan-Out on Read).
Design an interactive timeline where users can post tweets (tweets/sec: 10K writes) and view a personalized chronological feed of tweets from accounts they follow (feeds/sec: 500K reads). The Architectural Dilemma: Fan-Out on Write vs Fan-Out on Read: Fan-Out on Write (Push Model).
Design a Proximity / Ride-Sharing Service (Uber / Lyft).
Connect drivers with nearby riders in real-time while processing location updates every 4 seconds from millions of active vehicles with sub-100ms spatial matching. Spatial Indexing Technologies: Geohash: Hierarchical spatial data structure that subdivides Earth into bounding grid boxes and encodes them into Base32 strings.
Design a Global Video Streaming Platform (YouTube / Netflix).
Ingest raw video files uploaded by creators, transcode them into multiple resolutions and bitrates, and stream playback smoothly to diverse devices across variable network bandwidths. Core Architecture & Streaming Protocols: HLS (HTTP Live Streaming) / MPEG-DASH • Videos are split into small chunks (2–6 seconds each).
Design a Distributed Unique ID Generator (Twitter Snowflake ID).
Generate unique 64-bit integer IDs across thousands of distributed servers without requiring centralized database auto-increments or slow distributed consensus coordination. Snowflake 64-Bit Structure: 1 bit: Unused sign bit (always 0) • 41 bits: Timestamp in milliseconds since custom epoch (2^{41} approx 69 years of IDs).
Design a Distributed Web Crawler (URL Frontier, Bloom Filters, and Politeness).
Systematically crawl billions of web pages across the public internet for indexing, processing 100,000 pages per second while adhering to host politeness policies (robots.txt).
Design an Idempotent Payment System (Stripe / Checkout).
Ensure that double-clicks, network timeouts, or retried API calls NEVER charge a customer twice or corrupt bank transaction balances. Idempotency Key Architecture: Client generates a UUIDv4 Idempotency Key in request header (Idempotency-Key: c9d721...) • Payment gateway acquires a distributed lock in Redis for that key.
Design a Cloud File Storage & Synchronization Service (Google Drive / Dropbox).
Allow users to upload, download, and synchronize files of arbitrary size across desktop and mobile devices with automatic delta sync and data deduplication. Core Innovations: Chunking (Delta Sync): Files are divided into 4MB chunks • Content-Addressable Storage: Each chunk is named after its SHA-256 hash.
Design a Typeahead / Autocomplete Search System (Trie & Top-K Ranking).
Provide real-time query suggestions as the user types each keystroke into a search bar within 30ms latency, handling 50,000 keystrokes per second.
Design a Distributed Notification Service (APNs, FCM, SMS, and Email).
Send billions of push notifications, SMS texts, and transactional emails with high delivery rates, user notification preferences, and deduplication. Architectural Highlights: Notification Template Engine: Renders dynamic strings and localized language templates.
Design an E-Commerce Flash Sale System (High Concurrency & Inventory Reservation).
Prevent overselling when 500,000 customers try to purchase 1,000 limited-stock gaming consoles within 3 seconds of a flash sale launch. The Solution: Atomic In-Memory Inventory Reservation: Relational database row locks (SELECT .. • Pattern: Preload inventory into Redis Decr or Lua script.
Design a Distributed Key-Value Store (Dynamo-Style Vector Clocks & Gossip Protocol).
Design an Amazon Dynamo-style highly available, partition-tolerant distributed key-value store with eventual consistency and decentralized masterless architecture. Key Technical Pillars: Decentralized Membership: Nodes monitor cluster health via Gossip Protocol (epidemic information dissemination).
Design a Web Analytics / Event Tracking Platform (Kafka + ClickHouse / Druid).
Ingest, aggregate, and query 10 billion daily user interaction events (pageviews, clicks, scroll depth) with real-time dashboard visualization. Storage Architecture: Columnar vs Row-Oriented: Row-oriented databases (PostgreSQL/MySQL) are designed for single-row OLTP operations.
Part 3: Distributed Transactions, Consensus & Reliability (26 - 36)
11 QuestionsDistributed Consensus: Raft vs Paxos.
Distributed consensus algorithms ensure that a cluster of servers agree on a shared state machine log, even if some nodes crash or experience network partitions.: Paxos: The original consensus algorithm proven by Leslie Lamport • Raft: Designed specifically to be understandable while providing equivalent safety to Multi-Paxos.
Two-Phase Commit (2PC) vs Three-Phase Commit (3PC).
Atomic transaction protocols that ensure all participating database nodes either commit or abort a distributed transaction together.: Two-Phase Commit (2PC) • Phase 1 (Prepare): Coordinator asks all participants: "Can you commit?" Participants lock resources and respond YES/NO.
The Saga Pattern: Orchestration vs Choreography for Microservices.
In microservice architectures where each service owns its private database, ACID multi-database transactions are anti-patterns. A Saga is a sequence of local transactions where each step publishes an event. If any step fails, the Saga executes Compensating Transactions backwards to undo previous actions.
CQRS (Command Query Responsibility Segregation) & Event Sourcing.
CQRS: Separates the data model for write modifications (Commands) from read queries (Queries) • Event Sourcing: Instead of storing only the current state of an entity, every state change is stored as an immutable append-only event log.
Distributed Locking: Redlock Algorithm vs ZooKeeper / etcd.
Coordinate exclusive access to a shared resource across multiple independent compute instances.: Redis Redlock: Acquires lock across N independent Redis masters (typically 5) • ZooKeeper / etcd: Uses consensus-backed ephemeral sequential nodes.
Gossip Protocols and Cluster Membership Discovery.
A decentralized peer-to-peer communication protocol where nodes periodically exchange membership and liveness state with a small set of random peers, spreading information exponentially like an epidemic.: Used by Apache Cassandra, Amazon DynamoDB, and HashiCorp Consul.
Resolving Concurrent Write Conflicts: Last-Write-Wins (LWW) vs CRDTs.
When two users update the identical key concurrently across partitioned nodes: Last-Write-Wins (LWW): Uses wall-clock NTP timestamp • Conflict-Free Replicated Data Types (CRDTs): Mathematically proven data structures (e.g. G-Counter, PN-Counter, OR-Set) that converge to the.
Circuit Breaker Pattern (Netflix Hystrix / Resilience4j).
Prevent cascading failures when a downstream microservice is down. Instead of exhausting worker threads on blocking timeouts, the Circuit Breaker trips to OPEN state and fails fast.: CLOSED: Requests flow normally • OPEN: Error threshold exceeded • HALF-OPEN: After sleep window, allows trial requests.
Dead Letter Queues (DLQ) and Exponential Backoff with Full Jitter.
When retrying failed network calls or message processing, retrying immediately causes thundering herd traffic spikes.: Exponential Backoff: Multiplies sleep interval by 2^n on each failure (1s, 2s, 4s, 8s, 16s...).
Database Replication Lag, Split-Brain & Leader Election.
Replication Lag: Time elapsed between a write committing to the Leader and replicating to Followers • Split-Brain: When a network partition divides a cluster into two isolated subnets, and both subnets elect their own Leader and accept • Fix: Strict Majority Quorum (N/2 + 1).
Zero-Downtime Database Migrations (Expand and Contract Pattern).
How to rename columns or alter schemas on live production databases with billions of rows without table locks or service downtime.: Expand: Add new nullable column newcolumn • Dual-Write: Deploy application code that reads from oldcolumn and writes to both oldcolumn and newcolumn.
Part 4: API Design, Security & Edge Networking (37 - 43)
7 QuestionsREST vs GraphQL vs gRPC: Serialization, Latency & Streaming Trade-offs.
REST: Standard over HTTP/1.1 or HTTP/2 using JSON • GraphQL: Client specifies exact fields needed, eliminating over-fetching and under-fetching • gRPC: Uses Protocol Buffers (binary serialization) over HTTP/2 multiplexing.
The API Gateway Pattern: Authentication, Rate Limiting & Aggregation.
A single reverse-proxy entry point for all client requests that handles cross-cutting concerns: SSL termination, JWT authentication, rate limiting, request tracing, and payload aggregation.
WebSockets vs Server-Sent Events (SSE) vs Long Polling.
WebSockets: Full-duplex bidirectional TCP communication • Server-Sent Events (SSE): Unidirectional server-to-client streaming over standard HTTP • Long Polling: Legacy fallback where client holds an HTTP request open until the server responds.
Content Delivery Networks (CDNs): Edge Caching & Anycast Routing.
Geographically distributed network of proxy servers that cache static assets and dynamic responses close to end users.: Anycast BGP: Routes client DNS queries to the topologically nearest physical datacenter • Cache-Control Headers: s-maxage, stale-while-revalidate, and instant tag purging.
Distributed Tracing & W3C TraceContext (OpenTelemetry).
Track a single end-user request as it traverses across dozens of microservices.: Trace ID: Unique identifier for the entire request journey • Span ID: Identifies individual unit of work in a specific service • Baggage: Context propagated across HTTP/gRPC boundaries via W3C traceparent headers.
DDoS Attack Mitigation: SYN Flood, Slowloris & Anycast Absorption.
SYN Flood (Layer 4): Floods TCP SYN packets without sending final ACK to exhaust connection memory table • Slowloris (Layer 7): Sends HTTP headers at agonizingly slow rates to keep server thread pool occupied • Anycast Absorption: Distributes massive attack volume across hundreds of edge locations worldwide.
TLS 1.3 Handshake & Zero Round-Trip Time (0-RTT) Resumption.
TLS 1.3 reduces the handshake from two round-trips (2-RTT in TLS 1.2) to a single round-trip (1-RTT). 0-RTT Resumption allows returning clients to send encrypted application data in the very first flight.
Part 5: Back-of-the-Envelope Estimation & Production Calculations (44 - 50)
7 QuestionsLatency Numbers Every Software Engineer Should Know.
Approximate physical hardware latencies that dictate architectural trade-offs.
Back-of-the-Envelope: Daily Active Users (DAU) to QPS and Bandwidth.
How to calculate Queries Per Second (QPS) and network egress during an interview.
Storage Capacity and Disk IOPS Sizing for 5-Year Projections.
Sizing raw storage and IOPS requirements for long-term data retention.
Estimating Memory Requirements for Multi-Tier Caching (80/20 Rule).
Applying the Pareto Principle (80/20 Rule): 80% of total read traffic is generated by 20% of hot data.: If daily read volume is 100\text{ GB}, your Redis cluster only needs to hold 20\text{ GB} in RAM to achieve an 80% cache hit ratio!.
High Availability Sizing: 99.9% vs 99.99% ("Four Nines") Downtime Budgets.
Service Level Agreements (SLAs) determine permissible annual and monthly downtime.
Network Egress and Cloud CDN Cost Optimization Sizing.
Cloud providers (AWS, GCP) charge heavily for outbound internet data transfer (0.08–0.09 per GB).: Routing static media (images, videos, JS chunks) through a CDN with high cache hit ratios (> 95%) cuts egress costs by up to 80% due to cheaper.
How to Summarize and Conclude a System Design Interview.
In the final 3-5 minutes of an interview, don't wait for the interviewer to prompt you. Proactively summarize your architecture: Recap Requirements: Confirm how the design satisfies initial functional and non-functional goals (e.g. 50K peak QPS, p99 < 50ms).