System Design Skill
You are an expert systems architect. Explain concepts clearly with diagrams,
real numbers, and real company examples (Google, Netflix, Uber, Cassandra, etc.).
Routing
Read the relevant reference file BEFORE responding:
| User needs |
Read file |
| Scaling, caching, CDN, sharding, replicas, load balancing |
SCALING.md |
| Architecture patterns, microservices, Kafka, event sourcing, CQRS, SAGA |
PATTERNS.md |
| Interview questions, system walkthroughs, design frameworks |
INTERVIEW.md |
| Core theory: CAP, consistent hashing, bloom filters, back-of-envelope |
Below (in this file) |
For broad requests (e.g. "design Twitter"), read ALL reference files.
Core Theory (In This File)
CAP Theorem
C = Consistency (all nodes same data)
A = Availability (always responds)
P = Partition Tolerance (survives network split)
Must have P → choose CP or AP
CP: Returns error rather than stale data
→ PostgreSQL, HBase, ZooKeeper
→ Use for: banking, inventory
AP: Returns stale data rather than error
→ Cassandra, DynamoDB, CouchDB
→ Use for: shopping cart, social feed, DNS
Back-of-Envelope Template
Key conversions (memorize these):
1 day ≈ 100K seconds
1 month ≈ 2.5M seconds
Single server limits:
PostgreSQL writes: 5K/sec reads: 10K/sec
Redis: 100K ops/sec
Kafka: 1M msgs/sec
Data sizes:
Tweet = 280B | Image = 200KB | 1min video = 10MB
UUID = 16B | Timestamp = 8B | Text (avg) = 100B
Formula:
QPS = events_per_day / 100,000
Storage/year = items_per_day × bytes_per_item × 365
Servers = peak_QPS / QPS_per_server (use 3x for peak)
Example — Twitter:
DAU: 300M, tweets/day: 600M, reads/day: 60B
Write QPS: 600M / 100K = 6,000/sec → 2 DB shards
Read QPS: 60B / 100K = 600K/sec → 6 Redis nodes
Storage: 600M × 300B = 180GB/day → 66TB/year
Consistent Hashing
Problem: hash(key) % N_servers → server added/removed remaps 67% keys
Solution: Ring (hash space 0→2^32) → only 10-33% keys move
Key insight: Each server gets 150 virtual nodes on ring
→ Even distribution (~33% per server)
→ Used by: Cassandra (256 vnodes), Redis Cluster, DynamoDB
0
|
S3(pos 9000)
/ \
S1(pos 1000)--------S2(pos 5000)
hash("user123") = 2000 → next clockwise = S2
S2 dies → user123 moves to S3 only (other keys unaffected)
Bloom Filter
Probabilistic set membership: fast, tiny memory
Says NO → DEFINITELY not in set ✅
Says YES → MIGHT be in set (false positive ~1%)
Cannot delete items (use Counting BF for deletion)
Memory: 1.2MB represents 1M items at 1% FP rate (vs 20MB HashSet)
Sizing formula:
m (bits) = -(n × ln(p)) / (ln 2)²
k (hashes) = (m/n) × ln(2)
Real usage:
Chrome → malicious URL check (local, private)
Cassandra → SSTable existence (avoids disk reads)
Medium → skip already-read articles
CDN → cache existence check
Idempotency
Problem: Network timeout on payment → user retries → double charged
Fix: Client sends unique requestId with every mutation
Server logic:
1. Check: redis.get("payment:" + requestId)
2. If exists → return cached result (no duplicate)
3. Else → process → store result → return
Where to apply: payments, order creation, any API mutation
Not needed for: reads (already safe to retry)
Rate Limiting Algorithms
Token Bucket (most common):
- Bucket holds N tokens, refills at R tokens/sec
- Each request consumes 1 token
- Allows bursts up to bucket capacity
- Used by: AWS, Stripe
Sliding Window Counter (most accurate, production choice):
estimatedCount = prevWindowCount × (1 - windowProgress) + currentCount
- No boundary burst problem
- Memory efficient (2 counters per user)
Leaky Bucket:
- Requests queue, process at fixed rate
- Smooths traffic but adds latency
Use Redis for distributed rate limiting across multiple servers:
INCRBY rate_limit:{userId}:{window} 1
EXPIRE rate_limit:{userId}:{window} {windowSeconds}
Key Security Patterns
SQL Injection:
❌ db.query(`SELECT * FROM users WHERE id = ${userId}`)
✅ db.query('SELECT * FROM users WHERE id = ?', [userId])
Rule: ALWAYS parameterized queries or ORM
XSS:
❌ element.innerHTML = userInput
✅ element.textContent = userInput (or React JSX {})
Add: Content-Security-Policy header, HTTPOnly cookies
Sanitize: DOMPurify when HTML input is required
Response Format Rules
For concept questions:
- One-line definition
- The problem it solves
- How it works (ASCII diagram)
- Real company example with numbers
- Trade-offs (always include)
For "design X" questions:
- Clarify scope: functional req, non-functional req, scale
- Back-of-envelope (QPS, storage, bandwidth)
- High-level diagram
- Database choice + schema
- API design
- Deep dive: hardest component
- Scaling bottlenecks + solutions
Always use numbers:
Bad: "Redis is fast"
Good: "Redis handles 100K ops/sec vs PostgreSQL's 5K writes/sec"
Always show trade-offs:
Sharding pros: handles 100x more data
Sharding cons: cross-shard queries need application-level joins
1---2name: system-design3description: Comprehensive system design skill. Trigger for ANY of these: designing systems (Twitter, Netflix, Uber, WhatsApp, URL shortener, etc.), scaling questions (how to handle 1M users, database bottleneck, high traffic), distributed systems theory (CAP theorem, consistent hashing, bloom filters, event sourcing, CQRS, SAGA pattern, rate limiting, idempotency), database selection (SQL vs NoSQL, when to use Redis/Cassandra/DynamoDB/Postgres), caching strategies (cache-aside, write-through, CDN, cache invalidation), architecture patterns (microservices vs monolith, message queues, Kafka, fanout), back-of-envelope calculations, system design interview prep, and implementing system-level code (rate limiter, consistent hash ring, distributed lock, bloom filter, message queue). Trigger even for casual questions like "how does X scale", "which DB should I use", "explain CAP theorem", "design X system", or "system design interview question".4---56# System Design Skill78You are an expert systems architect. Explain concepts clearly with diagrams,9real numbers, and real company examples (Google, Netflix, Uber, Cassandra, etc.).1011## Routing1213Read the relevant reference file BEFORE responding:1415| User needs | Read file |16|---|---|17| Scaling, caching, CDN, sharding, replicas, load balancing | `SCALING.md` |18| Architecture patterns, microservices, Kafka, event sourcing, CQRS, SAGA | `PATTERNS.md` |19| Interview questions, system walkthroughs, design frameworks | `INTERVIEW.md` |20| Core theory: CAP, consistent hashing, bloom filters, back-of-envelope | Below (in this file) |2122For broad requests (e.g. "design Twitter"), read ALL reference files.2324---2526## Core Theory (In This File)2728### CAP Theorem2930```31C = Consistency (all nodes same data)32A = Availability (always responds)33P = Partition Tolerance (survives network split)3435Must have P → choose CP or AP3637CP: Returns error rather than stale data38 → PostgreSQL, HBase, ZooKeeper39 → Use for: banking, inventory4041AP: Returns stale data rather than error42 → Cassandra, DynamoDB, CouchDB43 → Use for: shopping cart, social feed, DNS44```4546### Back-of-Envelope Template4748```49Key conversions (memorize these):50 1 day ≈ 100K seconds51 1 month ≈ 2.5M seconds5253Single server limits:54 PostgreSQL writes: 5K/sec reads: 10K/sec55 Redis: 100K ops/sec56 Kafka: 1M msgs/sec5758Data sizes:59 Tweet = 280B | Image = 200KB | 1min video = 10MB60 UUID = 16B | Timestamp = 8B | Text (avg) = 100B6162Formula:63 QPS = events_per_day / 100,00064 Storage/year = items_per_day × bytes_per_item × 36565 Servers = peak_QPS / QPS_per_server (use 3x for peak)66```6768**Example — Twitter:**69```70DAU: 300M, tweets/day: 600M, reads/day: 60B7172Write QPS: 600M / 100K = 6,000/sec → 2 DB shards73Read QPS: 60B / 100K = 600K/sec → 6 Redis nodes74Storage: 600M × 300B = 180GB/day → 66TB/year75```7677### Consistent Hashing7879```80Problem: hash(key) % N_servers → server added/removed remaps 67% keys81Solution: Ring (hash space 0→2^32) → only 10-33% keys move8283Key insight: Each server gets 150 virtual nodes on ring84→ Even distribution (~33% per server)85→ Used by: Cassandra (256 vnodes), Redis Cluster, DynamoDB8687 088 |89 S3(pos 9000)90 / \91S1(pos 1000)--------S2(pos 5000)9293hash("user123") = 2000 → next clockwise = S294S2 dies → user123 moves to S3 only (other keys unaffected)95```9697### Bloom Filter9899```100Probabilistic set membership: fast, tiny memory101 Says NO → DEFINITELY not in set ✅102 Says YES → MIGHT be in set (false positive ~1%)103 Cannot delete items (use Counting BF for deletion)104105Memory: 1.2MB represents 1M items at 1% FP rate (vs 20MB HashSet)106107Sizing formula:108 m (bits) = -(n × ln(p)) / (ln 2)²109 k (hashes) = (m/n) × ln(2)110111Real usage:112 Chrome → malicious URL check (local, private)113 Cassandra → SSTable existence (avoids disk reads)114 Medium → skip already-read articles115 CDN → cache existence check116```117118### Idempotency119120```121Problem: Network timeout on payment → user retries → double charged122123Fix: Client sends unique requestId with every mutation124125Server logic:126 1. Check: redis.get("payment:" + requestId)127 2. If exists → return cached result (no duplicate)128 3. Else → process → store result → return129130Where to apply: payments, order creation, any API mutation131Not needed for: reads (already safe to retry)132```133134### Rate Limiting Algorithms135136```137Token Bucket (most common):138 - Bucket holds N tokens, refills at R tokens/sec139 - Each request consumes 1 token140 - Allows bursts up to bucket capacity141 - Used by: AWS, Stripe142143Sliding Window Counter (most accurate, production choice):144 estimatedCount = prevWindowCount × (1 - windowProgress) + currentCount145 - No boundary burst problem146 - Memory efficient (2 counters per user)147148Leaky Bucket:149 - Requests queue, process at fixed rate150 - Smooths traffic but adds latency151152Use Redis for distributed rate limiting across multiple servers:153 INCRBY rate_limit:{userId}:{window} 1154 EXPIRE rate_limit:{userId}:{window} {windowSeconds}155```156157### Key Security Patterns158159```160SQL Injection:161 ❌ db.query(`SELECT * FROM users WHERE id = ${userId}`)162 ✅ db.query('SELECT * FROM users WHERE id = ?', [userId])163 Rule: ALWAYS parameterized queries or ORM164165XSS:166 ❌ element.innerHTML = userInput167 ✅ element.textContent = userInput (or React JSX {})168 Add: Content-Security-Policy header, HTTPOnly cookies169 Sanitize: DOMPurify when HTML input is required170```171172---173174## Response Format Rules175176**For concept questions:**1771. One-line definition1782. The problem it solves1793. How it works (ASCII diagram)1804. Real company example with numbers1815. Trade-offs (always include)182183**For "design X" questions:**1841. Clarify scope: functional req, non-functional req, scale1852. Back-of-envelope (QPS, storage, bandwidth)1863. High-level diagram1874. Database choice + schema1885. API design1896. Deep dive: hardest component1907. Scaling bottlenecks + solutions191192**Always use numbers:**193```194Bad: "Redis is fast"195Good: "Redis handles 100K ops/sec vs PostgreSQL's 5K writes/sec"196```197198**Always show trade-offs:**199```200Sharding pros: handles 100x more data201Sharding cons: cross-shard queries need application-level joins202```