← Interview prep

System Design interview questions

Scalable architecture, storage, and distributed design.

100 questions · Page 2 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 2 of 5

Questions 21–40 of 100 · 0 of 20 on this page marked learned

21.system-design-0021Mediumfresher

Explain the common rate limiting algorithms: fixed window, sliding window log, sliding window counter, token bucket and leaky bucket.

Fixed window counts requests per clock window and is simple but allows bursts at window edges. Sliding window log stores every timestamp and is exact but memory heavy. Sliding window counter blends two fixed windows for a cheap approximation. Token bucket allows bursts up to a capacity and then a steady refill rate; leaky bucket smooths output to a constant rate.

Full answer

Why limit

Rate limiting caps how many requests a client can make in a period. It protects services from overload and abuse (password guessing, scraping), and enforces fair use or paid tiers. A typical rule: 100 requests per minute per API key; 5 login attempts per minute per account.

Fixed window counter

Keep a counter per key per window (user:7:2026-12-04T10:15). Increment; reject when it exceeds the limit. Cheap: one counter per key. Problem: a user can send 100 requests at 10:15:59 and another 100 at 10:16:00, which is 200 in two seconds.

Sliding window log

Store the timestamp of every request (a Redis sorted set). On each request, remove timestamps older than 60 seconds, count the rest, allow if under the limit. Exact, but memory grows with the limit: 100 timestamps per user.

Sliding window counter

Keep counts for the current and previous fixed windows and weight the previous one by how much of it still overlaps the last 60 seconds:

estimate = current + previous x (1 - elapsed_fraction_of_current_window)

If the previous minute had 80 requests, the current has 30, and we are 25% into the current minute: 30 + 80 x 0.75 = 90, under a limit of 100. Two counters per key and close to exact.

Token bucket

A bucket holds up to capacity tokens and refills at rate tokens per second. Each request takes one token; with no tokens, reject. It allows short bursts (up to capacity) while enforcing an average rate. Used by many API gateways and cloud providers.

Run with Python 3.13, fixed timestamps so the result is the same every run:

python
class TokenBucket:
    def __init__(self, capacity, refill_per_sec):
        self.capacity = capacity
        self.rate = refill_per_sec
        self.tokens = capacity
        self.last = 0.0

    def allow(self, now):
        elapsed = now - self.last
        self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

bucket = TokenBucket(capacity=5, refill_per_sec=1)   # bursts of 5, then 1/s
times = [0, 0, 0, 0, 0, 0, 0.5, 1.0, 1.0, 3.0]
print([bucket.allow(t) for t in times])

Output:

[True, True, True, True, True, False, False, True, False, True]

Five requests at time 0 drain the bucket, the sixth is rejected, and from then on one token returns each second.

Leaky bucket

Requests enter a fixed-size queue that drains at a constant rate. Output is perfectly smooth, which suits protecting a fragile downstream (an SMS provider that accepts 10 messages per second). Bursts wait or are dropped when the queue is full.

Choosing

Token bucket for most public APIs (bursts are normal for real clients). Sliding window counter when you want a simple "N per minute" rule without edge bursts. Leaky bucket when the downstream needs a steady rate.

By level

Fresher: Explain fixed window and token bucket clearly with a small example, and why limits protect a service. Showing the window-edge burst with numbers is a strong fresher answer.

Mid: Compare all algorithms on accuracy, memory and burst behaviour, compute a sliding window estimate, and choose by use case. Expect a correct sliding window estimate calculation.

Senior: Discuss distributed enforcement, atomicity, clock issues, multi-tier limits, response headers, and how limits interact with retries and load shedding. It should cover how limits are enforced across many gateways.

Key points

  • Fixed window is cheap but allows double bursts at window edges
  • Sliding log is exact but stores every timestamp
  • Sliding window counter approximates with two counters
  • Token bucket allows bursts up to capacity and enforces an average rate
  • Leaky bucket produces a smooth constant output rate

Common mistakes

  • Confusing token bucket with leaky bucket
  • Ignoring the window boundary burst in fixed windows
  • Storing a timestamp log for very high limits
  • Not saying which key the limit applies to (user, IP, API key)

Follow-ups

  • How would you implement token bucket atomically in Redis?
  • How should the API tell a client it was limited?
  • How would you rate limit across 50 gateway servers?

Tips

  • Define the rule and the key first
  • Show the window-edge burst with numbers
  • Pick one algorithm for the stated use case and say why

Evaluation rubric

  • Correct description of all five algorithms
  • Identifies the fixed window edge problem
  • Explains burst behaviour of token bucket
  • Matches algorithm to use case
22.system-design-0022Mediummid

How do retries with exponential backoff and jitter, timeouts and circuit breakers work together to stop cascading failures?

Timeouts stop a caller waiting forever on a slow dependency. Retries recover from brief failures, but only with exponential backoff and random jitter, a retry budget, and idempotent operations, or they multiply load on a struggling service. A circuit breaker counts failures and, past a threshold, fails fast for a cool-down period before letting a few test requests through.

Full answer

How cascading failures start

The payment service slows down. The checkout service keeps waiting, so its threads fill up. Checkout now slows down, and the web tier waiting on it fills up too. Meanwhile every layer retries, so the payment service gets even more traffic. One slow dependency takes down the whole product.

Timeouts

Every network call needs a timeout based on the dependency's normal latency (for example a little above its p99), and the total budget for the user request. If the user request has a 2-second budget, an inner call cannot have a 5-second timeout. Pass a deadline down the call chain (gRPC does this natively).

Retries done safely

  • Retry only transient errors (timeouts, 503, connection reset), not 400 or 404.
  • Retry only idempotent operations, or use idempotency keys.
  • Exponential backoff: wait 100 ms, 200 ms, 400 ms, 800 ms... between attempts, with a cap.
  • Jitter: randomise the wait. Without it, a thousand clients that failed together retry together, in synchronised waves. "Full jitter" waits a random time between 0 and the current backoff.
  • Retry budget: limit retries to a small fraction of traffic (for example 10%), and retry at one layer only. If three layers each retry 3 times, one user request can become 4 x 4 x 4 = 64 calls to the bottom service.

Circuit breakers

A breaker wraps calls to one dependency and has three states:

  1. Closed: calls pass through; failures are counted over a rolling window.
  2. Open: when the failure rate passes a threshold (say 50% of the last 20 calls), calls fail immediately for a cool-down (say 30 seconds). The caller returns a fallback: cached data, a default, or a clear error.
  3. Half-open: after the cool-down, a few trial calls go through. Success closes the breaker; failure opens it again.

Failing fast frees threads and gives the dependency room to recover.

Related tools

  • Bulkheads: separate connection pools per dependency so one slow service cannot use all threads.
  • Load shedding: the overloaded service rejects excess requests early (429 or 503) instead of queueing them.
  • Fallbacks: show cached course recommendations if the recommendation service is down.

Libraries such as Resilience4j (Java) and Polly (.NET), and service meshes such as Envoy or Istio, provide these patterns.

By level

Fresher: Explain timeouts and why retrying immediately in a loop can make an outage worse, then describe backoff. Mentioning that every network call needs a timeout is expected.

Mid: Explain jitter, retry budgets, the circuit breaker state machine and bulkheads, and how timeouts relate to request deadlines. Expect the retry multiplication across layers to be shown.

Senior: Design resilience policy across a service graph: deadline propagation, retry at one layer, adaptive concurrency limits, load shedding priorities, and how to test these with fault injection. The senior answer describes how these policies are tested in practice.

Key points

  • Every remote call needs a timeout that fits the overall request deadline
  • Retry only transient errors and idempotent operations
  • Exponential backoff with jitter avoids synchronised retry storms
  • Retries at several layers multiply load; use a retry budget
  • Circuit breaker: closed, open, half-open; fail fast and use fallbacks

Common mistakes

  • Retrying without backoff or jitter
  • Retrying non-idempotent operations such as payments without keys
  • Letting every layer retry independently
  • Setting timeouts longer than the caller's own deadline

Follow-ups

  • How do you choose the failure threshold and cool-down of a breaker?
  • What fallback would you show if the pricing service is down?
  • How does deadline propagation work in gRPC?

Tips

  • Tell the cascading failure story in three steps
  • Do the retry multiplication arithmetic
  • Name the three breaker states in order

Evaluation rubric

  • Explains cascading failure mechanism
  • Correct backoff and jitter reasoning
  • Correct circuit breaker state machine
  • Mentions idempotency, budgets and fallbacks
23.system-design-0023Hardsenior

How do you keep data consistent across microservices? Compare two-phase commit, sagas and the transactional outbox pattern.

Two-phase commit uses a coordinator that asks every participant to prepare and then tells all to commit, giving atomicity but blocking if the coordinator fails. A saga splits the work into local transactions, each with a compensating action to undo it if a later step fails, giving eventual consistency. The transactional outbox writes the business change and the event to publish in one local transaction, so events are never lost or sent for rolled-back changes.

Full answer

The problem

Enrolling a student in a paid course touches three services: Payments charges the card, Enrolment creates the enrolment, Notifications sends a welcome email. Each owns its own database. There is no single database transaction that covers all three.

Two-phase commit (2PC)

  1. Prepare: the coordinator asks each participant "can you commit?". Each writes the change durably, holds locks, and votes yes or no.
  2. Commit or abort: if all voted yes, the coordinator tells everyone to commit; otherwise abort.

Strength: atomic outcome. Weaknesses: participants hold locks while waiting; if the coordinator crashes after prepare, participants are blocked until it recovers; every participant must support the protocol (XA), and latency is that of the slowest participant. 2PC is used inside some distributed databases, but rarely across independent microservices.

Sagas

A saga is a sequence of local transactions. If step N fails, run compensating transactions for steps N-1 back to 1.

StepActionCompensation
1Reserve seat in courseRelease seat
2Charge paymentRefund payment
3Activate enrolmentDeactivate enrolment
  • Orchestration: a saga orchestrator tells each service what to do next and tracks state. Easier to follow and debug.
  • Choreography: each service reacts to events from the previous one. Less central logic, harder to see the whole flow.

Sagas give eventual consistency: between steps, other users can see a seat reserved but not yet paid. Design for that with states such as PENDING_PAYMENT, and make every step and compensation idempotent because messages are retried. Some actions cannot be undone (an email sent), so put them last.

Transactional outbox

A service must update its database and publish an event. Doing them separately fails in two ways: commit then crash before publishing (event lost), or publish then rollback (event for a change that never happened).

The outbox fixes this:

  1. In one local transaction, update the business table and insert a row into an outbox table.
  2. A relay process reads the outbox (polling, or change data capture from the database log) and publishes to the broker, then marks rows sent.
  3. Delivery is at least once, so consumers deduplicate by event ID.

Sagas typically use the outbox for every step.

Choosing

Prefer keeping data that must change atomically inside one service and database. Use sagas with an outbox across services. Use 2PC only where all participants support it and blocking is acceptable.

By level

Fresher: Explain why a single transaction cannot span separate services and describe undoing earlier steps when a later step fails. A fresher can describe the compensation idea without naming every pattern.

Mid: Describe 2PC phases and blocking, sagas with compensations and orchestration versus choreography, and the outbox pattern. Expect the dual-write problem to be explained before the outbox.

Senior: Handle compensation failures, saga state persistence, timeouts, semantic locks, CDC-based relays, ordering guarantees, and decide when service boundaries are wrong instead of adding coordination. It should consider merging services as a real option.

Key points

  • 2PC gives atomicity but blocks on coordinator failure and holds locks
  • Sagas chain local transactions with compensations; consistency is eventual
  • Orchestration is easier to trace than choreography
  • Outbox writes the change and the event in one local transaction
  • All steps and compensations must be idempotent

Common mistakes

  • Proposing 2PC across independent microservices without discussing blocking
  • Forgetting that compensations can also fail and must be retried
  • Publishing an event outside the database transaction
  • Ignoring intermediate states that users can see during a saga

Follow-ups

  • What happens if a compensation fails?
  • How would the outbox relay avoid publishing an event twice?
  • When would you merge two services to avoid a saga?

Tips

  • Use one concrete business flow with three services
  • Draw the saga as a table of actions and compensations
  • Explain the dual-write problem before the outbox

Evaluation rubric

  • Correct 2PC phases and failure mode
  • Correct saga mechanics including compensations and idempotency
  • Explains dual-write problem and outbox solution
  • Gives a sensible recommendation
24.system-design-0024Mediumfresher

Compare REST, gRPC and GraphQL. When would you choose each for an API?

REST exposes resources over HTTP with standard methods and usually JSON; it is simple, cacheable and works everywhere. gRPC uses Protocol Buffers over HTTP/2 with generated clients, giving compact messages, strict contracts and streaming, which suits service-to-service calls. GraphQL exposes one endpoint where clients ask for exactly the fields they need, which suits varied front-end screens but makes caching and cost control harder.

Full answer

REST

Resources are nouns with URLs; HTTP methods are the verbs.

GET /courses/42 read a course POST /courses/42/enrolments enrol a student PATCH /students/7 update some fields

Strengths: every language and tool speaks HTTP and JSON; responses can be cached by browsers and CDNs with standard headers; easy to debug with curl. Weaknesses: a screen may need several calls (course, teacher, reviews), or get more fields than it needs. Contracts are loose unless you add OpenAPI.

gRPC

You define services and messages in a .proto file:

proto
syntax = "proto3";

service Grades {
  rpc GetReportCard (ReportCardRequest) returns (ReportCard);
  rpc StreamScores (ExamId) returns (stream Score);
}

message ReportCardRequest { int64 student_id = 1; }
message ReportCard { int64 student_id = 1; repeated Score scores = 2; }
message Score { string subject = 1; int32 marks = 2; }
message ExamId { int64 id = 1; }

Code generators create typed clients and servers. Messages are binary Protobuf, smaller and faster to parse than JSON. HTTP/2 allows many concurrent calls on one connection and supports client, server and bidirectional streaming. Deadlines propagate across calls. Weaknesses: browsers cannot call it directly (gRPC-Web or a gateway is needed), binary payloads are harder to inspect, and HTTP caching does not apply.

GraphQL

One endpoint (POST /graphql). The client sends a query naming the fields it wants:

graphql
query {
  course(id: 42) {
    title
    teacher { name }
    reviews(first: 3) { rating }
  }
}

Strengths: one round trip per screen, no over-fetching, a typed schema, and front-end teams can evolve screens without new endpoints. Weaknesses: caching by URL does not work (needs persisted queries or client caches); a nested query can be very expensive, so you need depth or cost limits; the N+1 database query problem needs batching (DataLoader); errors often come back with HTTP 200.

Choosing

SituationGood fit
Public API for third partiesREST (with OpenAPI)
Internal service-to-service calls, low latency, streaminggRPC
Many client screens with different data needs (web, mobile)GraphQL, often as a layer over internal services
Heavy CDN caching of public readsREST

Many companies use all three: gRPC between services, GraphQL or a REST backend-for-frontend for apps, and REST for partners.

By level

Fresher: Describe REST with methods and URLs, and explain in simple terms what gRPC and GraphQL change. A fresher should give one use case for each style.

Mid: Compare on payload, contract, caching, streaming and tooling, and choose for public, internal and front-end use cases. Expect one weakness of each style, such as GraphQL query cost.

Senior: Discuss schema evolution and backward compatibility, API gateways and federation, observability of each style, cost control in GraphQL, and migration between styles. Expect a strategy for backward compatibility of each style.

Key points

  • REST: resources plus HTTP methods, cacheable, universal
  • gRPC: Protobuf over HTTP/2, typed generated clients, streaming, deadlines
  • GraphQL: client chooses fields from one endpoint, one round trip per screen
  • GraphQL needs query cost limits and batching for N+1
  • Mixing them by audience is common

Common mistakes

  • Saying gRPC works directly from browsers without gRPC-Web or a proxy
  • Claiming GraphQL is always faster
  • Forgetting HTTP caching advantages of REST
  • Ignoring query cost and N+1 problems in GraphQL

Follow-ups

  • How do you version a gRPC API safely?
  • How would you stop an expensive GraphQL query from hurting the database?
  • What is a backend-for-frontend?

Tips

  • Describe each in one line before comparing
  • Pick by audience: partners, services, front-ends
  • Mention one weakness of each

Evaluation rubric

  • Accurate description of all three
  • Correct strengths and weaknesses
  • Sensible choice by use case
  • Mentions caching, contracts and performance aspects
25.system-design-0025Easyfresher

What makes a well-designed REST API? Cover resource naming, HTTP methods, status codes and versioning.

A good REST API names resources with plural nouns, uses HTTP methods for their defined meaning, returns accurate status codes with a consistent error body, supports filtering and pagination, and versions changes without breaking existing clients. It is predictable: a developer can guess the next endpoint correctly.

Full answer

Resources and URLs

Use nouns, not verbs, and plural collections:

GET /students list students GET /students/7 one student POST /students create PATCH /students/7 partial update DELETE /students/7 delete GET /students/7/attendance attendance records for student 7

Avoid /getStudent?id=7 or /createStudent. Keep nesting shallow (one level is usually enough). For actions that do not fit CRUD, a sub-resource is clearer than a verb: POST /exams/12/publications rather than POST /publishExam.

Methods

  • GET: read, no side effects, cacheable.
  • POST: create or trigger processing; not idempotent.
  • PUT: replace the whole resource; idempotent.
  • PATCH: partial update.
  • DELETE: remove; idempotent.

Status codes

CodeUse
200 OKSuccessful read or update with a body
201 CreatedResource created; include a Location header
204 No ContentSuccess, no body (often DELETE)
400 Bad RequestMalformed input or failed validation
401 UnauthorizedNot authenticated (missing or bad credentials)
403 ForbiddenAuthenticated but not allowed
404 Not FoundResource does not exist
409 ConflictState conflict, such as a duplicate email
422 Unprocessable ContentValid JSON but semantic validation failed (some APIs use 400 for this)
429 Too Many RequestsRate limited; send Retry-After
500 / 503Server error / temporarily unavailable

Never return 200 with {"error": ...} in the body; clients and monitoring rely on the code.

Use one error shape everywhere, for example:

json
{"error": {"code": "EMAIL_TAKEN", "message": "This email is already registered.", "field": "email"}}

Lists

Support filters and sorting through query parameters (GET /students?class=10B&sort=-score) and always paginate lists (?limit=50&cursor=...).

Versioning and compatibility

Adding a field is safe. Removing or renaming a field, or changing its type or meaning, breaks clients. For breaking changes, introduce a new version, commonly in the path (/v2/students) or a header, and keep the old version running with a deprecation date.

Other good habits

HTTPS only; authentication through a standard scheme (OAuth 2.0 bearer tokens); idempotency keys on payment-like POSTs; consistent naming (snake_case or camelCase, not both); ISO 8601 timestamps with time zone (2026-12-04T10:15:00Z); documentation in OpenAPI.

By level

Fresher: Name resources as nouns, map CRUD to methods, and use the right common status codes with examples. Getting 401 and 403 right is a common screening check.

Mid: Add error format, pagination, filtering, idempotency and compatibility rules, and design an action endpoint cleanly. Expect a consistent error body and pagination on every list.

Senior: Discuss versioning policy across many clients, long-running operations (202 with a status resource), API governance, rate limit contracts, and how to evolve an API used by partners without breaking them. The answer should describe a deprecation timeline that partners can follow.

Key points

  • Plural nouns for resources; HTTP methods carry the action
  • Status codes must match the outcome; 401 versus 403 matters
  • Use one consistent error body
  • Always paginate and allow filtering on lists
  • Additive changes are safe; breaking changes need a new version

Common mistakes

  • Verbs in URLs like /getStudents
  • Returning 200 for errors
  • Mixing up 401 and 403
  • Removing fields without a new version or deprecation period

Follow-ups

  • How would you design an endpoint that triggers a long-running report?
  • When would you use PUT instead of PATCH?
  • How do you deprecate an API version?

Tips

  • Write three example endpoints before talking theory
  • Get 401 versus 403 right
  • Mention backward compatibility explicitly

Evaluation rubric

  • Correct resource naming and method use
  • Accurate status codes
  • Consistent error format and pagination
  • Sensible versioning strategy
26.system-design-0026Mediumfresher

Compare offset-based and cursor-based pagination. Why do large feeds use cursors?

Offset pagination uses LIMIT and OFFSET; it is simple and supports jumping to page N, but large offsets are slow because the database still walks the skipped rows, and new rows shift pages, causing duplicates or gaps. Cursor (keyset) pagination remembers the last item's sort key and asks for rows after it, which stays fast at any depth and is stable when data changes.

Full answer

Offset pagination

GET /posts?limit=20&offset=40 SELECT ... ORDER BY created_at DESC LIMIT 20 OFFSET 40;

Easy to build, and a UI can show "page 1, 2, 3 ... 50". Two problems:

  1. Performance: for OFFSET 100000, the database reads and throws away 100,000 rows. Deep pages get slower and slower.
  2. Shifting data: if a new post is added at the top while a user reads page 1, everything moves down by one, so page 2 repeats the last item of page 1. Deletes cause skipped items.

Cursor (keyset) pagination

The response includes a cursor that encodes where the page ended. The next request asks for items after that point using an indexed condition:

sql
SELECT id, created_at FROM posts
WHERE (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 20;

id is a tie-breaker so two posts with the same timestamp are not lost. With an index on (created_at, id), the database seeks straight to the position, so page 1,000 is as fast as page 1.

A small demonstration (Python 3.13 with SQLite 3.46.1, same output on two runs). A new post arrives between page 1 and page 2:

python
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE posts (id INTEGER PRIMARY KEY, created_at TEXT, title TEXT)")
db.executemany("INSERT INTO posts VALUES (?, ?, ?)",
               [(i, f"2026-12-01 10:{i:02d}", f"post {i}") for i in range(1, 8)])

def page(cursor=None, limit=3):
    if cursor is None:
        rows = db.execute("SELECT id, created_at FROM posts "
                          "ORDER BY created_at DESC, id DESC LIMIT ?", (limit,)).fetchall()
    else:
        c_time, c_id = cursor
        rows = db.execute("SELECT id, created_at FROM posts "
                          "WHERE (created_at, id) < (?, ?) "
                          "ORDER BY created_at DESC, id DESC LIMIT ?",
                          (c_time, c_id, limit)).fetchall()
    next_cursor = (rows[-1][1], rows[-1][0]) if len(rows) == limit else None
    return [r[0] for r in rows], next_cursor

ids, cur = page()
print(ids, cur)
db.execute("INSERT INTO posts VALUES (8, '2026-12-01 10:08', 'new post')")  # arrives between pages
ids, cur = page(cur)
print(ids, cur)
print("offset page 2:", [r[0] for r in db.execute(
    "SELECT id FROM posts ORDER BY created_at DESC, id DESC LIMIT 3 OFFSET 3")])

Output:

[7, 6, 5] ('2026-12-01 10:05', 5) [4, 3, 2] ('2026-12-01 10:02', 2) offset page 2: [5, 4, 3]

The cursor version continues cleanly with 4, 3, 2. The offset version shows post 5 again.

API shape

Return an opaque cursor (base64 of the sort key) rather than raw values, so the server can change its format later:

json
{"items": [{"id": 4}, {"id": 3}, {"id": 2}], "next_cursor": "eyJ0IjoiMjAyNi0xMi0wMSAxMDowMiIsImlkIjoyfQ", "has_more": true}

Trade-offs

Cursors cannot jump to "page 37" and need a stable, indexed sort order. Offset is fine for small admin tables with page numbers. Infinite-scroll feeds, chat history and public APIs with large lists should use cursors.

By level

Fresher: Explain offset pagination, why deep pages get slow, and the idea of continuing from the last item seen. The fresher answer should mention both slowness and duplicate items.

Mid: Write a keyset query with tie-breaker, explain the index needed, opaque cursors and duplicates under concurrent inserts. Expect the tie-breaker column and the matching index.

Senior: Discuss pagination across shards and search indexes, bidirectional cursors, cursor expiry and consistency snapshots, and API contracts for large exports. Expect a plan for merging pages from several shards.

Key points

  • Offset is simple and allows page jumps but is slow at depth
  • Offset pages shift when rows are inserted or deleted
  • Cursor pagination seeks from the last seen sort key using an index
  • Add a unique tie-breaker such as id to the sort key
  • Return opaque cursors in the API

Common mistakes

  • Using a non-unique sort key without a tie-breaker
  • Exposing raw SQL values as the cursor format
  • Using offset pagination for infinite-scroll feeds
  • Sorting by a column that is not indexed

Follow-ups

  • How would you support "previous page" with cursors?
  • How do you paginate results merged from several shards?
  • How do you paginate when the sort is by score instead of time?

Tips

  • Explain both performance and correctness problems with offset
  • Write the keyset WHERE clause with a tie-breaker
  • Say when offset is still fine

Evaluation rubric

  • Correct explanation of both approaches
  • Identifies performance and shifting-data issues
  • Correct keyset query with tie-breaker and index
  • Recognises trade-offs
27.system-design-0027Easyfresher

What does it mean for a service to be stateless, and how do you handle user sessions in a horizontally scaled web application?

A stateless service keeps no per-user data in its own memory between requests, so any instance can serve any request. Session data moves elsewhere: into a shared store like Redis keyed by a session ID cookie, or into a signed token such as a JWT that the client sends with each request. This allows load balancing, autoscaling and painless restarts.

Full answer

The problem with in-memory sessions

If a student logs in and server A stores their session in A's memory, the next request might go to server B, which knows nothing about them, so they are logged out. Workarounds such as sticky sessions (always send this user to A) break when A restarts or is removed by autoscaling, and they spread load unevenly.

Stateless means

The server's memory holds no information a later request depends on. Everything needed is in the request itself or in a shared backing store. Then servers become interchangeable: add 10 during an exam rush, remove them after, deploy one at a time, and nobody notices.

Option 1: server-side sessions in a shared store

  1. On login, create a random session ID, store session:<id> -> {user_id, roles, expires} in Redis with a TTL.
  2. Send the ID in a cookie: Set-Cookie: sid=...; HttpOnly; Secure; SameSite=Lax.
  3. Every server looks up the session in Redis.

Pros: easy to revoke (delete the key), small cookie, the server controls the data. Cons: a Redis lookup per request and Redis must be highly available.

Option 2: signed tokens (JWT)

The server signs a token containing claims (sub, exp, roles). Any server with the verification key checks the signature without a lookup.

Pros: no shared session store, works across services. Cons: hard to revoke before expiry, so keep access tokens short-lived (for example 15 minutes) and use a refresh token stored server-side for longer sessions. Do not put secrets or large data in a JWT; it is only signed, not encrypted, by default.

Other state to move out

  • Uploaded files: to object storage (S3-compatible), not local disk.
  • Caches: shared cache, or accept that each instance has its own small local cache.
  • Scheduled jobs: a job scheduler or queue, not a timer inside one web server.
  • WebSocket connections are inherently stateful; keep connection routing in a separate gateway tier.

By level

Fresher: Explain why storing login data in one server's memory breaks with many servers, and describe a shared session store. The logged-out-on-another-server example is the expected starting point.

Mid: Compare Redis sessions and JWTs including revocation and cookie security, and list other state that must leave the instance. Expect cookie flags and JWT revocation to be covered.

Senior: Discuss session store availability and multi-region replication, token rotation and revocation lists, security implications, and how stateful components such as WebSockets are isolated. It should also say how stateful pieces like WebSockets are kept separate.

Key points

  • Stateless servers keep no per-user memory between requests
  • Sticky sessions are a fragile workaround
  • Shared session store: easy revocation, one lookup per request
  • JWT: no lookup, but hard to revoke, so keep it short-lived
  • Move files, caches and jobs out of the instance too

Common mistakes

  • Storing sessions in local memory behind a load balancer
  • Treating JWTs as encrypted
  • Using long-lived JWTs with no revocation plan
  • Saving uploads to the app server's local disk

Follow-ups

  • How would you log a user out of all devices with JWTs?
  • What happens if the Redis session store goes down?
  • Why should session cookies be HttpOnly and Secure?

Tips

  • Start with the logged-out-on-server-B example
  • Compare the two session options in a small table
  • Mention cookie security flags

Evaluation rubric

  • Clear definition of stateless
  • Explains why in-memory sessions fail
  • Compares shared store and token approaches correctly
  • Mentions other state such as files and jobs
28.system-design-0028Mediumfresher

Compare short polling, long polling, Server-Sent Events and WebSockets for real-time updates.

Short polling asks the server every few seconds and wastes requests. Long polling holds each request open until there is news, then the client reconnects. Server-Sent Events keep one HTTP response open for a one-way stream of server-to-client events with automatic reconnect. WebSockets upgrade to a full-duplex connection for low-latency two-way messages, at the cost of stateful connections to manage.

Full answer

Short polling

The client sends GET /notifications?since=... every N seconds. Simple and works everywhere. But most responses are empty, and updates arrive up to N seconds late. With 1 million open apps polling every 5 seconds, that is 200,000 requests per second, mostly for nothing.

Long polling

The client sends a request; the server holds it open until an event arrives or a timeout (say 30 seconds), then responds. The client immediately sends the next request. Latency is low, and it uses plain HTTP, so it passes most proxies. Costs: one held request per client, reconnect overhead after every event, and care needed to not miss events between requests (use a since cursor).

Server-Sent Events (SSE)

The browser opens new EventSource('/stream'). The server responds with Content-Type: text/event-stream and keeps writing lines like:

id: 1042 event: score data: {"match": 7, "runs": 182, "wickets": 4}

Each event ends with a blank line. One-way (server to client). Built-in reconnect, and the browser sends Last-Event-ID so the server can resume. Text only. Works over HTTP/2 well. A good fit for live cricket scores, notification badges, progress of a long report, and streaming text responses.

WebSockets

The client sends an HTTP request with Upgrade: websocket; after the 101 Switching Protocols response, the same TCP connection carries messages in both directions with tiny framing overhead. Best for chat, multiplayer games, collaborative editing and live classroom tools where the client also sends frequent messages.

Costs: each connection is stateful and pinned to one server, so you need a connection gateway tier, a way to route messages to the server holding a user's socket (for example a pub/sub channel per user), heartbeats to detect dead connections, and reconnect logic with resume. Some corporate proxies interfere with them.

Choosing

NeedChoice
Updates every few minutes, simplest possibleShort polling
Real-time, restrictive networks, simple serverLong polling
Server-to-client stream onlySSE
Frequent two-way messages, lowest latencyWebSockets

Mobile apps often combine a socket while in the foreground with push notifications (APNs, FCM) when in the background.

By level

Fresher: Explain each technique in simple terms and pick WebSockets for chat and SSE or polling for simple notifications. Choosing correctly between one-way and two-way needs is the main test.

Mid: Compare overhead and latency with numbers, explain reconnect and resume, and describe a connection gateway with pub/sub routing. Expect polling cost to be shown with numbers.

Senior: Discuss scaling millions of connections, load balancer settings for long-lived connections, graceful drain on deploys, back-pressure, presence, and fallbacks for restricted networks. The senior answer covers graceful drain of connections during deploys.

Key points

  • Short polling is simple but wasteful and delayed
  • Long polling holds a request until an event, then reconnects
  • SSE is a one-way event stream with built-in reconnect and Last-Event-ID
  • WebSockets give full-duplex, low-latency messaging but need stateful connection management
  • Mobile apps add push notifications for background delivery

Common mistakes

  • Choosing WebSockets for one-way updates where SSE is simpler
  • Forgetting heartbeats and reconnect logic
  • Missing events between long poll requests without a cursor
  • Ignoring how to route a message to the server holding the connection

Follow-ups

  • How would you send a message to a user connected to one of 500 WebSocket servers?
  • How does SSE resume after a dropped connection?
  • How many concurrent connections can one server hold, and what limits it?

Tips

  • Order the options from simplest to most capable
  • Do the polling arithmetic for a large user count
  • Mention the connection routing problem for WebSockets

Evaluation rubric

  • Correct mechanics of all four
  • Explains costs, especially of polling and WebSockets
  • Picks correctly for one-way versus two-way needs
  • Mentions reconnect and routing concerns
29.system-design-0029Easyfresher

What is the difference between a forward proxy, a reverse proxy and an API gateway?

A forward proxy acts for clients, sending their requests out to the internet, for example a school network filter. A reverse proxy acts for servers, receiving public requests and forwarding them to internal backends, adding TLS termination, caching, compression and load balancing. An API gateway is a reverse proxy specialised for APIs, adding authentication, rate limiting, routing to many services, request transformation and API keys.

Full answer

Forward proxy

Sits in front of clients. The client is configured to send requests through it.

  • A school or office network sends all browsing through a proxy that blocks some sites and logs usage.
  • It can cache popular downloads for the whole network.
  • It hides the client's IP address from the destination.

The website sees the proxy, not the student's laptop.

Reverse proxy

Sits in front of servers. Clients think they are talking to the website; the proxy forwards to a backend they never see.

  • TLS termination: handles HTTPS certificates in one place.
  • Load balancing across app servers.
  • Caching and compression of responses.
  • Security: hides internal topology, filters bad requests, absorbs slow clients.

Nginx, HAProxy, Envoy and Caddy are common reverse proxies. A minimal Nginx example (configuration sketch, not run here):

nginx
upstream app_servers {
    server 10.0.0.11:8080;
    server 10.0.0.12:8080;
}

server {
    listen 443 ssl;
    server_name learn.example.com;
    ssl_certificate     /etc/ssl/learn.crt;
    ssl_certificate_key /etc/ssl/learn.key;

    location /static/ {
        root /var/www;
        expires 30d;
    }

    location / {
        proxy_pass http://app_servers;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

API gateway

A reverse proxy with API-specific features, usually the single entry point for many microservices:

  • Route /payments/* to the payments service, /courses/* to the catalogue service.
  • Verify OAuth tokens or API keys before requests reach services.
  • Apply rate limits and quotas per client or plan.
  • Transform requests (REST to gRPC), aggregate responses, add request IDs for tracing.
  • Collect per-API metrics.

Examples: Kong, Amazon API Gateway, Apigee, Envoy-based gateways.

Cautions

The gateway is on every request, so it must be horizontally scaled and redundant. Keep business logic out of it; it should route and protect, not compute prices. A load balancer, reverse proxy and gateway are often stacked: a cloud L4 load balancer in front of a gateway fleet in front of services.

By level

Fresher: Explain forward versus reverse proxy with simple examples and list what a reverse proxy does. Saying who each proxy works for is the key point.

Mid: Configure a reverse proxy conceptually, explain gateway features, and where authentication and rate limiting should live. Expect the backend to read the real client IP correctly.

Senior: Discuss layering of load balancers, gateways and service mesh, gateway scaling and failure modes, multi-region edge routing, and governance of shared gateway configuration. It should explain why business logic stays out of the gateway.

Key points

  • Forward proxy represents clients; reverse proxy represents servers
  • Reverse proxies terminate TLS, balance load, cache and compress
  • API gateways add auth, rate limits, routing and transformation for APIs
  • The gateway must be scaled and redundant
  • Keep business logic out of the gateway

Common mistakes

  • Mixing up forward and reverse proxies
  • Putting business logic in the gateway
  • Forgetting X-Forwarded-For when the backend needs the client IP
  • Making the gateway a single point of failure

Follow-ups

  • How does the backend learn the real client IP behind a proxy?
  • Where would you verify JWTs: gateway or service?
  • What is a service mesh and how does it differ from a gateway?

Tips

  • Say who the proxy works for in the first sentence
  • List three reverse proxy jobs
  • Name what the gateway adds beyond a reverse proxy

Evaluation rubric

  • Correct direction of each proxy type
  • Lists reverse proxy responsibilities
  • Explains API gateway features
  • Mentions availability and scope concerns
30.system-design-0030Easyfresher

How do you do back-of-the-envelope capacity estimation in a system design interview? Walk through an example.

State assumptions (users, actions per user, object sizes, read to write ratio), convert daily totals to per-second rates using about 86,400 seconds per day, add a peak factor, then estimate storage over the retention period and bandwidth. Round aggressively, show the arithmetic, and use the results to choose a design, not just to produce numbers.

Full answer

Why estimate

Numbers decide the design. 50 writes per second fits one database comfortably; 50,000 writes per second means sharding or a log-structured store. 2 GB of data fits in memory; 200 TB does not. The interviewer wants to see that you can get the order of magnitude right and draw conclusions from it.

Useful constants

  • 1 day = 86,400 seconds, about 10^5 for quick maths.
  • 1 million requests per day is about 12 per second.
  • 1 KB = 10^3 bytes, 1 MB = 10^6, 1 GB = 10^9, 1 TB = 10^12, 1 PB = 10^15 (decimal units are fine for estimates).
  • Rough latency orders of magnitude, commonly quoted and hardware dependent: memory access around 100 ns, SSD random read around 100 microseconds, round trip inside a data centre around 0.5 ms, round trip between continents around 100 to 200 ms.

The steps

  1. Users: daily active users (DAU).
  2. Actions: how many reads and writes per user per day.
  3. Rates: total per day / 86,400 = average per second. Multiply by a peak factor (2 to 5 is common; state yours).
  4. Storage: writes per day x size per item x days retained x replication factor.
  5. Bandwidth: requests per second x response size.
  6. Memory for cache: the hot fraction of data you want in RAM.
  7. Conclusion: what does this mean for the design?

Worked example: homework photo uploads

Assumptions: 10 million DAU; each user views 20 pages per day; 1 million photos uploaded per day; average photo 200 KB after compression; keep photos 1 year for now; peak factor 3.

  • Page reads: 10M x 20 = 200M per day. 200M / 86,400 = about 2,315 per second average, about 7,000 per second at peak.
  • Uploads: 1M / 86,400 = about 12 per second, about 35 per second at peak.
  • New photo storage: 1M x 200 KB = 200 GB per day. Over 365 days: 73 TB. With 3 copies for durability: about 219 TB. (Object stores handle replication for you, but the bytes are still paid for.)
  • Upload bandwidth at peak: 35 x 200 KB = 7 MB/s, small.
  • If each page view shows 5 photo thumbnails of 20 KB: 7,000 x 5 x 20 KB = 700 MB/s at peak, which is why thumbnails go through a CDN.

Conclusions: writes are low and fit one database for metadata; storage is large and belongs in object storage; read bandwidth for images needs a CDN.

Habits that help

  • Say each assumption out loud and write it down.
  • Round to easy numbers (86,400 to 100,000) when the interviewer does not need precision, and say you are rounding.
  • Keep units in every line.
  • Sanity check: does the answer match something you know? A single modern database server handling a few thousand simple writes per second is plausible; a million is not.

By level

Fresher: Convert daily users and actions into requests per second and estimate storage for a year with simple, stated assumptions. Each number should be followed by what it means for the design.

Mid: Include peak factors, replication, bandwidth and cache sizing, and use the numbers to justify concrete choices such as sharding or a CDN. Expect units on every line and no mix-up of bits and bytes.

Senior: Estimate cost, headroom and growth, identify which resource saturates first, model failure scenarios (one region down means the others take the load), and challenge assumptions that drive the biggest numbers. The senior answer names the resource that will run out first.

Key points

  • State assumptions before calculating
  • Divide daily totals by 86,400 and apply a stated peak factor
  • Storage = items per day x size x retention x replication
  • Keep units on every line and round openly
  • Turn every number into a design decision

Common mistakes

  • Producing numbers without saying what they imply for the design
  • Forgetting the peak factor or replication
  • Mixing bits and bytes in bandwidth
  • Spending ten minutes on precise arithmetic the interviewer did not need

Follow-ups

  • How would the estimate change if videos replaced photos?
  • How many cache servers would you need for the hot 20% of data?
  • What peak factor would you use for an exam results day?

Tips

  • Write assumptions on the board in a short list
  • Use 1 million per day is about 12 per second as a shortcut
  • End each estimate with "so we need..."

Evaluation rubric

  • Clear, explicit assumptions
  • Correct arithmetic with units
  • Covers rate, storage and bandwidth
  • Draws design conclusions from the numbers
31.system-design-0031Easyfresher

What do availability "nines" mean, and how do SLAs, SLOs and SLIs differ?

Availability is the fraction of time or requests a service works correctly; 99.9% allows about 8.76 hours of downtime per year and 99.99% about 52.6 minutes. An SLI is the measured indicator, an SLO is the internal target for it, and an SLA is the contract with customers, with penalties if missed. The gap between 100% and the SLO is the error budget.

Full answer

The nines

AvailabilityDowntime per yearPer 30-day month
99%3.65 days7.2 hours
99.9%8.76 hours43.2 minutes
99.99%52.56 minutes4.32 minutes
99.999%5.26 minutesabout 26 seconds

Each extra nine costs much more: redundancy across zones or regions, automated failover, careful deploys and on-call staff.

Dependencies multiply

If a request needs three services in a chain, each 99.9% available and failing independently, the chain is about 0.999 x 0.999 x 0.999 = 99.7%. Serial dependencies lower availability.

Redundancy raises it. Two independent replicas, each 99% available, where either can serve: 1 - (0.01 x 0.01) = 99.99%. In practice failures are often correlated (same bad deploy, same region), so real gains are smaller.

SLI, SLO, SLA

  • SLI (indicator): what you measure. "Percentage of GET /results requests that return 2xx in under 300 ms."
  • SLO (objective): the target. "99.9% of those requests meet the SLI over 30 days."
  • SLA (agreement): a contract with customers, usually looser than the SLO, with consequences such as service credits.

Measure request-based SLIs where possible ("good requests / total requests"), because "the server was up" does not mean users were served.

Error budgets

With a 99.9% SLO over a month of 10 million requests, the budget is 0.1% = 10,000 failed or slow requests. While budget remains, teams ship features. When it is spent, they slow releases and work on reliability. This turns "how reliable should we be?" into a shared, measurable rule.

Choosing a target

Pick by user impact. A results portal on result day needs high availability during that window; an internal analytics dashboard can be 99%. Users cannot tell 99.99% from 99.999% if their own network is less reliable than that.

By level

Fresher: Convert nines into downtime and define SLA, SLO and SLI with a simple example. Knowing the downtime for 99.9% and 99.99% is expected.

Mid: Compose availability across dependencies, define request-based SLIs, and explain error budgets with numbers. Expect one multiplication for chained dependencies.

Senior: Set SLOs across a service graph, discuss correlated failures, multi-region cost per extra nine, alerting on burn rate, and negotiating SLAs with dependencies. It should cover alerting on how fast the error budget is being used.

Key points

  • 99.9% is about 8.76 hours per year; 99.99% about 52.6 minutes
  • Serial dependencies multiply availability downward
  • Redundancy helps only when failures are independent
  • SLI is measured, SLO is the target, SLA is the contract
  • Error budget = 100% minus SLO, used to balance speed and reliability

Common mistakes

  • Confusing SLA with SLO
  • Measuring uptime of a server instead of successful user requests
  • Assuming redundancy failures are independent
  • Setting an SLO tighter than dependencies allow

Follow-ups

  • Your service depends on a 99.9% database; can you offer 99.99%?
  • How would you define an SLI for a video player?
  • What should happen when the error budget runs out?

Tips

  • Memorise the 99.9% and 99.99% downtime figures
  • Show one multiplication for serial dependencies
  • Define SLI, SLO and SLA in one sentence each

Evaluation rubric

  • Correct downtime arithmetic
  • Explains serial and redundant composition
  • Distinguishes SLI, SLO and SLA
  • Explains error budgets
32.system-design-0032Mediummid

What is a Bloom filter, how do you size it, and where is it used in system design?

A Bloom filter is a compact bit array with k hash functions that answers "definitely not in the set" or "probably in the set". It has no false negatives but a tunable false positive rate, and plain Bloom filters do not support deletes. For n items and false positive rate p, use about m = -n ln p / (ln 2)^2 bits and k = (m / n) ln 2 hash functions.

Full answer

How it works

Start with an array of m bits, all 0, and k independent hash functions.

  • Add an item: compute its k hashes, set those k bit positions to 1.
  • Check an item: compute its k positions. If any bit is 0, the item was never added (definitely not present). If all are 1, it was probably added, but other items may have set those bits (a false positive).

You cannot remove an item by clearing its bits, because other items share them. Counting Bloom filters (small counters instead of bits) or cuckoo filters support deletion.

Sizing

For n items and a target false positive rate p:

  • bits: m = -n x ln(p) / (ln 2)^2
  • hash functions: k = (m / n) x ln 2

Example: 1 million usernames with p = 1%:

  • m = 1,000,000 x 4.605 / 0.4805 = about 9.59 million bits = about 1.2 MB
  • k = 9.59 x 0.693 = about 6.6, so use 7 hash functions

That is about 9.6 bits per item regardless of how long the usernames are. Storing the usernames themselves in a hash set would take many times more memory.

Where it is used

  • LSM-tree databases (Cassandra, RocksDB, HBase): each on-disk file has a Bloom filter, so a read skips files that definitely do not contain the key, saving disk reads.
  • Cache protection: check a filter of existing IDs before querying the database, so requests for non-existent keys (including attacks with random IDs) do not hit the database.
  • Username or short-code availability: a fast "definitely free" check before the authoritative database check.
  • Web crawlers: "have we seen this URL?" over billions of URLs.
  • CDNs: only cache an object on its second request ("one-hit wonders" skip the cache) using a filter of seen objects.

Trade-offs

  • False positives are acceptable only when a positive is followed by an exact check or when an occasional wrong "yes" is harmless.
  • The filter must be sized for the final n; inserting more items than planned raises p sharply. Scalable Bloom filters add new layers as they fill.
  • Rebuilding is needed for deletes in the plain version.

By level

Fresher: Explain the bit array and hashes, and that the answer is "definitely not" or "maybe yes". Saying that it can wrongly say yes but never wrongly say no is the key point.

Mid: Size a filter for given n and p, explain false positive implications and where it saves database reads. Expect the sizing arithmetic for a given item count.

Senior: Discuss distributed and scalable filters, rebuild strategies, memory versus accuracy trade-offs at scale, and alternatives such as cuckoo filters and quotient filters. The senior answer weighs memory against accuracy at large scale.

Key points

  • Answers definitely-not or probably-yes; no false negatives
  • m = -n ln p / (ln 2)^2 and k = (m/n) ln 2
  • About 9.6 bits per item for 1% false positives
  • Plain Bloom filters cannot delete; counting or cuckoo filters can
  • Used in LSM databases, crawlers, cache protection and CDNs

Common mistakes

  • Claiming Bloom filters can have false negatives
  • Trying to delete by clearing bits
  • Overfilling a filter sized for fewer items
  • Using it where a false positive causes real harm without a follow-up check

Follow-ups

  • How would you use a Bloom filter to speed up a URL shortener's custom alias check?
  • Why do LSM-tree reads benefit so much from Bloom filters?
  • How does a cuckoo filter differ?

Tips

  • Explain add and check with a small bit array
  • Do the sizing arithmetic for one million items
  • Name one database that uses Bloom filters internally

Evaluation rubric

  • Correct mechanism and error types
  • Correct sizing formulas and arithmetic
  • Real use cases
  • Discusses deletion and overfilling limits
33.system-design-0033Hardsenior

How does leader election and consensus work in a system like Raft, and why do clusters use an odd number of nodes?

Raft keeps a replicated log consistent across nodes. One leader is elected for a numbered term by majority vote; it appends client commands to its log and replicates them, and an entry is committed once a majority stores it. A majority is needed for both election and commit, so two leaders cannot both make progress. Odd sizes are used because 4 nodes tolerate no more failures than 3.

Full answer

Why consensus

Some decisions must be agreed by all nodes even with crashes and network delays: who is the leader, which configuration is current, who holds a lock. Consensus protocols such as Raft and Paxos solve this. etcd (behind Kubernetes) and Consul use Raft; ZooKeeper uses a similar protocol (ZAB).

Raft roles and terms

Each node is a follower, candidate or leader. Time is split into terms numbered 1, 2, 3... At most one leader per term.

Leader election

  1. The leader sends regular heartbeats.
  2. If a follower hears nothing for a randomised election timeout (for example 150 to 300 ms), it becomes a candidate, increments the term, votes for itself and asks others for votes.
  3. Each node votes for at most one candidate per term, and only for a candidate whose log is at least as up to date as its own.
  4. A candidate with votes from a majority becomes leader.

Randomised timeouts make it unlikely that two candidates split the vote repeatedly.

Log replication

  1. A client sends a command to the leader.
  2. The leader appends it to its log and sends it to followers.
  3. Once a majority (including the leader) has stored it, the entry is committed; the leader applies it and replies.
  4. Followers apply committed entries in the same order, so every node's state machine ends up identical.

If a follower's log differs, the leader overwrites the follower's uncommitted conflicting entries with its own.

Why majorities prevent split brain

Any two majorities of the same cluster share at least one node. If a network partition splits 5 nodes into 3 and 2, only the side with 3 can elect a leader or commit. The 2-node side cannot, even if it contains the old leader; that old leader cannot get acknowledgements and stops making progress. Clients writing to it will time out.

Why odd numbers

A cluster of N tolerates floor((N - 1) / 2) failures:

NodesMajorityFailures tolerated
321
431
532
642
743

A 4th node adds cost and replication work without extra tolerance. Most clusters use 3 or 5; larger clusters slow down commits because more acknowledgements travel per write.

Practical points

  • Every write goes through the leader and needs a majority round trip, so consensus stores are for small, critical data (configuration, membership, locks), not bulk data.
  • Linearizable reads need the leader to confirm it is still leader (a read index round or a time-based lease).
  • Spread nodes across failure zones: 3 nodes in 3 availability zones survive one zone failure.

By level

Fresher: Explain that a cluster picks one leader by majority vote and that a write is safe once most nodes have it. Explaining why a cluster of three survives one failure is enough.

Mid: Walk through election, terms, log replication and commit, and explain why 3 or 5 nodes are typical. Expect the commit rule and the role of terms.

Senior: Discuss partitions and stale leaders, linearizable reads with read index or leases, membership changes, zone placement, write latency across regions and when to use an existing consensus service instead of building one. It should explain what an old leader in a minority partition can and cannot do.

Key points

  • Raft elects one leader per term by majority vote with randomised timeouts
  • Entries commit once stored on a majority
  • Overlapping majorities prevent two leaders from both committing
  • N nodes tolerate floor((N-1)/2) failures, so odd sizes are efficient
  • Consensus stores hold small critical data, not bulk data

Common mistakes

  • Thinking the minority side keeps accepting writes
  • Saying 4 nodes tolerate 2 failures
  • Using a consensus store as a general high-throughput database
  • Forgetting that reads also need care to be linearizable

Follow-ups

  • What happens to an old leader stuck in a minority partition?
  • How would you place a 5-node cluster across 3 zones?
  • How does etcd serve linearizable reads?

Tips

  • Separate election from replication in your explanation
  • Draw the 3-versus-2 partition
  • Show the failures tolerated table for 3, 4 and 5 nodes

Evaluation rubric

  • Correct election mechanics including terms and vote rules
  • Correct commit rule
  • Explains split-brain prevention with overlapping majorities
  • Correct odd-number reasoning
34.system-design-0034Mediummid

Monolith vs microservices: what are the real trade-offs, and when should a team split a monolith?

A monolith deploys as one unit with in-process calls and one database, which is simple to build, test and keep consistent. Microservices split the system into independently deployable services that own their data, which lets large teams ship and scale parts separately but adds network failures, distributed data consistency and operational overhead. Split when team size and deploy contention, or very different scaling needs, outweigh that cost, and split along business boundaries.

Full answer

Monolith

One codebase and one deployable process (possibly many identical copies behind a load balancer), usually with one database.

  • Function calls instead of network calls: fast and no partial failures.
  • Transactions across features are easy: enrol and charge in one database transaction.
  • One build, one deploy pipeline, easy local development and debugging.
  • Problems grow with size: slow builds and tests, teams blocking each other's releases, one bad change taking down everything, and the whole app scaled together even if only video encoding needs more CPU.

A modular monolith keeps one deployable but enforces internal module boundaries (separate packages, no reaching into another module's tables). It keeps most monolith benefits and makes a later split far easier.

Microservices

Each service owns one business capability and its own data, exposes an API, and is deployed independently.

  • Teams own services end to end and release on their own schedule.
  • Services scale independently and can use different technology where justified.
  • Failures can be isolated, if designed for it.

Costs:

  • Every call can fail or be slow: timeouts, retries, circuit breakers are required.
  • No cross-service transactions: sagas, outbox and eventual consistency.
  • Queries across services need API composition or replicated read models.
  • Platform work: service discovery, CI/CD per service, distributed tracing, centralised logs, secrets, versioned APIs.
  • More things to monitor and be paged for.

When to split

Good signals:

  • Many teams (often several teams of 5 to 10 people) blocked by a shared release train.
  • A component with very different scaling or reliability needs (video transcoding, search indexing).
  • A clear business boundary with little shared data (billing versus content authoring).

Poor reasons: "microservices are modern", or splitting a small team's product into ten services.

How to split safely

  1. Make module boundaries clean inside the monolith first.
  2. Use the strangler fig pattern: route one capability's traffic to a new service, keep the rest in the monolith, repeat.
  3. Give the new service its own data store and migrate data with change data capture or dual writes plus verification.
  4. Avoid a "distributed monolith" where services share a database or must deploy together; that has the costs of both and the benefits of neither.

Boundaries follow the business domain (bounded contexts), not technical layers. A "database service" and a "UI service" are layers, not good service boundaries.

By level

Fresher: Describe both styles in simple terms and give one benefit and one drawback of each. A fresher can describe a modular monolith as a middle step.

Mid: Discuss data ownership, sagas, observability and deployment, and when a modular monolith is the better choice. Expect concrete signals for when to split.

Senior: Plan an incremental extraction with the strangler fig pattern and data migration, define service boundaries by domain, assess platform cost, and recognise and fix a distributed monolith. The senior answer includes a step-by-step extraction and data migration plan.

Key points

  • Monoliths are simple, fast and transactional but hurt large teams
  • Microservices enable independent deploys and scaling at the cost of distributed-system complexity
  • A modular monolith is often the right middle step
  • Split for team autonomy or distinct scaling needs, along business boundaries
  • Avoid the distributed monolith with shared databases

Common mistakes

  • Splitting by technical layer instead of business capability
  • Sharing one database across services
  • Ignoring the platform and observability work microservices need
  • Starting a small product as dozens of services

Follow-ups

  • How would you extract the payments module from a monolith?
  • What is the strangler fig pattern?
  • How do you run a report that needs data from five services?

Tips

  • Give two benefits and two costs of each
  • Name concrete signals for splitting
  • Mention modular monolith as an option

Evaluation rubric

  • Balanced trade-offs
  • Correct consequences for data and failures
  • Clear criteria for when to split
  • Safe migration approach
35.system-design-0035Mediumfresher

Design a URL shortener like bit.ly that handles 100 million new short links per day.

Store a mapping from a 7-character base62 code to the long URL in a horizontally scaled key-value store, generate codes from a unique counter or ID service so there are no collisions, and serve redirects from a cache in front of the store because reads outnumber writes about 100 to 1. With 100M links per day for 5 years you need about 182.5 billion codes, so 6 characters (56.8 billion) are not enough and 7 (3.52 trillion) are.

Full answer

Requirements

Functional:

  • Given a long URL, return a short URL such as https://sho.rt/aZ3kP9q.
  • Visiting the short URL redirects to the long URL.
  • Optional custom alias and expiry date; basic click counts.

Non-functional:

  • Redirects are fast (low tens of milliseconds at p99 inside a region) and highly available; a broken link is very visible.
  • Codes must never collide and should not be easy to enumerate.
  • Links last at least 5 years.

Capacity estimates

Assumptions: 100M new links per day, read to write ratio 100:1, 500 bytes per record (long URL, code, owner, timestamps), peak factor 2.

  • Writes: 100M / 86,400 = about 1,160 per second; about 2,300 per second at peak.
  • Reads: 100 x 1,160 = about 116,000 per second; about 230,000 per second at peak.
  • Storage: 100M x 500 B = 50 GB per day, 18.25 TB per year, about 91 TB for 5 years before replication (about 274 TB with 3 replicas).
  • Code space: 100M x 365 x 5 = 182.5 billion links. Base62 (a-z, A-Z, 0-9): 62^6 = 56.8 billion is too small; 62^7 = 3.52 trillion leaves plenty of room.
  • Cache: keeping the 20% of each day's new links that get most clicks: 20M x 500 B = 10 GB, which fits in memory on a small cache cluster.

API

POST /api/v1/links body: {"long_url": "https://...", "custom_alias": "optional", "expires_at": "optional ISO 8601"} 201 {"code": "aZ3kP9q", "short_url": "https://sho.rt/aZ3kP9q"} GET /{code} 302 Location: https://original.example.com/page (or 404 / 410 if expired) GET /api/v1/links/{code}/stats -> {"clicks": 1234, ...}

Data model

links: code (primary key, string), long_url, owner_id, created_at, expires_at. Access is almost always "look up by code", so a key-value or wide-column store (DynamoDB, Cassandra) partitioned by code fits well; sharded MySQL or PostgreSQL also works. Click events go to a separate analytics pipeline, not the links table.

High-level design

mermaid
flowchart LR
  C[Client] --> LB[Load balancer]
  LB --> W[Write service]
  LB --> R[Redirect service]
  W --> IDS[ID range allocator]
  W --> DB[(Links store)]
  R --> CACHE[(Redis cache)]
  CACHE -. miss .-> DB
  R --> Q[Click events queue] --> AN[Analytics]

Generating codes

  1. Counter plus base62 (chosen). Each write server leases a block of IDs (for example 1 million at a time) from a small coordination service, then converts each ID to base62. No collisions, no database check. To avoid sequential, guessable codes, pass the ID through a reversible scramble (a keyed permutation) before encoding.
  2. Hash the URL (MD5 or SHA-256, take 7 base62 characters). The same URL gets the same code, but collisions must be checked and retried, which adds a read per write.
  3. Pre-generated random codes stored in a pool table; workers take unused codes. Works, but the pool needs management.

Custom aliases are inserted with a conditional write ("only if code does not exist").

Redirect path and scaling

The redirect service checks Redis first; on a miss it reads the store and fills the cache with a TTL. At a 90% hit ratio, the store sees about 23,000 reads per second at peak, spread over its partitions. Popular links can also be cached at a CDN edge.

301 or 302? A 301 (permanent) is cached by browsers, so repeat visits never reach you: less load, but no click counts and no way to change the target. A 302 keeps every visit visible for analytics. Most shorteners use 302.

Bottlenecks and trade-offs

  • The ID allocator is tiny but critical: run it replicated, and since servers hold blocks, a short outage does not stop writes.
  • Hot links (a viral link) are absorbed by the cache and CDN.
  • Expired links are removed by a background job or the store's TTL feature; codes are not reused to avoid sending old links to new places.
  • Abuse: scan long URLs against malware lists and rate limit creation per user or IP.
  • Choosing counters over hashing trades "same URL gets same code" for collision-free writes; most products accept duplicate codes for the same URL.

By level

Fresher: List the requirements, sketch the two endpoints and a table with code and long URL, and explain base62 encoding and caching of redirects. Basic arithmetic for requests per second is a bonus at this level.

Mid: Do the throughput, storage and code-space math, compare key generation methods, choose a datastore and cache, and explain 301 versus 302. The 6 versus 7 character decision should come from the math.

Senior: Cover allocator availability, hot links, multi-region reads and replication, abuse prevention, non-guessable codes, analytics pipelines and storage cost over five years. Expect a clear plan for one region failing.

Key points

  • Reads dominate about 100 to 1, so cache the redirect path
  • 182.5 billion codes over 5 years need 7 base62 characters
  • Counter ranges plus base62 avoid collisions; scramble to avoid guessable codes
  • 302 keeps analytics; 301 reduces load but hides clicks
  • Key-value store partitioned by code fits the access pattern

Common mistakes

  • Using 6 characters without checking the code space against 5-year volume
  • Hashing URLs without handling collisions
  • Using 301 and then promising click analytics
  • Writing click counts synchronously into the links table on every redirect

Follow-ups

  • How would you support custom aliases without races?
  • How would you prevent people from enumerating all short links?
  • How would you serve redirects if one region goes down?

Tips

  • Do the code-space arithmetic early; it decides the code length
  • Explain the 301 versus 302 choice
  • Keep analytics off the hot redirect path

Evaluation rubric

  • Clear functional and non-functional requirements
  • Correct capacity math including code length
  • Sound key generation with collision handling
  • Caching, redirect semantics and trade-offs discussed
36.system-design-0036Mediummid

Design a distributed rate limiter for an API gateway that serves about 1 million requests per second.

Run the limiter inside the gateway, look up the rule for each request's key, and keep token-bucket state in a sharded Redis cluster updated atomically with a Lua script, so every gateway instance sees the same counts. Return 429 with Retry-After when limited. At 1M requests per second you need about 10 or more Redis shards under a stated per-shard assumption, plus a local fallback and a decision on failing open or closed.

Full answer

Requirements

Functional:

  • Limit requests per key (API key, user ID or IP) per rule, for example "free plan: 100 requests per minute", "login: 5 per minute per account".
  • Different rules per endpoint and plan, changeable without redeploying.
  • Tell clients when they are limited and when to retry.

Non-functional:

  • Adds under about 1 to 2 ms to request latency.
  • Accurate enough across many gateway servers (small overshoot is acceptable).
  • The limiter failing must not take down the API.

Capacity estimates

Assumptions: 1M requests per second at peak across 100 gateway instances; 50M distinct keys active per day; about 100 bytes of state per key (key name, token count, last refill timestamp, overhead); one Redis node handles about 100,000 simple script calls per second (an assumption to verify with load tests).

  • State memory: 50M x 100 B = 5 GB. Small; it fits in memory across a few nodes.
  • Operations: one atomic check per request = 1M operations per second. At 100k per node that is 10 primary shards; plan 15 to 20 for headroom, each with a replica.
  • Network: each call is a few hundred bytes, so about 1M x 300 B = 300 MB/s across the cluster, fine for a data centre network.

API and responses

Internal check, called by the gateway:

allow(key="apikey:abc123", rule="free_api", cost=1) -> {allowed: bool, remaining: int, reset_ms: int}

Client-facing behaviour:

HTTP/1.1 429 Too Many Requests Retry-After: 12 RateLimit-Limit: 100 RateLimit-Remaining: 0

(The RateLimit-* header names follow an IETF draft; many APIs use X-RateLimit-*.)

Data model

Rules (in a config store, cached in each gateway): rule_id, match (path, method, plan), key_type (api_key, user, ip), capacity, refill_per_second. State (Redis): hash rl:{rule}:{key} with fields tokens and ts, with an expiry so idle keys disappear.

High-level design

mermaid
flowchart LR
  C[Clients] --> LB[Load balancer]
  LB --> G1[Gateway + limiter]
  LB --> G2[Gateway + limiter]
  G1 --> RC[(Redis cluster: bucket state)]
  G2 --> RC
  CFG[(Rule config store)] -. push / poll .-> G1
  CFG -. push / poll .-> G2
  G1 --> S[Backend services]
  G2 --> S

Atomic token bucket

Read-modify-write from the gateway would race between instances, so the check runs as one Lua script inside Redis (shown for illustration, not run here):

lua
-- KEYS[1] = bucket key; ARGV[1] = capacity, ARGV[2] = tokens per ms, ARGV[3] = now in ms
local cap  = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now  = tonumber(ARGV[3])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or cap
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + math.max(0, now - ts) * rate)
local allowed = 0
if tokens >= 1 then
  tokens = tokens - 1
  allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate) + 1000)
return allowed

Keys hash to shards, so each bucket lives on exactly one shard and the script stays atomic.

Bottlenecks and how to handle them

  • Hot keys: one huge customer hitting one shard. Give such keys a local pre-allocation: each gateway takes a batch of tokens (say 50) from Redis and spends them locally, cutting Redis calls by the batch size at the cost of small overshoot.
  • Latency: keep Redis in the same zone as gateways; pipeline calls; skip the check for unlimited internal traffic.
  • Redis failure: decide per rule. Fail open (allow) for normal API traffic so an outage of the limiter does not become an outage of the API, with a coarse local in-memory limit as a safety net. Fail closed for security limits like login attempts.
  • Clock differences: pass Redis TIME or a single gateway clock; the math.max(0, ...) guard prevents negative refill if clocks disagree.
  • Multi-region: limits are usually enforced per region with the global quota divided between regions; exact global limits need cross-region coordination and add latency.

Trade-offs

Central Redis state gives accurate shared limits but adds a network hop. Purely local limits (each gateway allows limit / number_of_gateways) are zero-latency but inaccurate when traffic is uneven across gateways. Token batching sits between the two. Token bucket allows bursts, which suits most APIs; use sliding window counters if bursts are a problem.

By level

Fresher: Explain where the limiter sits, describe the token bucket, show the 429 response, and explain why counts must be shared across servers. A fresher should also describe the 429 response and Retry-After header.

Mid: Size Redis for the request rate, make the update atomic, design rule configuration, and choose per-rule failure behaviour. Expect a stated per-shard assumption behind the Redis sizing.

Senior: Handle hot keys with local batching, multi-region quotas, clock skew, limiter observability, and the accuracy versus latency versus availability trade-off across thousands of gateways. The senior answer justifies fail-open or fail-closed per rule.

Key points

  • Enforce in the gateway with shared state in a sharded Redis cluster
  • Make the check atomic with a Lua script per bucket
  • About 1M checks per second needs about 10+ shards under a stated per-node assumption
  • Return 429 with Retry-After and remaining-quota headers
  • Decide fail-open versus fail-closed per rule and handle hot keys with local token batches

Common mistakes

  • Doing read-then-write from the gateway and racing between instances
  • Failing closed for all traffic when Redis is down
  • Ignoring hot keys on a single shard
  • Promising exact global limits across regions without discussing latency

Follow-ups

  • How would you limit by cost (an expensive endpoint counts as 10)?
  • How do you change a customer's limit instantly?
  • How would you test that the limiter overshoots by less than 5%?

Tips

  • Ask which key and which algorithm the product needs
  • Size Redis from requests per second, not from memory
  • State your fail-open policy explicitly

Evaluation rubric

  • Requirements include latency and failure behaviour
  • Capacity math for operations and memory with stated assumptions
  • Atomic distributed algorithm
  • Covers hot keys, failures, multi-region and trade-offs
37.system-design-0037Mediumfresher

Design a notification system that sends push, email, SMS and in-app notifications to 50 million daily users.

Accept notification requests through an API, check user preferences and deduplicate, render templates, and put one message per channel on separate queues. Channel workers call providers such as APNs, FCM, an email service and an SMS gateway, with retries, rate limits and a dead-letter queue. About 500M notifications per day means roughly 5,800 per second on average and about 29,000 at a 5x peak.

Full answer

Requirements

Functional:

  • Other services (assignments, payments, live classes) send notifications to users by push, email, SMS or in-app inbox.
  • Users can opt out per channel and per category ("marketing", "class reminders").
  • Templates with variables and multiple languages.
  • Scheduled sends ("remind 15 minutes before class") and delivery status.

Non-functional:

  • At-least-once delivery for important messages; no duplicates visible to users.
  • Time-sensitive messages (OTP codes, class starting) go out within seconds even when a marketing campaign is running.
  • Survives provider outages; scales for campaign spikes.

Capacity estimates

Assumptions: 50M DAU, 10 notifications per user per day on average, peak factor 5 (campaigns and class start times cluster), 1 KB stored per notification record, 30 days retention for the history and in-app inbox.

  • Volume: 50M x 10 = 500M per day; 500M / 86,400 = about 5,800 per second; about 29,000 per second at peak.
  • Storage: 500M x 1 KB = 500 GB per day; 30 days = 15 TB.
  • Device tokens: 50M users x 2 devices x about 200 bytes = about 20 GB.

These numbers say: queues are required to absorb peaks, and the history store should be a horizontally scaled store partitioned by user.

API

POST /v1/notifications { "idempotency_key": "class-981-reminder-user-77", "user_id": 77, "category": "class_reminder", "template": "class_starting", "params": {"class_name": "Physics 10B", "minutes": 15}, "channels": ["push", "in_app"], "priority": "high", "send_at": "2026-12-04T09:45:00Z" } -> 202 {"notification_id": "n_8f2c..."} GET /v1/users/77/inbox?cursor=... in-app list PUT /v1/users/77/preferences opt-in/out per channel and category

Data model

  • notifications (partition by user_id, sort by time): id, user_id, category, channel, status (queued, sent, delivered, failed), created_at, rendered_body.
  • preferences: user_id, category, channel, enabled, quiet hours, time zone.
  • devices: user_id, platform, push_token, last_seen.
  • templates: name, locale, version, body.

High-level design

mermaid
flowchart LR
  S[Producer services] --> API[Notification API]
  API --> V[Validate + preferences + dedup]
  V --> SCH[Scheduler for send_at]
  V --> HQ[High-priority queues]
  V --> LQ[Bulk queues]
  SCH --> HQ
  HQ --> PW[Push workers] --> APNS[APNs / FCM]
  HQ --> SW[SMS workers] --> SMS[SMS provider]
  LQ --> EW[Email workers] --> ESP[Email provider]
  PW --> DB[(Notification store)]
  EW --> DB
  SW --> DB
  PW -. failures .-> DLQ[Dead-letter queue]

Flow

  1. The API validates the request and stores the idempotency key; repeats return the original ID.
  2. It reads the user's preferences and devices (cached), drops disabled channels, respects quiet hours in the user's time zone.
  3. It renders the template and enqueues one message per channel. Future send_at goes to a scheduler (a time-bucketed table or delayed queue) that enqueues at the right time.
  4. Channel workers send through providers, record status, and retry with exponential backoff on temporary errors.
  5. Provider callbacks (delivered, bounced, token invalid) update status; invalid push tokens are deleted.

Scaling and bottlenecks

  • Separate queues per channel and priority so a 20M-email campaign cannot delay OTP SMS.
  • Provider rate limits: SMS and email providers limit sends per second; workers use a leaky bucket per provider account.
  • Provider outage: keep a second provider for SMS and email and switch on error rate.
  • Duplicates: at-least-once queues can redeliver, so workers check a per-message sent flag (or pass an idempotency key to the provider) before sending.
  • Campaign fan-out: a campaign to 10M users is expanded in batches by a separate job, not in the API request.

Trade-offs

Per-channel queues add infrastructure but isolate failures. Storing every notification enables history and debugging but costs 15 TB per month of retention; shorter retention for bulk categories saves money. Strict exactly-once delivery is not possible with external providers, so the design aims for at-least-once with deduplication.

By level

Fresher: Describe the API, preferences check, a queue, and workers that call push, email and SMS providers, with retries. A fresher should mention user opt-outs.

Mid: Estimate volume and storage, separate queues by channel and priority, design the data model and scheduling, and handle duplicates. Expect separate queues so marketing cannot delay one-time passwords.

Senior: Plan for campaign fan-out, provider failover and rate limits, multi-region delivery, observability of delivery rates, cost per channel and compliance rules such as opt-out and quiet hours. Expect provider failover and cost per channel to be discussed.

Key points

  • Queue per channel and priority to isolate failures and campaigns
  • Check preferences, quiet hours and idempotency before enqueueing
  • About 5,800 per second average and 29,000 at a 5x peak for 500M per day
  • Workers retry with backoff, respect provider limits, and use a dead-letter queue
  • Delivery is at-least-once with deduplication, not exactly-once

Common mistakes

  • Sending directly from the API request without a queue
  • One shared queue where marketing blocks OTPs
  • Ignoring user preferences and time zones
  • Not cleaning invalid push tokens

Follow-ups

  • How would you send a campaign to 10 million users without overloading providers?
  • How do you guarantee a reminder goes out 15 minutes before class?
  • How would you track whether a push notification was opened?

Tips

  • Separate time-critical and bulk traffic early in your design
  • Mention provider rate limits and failover
  • Show the idempotency key in the API

Evaluation rubric

  • Covers channels, preferences, templates and scheduling
  • Capacity math with stated assumptions
  • Queue-based design with retries and DLQ
  • Discusses duplicates, priorities and provider failures
38.system-design-0038Hardsenior

Design a social news feed like Facebook or LinkedIn for 300 million daily active users.

Store posts once, and build each user's feed as a list of post IDs. Use fan-out on write (push post IDs into followers' cached feeds) for normal users and fan-out on read (merge at request time) for accounts with huge follower counts, then rank and hydrate the candidates. With 60M posts per day and 200 average followers, fan-out alone means about 139,000 feed inserts per second on average.

Full answer

Requirements

Functional:

  • Users create posts (text, images, links) and follow other users.
  • The home feed shows recent, relevant posts from people and pages they follow, with infinite scroll.
  • Likes and comments counts appear with each post.

Non-functional:

  • Feed loads fast (target p99 around 300 ms server time).
  • High availability; a few seconds of delay before a new post appears in followers' feeds is acceptable (eventual consistency).
  • The author sees their own post immediately.

Capacity estimates

Assumptions: 300M DAU; 10 feed loads per user per day; 20% of users post once a day; average 200 followers; peak factor 2; a feed cache holds 500 post IDs per user at 8 bytes each.

  • Feed reads: 300M x 10 = 3B per day = about 34,700 per second; about 70,000 at peak.
  • Posts: 300M x 0.2 = 60M per day = about 700 per second.
  • Fan-out writes: 60M x 200 = 12B feed inserts per day = about 139,000 per second on average.
  • Feed cache: 500 x 8 B = 4 KB per user; 300M users x 4 KB = 1.2 TB, before replication. A Redis cluster can hold this, or keep cached feeds only for recently active users.
  • Post storage: if a post record averages 1 KB (media stored separately in object storage), 60M x 1 KB = 60 GB per day.

API

POST /v1/posts {"text": "...", "media_ids": ["m1"]} -> 201 {"post_id": ...} GET /v1/feed?cursor=...&limit=20 -> {"items": [{post, author, like_count, comment_count, liked_by_me}], "next_cursor": "..."} POST /v1/users/{id}/follow

Data model

  • posts: post_id (time-ordered ID), author_id, body, media, created_at. Partitioned by post_id or author_id.
  • follows: follower_id, followee_id, stored both ways (who I follow, who follows me) for fast fan-out.
  • feed_cache (Redis sorted set per user): member = post_id, score = time or rank score; trimmed to 500 entries.
  • Counters for likes and comments in a separate counter service.

High-level design

mermaid
flowchart LR
  U[Client] --> GW[API gateway]
  GW --> PS[Post service] --> PDB[(Posts store)]
  PS --> K[Post events: Kafka]
  K --> FO[Fan-out workers]
  FO --> SG[(Follow graph)]
  FO --> FC[(Feed cache: Redis)]
  GW --> FS[Feed service]
  FS --> FC
  FS --> CEL[Celebrity posts lookup]
  FS --> RK[Ranking]
  FS --> HY[Hydration: posts, users, counts]

Fan-out strategies

  • Fan-out on write (push): when a post is created, workers add its ID to each follower's feed cache. Reads are cheap (one sorted-set range), writes are expensive and delayed for large follower lists.
  • Fan-out on read (pull): at read time, fetch recent posts from everyone the user follows and merge. Writes are cheap; reads are expensive for users following many accounts.
  • Hybrid (chosen): push for authors with fewer than, say, 10,000 followers. For celebrities (millions of followers), do not fan out; at read time the feed service fetches their recent posts and merges them in. One celebrity post with 50M followers would otherwise create 50M writes.

Also skip fan-out to inactive users (no login in 30 days); build their feed on demand when they return.

Ranking and hydration

The feed service takes a few hundred candidate IDs (cache plus celebrity posts), scores them with a ranking model (recency, relationship strength, engagement predictions), then hydrates the top 20 with post bodies, author info and counts using batched multi-get calls to caches. The author's own new post is inserted directly into their own feed so they see it at once.

Bottlenecks and trade-offs

  • Fan-out throughput (about 139k inserts per second, more at peak) is handled by partitioned Kafka topics and horizontally scaled workers; spikes just add delay.
  • Hot posts: like counts for viral posts use sharded counters; hydration caches post data heavily.
  • Cache loss: feeds can be rebuilt from the follow graph and posts store, so the cache does not need full durability, but the database must handle rebuild load gradually.
  • Pagination uses a cursor on the ranked list; re-ranking between pages can cause duplicates, so the client sends seen IDs or the server snapshots the ranked list for the session.
  • Trade-off summary: push gives fast reads at high write cost; pull gives cheap writes and slow reads; the hybrid keeps reads fast while capping write amplification, at the cost of more complex merge logic.

By level

Fresher: Describe posts, follows and feed tables, and explain the idea of copying post IDs to followers' feeds versus collecting them at read time. A fresher can explain push versus pull with a small example.

Mid: Estimate fan-out and cache size, design the hybrid approach, data model and feed API with cursors, and explain hydration. Expect the fan-out multiplication to justify the hybrid approach.

Senior: Handle celebrity and inactive users, cache rebuild, ranking latency budgets, deletes and privacy changes across feeds, multi-region feed generation and cost of fan-out storage. The senior answer covers deletes and privacy changes across millions of feeds.

Key points

  • Feed = list of post IDs plus hydration at read time
  • Hybrid fan-out: push for normal authors, pull for celebrities
  • 60M posts x 200 followers = 12B inserts per day, about 139k per second
  • Feed cache of 500 IDs per user is about 1.2 TB for 300M users
  • Rank candidates, then hydrate the top results in batches

Common mistakes

  • Using pure fan-out on write and ignoring celebrities
  • Storing full post bodies in every follower's feed
  • Fanning out to inactive users
  • Offset pagination on a ranked, changing feed

Follow-ups

  • How would you remove a deleted post from millions of feeds?
  • How would you add ads into the feed?
  • How would the design change if feeds were strictly chronological?

Tips

  • Do the fan-out multiplication; it justifies the hybrid
  • Separate candidate generation, ranking and hydration
  • Mention the author seeing their own post immediately

Evaluation rubric

  • Requirements with consistency expectations
  • Correct capacity math including fan-out volume and cache size
  • Clear fan-out strategy with celebrity handling
  • Ranking, hydration, pagination and failure trade-offs
39.system-design-0039Hardsenior

Design a chat application like WhatsApp that supports one-to-one and group messaging for 500 million daily users.

Clients keep a WebSocket to a gateway tier; a chat service assigns each message a per-conversation sequence number, stores it in a store partitioned by conversation, and routes it to recipients' gateways using a session registry, falling back to push notifications for offline users. Delivered and read receipts flow back the same way. At 20 billion messages per day the system averages about 231,000 messages per second and needs on the order of 1,500 gateway servers for 150 million concurrent connections under a stated per-server assumption.

Full answer

Requirements

Functional:

  • One-to-one and group chats (groups up to 1,024 members).
  • Sent, delivered and read receipts; online and last-seen presence.
  • Offline users receive messages when they reconnect, plus a push notification.
  • Message history synced across a user's devices; media sent as attachments.

Non-functional:

  • Low latency: under about 300 ms end to end for users in the same region.
  • Messages are never lost once the sender sees "sent", and they appear in the same order for all members of a conversation.
  • High availability; end-to-end encryption means the server stores only ciphertext.

Capacity estimates

Assumptions: 500M DAU; 40 messages sent per user per day; 200 bytes per stored message (ciphertext plus metadata, media stored separately); peak factor 2; 30% of DAU connected at peak; one gateway server holds 100,000 connections (an assumption that depends on hardware and tuning).

  • Messages: 500M x 40 = 20B per day; 20B / 86,400 = about 231,000 per second; about 463,000 per second at peak.
  • Storage: 20B x 200 B = 4 TB per day; about 1.46 PB per year before replication. If, like WhatsApp, the server deletes messages after delivery to all devices, stored volume drops to the undelivered backlog, but multi-device history sync requires keeping them.
  • Connections: 30% x 500M = 150M concurrent; 150M / 100,000 = 1,500 gateway servers, plus headroom.

API

Over the WebSocket (JSON shown for readability; production often uses a binary format):

client -> server {"type":"send","client_msg_id":"c-71","conv_id":"g42","body":"<ciphertext>"} server -> client {"type":"ack","client_msg_id":"c-71","msg_id":"m-9001","seq":5512} server -> client {"type":"message","conv_id":"g42","seq":5512,"from":77,"body":"..."} client -> server {"type":"receipt","conv_id":"g42","up_to_seq":5512,"kind":"read"}

HTTP for the rest: GET /v1/conversations/{id}/messages?after_seq=5400, POST /v1/media (returns an upload URL).

Data model

  • messages (wide-column store such as Cassandra or ScyllaDB): partition key conv_id (with a time bucket for very active groups), clustering key seq; columns msg_id, sender_id, body, created_at.
  • conversations and members: conv_id, user_id, last_read_seq, last_delivered_seq.
  • user_inbox (per user, per device): pending message references for offline delivery.
  • sessions (Redis): user_id -> [gateway_id, device_id], refreshed by heartbeats.

High-level design

mermaid
flowchart LR
  A[Sender app] -- WebSocket --> GW1[Gateway]
  GW1 --> CS[Chat service]
  CS --> SEQ[Per-conversation sequencer]
  CS --> MS[(Message store)]
  CS --> SR[(Session registry)]
  CS --> GW2[Recipient gateway]
  GW2 -- WebSocket --> B[Recipient app]
  CS --> PN[Push notification service]
  PN --> APNS[APNs / FCM]

Message flow

  1. Sender sends with a client_msg_id (for idempotent retries).
  2. Chat service assigns the next seq for the conversation (owned by one partition leader, or an atomic counter per conversation), writes the message, then acks the sender: one tick.
  3. It looks up each recipient's sessions. Online: forward to their gateway. Offline: add to their inbox and send a push notification.
  4. Recipient device acks delivery; the sender gets two ticks. Read receipts update last_read_seq.
  5. On reconnect, a device asks for everything after its last seen seq per conversation, so missed messages are filled in order.

Group chats

Write the message once per conversation, then fan out delivery to members. With a cap of 1,024 members the fan-out is bounded. For end-to-end encryption, the sender's client encrypts for each member device (or uses a group key scheme), which is one reason group sizes are capped.

Bottlenecks and trade-offs

  • Gateways are stateful. Deploys drain connections gradually; clients reconnect with jittered backoff to avoid a reconnect storm after a gateway failure.
  • Sequencing per conversation gives a total order inside a chat without global coordination. A very hot group serialises on one sequencer; that is acceptable because one conversation's write rate is modest.
  • Presence is expensive at scale: publishing every online/offline change to every contact is a large fan-out. Update presence lazily (when a chat is opened) and batch changes.
  • Storage choice: a wide-column store handles the write rate and "latest messages in a conversation" reads well; it does not offer cross-partition transactions, which chat does not need.
  • Multi-region: users connect to the nearest region; a conversation has a home region for sequencing, so cross-region chats pay one extra hop. The alternative, multi-leader writes, would break the single order per chat.

By level

Fresher: Explain why chat uses WebSockets, sketch the message table and the send-deliver-read flow, and how offline users get messages later. A fresher should describe what the single and double ticks mean.

Mid: Estimate messages, storage and connections, design the session registry and per-conversation ordering, and choose a storage engine. Expect per-conversation sequence numbers to explain ordering.

Senior: Address gateway failure and reconnect storms, presence fan-out, end-to-end encryption effects on groups and multi-device, multi-region sequencing, and storage retention cost. Expect a plan for reconnect storms after a gateway fails.

Key points

  • Persistent WebSocket connections through a stateful gateway tier
  • Session registry maps users to gateways for routing
  • Per-conversation sequence numbers give consistent order and gap-free sync
  • 20B messages per day is about 231k per second; 150M connections needs about 1,500 gateways at 100k each
  • Offline delivery through per-device inbox plus push notification

Common mistakes

  • Ordering by client timestamps
  • Polling the server for new messages
  • Storing messages partitioned by user instead of conversation, duplicating writes
  • Ignoring reconnect storms when a gateway dies

Follow-ups

  • How do you sync history to a newly added device?
  • How would you implement "last seen" without a huge fan-out?
  • What changes for groups of 100,000 members (channels)?

Tips

  • Lead with the connection model, then the message path
  • Use client_msg_id and seq to show idempotency and ordering
  • Do the connection count math to size gateways

Evaluation rubric

  • Complete requirements including receipts and offline delivery
  • Correct capacity math with assumptions
  • Sound routing, ordering and storage design
  • Discusses gateways, presence, groups and multi-region trade-offs
40.system-design-0040Hardsenior

Design a cloud file storage and sync service like Dropbox or Google Drive.

Split files into content-addressed chunks (for example 4 MB, named by SHA-256), upload only chunks the server does not have, and store them in object storage. Keep file trees, versions and chunk lists in a sharded metadata database, and notify other devices of changes through a change log they poll or long-poll with a cursor. Conflicts create a "conflicted copy" rather than silently overwriting.

Full answer

Requirements

Functional:

  • Upload, download, delete and rename files and folders from web, desktop and mobile.
  • Automatic sync of changes across a user's devices.
  • Share files and folders with other users; keep version history.

Non-functional:

  • Durability is the top priority: no file loss.
  • Large files (several GB) upload reliably on poor networks; only changed parts are sent again.
  • Sync changes appear on other devices within seconds.

Capacity estimates

Assumptions: 50M registered users, 10M DAU, 4 GB stored per user on average, 2 file changes per active user per day with average changed size 2 MB, 1,000 files per user, 500 bytes of metadata per file.

  • Logical storage: 50M x 4 GB = 200 PB before deduplication and replication. This rules out anything except object storage with erasure coding or replication.
  • Upload rate: 10M x 2 = 20M uploads per day = about 230 per second; bytes in: 20M x 2 MB = 40 TB per day, about 463 MB/s on average.
  • Metadata: 50M x 1,000 files = 50B file records x 500 B = 25 TB. Too big for one database, so shard metadata.

API

POST /v1/uploads {"path": "/notes/physics.pdf", "size": 52428800, "chunks": ["sha256:ab12...", "sha256:9f3c...", ...]} -> {"upload_id": "u1", "missing": ["sha256:9f3c..."], "urls": {"sha256:9f3c...": "<presigned PUT>"}} PUT <presigned URL> raw chunk bytes, straight to object storage POST /v1/uploads/u1/commit {"base_revision": 17} -> {"file_id": "f9", "revision": 18} or 409 if the base revision is stale GET /v1/files/f9?revision=18 -> chunk list with presigned GET URLs GET /v1/changes?cursor=... long-poll; returns changed entries and a new cursor

Data model

  • files: namespace_id (a user's root or a shared folder), file_id, path, latest_revision, is_deleted.
  • revisions: file_id, revision, chunk_hashes (ordered list), size, modified_by, created_at.
  • chunks: hash, size, ref_count, storage location.
  • journal: per namespace_id, an ordered log of changes (seq, file_id, revision) that devices read with a cursor.

Shard everything by namespace_id, so one folder tree's operations and its journal stay on one shard.

High-level design

mermaid
flowchart LR
  D[Desktop / mobile client] --> API[Metadata API]
  API --> MDB[(Sharded metadata DB)]
  API --> J[(Change journal)]
  D -- presigned PUT/GET --> OS[(Object storage: chunks)]
  API --> NS[Notification / long-poll service]
  NS --> D2[Other devices]
  OS --> CDN[CDN for downloads]

How sync works

  1. The client watches the local folder, splits changed files into 4 MB chunks, hashes each chunk.
  2. It sends the chunk list; the server replies with only the hashes it does not already have. Editing one page of a 50 MB PDF usually changes one or two chunks, so only those upload. Identical files from different users are stored once (deduplication), though some services limit cross-user dedup for privacy reasons.
  3. Chunks go directly to object storage using presigned URLs, so API servers never carry file bytes.
  4. Commit creates a new revision atomically, appends to the namespace journal, and wakes long-polling devices.
  5. Other devices fetch changes after their cursor, download missing chunks, and rebuild the file.

Conflicts

Commit includes base_revision. If another device committed first, the server returns 409 and the client saves its version as "physics (conflicted copy from Asha's laptop).pdf". Silent last-writer-wins would lose work.

Bottlenecks and trade-offs

  • Metadata hot spots: a folder shared with 10,000 people generates heavy reads; cache its listing and rate limit writes.
  • Garbage collection: deleted chunks are freed only when ref_count reaches zero and after the version retention window; run it as a careful background job.
  • Durability vs cost: erasure coding (for example 10 data + 4 parity fragments) stores 1.4x the data instead of 3x for triple replication, at the cost of more CPU and slower repair. Cold, rarely read versions can move to cheaper storage tiers.
  • Chunk size: smaller chunks improve dedup and resume granularity but increase metadata rows; fixed 4 MB is simple, content-defined chunking finds shared regions even when bytes shift.
  • Long-poll vs push: long-poll is simple and firewall friendly; mobile devices rely on push notifications to wake up.

By level

Fresher: Explain splitting files into chunks, storing them in object storage, keeping a metadata table, and notifying other devices of changes. A fresher should explain why only changed chunks are uploaded.

Mid: Estimate storage and metadata size, design the upload handshake and commit API, the revision and journal tables, and conflict handling. Expect conflict handling through a base revision check.

Senior: Cover sharding by namespace, shared folder hot spots, garbage collection, erasure coding versus replication cost, multi-region durability, and security of dedup and presigned URLs. The senior answer weighs erasure coding against replication cost.

Key points

  • Content-addressed chunks give dedup, resumable uploads and delta sync
  • Clients upload chunks straight to object storage with presigned URLs
  • Metadata (files, revisions, chunk lists, journal) is sharded by namespace
  • Devices sync by reading a per-namespace change journal with a cursor
  • Stale base revision on commit creates a conflicted copy instead of overwriting

Common mistakes

  • Sending file bytes through API servers
  • Re-uploading the whole file on every change
  • Last-writer-wins for conflicts
  • Keeping all metadata in one unsharded database at tens of terabytes

Follow-ups

  • How would you implement sharing a folder with another user's account?
  • How do you garbage collect chunks safely?
  • How would you support offline edits on mobile?

Tips

  • Separate the metadata path from the bytes path immediately
  • Show the "which chunks are missing?" handshake
  • State durability as the top non-functional requirement

Evaluation rubric

  • Clear functional and durability requirements
  • Storage and metadata math with assumptions
  • Chunking, dedup, journal-based sync and conflict handling
  • Trade-offs on storage cost, chunk size and notification method