CodeWithYash
DSA
Spring Boot
System Design
Series
Articles
Leaderboard
Sign In

Subscribe to Newsletter

Get the latest articles, DSA sheets, and system design challenges delivered to your inbox.

<CODEWITHYASH/>

The ultimate sanctuary for software engineers seeking deep mastery of core technical principles.

Library

  • Articles
  • DSA Sheets
  • Roadmaps

Connect

  • GitHub
  • LinkedIn
  • About
  • Contact

Legal

  • Privacy
  • Terms
  • Support

© 2026 CodeWithYash Global Systems.

Status: OperationalVersion: 4.2.0
System Design
OverviewTheory lessonsHLDLLD
All SeriesSeries
Distributed Systems
Back to System Design

Foundation · Interview method

Design from requirements, not from fashionable boxes

A repeatable 45-minute framework for clarifying a prompt, estimating scale, defining contracts and data, tracing the architecture, and defending it under failure.

Control the scope

Turn an ambiguous prompt into testable functional and quality requirements.

Justify each component

Use estimates and access patterns to decide when architecture must evolve.

Trace and defend

Walk through normal requests, failures, recovery, and the cost of every trade-off.

Treat the interview as a sequence of risk-reduction decisions

A system design interview is not a contest to draw the most boxes. The interviewer is evaluating whether you can turn an ambiguous product into explicit constraints, choose components for reasons, and discover where the design breaks. Begin with the simplest design that satisfies the stated requirements, then evolve it only when evidence exposes a limit.

  1. 01Clarify scope (3–5 minutes). Name the primary users, core actions, exclusions, and success criteria.
  2. 02Rank quality goals (2–3 minutes). Discuss availability, latency, durability, consistency, privacy, and cost. Rank them; “all of them” is not a trade-off.
  3. 03Estimate scale (5 minutes). Calculate peak reads and writes, stored bytes, bandwidth, object size, retention, and geographic distribution.
  4. 04Write the contract (5 minutes). Define APIs or events, identifiers, idempotency behavior, pagination, and important errors.
  5. 05Model the data (5 minutes). Identify entities, keys, access patterns, indexes, ownership, and consistency requirements.
  6. 06Draw and trace (10–15 minutes). Narrate one write, one read, and one failure through the architecture.
  7. 07Stress and evolve. Find the first bottleneck, mitigate it, and state the new cost and operational burden.

Do not solution before you know the problem

Starting with “use Kafka, Redis, and sharding” creates accidental requirements. A component is justified only when a stated access pattern, scale estimate, correctness rule, or failure mode requires it.

Active Recall Checkpoint

When should you introduce sharding in an interview design?

Hint: Name the measured or estimated limit first.

Show answer & explanation

Introduce it when one database cannot satisfy the estimated write rate, storage size, or operational isolation requirement. State the bottleneck, select a shard key from access patterns, and acknowledge cross-shard query and transaction costs.

Turn the product prompt into a testable contract

Separate functional requirements—what users can do—from non-functional requirements—how safely and quickly the system must do it. A useful requirement changes a design decision or can be verified. “Highly scalable” is not testable; “sustain 20,000 writes per second while keeping p99 latency below 200 ms” is.

QuestionWhy it changes the design
Who reads and writes?Defines authentication, tenancy, abuse controls, and traffic shape
What may be stale?Determines cache, replica, and consistency options
What may be lost?Determines durability, acknowledgement, and recovery requirements
What is the peak, not the average?Determines capacity, queues, and overload protection
Which operations must be ordered?Determines keys, partitions, and coordination scope
What is explicitly out of scope?Protects the interview from uncontrolled breadth

Use it when

Use a short requirement table when the prompt is broad or stakeholders value different outcomes.

Reconsider when

Do not spend ten minutes collecting every possible feature. Confirm the two or three flows that drive architecture, state exclusions, and proceed.

Estimate only what can change a decision

Back-of-the-envelope estimates establish order of magnitude. Write units on every value, keep one significant digit, distinguish average from peak, and explain the decision the estimate informs. Precision without defensible assumptions is false confidence.

EstimateUseful formulaDecision it informs
Average requests/smonthly operations ÷ seconds per monthBaseline service and database load
Peak requests/saverage × stated or assumed peak factorHeadroom, autoscaling, and overload policy
Storage/yearobjects/s × bytes/object × seconds/yearRetention, partitioning, and cost
Bandwidthresponses/s × response bytesNetwork, CDN, and fan-out pressure
Concurrent workarrival rate × average time in systemConnection pools, worker count, and queue bounds

Say what would invalidate the estimate

Traffic skew, a celebrity hot key, regional failover, large attachments, and retry amplification can dominate averages. State which assumption you would measure first in production.

Derive APIs and storage from access patterns

An API names the work the system promises; the data model makes its dominant access patterns efficient and its invariants enforceable. Define the contract before selecting a database brand. For each operation, write its key, query shape, result size, rate, latency goal, and consistency expectation.

access-pattern.txttext
Operation: getOrder(orderId)
Peak rate: 20,000 reads/second
Result size: under 20 KB
Latency objective: p99 under 80 ms
Consistency: read-your-writes for the buyer
Query shape: point lookup by primary key
Retention: seven years
  1. 01Choose identifiers and define whether clients may safely retry creation with an idempotency key.
  2. 02Use cursor pagination when results change while the client is paging; define the stable sort key.
  3. 03Enforce uniqueness and conditional state transitions in the authoritative write, not only in application memory.
  4. 04Add an index only for a named query and account for its storage and write amplification.
  5. 05Identify derived copies such as caches, search indexes, and feeds; define repair when an update is missed.

Trace normal work, then attack the weakest boundary

A diagram becomes a design only when you can narrate state changes through it. Trace a successful write, a successful read, and one dependency failure. At each hop, state ownership, timeout, retry behavior, persistence, and the signal that proves success.

BoundaryQuestions to ask
Client → edgeAuthentication, rate limit, request size, idempotency, timeout
Service → cacheSource of truth, stale-data limit, stampede behavior, outage fallback
Service → databaseTransaction boundary, index, isolation, pool limit, failover
Producer → queue/logAcknowledgement, ordering scope, duplicates, retention, backpressure
Region → regionReplication lag, RPO/RTO, fencing, conflict policy, failback

Every mitigation spends something

Replication spends money and consistency; retries spend downstream capacity; caching spends freshness and invalidation complexity; queues spend immediacy and operational effort. Name the cost immediately after the benefit.

Worked interview: design a URL shortener

Scope the first version to creating short links, redirecting a code, optional custom aliases, expiration, and asynchronous click analytics. Redirects are public; creation is authenticated and rate-limited. The mapping must never resolve to the wrong destination, while analytics may lag.

RequirementDecision
Redirect availabilityPrefer a bounded stale mapping over a failed redirect
Redirect latencyTarget p99 below 100 ms at the service boundary
Custom aliasEnforce uniqueness in the authoritative database
AnalyticsPublish asynchronously with at-least-once delivery and deduplication
Abuse responseAllow rapid disablement and cache invalidation

Assume 10 million new links per month and a 100:1 redirect-to-create ratio. That is roughly 4 creates/s and 400 redirects/s on average. Designing for a 10× peak gives 40 creates/s and 4,000 redirects/s. At about 500 bytes per mapping, one year adds roughly 60 GB before indexes and replicas. This estimate does not justify sharding on day one.

url-shortener.httphttp
1
2
3
4
5
6
7
8
9
10
11
12
POST /v1/links
Idempotency-Key: 0b8d...
Content-Type: application/json

{"url":"https://example.com/long/path","customAlias":"docs"}

201 {"code":"docs","shortUrl":"https://sho.rt/docs"}
409 when a requested custom alias already exists

GET /docs
302 Location: https://example.com/long/path
404 when absent; 410 when known but expired

Use 302 while destinations may change. Use 301 only when permanent intermediary and browser caching is intended. Store Link(code PK, destinationUrl, ownerId, createdAt, expiresAt, status) and add (ownerId, createdAt) only if owner-history queries are required.

  1. 01Create: authenticate, validate URL policy, rate-limit, check the idempotency key, generate a random code, insert with a unique constraint, then populate or invalidate cache after commit.
  2. 02Redirect: validate the path, check edge/service cache, read by primary key on miss, reject expired or disabled links, cache with a bounded TTL, and return the redirect.
  3. 03Analytics: publish a click event after deciding the redirect. Never make analytics part of the redirect’s success path.
  4. 04Hot link: serve from edge cache and coalesce misses; accept the invalidation and staleness cost.
  5. 05Primary failure: fence the old writer before promoting a replica; creation may pause while cached redirects remain available.

Active Recall Checkpoint

Why is a relational database a reasonable starting point here?

Show answer & explanation

The estimated write rate and storage fit one database, point lookup by code is easy to index, and a unique constraint provides correct custom-alias reservation. Sharding would add routing and migration complexity before an identified bottleneck requires it.

Close with evidence and interviewer follow-ups

Correctness

Which invariant prevents two meanings for one short code?

Scale

What changes first at one million redirects per second?

Consistency

How quickly must a disabled malicious link stop resolving?

Recovery

How are mappings restored and how is restore time verified?

Operations

Which metric proves the cache, database, and analytics pipeline are healthy?

Security

How are dangerous destinations, enumeration, and abusive creation controlled?

End by restating the most important trade-off and the first production measurement you would validate. A strong answer is explicit about uncertainty: it distinguishes what the requirements proved, what the estimates assumed, and what operational evidence would trigger the next architectural change.

Interview Playbook Pacer & Traps Tracker

Live Interview Time & Phase Coach

Pace your FAANG interview, evade examiner traps, and demonstrate staff-level insights.

00:00/ 45:00 minPhase 1 of 5

1. Clarify Scope & Requirements — 05:00 remaining in this phase

Target Outcome for 1. Clarify Scope & Requirements (0 - 5 min)

Establish functional & non-functional requirements, traffic shape, and explicit exclusions.

Examiner Traps (Common Mistakes That Fail Candidates)
  • ✗Jumping straight into drawing boxes before confirming what the system actually does.
  • ✗Accepting vague goals like "high availability" without quantifying target SLA (e.g. 99.99%) or p99 latency < 100ms.
  • ✗Failing to identify whether the system is read-heavy or write-heavy.
Senior / Staff Differentiators (Upleveling Signals)
  • ✓Proactively stating what is explicitly out-of-scope to protect interview time.
  • ✓Framing non-functional goals as trade-off priorities (e.g. AP over CP for social timelines; CP over AP for billing).
  • ✓Establishing multi-tenancy, data privacy (GDPR), and regulatory compliance boundaries upfront.
Back-of-the-Envelope Capacity Estimator

System Sizing & Scale Calculator

Compute QPS, bandwidth, replicated storage, and RAM caching requirements live.

300.0M
1M100M500M1B
100 : 1
2 KB
Retention Horizon5 Years
Query Throughput (QPS)Peak Multiplier: 3x
Average QPS

701.4Kreq/s

Reads: 694.4K/sWrites: 6.9K/s
Peak QPS (3x)

2.1Mreq/s

Peak Reads: 2.1M/sPeak Writes: 20.8K/s
Network Bandwidth
Peak Ingress (Writes)

41.67 MB/s

0.33 Gbps

Peak Egress (Reads)

4166.67 MB/s

33.33 Gbps

Total Storage Capacity5 Year Horizon
Raw Storage

1.9 PB

~398 TB / year

With 3x Replication

5.8 PB

3 Availability Zones / Replicas

Cache Memory Sizing (80/20 Rule)20% of Daily Unique Data
RAM Needed for Working Set

279 GB

Estimated Daily Unique Data: 1.1 TB

Includes 25% metadata and capacity headroom

Architectural Trade-Off Matrix

Architecture Decision Matrix

Multi-axis engineering evaluation and FAANG interview rules of thumb.

Option A

SQL (Postgres / MySQL)

Relational ACID Store

Structured schema, relational joins, ACID transactions, and strict foreign keys.

Option B

NoSQL (Cassandra / DynamoDB)

Distributed Non-Relational Store

Horizontal partition keys, denormalized documents/wide-columns, and tunable consistency.

Evaluation AxisSQL (Postgres / MySQL)NoSQL (Cassandra / DynamoDB)Details
Latency
Moderate Strong
Throughput
Moderate Strong
Scalability
Moderate Strong
Consistency
Strong Moderate
Complexity
Strong Moderate
Cost
Moderate Strong
FAANG Interview Rule of Thumb

When to Choose in an Architecture Interview

Pick SQL (Postgres / MySQL) If:

Choose SQL when ACID guarantees are non-negotiable (financial ledgers, payment processing, inventory checkout) or when query access patterns are unpredictable and require ad-hoc analytical joins.

Pick NoSQL (Cassandra / DynamoDB) If:

Choose NoSQL when write volume exceeds single-node capacity (>20K writes/sec), data is unstructured/hierarchical (logs, telemetry, user feeds), or multi-region active-active replication is mandatory.

Examiner Trap to Avoid:

Never say "NoSQL is faster than SQL" without qualification. SQL with proper B-Tree indexes on indexed primary keys is lightning fast. NoSQL wins on horizontal write scaling, not inherent single-row read speed.

Continue to load balancingContinue to caching