System Design Interviews: Load Balancing, Caching (Redis), Sharding, CAP/PACELC, Message Queues (Kafka) & Rate Limiting

Staff/Senior System Design interview mastery covering L4 vs L7 Load Balancing, Consistent Hashing with Virtual Nodes, Caching strategies & Thundering Herd prevention, Redis internals & Redlock, Database Replication (Leaderless Quorum W+R>N) & Sharding, CAP/PACELC, 2PC vs Saga & Outbox, Kafka internals, Rate Limiting algorithms, Snowflake IDs, and Bloom Filters.

Category
Coding Interviews (Blind 75 / NeetCode DSA), Distributed System Design & Advanced SQL
Level
advanced
Languages
en → en
Cards
32
Markdown
System Design Interviews: Load Balancing, Caching (Redis), Sharding, CAP/PACELC, Message Queues (Kafka) & Rate Limiting (.md)

Flashcards (32)

#Front (Term / Question)Back (Definition / Answer)ExampleMultiple-Choice Options
1Explain the internal architecture of **Apache Kafka**: `Topics`, `Partitions`, `Offsets`, `Consumer Groups`, and why Partition count bounds consumer parallelism.A Kafka **Topic** is split into append-only, immutable ordered logs called **Partitions** distributed across brokers (each Partition has 1 Leader replica handling reads/writes and $k$ In-Sync Follower Replicas `ISR`). Messages with the same `partition_key` (`hash(key) % num_partitions`) always land in the same Partition, guaranteeing strict **FIFO ordering ONLY within a single Partition** (not across the whole Topic!). Within a **Consumer Group**, each Partition can be assigned to **at most ONE consumer instance** at a time—so if a Topic has 8 Partitions and a Consumer Group has 12 consumers, 4 consumers will sit completely idle!
2Compare Layer 4 (Transport) and Layer 7 (Application) Load Balancers in System Design, including how connection termination works.**Layer 4 Load Balancer** (e.g., AWS NLB, IPVS, Linux LVS, Maglev): Operates on TCP/UDP 5-tuple `(src_ip, src_port, dst_ip, dst_port, proto)` using NAT or Direct Server Return (DSR); does NOT inspect HTTP headers or decrypt TLS, achieving millions of packets/sec with sub-millisecond latency. **Layer 7 Load Balancer** (e.g., NGINX, Envoy, HAProxy, AWS ALB): Terminates the client's TCP and TLS connection, inspects decrypted HTTP/gRPC headers, cookies, and URL paths (`/api/v1/chat`), and pools separate persistent backend TCP connections—enabling smart routing, WAF, rate limiting, and gRPC per-RPC load balancing.
3Why is **Two-Phase Commit (2PC)** an anti-pattern across distributed microservices, and how does the **Transactional Outbox + CDC Pattern** solve dual-write bugs?**2PC** is a blocking atomic commitment protocol: if the Coordinator crashes after participants vote `YES` in Phase 1, participants must hold database row locks indefinitely until the coordinator recovers, destroying availability and throughput. Furthermore, writing to your DB and publishing to Kafka in app code (`db.save(); kafka.send()`) is a **Dual-Write Bug** (if the app crashes in between, DB and Kafka diverge!). **Transactional Outbox Pattern**: Inside the *exact same local ACID database transaction* as `INSERT INTO orders`, insert the event into an `outbox` table (`INSERT INTO outbox`); a separate **CDC (Change Data Capture, e.g., Debezium)** process tails the DB's WAL/binlog and publishes `outbox` rows to Kafka with at-least-once delivery!
4Why is Redis single-threaded for command execution yet capable of 100,000+ ops/sec, and what core Redis data structures power System Design interviews?Redis executes commands on a single main event-loop thread using **in-memory data structures** and **I/O Multiplexing (`epoll`/`kqueue`)** (with multi-threaded network I/O read/write in Redis 6+), completely avoiding OS thread context-switching and lock contention! Essential structures: 1. `String` (atomic counters `INCR`, distributed locks `SET key val NX PX 10000`); 2. `Hash` (user profiles/sessions); 3. `Sorted Set` (`ZSET`: Skip List + Hash Table for **Real-Time Leaderboards** `ZADD`/`ZREVRANGE` and **Sliding Window Rate Limiters** in $O(\log N)$); 4. `HyperLogLog` (`PFADD`/`PFCOUNT`: counts billions of unique visitors in **12 KB** with $0.81\%$ standard error); 5. `Streams` / `PubSub`; 6. `Geo` (`GEOADD`/`GEORADIUS` geohashes).
5Compare Geospatial Indexing approaches for **Proximity Services (Uber / Yelp / DoorDash)**: `Geohash`, `Quadtree`, and `Uber H3`.Why fails: `WHERE lat BETWEEN ... AND lng BETWEEN ...` cannot use a single 1D B+ Tree index efficiently on both columns simultaneously! 1. **Geohash**: Interleaves latitude and longitude bits (Z-order space-filling curve) into a Base32 string (e.g., `9q8yyk` = ~1.2km $\times$ 0.6km box); points in the same cell share a string prefix (indexable via standard B+ Tree / Redis!), and you always query the target cell plus its **8 surrounding neighbor cells** to solve boundary edge cases. 2. **Quadtree**: In-memory tree that recursively subdivides cells into 4 quadrants ONLY when point density exceeds a threshold $K$ (adapts to dense cities vs empty oceans). 3. **Uber H3**: Hierarchical **hexagonal** grid where every cell has 6 equidistant neighbors (eliminating square corner distance distortion for ETA/surge pricing).
6Compare the four Caching Strategies: `Cache-Aside`, `Read-Through`, `Write-Through`, and `Write-Behind (Write-Back)`.1. **Cache-Aside (Lazy Loading)**: App checks cache first; on miss, app reads from DB, writes to cache with a TTL, and returns data (on write, app updates DB and **deletes/invalidates** the cache key rather than updating it to avoid race conditions!). 2. **Read-Through**: Cache library/proxy sits inline and fetches from DB transparently on miss. 3. **Write-Through**: Every write synchronously updates BOTH cache and DB before returning (strong cache consistency, higher write latency). 4. **Write-Behind (Write-Back)**: App writes only to fast in-memory cache and returns immediately; cache asynchronously batches writes to DB (highest write throughput for counters/likes, risks data loss if cache crashes before flush).
7Why does naive `hash(key) % N` fail for distributed caches/shards when nodes scale, and how does **Consistent Hashing with Virtual Nodes** solve it?With `hash(key) % N`, when a single cache node crashes or is added ($N \to N \pm 1$), almost **100% of keys** ($(N-1)/N$) remap to a different server, triggering a catastrophic cache miss storm! **Consistent Hashing** maps both servers and keys onto a $2^{32}$ hash ring `[0, 2^32 - 1]`; each key routes clockwise to the first server on the ring, so adding/removing 1 server only remaps **$1/N$ of keys**! Because placing only 1 physical point per server on the ring causes uneven load skew, each physical server is assigned $100–200$ **Virtual Nodes (vnodes)** scattered across the ring, ensuring uniform standard deviation and allowing heterogeneous hardware weights.
8How do you prevent **Double-Booking in a High-Concurrency Ticket/Hotel Reservation System (`Ticketmaster` / `Airbnb`)** when 100,000 users click the same seat?Two-Phase Reservation with Hold TTL: 1. When User A selects `Seat 14A` to enter payment details, execute an atomic conditional update in the relational DB (`UPDATE seats SET status = 'RESERVED', reserved_by = :user, expires_at = NOW() + INTERVAL '7 minutes' WHERE seat_id = '14A' AND (status = 'AVAILABLE' OR (status = 'RESERVED' AND expires_at < NOW()))`)—or use a per-seat Redis lock/Lua script backed by DB ACID commit before payment. 2. If User A completes Stripe payment within 7 minutes (using an `Idempotency-Key`), transition seat to `BOOKED`; if not, the hold automatically expires for the next user! For Taylor Swift-level flash sales, place a **Virtual Waiting Room (Queue-it)** at the CDN edge to meter traffic entering the booking tier.
9How do you implement a safe Distributed Lock in Redis, and what is Martin Kleppmann's critique of `Redlock` regarding GC pauses and Fencing Tokens?Single-instance lock: Acquire via `SET resource_name my_random_uuid NX PX 30000` (atomic set-if-not-exists with 30s TTL); release ONLY via an **atomic Lua script** that checks `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1])` (so a slow worker whose lock expired never deletes another worker's newly acquired lock!). `Redlock` acquires locks across $\ge 3/5$ independent Redis masters for HA. Kleppmann's critique: If Client 1 hits a long stop-the-world GC pause after acquiring the lock, the lock expires and Client 2 acquires it—for true correctness, the lock service must issue a monotonically increasing **Fencing Token** verified by the downstream storage server (e.g., via etcd/ZooKeeper Raft/ZAB).
10How do you design a globally distributed **Chat System (WhatsApp / Slack / Discord)** for 1-on-1 and Group Messaging?1. Stateful **Chat Gateway Servers** hold persistent **WebSocket** connections with online clients, registering `user_id -> gateway_node` mappings inside a Presence/Session store (Redis/etcd). 2. When User A sends a message to User B: Gateway A writes the message with a per-conversation monotonically increasing `sequence_id` / Snowflake ID to a wide-column store (**Cassandra / ScyllaDB / HBase** partitioned by `(channel_id, bucket)`, ideal for append-heavy chronological range scans of recent chat history), looks up User B's Gateway in Redis, and routes the message over internal gRPC (or triggers APNs/FCM **Push Notification** if B is offline). 3. For small groups (<500), fan-out to member inboxes; for huge Discord channels (100k members), use pub/sub channel routing + pull on active view.
11Compare **Apache Kafka** (Distributed Log) and **RabbitMQ / Amazon SQS** (Traditional Message Broker) in System Design interviews.**RabbitMQ / SQS**: Queue deletes a message as soon as it is acknowledged (`ack`); supports complex routing (AMQP Exchanges: Direct, Topic, Fanout, Headers), per-message priorities, and per-message retries—ideal for background task queues where individual work items take variable time. **Apache Kafka**: Retains messages on disk for days/forever (or via **Log Compaction**, keeping the latest value per key) regardless of consumption; multiple independent Consumer Groups can read the same stream at their own `offset` and **replay historical events**—ideal for high-throughput event streaming, CDC, event sourcing, and real-time analytics.
12Why must every distributed consumer and payment API be **Idempotent**, and how do you implement an `Idempotency-Key` in System Design?Because network timeouts and message queues (Kafka, SQS, Pub/Sub) guarantee **at-least-once delivery** (if a client's HTTP response is dropped after the server charged their credit card, the client WILL retry!). To guarantee **effectively-once processing**: the client generates a unique UUID `Idempotency-Key` in the request header. The server stores an `idempotency_keys` table with a `UNIQUE` constraint (or Redis lock) inside the same ACID transaction as the balance deduction: if the key already exists in state `COMPLETED`, immediately return the cached response without executing the charge again; if `IN_PROGRESS`, return `409 Conflict` / wait.
13How do you design a **Search Autocomplete / Typeahead System** returning the Top 5 suggestions within $< 50\text{ms}$ on every keystroke?Never run `SELECT ... WHERE query LIKE 'sys%' ORDER BY freq DESC LIMIT 5` against a production DB on every keystroke! Instead: 1. Build an in-memory **Prefix Trie** where **every TrieNode pre-caches the Top 5 `(query, frequency)` strings in its subtree**—making lookup for any prefix of length $p$ strictly $O(p)$ (and $O(1)$ once serialized as a flat `prefix -> top_5_json` Hash Map in Redis + CDN edge cache!). 2. **Write Path Decoupling**: Do NOT update the Trie synchronously on every search! Sample 1% of search logs into Kafka $\to$ aggregate hourly frequencies via Spark/Flink $\to$ rebuild a new Trie snapshot offline and swap it onto read replicas.
14How do you design a **URL Shortener (`TinyURL` / `bit.ly`)** handling 10,000 writes/sec and 100,000 reads/sec without hash collisions?A **7-character Base62** string (`[0-9a-zA-Z]`) supports $62^7 \approx 3.52 \text{ trillion}$ unique URLs! Why not truncate `MD5(long_url)[:7]`? Because of the Birthday Paradox, random 7-char hashes collide frequently and require a DB check-and-retry loop. Instead, generate a guaranteed-unique 64-bit integer ID (via **Snowflake** or a **Range-Allocated Ticket Server** where app servers claim blocks of 10,000 IDs from ZooKeeper/DB in memory) and deterministically convert that integer into **Base62** (zero collisions, 1 write!). On read (`GET /abc1234`), check Redis cache first (`90%+` hit rate), and return **`301 Moved Permanently`** (if optimizing reduced server load via browser caching) or **`302 Found`** (if tracking click analytics on every click!).
15How does a **Bloom Filter** work, why can it have False Positives but NEVER False Negatives, and what is a **Count-Min Sketch**?A **Bloom Filter** is a space-efficient probabilistic bit array of $m$ bits initialized to `0` with $k$ independent hash functions. To `add(x)`: set bits `h_1(x) % m, ..., h_k(x) % m` to `1`. To `query(x)`: check if all $k$ bits are `1`. If ANY bit is `0`, $x$ is **100% definitely NOT in the set (Zero False Negatives)**. If all $k$ bits are `1`, $x$ is *probably* in the set (a **False Positive** can occur if other elements happened to set those same $k$ bits; standard Bloom filters do not support deletion unless using a Counting Bloom Filter or Cuckoo Filter). A **Count-Min Sketch** uses a $d \times w$ 2D grid of counters (`min` across $d$ hash rows) to estimate item frequencies (Heavy Hitters) in constant memory.
16How do you design a **Top-K Heavy Hitters** system (e.g., Trending Hashtags or Most Viewed YouTube Videos over the last 1 hour / 24 hours)?1. **Fast Approximate Path** (real-time low-latency dashboard): Edge/Ingest processors maintain an in-memory **Count-Min Sketch + Min-Heap of size $K$** (or **Lossy Counting / Misra-Gries** frequent items algorithm) over 1-minute tumbling windows and flush only local heavy hitters downstream, avoiding network bottlenecks on hot keys. 2. **Accurate Path** (billing/analytics): Partition events in Kafka $\to$ stream processor (**Apache Flink**) aggregates counts in tumbling 1-minute/5-minute windows (`watermark` handling late events) $\to$ store window buckets in ClickHouse/Druid/Redis `ZSET` so any 1-hour sliding query simply sums the last 12 five-minute buckets!
17How do you design a **Distributed Web Crawler** covering politeness, deduplication, URL Frontier prioritization, and spider traps?1. **URL Frontier** split into two stages: (a) *Prioritizer* (Front queues ranking URLs by PageRank/freshness) and (b) *Politeness Router* (Back queues where each destination hostname `example.com` maps via consistent hash to a dedicated single worker queue with a delay timer respecting `robots.txt` so we never DDoS a host!). 2. **DNS Resolver Cache** (local async DNS cache avoids synchronous DNS bottlenecks). 3. **Deduplication**: Check **URL Seen** via a distributed **Bloom Filter** + RocksDB, and check **Content Seen** (different URLs serving identical HTML mirror content) via **SimHash / Charikar's locality-sensitive hash** or SHA-256 of normalized text. 4. **Spider Traps**: Cap max URL depth/length to avoid infinite calendar/dynamic URL loops.
18Compare the five **Rate Limiting Algorithms**: `Token Bucket`, `Leaky Bucket`, `Fixed Window Counter`, `Sliding Window Log`, and `Sliding Window Counter`.1. **Token Bucket** (Stripe/AWS default): Bucket holds max $B$ tokens refilled at $R$ tokens/sec; allows controlled **short bursts** up to $B$ while capping long-term rate at $R$ (2 values per user in Redis). 2. **Leaky Bucket**: FIFO queue draining at a strict constant rate (smooths out bursts completely, adds queuing latency). 3. **Fixed Window Counter**: `INCR user:123:min_45`; tiny memory, but suffers from the **2x boundary spike bug** (user sends $N$ requests at `00:59` and $N$ at `01:01` = $2N$ in 2 seconds!). 4. **Sliding Window Log**: Stores every request timestamp in a Redis `ZSET` (`ZREMRANGEBYSCORE` + `ZCARD`); 100% exact, high memory for high limits. 5. **Sliding Window Counter**: Weighted average of previous and current fixed windows: $\text{prev\_count} \times (1 - \text{overlap}) + \text{curr\_count}$; tiny memory and eliminates boundary spikes!
19How do you architect the Fan-Out service for a Social Media News Feed (Twitter/Instagram): **Push (Fan-out-on-Write)** vs. **Pull (Fan-out-on-Read)** vs. **Hybrid**?1. **Push Model (Fan-out-on-Write)**: When a normal user with 500 followers posts a tweet, background workers immediately push `tweet_id` into the Redis feed caches of all 500 followers—making timeline reads $O(1)$ ultra-fast from cache! However, when a **Celebrity** with 50,000,000 followers tweets, pushing to 50M caches causes massive write amplification and lag ('Hotkey/Celebrity problem'). 2. **Pull Model (Fan-out-on-Read)**: Tweets are only written to the author's own table; when a user opens their app, it fetches and merges recent posts from accounts they follow (slow on read). 3. **Hybrid Architecture (Production winner)**: Use **Push (Fan-out-on-Write)** for normal users ($< 10,000$ followers), and **Pull (Fan-out-on-Read)** for Celebrities, merging the user's precomputed Redis timeline with recent posts from the few celebrities they follow at read time!
20How do you design a Distributed Unique ID Generator (`Twitter Snowflake` 64-bit ID) that is roughly time-sortable and generates millions of IDs/sec without coordination?Why not Auto-Increment DB ID (`SPOF` bottleneck, leaks business volume) or UUIDv4 (`128-bit` strings fragment B+ Tree Clustered Indexes with random page splits!)? **Twitter Snowflake** packs a **64-bit integer** (`bigint`) locally on each machine with zero network calls: **1 bit** (sign bit `0`) + **41 bits** (milliseconds since custom epoch = **69.7 years**) + **10 bits** (`datacenter_id` + `worker_id` = **1,024 nodes**) + **12 bits** (per-millisecond atomic counter = **4,096 IDs/ms/node** = 4.096M IDs/sec/node!). Because timestamp is in the most significant bits, Snowflake IDs are naturally **k-sorted by time** for fast B+ Tree appends! (Note: Modern **UUIDv7** applies this same timestamp-prefix principle to 128-bit UUIDs).
21Compare **Full-Text Search (Inverted Index + BM25)** and **Vector Search (Embeddings + HNSW ANN)** in modern Search & RAG System Design.1. **Lexical Search (Elasticsearch / OpenSearch / Lucene)**: Tokenizes documents (lowercasing, stemming, stop-word removal) into an **Inverted Index** mapping each `term -> sorted posting list of (doc_id, term_freq, positions)`, scored via **BM25** (TF-IDF with document length normalization); excels at exact keyword, SKU, and rare identifier matching. 2. **Semantic Vector Search (pgvector, Milvus, Pinecone, Qdrant)**: Encodes text/images via an embedding model into dense vectors (e.g., 768/1536 floats) and builds an **HNSW (Hierarchical Navigable Small World)** graph or **IVF-PQ** (Inverted File with Product Quantization) index for sub-linear Approximate Nearest Neighbor (ANN) cosine/dot-product search. Production RAG systems use **Hybrid Search** combining BM25 + Vector ANN via **Reciprocal Rank Fusion (RRF)** followed by a Cross-Encoder Reranker!
22Explain the **CQRS (Command Query Responsibility Segregation)** and **Event Sourcing** patterns and when they are justified in System Design.**CQRS** separates the **Write Model (Commands)**—which validates business rules on a normalized ACID relational database—from the **Read Model (Queries)**—which reads from denormalized, query-tailored views in Elasticsearch, Redis, or read replicas updated asynchronously via CDC/Kafka events. **Event Sourcing** stores the system's state not as mutable current rows, but as an immutable append-only log of domain events (`AccountOpened`, `MoneyDeposited`, `OrderPlaced`), reconstructing current state by replaying events (plus periodic snapshots). Use for financial ledgers, audit-critical systems, and collaborative undo/redo—avoid for simple CRUD apps due to eventual consistency and schema evolution complexity.
23What is a **Cache Stampede (Thundering Herd)** vs. **Cache Penetration** vs. **Cache Avalanche**, and how do you mitigate each?1. **Cache Stampede (Hot Key Expiry)**: A celebrity/homepage cache key expires and 50,000 concurrent requests miss simultaneously and hammer the database. Mitigations: **Singleflight / Request Coalescing / Mutex Lock** (only 1 thread queries DB while 49,999 wait on the shared promise), logical early expiration (Probabilistic Early Recomputation / XFetch), or background refresh before TTL expires. 2. **Cache Penetration**: Requests for non-existent IDs (`id = -999`) always miss cache and hit DB. Mitigations: Cache `NULL` sentinel with short TTL (30s) or place a **Bloom Filter** in front of the cache. 3. **Cache Avalanche**: Thousands of keys expire at the exact same second (or Redis node fails). Mitigation: Add random **TTL Jitter** (`TTL = 3600 + random(0, 600)`).
24In Leaderless (Dynamo-style) databases, how do **Read Repair**, **Hinted Handoff / Sloppy Quorum**, and **Anti-Entropy with Merkle Trees** work?1. **Read Repair**: When a client reads from $R$ replicas and detects that replica C returned a stale version `v1` while A and B returned `v2`, the coordinator asynchronously writes `v2` back to C. 2. **Anti-Entropy with Merkle Trees**: Background processes compare hierarchical cryptographic hash trees of key ranges between replicas to pinpoint and sync out-of-date key ranges in $O(\log K)$ network transfers. 3. **Sloppy Quorum & Hinted Handoff**: During a network partition when true home nodes aren't reachable, writes are temporarily accepted on healthy neighbor nodes ('hints') and handed back once the home nodes recover (maximizing write availability $A$ at the expense of strict $W+R>N$ consistency).
25How do you architect a **Large File Upload & Video Streaming System (YouTube / Dropbox / Google Drive)**?1. **Direct-to-Object-Storage Multipart Upload**: Client asks API Server for **Presigned URLs** (`S3 Multipart Upload`) and uploads 5–10 MB chunks directly to S3/GCS in parallel; supports **Resumable Uploads** (only retry failed chunks) and client-side SHA-256 chunk deduplication (Dropbox block-level sync). 2. **DAG Transcoding Pipeline**: Once S3 fires an `ObjectCreated` event to Kafka/SQS, distributed workers split the video by GOP (Group of Pictures) scenes, transcode in parallel into multiple resolutions (`360p, 720p, 1080p, 4K`) and codecs (`H.264, VP9, AV1`), and generate **HLS (`.m3u8`) / DASH** adaptive bitrate segments. 3. **CDN Delivery**: Popular video segments are cached at ISP/Edge CDN POPs worldwide.
26What back-of-the-envelope numbers and estimation formulas should every candidate know for System Design capacity planning?1. **Seconds per day**: $86,400 \approx 10^5\text{ s/day}$ (so $100\text{M requests/day} \approx \frac{10^8}{10^5} = 1,000\text{ QPS}$ average; Peak QPS $\approx 2\times–3\times \text{Avg QPS}$). 2. **Powers of 10 bytes**: $10^3 = 1\text{ KB}$, $10^6 = 1\text{ MB}$, $10^9 = 1\text{ GB}$, $10^{12} = 1\text{ TB}$, $10^{15} = 1\text{ PB}$. 3. **Latency Hierarchy**: L1/L2 Cache $\sim 1–4\text{ ns}$; RAM read $\sim 100\text{ ns}$; Redis/Same-AZ RPC $\sim 0.5\text{ ms}$; NVMe SSD random read $\sim 0.1\text{ ms}$ ($100\text{ }\mu\text{s}$); Intra-region cross-AZ RTT $\sim 1–2\text{ ms}$; Cross-continental US-East to US-West RTT $\sim 60–70\text{ ms}$; US to Europe/Asia RTT $\sim 100–200\text{ ms}$. 4. **Single node rules of thumb**: 1 SQL DB primary $\approx 2,000–10,000\text{ writes/s}$; 1 Redis instance $\approx 50,000–100,000\text{ ops/s}$; 1 L7 App Server $\approx 1,000–10,000\text{ RPS}$.
27Compare the four real-time client-server communication protocols: `HTTP Short Polling`, `HTTP Long Polling`, `Server-Sent Events (SSE)`, and `WebSockets`.1. **Short Polling**: Client polls `GET /status` every 2s (wastes bandwidth/headers with empty responses). 2. **Long Polling**: Client sends `GET`; server holds the HTTP request open until new data arrives or a 30s timeout occurs, then client immediately reconnects (used by SQS `WaitTimeSeconds`). 3. **Server-Sent Events (SSE)**: Standard HTTP (`text/event-stream`) **unidirectional** stream from Server to Client; supports native browser `EventSource` auto-reconnect, works seamlessly over HTTP/2 multiplexing and standard L7 proxies—ideal for **LLM token streaming**, stock tickers, and live notifications! 4. **WebSockets**: Persistent **full-duplex bidirectional** TCP connection (`ws://` / `wss://` via HTTP `101 Switching Protocols`)—ideal for low-latency multiplayer games, collaborative editing, and bidirectional chat.
28Compare Database Replication topologies: **Single-Leader**, **Multi-Leader (Master-Master)**, and **Leaderless (Dynamo-style Quorum)**.1. **Single-Leader**: All writes go to 1 Primary; Read Replicas serve read-heavy traffic via async/semi-sync replication (requires handling **replication lag** via Read-Your-Own-Writes routing or Monotonic Reads). 2. **Multi-Leader**: Multiple datacenters each have a writable leader replicating asynchronously to each other; lower cross-region write latency, but requires conflict resolution (Last-Write-Wins, custom merge, or CRDTs). 3. **Leaderless (Amazon Dynamo, Cassandra, Riak)**: Client sends writes to all $N$ replicas in parallel ($W$ must acknowledge) and reads from $R$ replicas in parallel; when **$W + R > N$** (Strict Quorum, e.g., $N=3, W=2, R=2$), the read set and write set are guaranteed to overlap by at least 1 replica holding the latest version!
29Compare Horizontal Database Sharding strategies (`Range-Based`, `Hash-Based`, `Directory-Based`) and how you mitigate the **Celebrity / Hot-Shard Problem**.1. **Range-Based Sharding**: Shards contiguous key ranges (`A-F`, `G-M`, or timestamps); supports efficient range scans, but suffers from hot spots if all recent writes hit the latest time range. 2. **Hash-Based Sharding**: `consistent_hash(shard_key) -> shard`; distributes load uniformly, but scatter-gather is required for range queries. 3. **Directory-Based**: Lookup service maps keys to shards. **Celebrity / Hot-Shard Mitigation**: If Justin Bieber's `user_id` receives 100,000 writes/sec on one shard, append a random shard suffix `0..99` (`bieber_id#42`, **Key Salting / Write Sharding**) to spread writes across 100 shards, and aggregate across `0..99` on read (or isolate hot tenants onto dedicated shards).
30Compare Redis Persistence options (`RDB` Snapshots vs. `AOF` Append-Only File) and Redis High Availability (`Replication + Sentinel` vs. `Redis Cluster`).Persistence: **RDB** forks a child process (`fork()` copy-on-write) to dump a compact point-in-time binary snapshot (fast restarts, but loses minutes of data on crash); **AOF** logs every write command with `appendfsync everysec` (at most 1 second of data loss, larger files with background rewrite; production combines RDB + AOF). High Availability: **Redis Sentinel** monitors a single-shard Primary + Replicas for automatic failover; **Redis Cluster** shards data across multiple masters using **16,384 deterministic Hash Slots** (`CRC16(key) % 16384`) with gossip protocol and built-in replica failover.
31What are the two reasons Apache Kafka achieves millions of messages/sec on spinning disks/SSDs (`Sequential Disk I/O + OS Page Cache` and `Zero-Copy sendfile()`)?1. **Sequential Append-Only I/O + OS Page Cache**: Kafka never performs random disk writes; appending sequentially to the end of partition segment files is orders of magnitude faster than random I/O, and active consumers read directly from the Linux kernel **Page Cache** in RAM. 2. **Zero-Copy (`sendfile` syscall)**: Traditional brokers copy data 4 times (`Disk -> OS Page Cache -> Broker User-Space JVM -> Socket Buffer -> NIC`). Kafka uses Linux `sendfile()` to transfer bytes directly from the **OS Page Cache to the Network Interface Card (NIC) DMA buffer** entirely in kernel space with zero CPU copies and zero JVM garbage collection pressure!
32How do you handle **Secondary Indexes** in a Sharded Database: `Document-Partitioned (Local)` vs. `Term-Partitioned (Global)` Indexes?1. **Local Index (Document-Partitioned)**: Each shard maintains a secondary index covering ONLY the documents stored on that local shard. Writes are fast (touch only 1 shard), but querying by secondary index requires a **Scatter-Gather** query across ALL shards in parallel (tail latency bottleneck!). 2. **Global Index (Term-Partitioned)**: The secondary index itself is sharded by the indexed attribute (`email` or `status`) across shards separately from the primary table. Reads by secondary index hit only 1 index shard, but a single document write now has to update multiple index shards asynchronously (eventual consistency) or via distributed transaction.