Comprehensive Guide to System Design Interfaces and Distributed Systems
Introduction to System Design Interviews
- Software engineers often struggle with system design interviews (SDIs) due to the unstructured nature of open-ended problems, lack of experience with large-scale systems, and insufficient preparation.
- Top companies like Google, Facebook, Amazon, and Microsoft require above-average performance for offers; good performance often leads to higher positions and salary.
Seven-Step Approach to System Design
- Step 1: Requirements Clarification
- Design questions are open-ended without a single correct answer. Clarifying ambiguities early is critical.
- Example (Twitter-like service): Ask if users can post and follow others, if there is a timeline, media support (photos/videos), backend vs. frontend focus, search capabilities, trending topics, and push notifications.
- Step 2: System Interface Definition
- Define APIs to establish a contract and ensure requirements are correct.
- Example:
postTweet(user_id, tweet_data, tweet_location, user_location, timestamp, ...). - Step 3: Back-of-the-Envelope Estimation
- Estimate scale for storage, optimal bandwidth, and QPS (Queries Per Second) to guide scaling and caching strategies.
- Step 4: Defining Data Model
- Identify entities and how they interact. Determine storage (SQL vs. NoSQL) and block storage for media.
- Example: User (UserID, Name), Tweet (TweetID, Content), UserFollow (UserID1, UserID2).
- Step 5: High-Level Design
- Draw block diagrams (5-6 boxes) representing core components from end-to-end.
- Components: Application servers, load balancers, databases, and distributed file storage.
- Step 6: Detailed Design
- Dig deep into 2-3 components based on interviewer feedback. Discuss trade-offs and constraints.
- Topics: Data partitioning (storing user data on a single database), handling hot users, caching layers, and load balancing.
- Step 7: Identifying and Resolving Bottlenecks
- Discuss single points of failure, data replicas, service redundancy, and performance monitoring/alerting.
Designing a URL Shortening Service (TinyURL)
- Requirements
- Functional: Generate unique aliases (short links), redirect to original URLs, support custom aliases, and link expiration.
- Non-functional: High availability, real-time redirection, and non-guessable links.
- Capacity Estimation
- Read-heavy system (100:1 read/write ratio).
- New URLs: 500 million/month.
- QPS (Write): 30×24×3600500×106≈200URL/s.
- QPS (Read): 200×100=20K/s.
- Storage (5 years): 500×106×5×12=30billion objects. At 500bytes per object, total storage is 15TB.
- Bandwidth: Ingress is 100KB/s; Egress is 10MB/s.
- Cache: To cache 20% of daily traffic (1.7billion requests), memory needed is ≈170GB.
- System APIs
-
createURL(api_dev_key, original_url, custom_alias=None, user_name=None, expire_date=None).
- deleteURL(api_dev_key, url_key). - Algorithm and Data Model
- Encoding URL: Use MD5 or SHA256. Base64 encoding a 6-letter key allows for 646≈68.7billion strings.
- Offline Key Generation Service (KGS): A standalone service generates unique keys beforehand and stores them in a
key-DB. Application servers pull keys from KGS to avoid collisions.
- KGS uses two tables for "used" and "unused" keys. It can cache keys in memory for speed but must synchronize access to prevent duplicate assignment. - Data Partitioning
- Range-based partitioning can lead to unbalanced servers.
- Hash-based partitioning (using Consistent Hashing) distributes URLs based on the key or URL hash.
- Purging and Cleanup
- Lazy cleanup: Delete expired links when users try to access them.
- Separate cleanup service: A lightweight periodic process removes expired links during low-traffic periods.
Designing Pastebin
- Requirements
- Users upload text and get a unique URL. Max size: 10MB.
- System must be highly reliable (no data loss) and available.
- Capacity Estimation
- 1million new pastes/day; 5:1 read/write ratio.
- Storage (10 years): 1million×365×10=3.6billion pastes.
- Total Storage: 3.6billion×10KB=36TB. At 70% capacity model, needed storage is 51.4TB.
- Design
- Separate metadata storage (SQL/NoSQL) from content storage (Object storage like Amazon S3).
- Application layer uses KGS for unique key generation.
Designing Instagram
- Requirements
- Upload/download/view photos, follow users, and News Feed generation.
- Constraints: 200ms latency for News Feed; eventual consistency is acceptable for feed viewing.
- Capacity
- 500million users, 1million daily active users.
- 2million new photos/day (23/s). Average photo: 200KB.
- Storage (10 years): ≈1425TB.
- Data Sharding
- Partitioning by UserID: Keeps all user data together but creates hot user issues and non-uniform storage.
- Partitioning by PhotoID: Uses a separate DB to generate auto-incrementing IDs. To solve single point of failure, use two DBs (one for even IDs, one for odd).
- News Feed Generation
- Pre-generation: Dedicated servers generate feeds and store them in a
UserNewsFeed table to lower latency.
- Push vs. Pull: Use "Push" for regular users and "Pull" for celebrity users followed by millions (Hybrid model).
Designing Dropbox
- Requirements
- Upload/download files (up to 1GB), sync across devices, support offline editing, and ACID-ity for operations.
- High-Level Components
- Client Application: Watches workspace, chunks files into 4MB parts, and handles conflict resolution.
- Metadata Database: Stores chunk versions, file names, and user data.
- Synchronization Service: Uses a differencing algorithm to sync only modified chunks.
- Client Internal Architecture
- Internal Metadata DB: Tracks local file versions.
- Chunker: Splits files for bandwidth efficiency.
- Watcher: Monitors local folder changes.
- Indexer: Communicates changes to the remote Sync Service using HTTP Long Polling.
- Data Deduplication
- Post-process: Duplicate data is stored briefly then removed by a background process.
- In-line: Hash calculations occur during upload; if the hash exists, only a reference is stored.
Designing Facebook Messenger
- Requirements
- One-on-one chat, online/offline status, and persistent history.
- Scale: 500million daily active users; 20billion messages/day.
- Message Handling
- Use a "Push" model via HTTP Long Polling or WebSockets for real-time delivery.
- Status Management: To avoid resource wastage, the server only broadcasts status changes to active friends or users in the current viewport.
- Storage
- Use a wide-column database like HBase to handle high rates of small updates and range scans for history.
- Sequencing
- Store sequence numbers per client (not just global timestamps) to ensure consistent message ordering across devices.
Designing YouTube or Netflix
- Detailed Design
- Metadata stored in MySQL; videos in HDFS/GlusterFS.
- Thumbnails: Use BigTable as it is efficient at grouping small files (5KB) into blocks, reducing disk seeks.
- Video Deduplication
- Inline matching (Block Matching/Phase Correlation) prevents redundant encoding and storage wastage.
- Content Delivery Network (CDN)
- Popular videos are pushed to geographically distributed CDNs. Less popular content is served from origin data centers.
Designing Typeahead Suggestion
- Data Structure: Trie (Prefix Tree)
- Nodes store characters. To find suggestions for "cap", traverse to node 'P' and gather all child terms.
- Optimization: Store the top 10 suggestions and their frequencies at each node to avoid traversing sub-trees during runtime.
- Updates
- Trie is updated offline via MapReduce processing logs from the last hour.
- Use Exponential Moving Average (EMA) to give more weight to recent search trends.
- Partitioning
- Partition by server capacity: Store 'A-AABC' on Server 1, 'AABD-BXA' on Server 2.
- Use an Aggregator layer to merge results if a prefix spans multiple trie servers.
Designing an API Rate Limiter
- Algorithms
- Fixed Window: Counters reset at the start of time units. Problem: Spikes can double the limit at window boundaries.
- Rolling Window: Counts requests in a sliding time frame relative to the request time.
- Sliding Window with Counters: Tracks counts in smaller fixed units (e.g., minutes within an hour) to approximate a sliding window with less memory than a full log.
- Implementation Detail
- Use Redis Sorted Sets to store timestamps for a sliding window. Memory: ≈12GB for 1million users.
- Atomicity in distributed systems: Use Redis locks or Lua scripts to prevent race conditions during "read-modify-write" cycles.
- Indexing Strategy
- Sharding by Word: High risk of hot words (e.g., "the", "Trump") overloading a single server.
- Sharding by Tweet Object: Query all servers for every search term; results are merged by an aggregator. This is generally more balanced.
- Fault Tolerance
- Store a reverse index (mapping TweetID to index server) in an Index-Builder server to allow quick rebuilds of failed nodes.
Designing a Web Crawler
- Components
- URL Frontier: Prioritizes and stores URLs to visit.
- Document Input Stream (DIS): Caches downloaded content for processing by multiple modules (HTML parser, dedupe test).
- Distributed Crawling
- Politeness: Map hostnames to specific worker threads to ensure only one connection per server at a time.
- Dedupe: Use a 64−bit checksum (MD5/SHA) for documents and URLs. For 15billion pages, the checksum store is ≈120GB.
- Checkpointing: Snapshots of the frontier and state are written to disk every few hours to allow recovery from interruption.
Designing Facebook Newsfeed
- Feed Generation
- Pre-generate feeds for active users in a
LinkedHashMap structure in memory.
- Fan-out-on-write (Push): Update followers' feeds immediately when a post is made.
- Fan-out-on-load (Pull): Generate feed only when the user logs in.
- Hybrid: Push for regular users; Pull for celebrities to avoid the "celebrity fan-out" bottleneck.
Designing Yelp (Proximity Server)
- The QuadTree
- A tree where each node has four children. A node splits if it contains more than 500 locations.
- Leaf nodes store actual LocationIDs.
- Neighboring grids are found via parent pointers or a doubly linked list connecting all leaf nodes.
- Uber Modification
- Uber requires rapid updates (3seconds). Instead of rebuilding the QuadTree, store current locations in a hash table (
DriverLocationHT) and update the QuadTree every 15seconds.
Designing Ticketmaster
- Workflow and Concurrency
- Users put a 5-minute hold on seats. Database status changes to "Reserved (1)".
- Concurrency is managed via SQL Transactions with the isolation level set to
SERIALIZABLE to prevent double-booking. - Waiting User Service
- Uses a
LinkedHashMap to maintain a first-come-first-served queue for people waiting for seats to be released from expired holds.
System Design Basics and Scalability
- Key Characteristics
- Reliability: Probability the system will perform its function (redundancy helps eliminate single points of failure).
- Availability: Percentage of time a system is operational. It differs from reliability; an available system may still be insecure or prone to failure under certain conditions.
- Scalability: Horizontal (adding more servers) vs. Vertical (adding CPU/RAM to one server).
- Load Balancing (LB)
- Sits between client and server. Algorithms include Round Robin, Least Connections, Least Response Time, and IP Hash.
- Caching Strategies
- Write-through: Updates DB and cache simultaneously (safe but slow).
- Write-around: Bypasses cache for writes (prevents cache flooding).
- Write-back: Updates cache only; DB updated later (fast but risky).
- SQL vs. NoSQL
- SQL: Relational, fixed schema, vertically scalable, ACID compliant (best for finance).
- NoSQL: Non-relational, dynamic schema, horizontally scalable (Key-Value, Document, Wide-Column, Graph).
- CAP Theorem
- States that a distributed system can only provide two of three: Consistency (C), Availability (A), and Partition Tolerance (P).
- Consistent Hashing
- Mapped via a hash ring. Adding/removing a node only requires remapping nk keys. Virtual replicas ensure even load distribution.
- Communication Protocols
- Ajax Polling: Client keeps asking; many empty responses.
- Long Polling: Server holds request until data is available or timeout.
- WebSockets: Persistent full-duplex bi-directional connection.
- Server-Sent Events (SSE): One-way persistent stream from server to client.