# System Design roadmap

> From latency numbers and load balancers to LLD, classic HLD case studies and cracking design rounds at Indian product companies.

Canonical: https://www.internhack.in/roadmaps/tracks/system-design
Last updated: 2026-11-28

13 sections, 57 topics, about 209 hours.

A complete system design roadmap for students and early-career engineers. Start with fundamentals: requirements, how requests travel over the internet, latency numbers and back-of-the-envelope estimation, then DNS, CDNs, load balancers and API gateways. Go deep on storage (SQL vs NoSQL, indexing, replication, sharding, consistency models, CAP and PACELC, object storage), caching and Redis, queues and Kafka, and distributed systems essentials such as consistent hashing, ID generation, consensus and sagas. Learn API design, rate limiting, idempotency, monolith vs microservices, reliability patterns, observability, availability targets and security basics. Then practise low-level design with SOLID, design patterns and classic problems like parking lot, BookMyShow and Splitwise, plus the machine coding round. Finish with classic HLD case studies (URL shortener, rate limiter, notifications, distributed cache, web crawler, autocomplete, WhatsApp, news feed, Hotstar streaming, Uber matching, UPI-style payments) and a practical framework for system design interviews at Flipkart, Swiggy, Razorpay and similar companies.

## Outcomes

- Turn vague product ideas into clear functional and non-functional requirements
- Estimate QPS, storage, bandwidth and cache size for a system in minutes
- Place DNS, CDNs, load balancers and API gateways correctly in an architecture
- Choose between relational and NoSQL stores and design indexes, replication and sharding
- Reason about consistency models, CAP and PACELC for each feature of a product
- Apply caching strategies with Redis while avoiding stampedes and stale data
- Use queues and Kafka with correct delivery guarantees, idempotent consumers and the outbox pattern
- Design clean APIs with pagination, rate limits, idempotency keys and safe retries
- Build reliable, observable services with circuit breakers, SLOs and disaster recovery plans
- Write extensible object-oriented designs using SOLID and design patterns, and pass machine coding rounds
- Design classic systems such as a URL shortener, chat app, news feed, streaming platform, ride matching and payments
- Run a structured system design interview and defend trade-offs under pushback

## Prerequisites

- Comfort with at least one programming language (Java, Python, Go, C++ or JavaScript)
- Basic understanding of how web apps and databases work
- Some experience building a small backend or full-stack project

## System Design Foundations

What system design is, how requests travel from a phone to a server and back, and the numbers you need to reason about scale.

### What System Design Is (HLD vs LLD)

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/system-design/what-is-system-design

Understand what system design means, the difference between high-level and low-level design, and how requirements drive every decision.

System design is the practice of deciding **which components a software system needs, how they talk to each other, and how data flows through them**, so that the system meets its requirements today and can grow tomorrow. There is rarely one right answer; there are trade-offs you can defend.

#### Two levels of design
- **High-level design (HLD)**: the big boxes. Clients, load balancers, services, databases, caches, queues, CDNs and how they connect. Questions like "how do we serve 10 crore users?" live here.
- **Low-level design (LLD)**: the inside of one box. Classes, interfaces, data models, APIs and design patterns. Questions like "design the classes for a parking lot" live here.

Product companies in India usually test both: an LLD or machine coding round for SDE-1 and SDE-2, and an HLD round that gets heavier as seniority grows.

#### Requirements come first
- **Functional requirements**: what the system does (users can shorten a URL, users can book a seat).
- **Non-functional requirements**: how well it does it. Latency, throughput, availability, durability, consistency, cost and security.
- **Constraints**: team size, budget, existing tech, regulation (for example RBI data localisation for payments).

A design that is perfect for a college fest app with 2,000 users is wrong for IRCTC Tatkal booking. Always ask "for how many users, how fast, and how correct?".

#### Pitfalls
- Jumping to "use Kafka and microservices" before writing down what the system must do.
- Treating system design as memorising famous architectures instead of reasoning from requirements.

You are ready to move on when you can take any app on your phone and list its top three functional requirements and top three non-functional requirements.

Key concepts: High-level design (HLD), Low-level design (LLD), Functional requirements, Non-functional requirements, Constraints and assumptions, Thinking in trade-offs.

Mini project: Pick three apps (for example Swiggy, IRCTC and Google Pay) and write a one-page requirements sheet for each: five functional requirements, five non-functional requirements with rough targets, and two constraints.

Self-check: Why might the right database for a ride-hailing app's trip history be different from the right database for its live driver locations?

Resources:
- [The System Design Primer](https://github.com/donnemartin/system-design-primer) (GitHub)
- [System Design Roadmap](https://roadmap.sh/system-design) (roadmap.sh)
- [ByteByteGo System Design 101](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)

### Client-Server Model and How the Internet Works

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/client-server-internet

Follow a request from a browser or mobile app through the network to a server and back, and learn the layers that make it possible.

Almost every system you will design is a **client-server** system. A client (browser, Android app, another service) sends a request; a server processes it and sends a response. Knowing what happens in between helps you reason about latency and failure.

#### The path of a request
1. The client resolves a domain name to an IP address using **DNS**.
2. It opens a **TCP** connection (a three-way handshake) and, for HTTPS, performs a **TLS** handshake.
3. It sends an **HTTP** request over that connection.
4. Packets hop across routers and ISPs using **IP**, possibly through a CDN or load balancer.
5. The server responds; the client renders or uses the data.

Every step adds round trips. A user in Patna talking to a server in Mumbai pays roughly 30 to 50 ms per round trip, and a fresh HTTPS connection can need three or four round trips before the first byte.

#### Layers worth knowing
- **IP**: addressing and routing, best effort delivery.
- **TCP**: reliable, ordered byte streams with congestion control. Used by HTTP/1.1 and HTTP/2.
- **UDP**: no handshake, no guarantees. Used by DNS, video calls, games and QUIC (HTTP/3).
- **TLS**: encryption and server identity on top of TCP.

#### Stateless vs stateful servers
A **stateless** server keeps no per-user memory between requests, so any instance can handle any request and you can scale by adding instances. Session data then lives in a shared store such as Redis or a database. Stateful servers (WebSocket chat servers, game servers) are harder to scale and need sticky routing.

#### Pitfalls
- Ignoring the cost of new connections; connection reuse and keep-alive matter at scale.
- Assuming the network is reliable. Packets drop, connections reset and timeouts happen.

You are ready to move on when you can explain every step between typing a URL and seeing the page, and say which steps add latency.

Key concepts: Client-server model, IP, TCP and UDP, TLS handshake, Round trips and network latency, Stateless vs stateful servers, OSI vs TCP/IP model.

Mini project: Use curl with timing output (curl -w) against five websites hosted in different regions and record DNS, connect, TLS and first-byte times. Write a short note explaining which phase dominates and why.

Self-check: Why does making a web server stateless make horizontal scaling easier, and where does the session data go instead?

Resources:
- [Cloudflare Learning Center](https://www.cloudflare.com/learning/) (Cloudflare)
- [High Performance Browser Networking](https://hpbn.co/) (Ilya Grigorik)
- [An overview of HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview) (MDN)

### HTTP, Connections and Real-Time Protocols

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/http-for-system-design

Learn the HTTP features that shape system design (methods, status codes, caching headers, HTTP/2 and HTTP/3) and the options for real-time push.

HTTP is the language most of your components will speak, so its details show up in every design discussion.

#### The parts that matter for design
- **Methods**: GET is safe and should be cacheable; PUT and DELETE are idempotent; POST is neither by default. This drives retries and caching.
- **Status codes**: 2xx success, 3xx redirect (a URL shortener lives on 301 vs 302), 4xx client error (429 means rate limited), 5xx server error (retry candidates).
- **Headers**: Cache-Control, ETag and Last-Modified for caching; Authorization for identity; Idempotency-Key for safe retries.

#### Versions
- **HTTP/1.1**: one request at a time per connection, so browsers open several connections.
- **HTTP/2**: many streams multiplexed over one TCP connection, header compression. Head-of-line blocking still exists at the TCP layer.
- **HTTP/3**: runs on QUIC over UDP, avoids TCP head-of-line blocking and handles network switches (Wi-Fi to 4G) better.

#### Getting data to clients in real time
- **Short polling**: client asks every few seconds. Simple, wasteful.
- **Long polling**: server holds the request until there is news. Works everywhere.
- **Server-Sent Events (SSE)**: one-way stream from server to client over HTTP. Good for live scores and notifications.
- **WebSockets**: full duplex, persistent connection. Used for chat, multiplayer and trading screens.

Persistent connections change your scaling story: a server may hold lakhs of open sockets, and you need a way to route a message to whichever server holds the recipient's connection.

#### Pitfalls
- Using POST for everything and losing caching and safe retries.
- Choosing WebSockets when SSE or polling every 30 seconds would do.

You are ready to move on when you can pick between polling, SSE and WebSockets for a cricket score app, a chat app and an order tracking page, with a reason for each.

Key concepts: Methods, safety and idempotency, Status codes that matter, Caching headers, HTTP/2 and HTTP/3, Long polling, Server-Sent Events, WebSockets.

Mini project: Build a tiny server that pushes a live counter to the browser three ways (polling, SSE and WebSocket). Measure requests per minute for each with 10 open tabs and write down the trade-offs.

Self-check: Why is it safe for a client to retry a timed-out PUT but risky to retry a timed-out POST that creates an order?

Resources:
- [MDN HTTP documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP) (MDN)
- [The WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) (MDN)
- [RFC 9110: HTTP Semantics](https://datatracker.ietf.org/doc/html/rfc9110) (IETF)

### Latency Numbers and Performance Metrics

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/system-design/latency-numbers

Memorise the rough cost of memory, disk, network and cross-region calls, and learn to talk about latency, throughput and percentiles.

Good designers carry a rough mental table of how long things take. You do not need exact values; you need the **orders of magnitude**.

#### Numbers to remember (approximate)
- L1 cache reference: about 1 ns
- Main memory reference: about 100 ns
- Read 1 MB sequentially from memory: about 10 to 50 microseconds
- SSD random read: about 100 microseconds
- Round trip inside one data centre: about 0.5 ms
- Read 1 MB sequentially from SSD: about 1 ms
- HDD seek: about 10 ms
- Round trip Mumbai to Singapore: about 60 ms; Mumbai to US East: about 200 ms

The lessons: memory is far faster than disk, disk is faster than crossing the planet, and **network round trips usually dominate**. Batch calls, cache hot data in memory and keep chatty services close together.

#### Metrics you will use
- **Latency**: time for one request. Always discuss **percentiles** (p50, p95, p99), not averages. One slow dependency can make p99 terrible while the average looks fine.
- **Throughput**: requests or bytes handled per second (QPS, RPS).
- **Utilisation and saturation**: how busy a resource is and whether work is queuing.
- **Little's law**: items in the system = arrival rate x time in system. Useful for sizing thread pools and queues.

#### Tail latency
If a page calls 20 services in parallel, it is as slow as the slowest one. With fan-out, rare slow responses become common for the user. Techniques like timeouts, hedged requests and caching protect the tail.

#### Pitfalls
- Quoting average latency in an interview; interviewers expect p99.
- Optimising CPU code while the request makes five sequential network calls.

You are ready to move on when you can estimate, without looking anything up, whether reading 1 GB from SSD or fetching 1 KB from another continent is slower, and explain p99.

Key concepts: Memory vs disk vs network costs, Latency percentiles (p50, p95, p99), Throughput and QPS, Tail latency and fan-out, Little's law, Hedged requests.

Mini project: Write a script that calls a public API 500 times and prints p50, p95, p99 and max latency. Then add an in-memory cache and compare the distribution before and after.

Self-check: A service has 50 ms average latency but 2 s p99. A page fans out to 10 such calls in parallel. Roughly how often will a user see a slow page?

Resources:
- [Latency numbers every programmer should know](https://gist.github.com/jboner/2841832) (GitHub Gist)
- [Interactive latency numbers by year](https://colin-scott.github.io/personal_website/research/interactive_latency.html) (Colin Scott)
- [Little's law](https://en.wikipedia.org/wiki/Little%27s_law) (Wikipedia)

### Back-of-the-Envelope Estimation

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/back-of-envelope-estimation

Estimate QPS, storage, bandwidth and server counts from user numbers, so your design is sized to reality instead of guesses.

Before drawing boxes, size the problem. Estimation tells you whether one Postgres box is enough or whether you need sharding, and it shows interviewers you think in numbers.

#### Handy conversions
- 1 day is about 86,400 seconds; round it to **100,000 (10^5)** for quick maths.
- 1 million requests per day is roughly **12 QPS**. 1 crore (10 million) per day is about 120 QPS.
- Peak traffic is often **2x to 10x** the average (IPL finals, Big Billion Days, Tatkal at 10 AM).
- 1 KB x 1 million = 1 GB; 1 MB x 1 million = 1 TB.

#### A standard flow
1. **Users**: daily active users (DAU) and actions per user per day.
2. **QPS**: DAU x actions / 10^5, then multiply for peak. Split read vs write QPS.
3. **Storage**: writes per day x size per record x retention (years x 365). Add replication (usually 3x).
4. **Bandwidth**: QPS x response size.
5. **Memory for cache**: often the 80/20 rule, caching around 20 percent of daily read data.
6. **Servers**: peak QPS / QPS one server handles (a few thousand simple requests per second is a fair rough guess).

#### Worked example: a URL shortener
100 million new URLs per month is about 40 writes per second. With a 100:1 read ratio, that is about 4,000 reads per second. At 500 bytes per record over 5 years: 100M x 12 x 5 x 500 B, about 3 TB. That fits in a sharded or even a large single database with replicas, and a Redis cache of hot links handles the reads.

#### Pitfalls
- Spending ten minutes on exact arithmetic. Round aggressively and state assumptions out loud.
- Forgetting peak traffic and replication overhead.
- Estimating and then never using the numbers to make a decision.

You are ready to move on when you can size QPS, storage and cache memory for a photo sharing app in under five minutes on paper.

Key concepts: DAU to QPS conversion, Peak vs average traffic, Storage estimation, Bandwidth estimation, Cache sizing (80/20 rule), Server count estimation, Powers of two and ten.

Mini project: Write estimation sheets for three systems (Instagram-style photo feed, WhatsApp-style chat, Zomato-style restaurant search) covering QPS, peak QPS, 5-year storage, bandwidth and cache memory, with every assumption written down.

Self-check: A chat app has 50 million DAU sending 40 messages each per day, 200 bytes per message. Estimate average write QPS and one year of storage before replication.

Resources:
- [System Design Primer: back-of-the-envelope appendix](https://github.com/donnemartin/system-design-primer) (GitHub)
- [ByteByteGo System Design 101](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)
- [ByteByteGo YouTube channel](https://www.youtube.com/@ByteByteGo) (YouTube)

## DNS, CDNs, Load Balancers and Gateways

The components that sit between users and your services: name resolution, edge caching, traffic distribution and API gateways.

### DNS in System Design

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/system-design/dns

Learn how DNS resolution works, how TTLs and record types affect failover, and how DNS is used for geo routing and load distribution.

DNS turns names like api.example.in into IP addresses. It is also one of the first levers you have for routing users and surviving outages.

#### How resolution works
The client asks a **recursive resolver** (your ISP, 8.8.8.8 or 1.1.1.1). If it has no cached answer, it walks the hierarchy: **root servers**, then the **TLD** servers for .in or .com, then the domain's **authoritative** name servers. Answers are cached at every level for the record's **TTL**.

#### Record types you will use
- **A / AAAA**: name to IPv4 / IPv6 address.
- **CNAME**: alias to another name (common for CDNs and managed load balancers).
- **NS**: which servers are authoritative for a zone.
- **MX** and **TXT**: mail routing and verification (SPF, DKIM, domain ownership).

#### DNS as a routing tool
- **Round-robin DNS**: return several IPs and let clients spread out. Crude; no health awareness.
- **Geo DNS / latency-based routing**: send users in Chennai to the Mumbai region and users in Europe to Frankfurt.
- **Weighted routing**: send 5 percent of traffic to a new region for a canary.
- **Health-checked failover**: managed DNS (Route 53, Cloudflare) stops returning a dead region's IP.

#### TTL trade-offs
Low TTLs (30 to 60 s) allow fast failover but cause more lookups. High TTLs reduce load and latency but mean clients keep using a dead IP for longer. Some clients and resolvers ignore TTLs entirely, so DNS failover is never instant.

#### Pitfalls
- Relying on DNS alone for fast failover.
- Forgetting that DNS itself can be a single point of failure; use a provider with anycast and redundancy.

You are ready to move on when you can explain the full lookup chain and choose a TTL for a service that must fail over between regions.

Key concepts: Recursive vs authoritative resolvers, Record types (A, CNAME, NS, TXT), TTL and caching, Geo and latency-based routing, Weighted and failover routing, Anycast.

Mini project: Use dig to trace the full resolution of three domains (dig +trace), note each hop and TTL, and write a one-page plan for routing users of a two-region app using geo DNS with health checks.

Self-check: Your Mumbai region goes down and DNS failover kicks in, yet some users still fail for 10 minutes. Give two reasons why.

Resources:
- [What is DNS?](https://www.cloudflare.com/learning/dns/what-is-dns/) (Cloudflare)
- [Amazon Route 53 routing policies](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html) (AWS)
- [The System Design Primer: DNS](https://github.com/donnemartin/system-design-primer) (GitHub)

### Content Delivery Networks (CDNs)

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/system-design/cdn

Use CDNs to serve static and media content from edge locations close to users, and understand push vs pull CDNs, cache keys and invalidation.

A **CDN** is a network of edge servers spread across cities. Users fetch content from the nearest edge instead of your origin server, which cuts latency and offloads huge amounts of traffic. Hotstar streaming a cricket final to crores of viewers is only possible because of CDNs.

#### What to put on a CDN
- Static assets: JS, CSS, fonts, images.
- Media: video segments, thumbnails, downloadable files.
- Cacheable API responses: product catalogue pages, public config.
- Increasingly, edge compute: redirects, A/B routing, auth checks at the edge.

#### Pull vs push
- **Pull CDN**: the edge fetches from your origin on the first miss, then caches per the Cache-Control headers. Easy to set up; first users pay the miss.
- **Push CDN**: you upload content ahead of time. Good for large, predictable files such as a new episode release.

#### Cache keys and invalidation
The edge caches by a **cache key** (usually URL plus some headers). Include only what really changes the response; adding cookies to the key destroys the hit ratio. For updates, prefer **versioned file names** (app.3f9c1.js) over purge requests: a new name is a guaranteed miss, while purges take time to propagate.

#### Origin protection
A **shield** or mid-tier cache sits between edges and your origin, so a cache miss storm from 200 edges becomes one request to origin. Combine with request collapsing for hot objects.

#### Pitfalls
- Caching personalised responses publicly and leaking one user's data to another.
- Long TTLs on files whose names never change, so fixes never reach users.

You are ready to move on when you can explain how a CDN would serve product images for a Flipkart sale, including cache keys, TTLs and how a changed image reaches users.

Key concepts: Edge locations and PoPs, Pull vs push CDN, Cache keys and Cache-Control, Versioned assets vs purging, Origin shield and request collapsing, Edge compute.

Mini project: Put a small static site behind a free CDN tier, set different Cache-Control headers on HTML and hashed assets, and use response headers to show hits vs misses. Document what changes when you redeploy.

Self-check: Why is renaming a file (app.v2.js) usually a better way to update cached content than sending a purge request?

Resources:
- [What is a CDN?](https://www.cloudflare.com/learning/cdn/what-is-a-cdn/) (Cloudflare)
- [HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching) (MDN)
- [Netflix Open Connect](https://openconnect.netflix.com/) (Netflix)

### Load Balancing

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/load-balancing

Distribute traffic across servers with L4 and L7 load balancers, choose balancing algorithms, and use health checks to route around failures.

A **load balancer (LB)** spreads incoming requests across a pool of servers so no single machine is overwhelmed, and it removes unhealthy servers from rotation. It is the component that turns "one server" into "a fleet".

#### L4 vs L7
- **Layer 4** balancers route by IP and port without reading the request. Very fast, protocol agnostic. Example: AWS NLB.
- **Layer 7** balancers understand HTTP. They can route by path or header (/api to one pool, /images to another), terminate TLS, add headers and retry. Examples: Nginx, HAProxy, Envoy, AWS ALB.

#### Algorithms
- **Round robin** and **weighted round robin**: simple and fair when requests cost about the same.
- **Least connections** / **least outstanding requests**: better when request costs vary.
- **IP hash / consistent hashing**: the same client or key goes to the same server. Useful for caches and sticky sessions.
- **Power of two choices**: pick two random servers, send to the less loaded one. Cheap and surprisingly good.

#### Health checks and failure
Active checks (hit /health every few seconds) and passive checks (watch for errors) decide who stays in the pool. Make health checks meaningful but cheap: a check that queries the database can take down the whole fleet when the database is slow.

#### Avoiding the LB as a single point of failure
Run LBs in pairs (active-passive with a floating IP, or active-active behind DNS or anycast). Managed cloud LBs handle this for you.

#### Sticky sessions
Pinning a user to one server makes stateful apps work but hurts even distribution and failover. Prefer stateless servers with session data in Redis.

#### Pitfalls
- Deep health checks that cascade failures.
- Forgetting that WebSocket connections are long-lived, so round robin at connect time can leave servers unbalanced.

You are ready to move on when you can choose L4 or L7 and a balancing algorithm for a REST API, a WebSocket chat service and a cache cluster.

Key concepts: L4 vs L7 load balancing, Round robin and weighted, Least connections, Consistent hashing based routing, Health checks, Sticky sessions, LB redundancy, Power of two choices.

Mini project: Run three copies of a small API behind Nginx or HAProxy in Docker. Try round robin and least connections, kill one container, and record how quickly the balancer stops sending it traffic.

Self-check: Why can a health check that queries the database make an outage worse during a database slowdown?

Resources:
- [What is load balancing?](https://www.cloudflare.com/learning/performance/what-is-load-balancing/) (Cloudflare)
- [NGINX documentation](https://nginx.org/en/docs/) (NGINX)
- [Envoy proxy documentation](https://www.envoyproxy.io/docs) (Envoy)
- [The System Design Primer: load balancer](https://github.com/donnemartin/system-design-primer) (GitHub)

### Reverse Proxies and API Gateways

core · intermediate · about 2 h · https://www.internhack.in/roadmaps/tracks/system-design/proxies-and-api-gateways

Understand forward vs reverse proxies and what an API gateway adds: routing, auth, rate limiting, request shaping and a single entry point.

A **forward proxy** acts on behalf of clients (a corporate proxy that filters browsing). A **reverse proxy** acts on behalf of servers: clients talk to it, and it forwards to backends. Load balancers are a kind of reverse proxy; so are API gateways.

#### What a reverse proxy gives you
- TLS termination in one place.
- Compression, response caching and serving static files.
- Hiding internal topology; backends are not exposed to the internet.
- Buffering slow clients so app servers are not tied up.

#### API gateway responsibilities
In a system with many services, an **API gateway** is the single front door:
- **Routing**: /orders to the order service, /payments to the payment service.
- **Authentication**: validate JWTs or API keys once, pass identity downstream.
- **Rate limiting and quotas** per user, API key or IP.
- **Request and response transformation**, API versioning and aggregation.
- **Observability**: one place for access logs, metrics and trace IDs.

Popular choices: Kong, AWS API Gateway, Envoy based gateways, Nginx, and Spring Cloud Gateway in Java shops.

#### Backend for Frontend (BFF)
Mobile and web clients often need differently shaped data. A **BFF** is a thin gateway per client type that aggregates calls, so the Android app makes one request instead of six.

#### Pitfalls
- Putting business logic in the gateway until it becomes a hidden monolith.
- A single gateway cluster with no redundancy: it is now your biggest single point of failure.
- Adding a gateway hop for a two-service system that does not need it.

You are ready to move on when you can sketch where the gateway sits in a food delivery app, list what it should and should not do, and explain how it differs from a plain load balancer.

Key concepts: Forward vs reverse proxy, TLS termination, API gateway routing and auth, Rate limiting at the edge, Backend for Frontend (BFF), Kong, Envoy, AWS API Gateway.

Mini project: Put Nginx or Kong in front of two small services, route by path, terminate TLS with a self-signed certificate, and add a per-IP rate limit. Document the config and what happens when one backend is down.

Self-check: List three responsibilities that belong in an API gateway and two that should stay inside the services, with a reason for each.

Resources:
- [What is a reverse proxy?](https://www.cloudflare.com/learning/cdn/glossary/reverse-proxy/) (Cloudflare)
- [API gateway pattern](https://microservices.io/patterns/apigateway.html) (microservices.io)
- [Kong Gateway documentation](https://docs.konghq.com/) (Kong)

## Data Storage and Databases

Choosing and scaling databases: relational vs NoSQL, indexing, replication, sharding, consistency models and object storage.

### Relational Databases and SQL for Design

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/relational-databases

Know what relational databases guarantee (schemas, joins, ACID transactions, isolation levels) and why they are the default choice for most systems.

Relational databases such as PostgreSQL and MySQL store data in tables with a fixed schema and let you query it with SQL. For most products, a well-tuned relational database is the right starting point; Razorpay, Zerodha and countless startups run core money flows on them.

#### What you get
- **Schema and constraints**: types, NOT NULL, UNIQUE, foreign keys. The database protects data quality for you.
- **Joins and flexible queries**: you can answer questions you did not plan for.
- **ACID transactions**: Atomicity (all or nothing), Consistency (constraints hold), Isolation (concurrent transactions do not see each other's half work), Durability (committed data survives a crash, thanks to the write-ahead log).

#### Isolation levels
- **Read committed** (Postgres default): no dirty reads, but a row can change between two reads in the same transaction.
- **Repeatable read / snapshot isolation**: a consistent snapshot for the whole transaction.
- **Serializable**: as if transactions ran one at a time; safest, with more aborts to retry.
Know the classic anomalies: dirty read, non-repeatable read, phantom read, lost update and write skew. Booking the last seat twice is a lost update problem.

#### Concurrency tools
- **Pessimistic locking**: SELECT ... FOR UPDATE holds a row lock while you decide.
- **Optimistic locking**: a version column; the update fails if someone else changed the row first.

#### Normalisation vs denormalisation
Normalise to avoid duplicate, inconsistent data. Denormalise selectively (store order_total, or a copy of the restaurant name on the order) when read speed matters more than write simplicity.

#### Pitfalls
- Leaving everything at default isolation and assuming money transfers are safe.
- Reaching for NoSQL "for scale" when a single Postgres with read replicas would serve years of growth.

You are ready to move on when you can explain ACID, name the isolation level that prevents double booking, and write a transaction that moves money between two accounts safely.

Key concepts: Tables, schemas and constraints, ACID transactions, Isolation levels and anomalies, Pessimistic vs optimistic locking, Normalisation and denormalisation, Write-ahead log, PostgreSQL vs MySQL.

Mini project: Model a wallet with accounts and transfers in PostgreSQL. Write a transfer function, then run 100 concurrent transfers with a script and show that balances stay correct with proper locking and break without it.

Self-check: Two users try to book the last seat at the same time. Describe one pessimistic and one optimistic way to make sure only one succeeds.

Resources:
- [PostgreSQL documentation](https://www.postgresql.org/docs/current/) (PostgreSQL)
- [PostgreSQL transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html) (PostgreSQL)
- [Designing Data-Intensive Applications](https://dataintensive.net/) (Martin Kleppmann)

### NoSQL Data Models and When to Use Them

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/nosql-data-models

Compare key-value, document, wide-column, graph and time-series stores, and learn to pick a data store from access patterns rather than hype.

"NoSQL" covers several very different families. Each trades some relational features for scale, flexibility or speed on a particular access pattern.

#### The families
- **Key-value** (Redis, DynamoDB, etcd): get and put by key. Extremely fast and easy to scale. Sessions, carts, feature flags, counters.
- **Document** (MongoDB, Couchbase): JSON-like documents with flexible fields. Good for product catalogues and user profiles that vary in shape.
- **Wide-column** (Cassandra, ScyllaDB, HBase, Bigtable): rows grouped by a partition key, sorted by clustering key. Built for huge write volumes: chat messages, IoT data, activity logs. Discord moved billions of messages to this model.
- **Graph** (Neo4j, Neptune): nodes and edges with fast traversals. Friend-of-friend recommendations, fraud rings.
- **Time-series** (InfluxDB, TimescaleDB, Prometheus): append-heavy metrics with time-based queries and downsampling.
- **Search engines** (Elasticsearch, OpenSearch): inverted indexes for full-text search and filters.

#### Design from access patterns
In relational design you model entities first and query later. In most NoSQL stores you **list the queries first** and shape tables to answer each one with a single key lookup or partition scan. Joins usually move into the application or are avoided by duplicating data.

#### Choosing in practice
Start with: Do I need multi-row transactions and ad hoc queries? (Relational.) Is the write volume massive and the query pattern fixed? (Wide-column.) Is it a simple lookup by ID at very high QPS? (Key-value.) Many real systems use **polyglot persistence**: Postgres for orders, Redis for sessions, Elasticsearch for search, S3 for images.

#### Pitfalls
- Choosing MongoDB to avoid "designing a schema"; the schema just moves into code.
- Picking a bad partition key in Cassandra or DynamoDB and creating hot partitions.

You are ready to move on when you can map five features of a food delivery app to a store type and justify each choice from its access pattern.

Key concepts: Key-value stores, Document databases, Wide-column stores, Graph databases, Time-series databases, Search engines (inverted index), Access-pattern driven modelling, Polyglot persistence.

Mini project: Design the tables for a chat app's messages in both PostgreSQL and Cassandra (or DynamoDB). For each, write the three main queries and explain which store handles 1 lakh writes per second more easily and why.

Self-check: Why do wide-column databases ask you to design tables around queries instead of entities?

Resources:
- [MongoDB manual](https://www.mongodb.com/docs/manual/) (MongoDB)
- [Apache Cassandra documentation](https://cassandra.apache.org/doc/latest/) (Apache)
- [What is Amazon DynamoDB?](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) (AWS)
- [How Discord stores trillions of messages](https://discord.com/blog/how-discord-stores-trillions-of-messages) (Discord)

### Indexes and Storage Engines

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/indexing

Learn how B-tree and LSM-tree indexes work, what composite and covering indexes do, and how indexes trade write cost for read speed.

Without an index, a database scans every row. With the right index, it jumps straight to the data. Index choices are some of the highest leverage decisions in a design.

#### B-trees
The default in PostgreSQL and MySQL. A balanced tree of pages keeps keys sorted, so lookups, range scans and ORDER BY are fast (logarithmic). Each write must update every index on the table, so more indexes mean slower inserts.

#### LSM trees
Used by Cassandra, RocksDB, ScyllaDB and many NoSQL stores. Writes go to an in-memory table and are flushed as sorted, immutable files that are merged in the background (**compaction**). Writes are very fast and sequential; reads may check several files, helped by **Bloom filters** that say "definitely not here".

#### Index types to know
- **Composite index** on (user_id, created_at): serves "latest orders for a user". Column order matters; the index helps queries that filter on the leftmost columns.
- **Covering index**: contains every column the query needs, so the table is never touched.
- **Unique index**: enforces uniqueness (one account per phone number).
- **Hash, GIN, GiST** and full-text indexes for special cases (equality only, JSON and arrays, geo data, text search).
- **Secondary indexes** in distributed databases can be local (per shard) or global, with very different costs.

#### Reading query plans
Use EXPLAIN ANALYZE to see whether a query uses an index or does a sequential scan. Low-selectivity columns (a boolean is_active) rarely benefit from their own index.

#### Pitfalls
- Indexing every column "just in case" and tanking write throughput.
- Wrapping an indexed column in a function (WHERE lower(email) = ...) and silently losing the index.
- Wrong column order in composite indexes.

You are ready to move on when you can design the indexes for an orders table given its three most common queries and read an EXPLAIN plan to confirm they are used.

Key concepts: B-tree indexes, LSM trees and compaction, Composite index column order, Covering indexes, Bloom filters, EXPLAIN ANALYZE, Local vs global secondary indexes.

Mini project: Load 5 million fake orders into PostgreSQL. Time three queries with no indexes, then add the right composite and covering indexes, and record the speedup and the change in bulk insert time.

Self-check: You have an index on (city, created_at). Will it help a query that filters only on created_at? Why or why not?

Resources:
- [Use The Index, Luke](https://use-the-index-luke.com/) (Markus Winand)
- [PostgreSQL indexes](https://www.postgresql.org/docs/current/indexes.html) (PostgreSQL)
- [Bloom filter](https://en.wikipedia.org/wiki/Bloom_filter) (Wikipedia)

### Replication

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/replication

Keep copies of data on several machines for availability and read scaling, and understand leader-follower, multi-leader and leaderless replication and their lag problems.

**Replication** keeps the same data on multiple nodes. It gives you fault tolerance (a node can die without data loss), read scaling (spread reads across replicas) and lower latency (replicas near users).

#### Leader-follower (primary-replica)
All writes go to one **leader**, which streams changes to **followers**. Reads can go to followers. This is how most Postgres and MySQL setups work.
- **Synchronous** replication waits for a follower to confirm before acknowledging: no data loss on failover, higher write latency.
- **Asynchronous** replication acknowledges immediately: fast, but recent writes can be lost if the leader dies.
- Many systems use **semi-synchronous**: one sync follower, the rest async.

#### Replication lag problems
- **Read-your-writes**: a user updates their profile, refreshes, and sees the old value from a lagging replica. Fix by reading from the leader for a short window after a write, or for that user's own data.
- **Monotonic reads**: a user sees new data, then old data on the next request. Pin a user to one replica.
- **Consistent prefix**: a reply appears before the question. Keep causally related writes in one partition.

#### Failover
When the leader dies, a follower is promoted. Dangers: losing async writes, and **split brain** where two nodes both think they are leader. Use a consensus-based coordinator or managed service for safe promotion.

#### Multi-leader and leaderless
- **Multi-leader**: each region accepts writes and syncs with others. Good for multi-region apps, but you must resolve **write conflicts** (last write wins, merge logic, CRDTs).
- **Leaderless** (Dynamo style, Cassandra): clients write to several replicas and read from several. With N replicas, write quorum W and read quorum R, **W + R > N** gives overlapping reads and writes.

#### Pitfalls
- Sending reads to replicas without handling read-your-writes.
- Treating replication as a backup. A bad DELETE replicates instantly; you still need backups.

You are ready to move on when you can explain sync vs async replication, describe one replication lag bug and its fix, and compute whether N=3, W=2, R=2 gives overlapping quorums.

Key concepts: Leader-follower replication, Sync vs async replication, Replication lag anomalies, Failover and split brain, Multi-leader replication, Leaderless and quorums, Conflict resolution and CRDTs.

Mini project: Set up a PostgreSQL primary with one streaming replica in Docker. Write to the primary and read from the replica in a loop to observe lag, then stop the primary and promote the replica, documenting what was lost.

Self-check: A user changes their delivery address and the checkout page still shows the old one. What replication issue is this and how would you fix it?

Resources:
- [PostgreSQL high availability and replication](https://www.postgresql.org/docs/current/high-availability.html) (PostgreSQL)
- [Amazon's Dynamo](https://www.allthingsdistributed.com/2007/10/amazons_dynamo.html) (All Things Distributed)
- [Designing Data-Intensive Applications](https://dataintensive.net/) (Martin Kleppmann)

### Sharding and Partitioning

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/sharding-partitioning

Split data across machines when one node is not enough, choose shard keys wisely, and handle hot spots, rebalancing and cross-shard queries.

When data or write traffic outgrows one machine, you **partition** (shard) it: each node holds a subset of the data. Replication copies data; sharding splits it. Real systems do both.

#### Strategies
- **Range-based**: users A to F on shard 1, G to M on shard 2, or orders by date. Range scans are easy, but ranges can get hot (everyone writes "today").
- **Hash-based**: shard = hash(key) mod N. Spreads load evenly, kills range queries, and naive mod N reshuffles almost everything when N changes.
- **Consistent hashing**: only a small fraction of keys move when nodes join or leave (covered in its own topic).
- **Directory-based**: a lookup service maps keys to shards. Flexible, but the directory is one more critical component.
- **Geo-based**: Indian users' data in the Mumbai cluster, EU users' data in Frankfurt, useful for data residency rules.

#### Choosing a shard key
A good shard key has **high cardinality**, spreads writes evenly, and keeps data that is queried together on the same shard. For a chat app, conversation_id keeps one chat's messages together. For an e-commerce order system, user_id makes "my orders" a single-shard query but "all orders for seller X" a scatter-gather.

#### Hard parts
- **Hot keys**: a celebrity account or a viral product overloads one shard. Mitigate with key salting, splitting hot keys or caching.
- **Cross-shard queries and joins**: scatter-gather to every shard is slow; denormalise or maintain a secondary index.
- **Cross-shard transactions**: avoid where possible, or use sagas.
- **Rebalancing**: use many small virtual shards mapped to fewer physical nodes so you can move shards, not rows.

Tools like Vitess (MySQL), Citus (Postgres), and built-in partitioning in Cassandra, MongoDB and DynamoDB handle much of this.

#### Pitfalls
- Sharding too early. Vertical scaling, read replicas and caching often buy years.
- Using a monotonically increasing ID or timestamp as a hash-free range key and sending all writes to the last shard.

You are ready to move on when you can pick a shard key for Instagram posts, explain the queries it makes easy and hard, and describe how you would handle a celebrity hot spot.

Key concepts: Vertical vs horizontal scaling, Range-based partitioning, Hash-based partitioning, Directory-based sharding, Choosing a shard key, Hot keys and salting, Rebalancing with virtual shards, Vitess and Citus.

Mini project: Write a small router library that sends reads and writes to one of four SQLite or Postgres databases by hashing user_id. Then simulate adding a fifth shard with naive mod N and measure what fraction of keys must move.

Self-check: Why is created_at a poor shard key for an orders table, and what would you choose instead?

Resources:
- [The System Design Primer: sharding](https://github.com/donnemartin/system-design-primer) (GitHub)
- [Vitess documentation](https://vitess.io/docs/) (Vitess)
- [DynamoDB partition key design](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html) (AWS)

### Consistency Models, CAP and PACELC

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/consistency-cap-pacelc

Understand strong, eventual and causal consistency, what the CAP theorem really says, and how PACELC adds the everyday latency trade-off.

Once data lives on several machines, you must decide what readers are allowed to see while updates propagate. That decision is your **consistency model**.

#### Consistency models, strongest to weakest
- **Linearizable (strong)**: every read sees the latest committed write, as if there were one copy. Needed for bank balances, seat inventory, unique usernames.
- **Sequential / causal**: everyone sees causally related events in order (a reply never appears before its message).
- **Read-your-writes, monotonic reads**: session-level guarantees that make apps feel sane.
- **Eventual**: if writes stop, replicas converge eventually. Fine for like counts, view counts and feeds.

#### CAP theorem
In a distributed system, when a **network Partition** happens you must choose between **Consistency** (refuse or delay requests that cannot see the latest data) and **Availability** (answer anyway, maybe with stale data). You cannot give up P in a real network, so the real choice is **CP vs AP during a partition**.
- CP examples: ZooKeeper, etcd, a single-leader SQL database, HBase.
- AP examples: Cassandra and DynamoDB in their default modes, DNS.

#### PACELC
CAP only talks about failures. PACELC adds: **Else (no partition), choose Latency or Consistency**. Even on a healthy day, waiting for replicas to agree costs time. Cassandra is PA/EL; a synchronously replicated SQL setup is PC/EC. This framing is closer to what you actually trade daily.

#### Tunable consistency
Many stores let you choose per request: Cassandra's QUORUM vs ONE, DynamoDB's strongly consistent reads. Use strong reads for money and inventory, eventual reads for everything else.

#### Pitfalls
- Saying "we pick CA". Without partitions there is no distributed system to discuss.
- Using strong consistency everywhere and paying latency for data nobody needs fresh.

You are ready to move on when you can classify each feature of a ticket booking app as needing strong or eventual consistency and explain the user-visible effect of each choice.

Key concepts: Strong (linearizable) consistency, Eventual consistency, Causal consistency, CAP theorem, PACELC, Tunable consistency, BASE vs ACID.

Mini project: Write a two-page note classifying 12 features of BookMyShow (seat holds, payments, reviews, ratings, recommendations and so on) as CP or AP with reasons, and the database or read mode you would use for each.

Self-check: Why is 'pick two of C, A and P' a misleading way to describe the CAP theorem?

Resources:
- [Consistency models](https://jepsen.io/consistency) (Jepsen)
- [Eventually Consistent, Revisited](https://www.allthingsdistributed.com/2008/12/eventually_consistent.html) (Werner Vogels)
- [CAP theorem](https://en.wikipedia.org/wiki/CAP_theorem) (Wikipedia)

### Object Storage and Large Files

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/system-design/object-storage

Store images, videos and backups in object stores like S3, use pre-signed URLs and multipart uploads, and keep only metadata in your database.

Databases are poor places for large binary files. **Object storage** (Amazon S3, Google Cloud Storage, Azure Blob, MinIO) stores files as objects in buckets with very high durability and cheap, almost unlimited capacity.

#### The standard pattern
- Store the file in the object store; store **metadata** (owner, size, content type, object key, status) in your database.
- Serve files through a **CDN** in front of the bucket.
- Let clients upload **directly** to the bucket with a **pre-signed URL**, so gigabytes never pass through your app servers.

#### Useful features
- **Multipart and resumable uploads**: upload a 2 GB video in chunks, retry only failed parts. Essential on flaky mobile networks.
- **Storage classes and lifecycle rules**: move old objects to cheaper, colder tiers automatically.
- **Versioning**: protect against accidental overwrites and deletes.
- **Event notifications**: trigger a thumbnail or transcoding job when an upload completes.

#### Durability vs availability
S3 is designed for eleven nines of durability (you will not lose the object) but lower availability guarantees (a request can occasionally fail). Design clients to retry.

#### Block and file storage
- **Block storage** (EBS, local SSD): raw disks for databases and VMs.
- **File storage** (EFS, NFS): shared file systems mounted by many servers.
Pick object storage for user content and backups, block storage for database volumes.

#### Pitfalls
- Storing images as BLOBs in Postgres and bloating backups and replication.
- Public buckets by mistake. Default to private and use pre-signed URLs or a CDN with signed URLs.
- Uploading through your API servers and tying up threads for minutes.

You are ready to move on when you can sketch the upload and download flow for profile photos using pre-signed URLs, a CDN and a metadata table.

Key concepts: Object vs block vs file storage, Metadata in DB, bytes in object store, Pre-signed URLs, Multipart and resumable uploads, Lifecycle rules and storage classes, Upload event triggers, MinIO for local development.

Mini project: Build an upload service with MinIO or S3: the API issues a pre-signed URL, the browser uploads directly, an event triggers thumbnail generation, and a metadata row tracks status from pending to ready.

Self-check: Why are pre-signed URLs better than streaming uploads through your API servers, and what security checks still belong on the server?

Resources:
- [Amazon S3 documentation](https://docs.aws.amazon.com/s3/) (AWS)
- [MinIO documentation](https://min.io/docs/minio/linux/index.html) (MinIO)
- [ByteByteGo System Design 101](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)

## Caching

Make reads fast and cheap with caches at every layer, keep them correct with the right write and invalidation strategy, and run Redis well.

### Caching Fundamentals and Cache Layers

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/system-design/caching-fundamentals

Learn where caches live (client, CDN, application, database), what makes data cacheable, and how to measure a cache by hit ratio.

A **cache** keeps a copy of data in a faster place so you do not recompute or refetch it. Caching is often the single biggest performance win in a design, and also a common source of bugs.

#### Where caches live
- **Client**: browser HTTP cache, mobile app local storage.
- **CDN / edge**: static files and public responses near users.
- **Application, in process**: a small LRU map inside each server. Fastest, but each instance has its own copy.
- **Distributed cache**: Redis or Memcached shared by all servers.
- **Database**: buffer pools and query caches inside the database itself.

#### What to cache
Good candidates are **read-heavy, expensive to compute and tolerant of a little staleness**: product pages, user profiles, feed fragments, configuration, results of slow aggregations. Poor candidates: data that changes on every request, or data where a stale read costs money (wallet balance at payment time).

#### Measuring a cache
- **Hit ratio**: hits / (hits + misses). A cache with 30 percent hits may cost more than it saves.
- **Latency** on hit vs miss.
- **Memory** and **eviction rate**.
Access patterns usually follow a power law: a small set of keys gets most traffic, which is why caches work.

#### TTLs and staleness
Every cached item should have a **TTL** unless you have a reliable invalidation path. Pick TTLs from business tolerance: menu prices maybe 1 minute, restaurant photos maybe a day.

#### Pitfalls
- Caching without a plan for invalidation.
- Treating the cache as the source of truth; it can be flushed at any moment.
- Caching personalised data under a shared key.

You are ready to move on when you can name the cache layers a request passes through in a typical web app and decide, for five pieces of data, whether to cache them and with what TTL.

Key concepts: Client and browser caching, In-process cache, Distributed cache, Hit ratio, TTL and staleness, Power-law access patterns.

Mini project: Add a Redis cache in front of a slow endpoint (simulate a 300 ms query). Expose hit ratio and latency metrics, run a load test with a Zipf-like key distribution, and graph the improvement.

Self-check: Why might a cache with a 20 percent hit ratio make a system slower overall?

Resources:
- [The System Design Primer: cache](https://github.com/donnemartin/system-design-primer) (GitHub)
- [Caching overview](https://aws.amazon.com/caching/) (AWS)
- [HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching) (MDN)

### Cache Strategies, Eviction and Invalidation

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/cache-strategies

Choose between cache-aside, read-through, write-through, write-behind and write-around, pick eviction policies, and avoid stampedes and stale data.

"There are only two hard things in computer science: cache invalidation and naming things." The strategy you pick decides how stale data can get and what happens on failure.

#### Read and write strategies
- **Cache-aside (lazy loading)**: app reads the cache; on a miss it reads the DB and fills the cache. On writes it updates the DB and **deletes** the cache key. The most common pattern.
- **Read-through**: the cache library itself loads from the DB on a miss.
- **Write-through**: write to cache and DB together. Cache is always fresh; writes are slower.
- **Write-behind (write-back)**: write to cache, flush to DB later. Very fast writes; risk of data loss if the cache dies.
- **Write-around**: write only to the DB; the cache fills on the next read. Good when written data is rarely read soon.

#### Eviction policies
When memory is full: **LRU** (least recently used, the usual default), **LFU** (least frequently used, good for stable hot sets), **FIFO**, random, or TTL-based. Redis offers several maxmemory policies; choose one deliberately.

#### Classic failure modes
- **Cache stampede / thundering herd**: a hot key expires and thousands of requests hit the DB at once. Fix with request coalescing (one loader, others wait), a lock per key, or refreshing early with jittered TTLs.
- **Cache penetration**: repeated lookups for keys that do not exist. Cache the "not found" result briefly or use a Bloom filter.
- **Cache avalanche**: many keys expire together or the cache cluster dies. Add TTL jitter and protect the DB with rate limits.
- **Inconsistency**: delete-then-write races can leave stale values. Delete after the DB commit, keep TTLs as a safety net, or drive invalidation from the database change stream (CDC).

#### Pitfalls
- Updating the cache value on write instead of deleting it, and racing with concurrent readers.
- Same TTL for every key, so they all expire together.

You are ready to move on when you can pick a strategy for a product catalogue, a leaderboard and a user session store, and explain how you would prevent a stampede on a viral product page.

Key concepts: Cache-aside, Read-through and write-through, Write-behind and write-around, LRU and LFU eviction, Cache stampede and request coalescing, Cache penetration and avalanche, TTL jitter, CDC-driven invalidation.

Mini project: Implement an LRU cache from scratch with O(1) get and put, then build a cache-aside wrapper around a slow function that coalesces concurrent misses for the same key. Show with a load test that the backend sees one call per expiry.

Self-check: In cache-aside, why is it usually safer to delete the cache key after updating the database than to write the new value into the cache?

Resources:
- [Caching patterns](https://docs.aws.amazon.com/whitepapers/latest/database-caching-strategies-using-redis/caching-patterns.html) (AWS)
- [Scaling Memcache at Facebook](https://www.usenix.org/conference/nsdi13/technical-sessions/presentation/nishtala) (USENIX)
- [Redis key eviction](https://redis.io/docs/latest/develop/reference/eviction/) (Redis)

### Redis in Practice

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/redis-in-practice

Use Redis data structures for caches, counters, leaderboards, rate limits and locks, and understand persistence, replication and clustering.

Redis is the most common building block in system design answers, and for good reason: an in-memory store with rich data structures and sub-millisecond latency.

#### Data structures and what they solve
- **Strings**: cached JSON, counters with INCR, simple flags.
- **Hashes**: objects with fields (a user session).
- **Lists**: simple queues, recent items.
- **Sets**: unique visitors, tags, "who liked this".
- **Sorted sets**: leaderboards, top-K, priority queues, sliding window rate limits.
- **Streams**: append-only logs with consumer groups for lightweight messaging.
- **HyperLogLog** and **bitmaps**: approximate unique counts and daily active flags in tiny memory.
- **Geo**: nearby drivers or restaurants by radius.

#### Operational basics
- **Persistence**: RDB snapshots (compact, can lose recent writes) and AOF logs (more durable, bigger). Many caches run with persistence off.
- **Replication and Sentinel**: replicas plus automatic failover.
- **Redis Cluster**: data split into 16,384 hash slots across nodes; multi-key operations must stay in one slot (use hash tags).
- Commands run on one main thread, so a single slow command (KEYS *, a huge set operation) blocks everyone.

#### Common patterns
Cache-aside caching, session storage, rate limiting with INCR and EXPIRE or Lua scripts, distributed locks with SET NX PX (understand their limits: a lock with a timeout is a lease, not a guarantee), pub/sub for fan-out, and idempotency key storage.

#### Pitfalls
- Using KEYS in production instead of SCAN.
- Huge "big keys" (a set with millions of members) that stall the server and break even sharding.
- Relying on a Redis lock for correctness where a database constraint or fencing token is needed.

You are ready to move on when you can pick the right Redis structure for a cricket fantasy leaderboard, a per-user rate limiter and an online-users counter.

Key concepts: Strings, hashes, lists, sets, Sorted sets for leaderboards, Streams and pub/sub, HyperLogLog and bitmaps, RDB vs AOF persistence, Redis Cluster and hash slots, Distributed locks and their limits, Memcached as an alternative.

Mini project: Build a fantasy cricket leaderboard service on Redis: sorted set for scores, a hash per user profile, HyperLogLog for unique daily players, and a sliding window rate limit on score updates. Load test it with 1 lakh simulated users.

Self-check: Why can a Redis lock with an expiry still allow two workers to act on the same resource, and what is a fencing token?

Resources:
- [Redis documentation](https://redis.io/docs/latest/) (Redis)
- [Redis University](https://university.redis.io/) (Redis)
- [How to do distributed locking](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html) (Martin Kleppmann)
- [Memcached](https://memcached.org/) (Memcached)

## Queues, Streams and Asynchronous Processing

Decouple services and absorb traffic spikes with message queues and event streams, and learn the delivery guarantees that make async systems correct.

### Message Queues and Async Processing

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/message-queues

Use queues to move slow or unreliable work off the request path, smooth out spikes and decouple producers from consumers.

Not every piece of work must finish before you reply to the user. Sending an email, generating an invoice PDF or transcoding a video can happen **asynchronously**. A **message queue** sits between the code that creates work (producer) and the code that does it (consumer).

#### Why queues help
- **Faster responses**: the API enqueues a job and returns "accepted" in milliseconds.
- **Load levelling**: a Big Billion Days spike fills the queue; workers drain it at a steady rate instead of the database melting.
- **Decoupling**: producers do not need to know who consumes or whether consumers are up right now.
- **Retries**: failed jobs go back on the queue or to a dead letter queue.

#### Core concepts
- **Point-to-point queue**: each message is processed by one consumer (a work queue).
- **Publish/subscribe**: each message goes to every subscriber (order placed: notify user, update analytics, alert restaurant).
- **Acknowledgements**: a consumer acks after finishing; unacked messages are redelivered after a **visibility timeout**.
- **Dead letter queue (DLQ)**: messages that keep failing are parked for inspection instead of blocking the queue.
- **Backpressure**: if consumers fall behind, queue depth grows. Monitor it and autoscale workers.

#### Typical tools
RabbitMQ, Amazon SQS, Google Pub/Sub, Redis lists or streams for light use, and Kafka when you need a durable log (next topics).

#### Pitfalls
- Using a queue for work the user must see succeed immediately, and then building fake "is it done yet?" flows.
- No DLQ, so one poison message retries forever.
- Ignoring queue depth until it is hours behind.

You are ready to move on when you can redraw a synchronous checkout flow so that only payment confirmation is synchronous and explain what happens when the email worker is down for an hour.

Key concepts: Producers, consumers and brokers, Point-to-point vs pub/sub, Acks and visibility timeout, Dead letter queues, Load levelling, Backpressure and queue depth, Delayed and scheduled jobs.

Mini project: Build a signup API that enqueues a welcome-email job to a queue (Redis, RabbitMQ or SQS). Add retries with backoff and a DLQ, then kill the worker for five minutes and show that no emails are lost.

Self-check: A consumer crashes after sending an email but before acking the message. What happens next, and what does that imply about your consumer code?

Resources:
- [Amazon SQS developer guide](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) (AWS)
- [Queue-based load leveling pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/queue-based-load-leveling) (Microsoft)
- [The System Design Primer: asynchronism](https://github.com/donnemartin/system-design-primer) (GitHub)

### Event Streaming with Kafka

recommended · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/system-design/kafka-event-streaming

Learn the log-based model behind Kafka: topics, partitions, offsets and consumer groups, and when a durable event stream beats a classic queue.

**Apache Kafka** is a distributed, append-only **log**. Producers append events; consumers read at their own pace and track their own position. Unlike a classic queue, messages are not deleted when read, so many independent consumers can replay the same history.

#### Core concepts
- **Topic**: a named stream of events (orders, payments, location-updates).
- **Partition**: a topic is split into ordered partitions spread across brokers. Ordering is guaranteed **only within a partition**.
- **Key**: events with the same key (order_id, driver_id) go to the same partition, so they stay in order.
- **Offset**: a consumer's position in a partition. Consumers commit offsets to resume after restarts.
- **Consumer group**: partitions are divided among the group's consumers. Parallelism is capped by the partition count.
- **Replication**: each partition has a leader and followers; acks=all plus min.insync.replicas gives durability.
- **Retention**: keep events for days or forever; **log compaction** keeps the latest value per key.

#### When Kafka shines
- High-throughput event pipelines (clickstream, location pings, logs).
- **Event-driven architecture**: one OrderPlaced event feeds payments, notifications, analytics and search indexing.
- **Change data capture** with Debezium, streaming DB changes to caches and search.
- Stream processing with Kafka Streams or Flink for real-time aggregations.

Swiggy, Flipkart, Uber and Hotstar all run Kafka at large scale for exactly these uses.

#### Pitfalls
- Too few partitions, capping consumer parallelism; too many, adding overhead.
- Choosing a key with skew (one huge merchant) and creating a hot partition.
- Expecting global ordering across a topic.
- Treating Kafka as a task queue with per-message retries and delays; it can be done, but a queue is simpler.

You are ready to move on when you can design the topics, keys and consumer groups for an order pipeline and explain how a new analytics service could replay last week's events.

Key concepts: Topics and partitions, Keys and per-partition ordering, Offsets and consumer groups, Replication and acks, Retention and log compaction, Change data capture (Debezium), Stream processing (Kafka Streams, Flink).

Mini project: Run Kafka locally with Docker. Produce simulated order events keyed by order_id to a 6-partition topic, run two consumer groups (notifications and analytics), kill a consumer mid-stream and show the group rebalances without losing events.

Self-check: You have 12 partitions and start 20 consumers in one group. How many are doing work, and why?

Resources:
- [Apache Kafka documentation](https://kafka.apache.org/documentation/) (Apache)
- [Introduction to Kafka](https://kafka.apache.org/intro) (Apache)
- [Kafka design: the log at the core](https://kafka.apache.org/documentation/#design) (Apache Kafka)

### RabbitMQ and Managed Queues (SQS, Pub/Sub)

alternative · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/rabbitmq-and-managed-queues

Use a classic broker with routing, per-message acks and delays, or a managed cloud queue, when you need task distribution rather than a replayable log.

If your main need is **distributing tasks to workers** rather than keeping a replayable event history, a classic message broker or a managed queue is simpler than Kafka.

#### RabbitMQ
- Producers publish to **exchanges**; exchanges route to **queues** by rules:
  - **Direct**: exact routing key match.
  - **Topic**: wildcard patterns such as order.*.created.
  - **Fanout**: copy to every bound queue.
- Per-message **acks**, **prefetch** limits to stop one worker hogging messages, TTLs, dead-letter exchanges and priority queues.
- Messages are removed once acked, so there is no replay by default (RabbitMQ Streams add log-like behaviour).

#### Managed cloud queues
- **Amazon SQS**: fully managed, scales without capacity planning. Standard queues give at-least-once delivery with best-effort order; FIFO queues give ordering per message group and deduplication with lower throughput.
- **Google Pub/Sub** and **Azure Service Bus**: similar managed options with pub/sub fan-out.
- Pair SQS with SNS for fan-out to multiple queues.

#### Choosing between them and Kafka
- Task queue with retries, delays and priorities, modest volume: RabbitMQ or SQS.
- High-volume event stream, many consumers, replay needed: Kafka.
- Small team on AWS who wants zero ops: SQS plus SNS.

#### Pitfalls
- Unbounded prefetch, so one slow consumer holds thousands of unacked messages.
- Assuming SQS standard queues deliver exactly once or in order.
- Running a self-managed broker cluster with no monitoring of queue depth and memory alarms.

You are ready to move on when you can set up a topic exchange that routes order events to three different worker queues and explain when you would pick SQS FIFO over a standard queue.

Key concepts: Exchanges, queues and bindings, Direct, topic and fanout exchanges, Prefetch and acks, Dead-letter exchanges, SQS standard vs FIFO, SNS + SQS fan-out.

Mini project: Build an order processing demo on RabbitMQ with a topic exchange routing to invoice, email and analytics queues, prefetch of 10, and a dead-letter exchange. Show what happens when the invoice worker throws for one specific order.

Self-check: Why does RabbitMQ not let a new consumer replay last week's messages, while Kafka does?

Resources:
- [RabbitMQ tutorials](https://www.rabbitmq.com/tutorials) (RabbitMQ)
- [RabbitMQ documentation](https://www.rabbitmq.com/docs) (RabbitMQ)
- [Amazon SQS developer guide](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) (AWS)

### Delivery Guarantees and Event-Driven Design

core · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/delivery-semantics-event-driven

Understand at-most-once, at-least-once and effectively-once delivery, idempotent consumers, ordering, and the outbox pattern for reliable events.

Async systems fail in subtle ways: messages get duplicated, reordered or lost between a database write and a publish. Getting the guarantees right is what separates a toy design from a production one.

#### Delivery semantics
- **At-most-once**: send and forget. Messages may be lost, never duplicated. Fine for metrics.
- **At-least-once**: retry until acked. Nothing is lost, but **duplicates happen**. The default for most brokers.
- **Exactly-once**: true end-to-end exactly-once is not achievable across arbitrary systems. In practice you build **effectively-once** with at-least-once delivery plus **idempotent consumers**.

#### Idempotent consumers
Give every event a unique ID. Consumers record processed IDs (in a table with a unique constraint, or in the same transaction as the side effect) and skip repeats. "Credit wallet for event 123" must have the same result whether it runs once or three times.

#### Ordering
Most systems only guarantee order per key or partition. Design consumers to tolerate out-of-order events: carry a version or timestamp and ignore stale updates.

#### The dual-write problem and the outbox pattern
Writing to the database and then publishing to Kafka can fail in between, leaving the two out of sync. The **transactional outbox** fixes this: write the business row and an outbox row in **one DB transaction**, then a relay (or CDC tool like Debezium) publishes outbox rows to the broker.

#### Event-driven architecture
- **Events** state facts (OrderPlaced). **Commands** request actions (SendEmail).
- **Choreography**: services react to each other's events; loose coupling, harder to see the whole flow.
- **Orchestration**: a coordinator tells services what to do; easier to follow and debug.
- **Event sourcing** and **CQRS** store events as the source of truth and build read models from them. Powerful, but add them only when you need the audit trail or separate read models.

#### Pitfalls
- Assuming the broker delivers exactly once.
- Publishing events outside the database transaction.

You are ready to move on when you can explain why a payment-success event might be processed twice and design the consumer so the user is credited only once.

Key concepts: At-most-once vs at-least-once, Effectively-once processing, Idempotent consumers, Per-key ordering, Transactional outbox, Choreography vs orchestration, Event sourcing and CQRS.

Mini project: Implement the outbox pattern: an order service writes orders and outbox rows in one transaction, a relay publishes them to a queue, and a consumer deduplicates by event ID. Inject crashes at each step and show no event is lost or double-applied.

Self-check: Why does writing to the database and then publishing to a broker in two separate steps eventually cause inconsistency, and how does the outbox pattern fix it?

Resources:
- [Transactional outbox pattern](https://microservices.io/patterns/data/transactional-outbox.html) (microservices.io)
- [What do you mean by Event-Driven?](https://martinfowler.com/articles/201701-event-driven.html) (Martin Fowler)
- [Debezium documentation](https://debezium.io/documentation/) (Debezium)

## Distributed Systems Essentials

The building blocks under every large system: consistent hashing, unique ID generation, consensus and leader election, and transactions across services.

### Consistent Hashing

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/consistent-hashing

Distribute keys across a changing set of nodes so that adding or removing a node moves only a small fraction of keys.

With naive hashing, server = hash(key) mod N. Add one server and almost every key maps somewhere new, so caches go cold and data must move. **Consistent hashing** fixes this.

#### How it works
- Place nodes on a **hash ring** (positions 0 to 2^32 minus 1) by hashing their IDs.
- Hash each key onto the same ring and walk clockwise to the first node: that node owns the key.
- When a node joins, it takes over only the keys between it and its predecessor. When a node leaves, only its keys move to the next node. On average just **1/N of keys move**.

#### Virtual nodes
With few nodes, ring positions are uneven and one node may own far more keys. Give each physical node many **virtual nodes** (say 100 to 200 points on the ring). Load evens out, and when a node dies its load spreads across many nodes instead of one neighbour. Stronger machines can get more virtual nodes.

#### Replication on the ring
To store 3 copies, write to the owner and the next two distinct physical nodes clockwise. This is how Dynamo-style systems such as Cassandra and Riak place replicas.

#### Where you will see it
Distributed caches (client-side sharding in Memcached), Cassandra and DynamoDB partitioning, load balancers that route the same user or key to the same backend, and CDN request routing. Alternatives such as **rendezvous (highest random weight) hashing** and **jump consistent hash** solve the same problem with different trade-offs.

#### Pitfalls
- Forgetting virtual nodes and ending up with badly skewed load.
- Assuming consistent hashing fixes hot keys. One celebrity key still lands on one node.

You are ready to move on when you can draw a ring with three nodes, add a fourth, and show exactly which keys move.

Key concepts: Problem with mod N hashing, Hash ring, Virtual nodes, Replica placement on the ring, Rendezvous hashing, Jump consistent hash.

Mini project: Implement a consistent hash ring with virtual nodes in your language of choice. Map 1 million keys to 5 nodes, add a sixth, and report the fraction of keys moved and the per-node load spread for 1, 10 and 200 virtual nodes.

Self-check: Why do virtual nodes improve both load balance and recovery when a node fails?

Resources:
- [Consistent hashing](https://en.wikipedia.org/wiki/Consistent_hashing) (Wikipedia)
- [Amazon's Dynamo](https://www.allthingsdistributed.com/2007/10/amazons_dynamo.html) (All Things Distributed)
- [ByteByteGo System Design 101](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)

### Unique ID Generation at Scale

core · intermediate · about 2 h · https://www.internhack.in/roadmaps/tracks/system-design/unique-id-generation

Generate unique, roughly sortable IDs across many servers with UUIDs, Snowflake-style IDs, ticket servers or ULIDs, and know their trade-offs.

A single database can hand out auto-increment IDs. Once you shard or run many writers, you need IDs that are unique **without coordination on every write**.

#### Options
- **UUID v4**: 128 random bits. No coordination, effectively no collisions. Downsides: large, not sortable, and random inserts fragment B-tree indexes.
- **UUID v7 / ULID**: time-ordered prefix plus randomness. Sortable by creation time and index friendly. A strong modern default.
- **Snowflake (Twitter)**: 64-bit integer = timestamp (41 bits) + machine/worker ID (10 bits) + per-millisecond sequence (12 bits). Compact, roughly time-sorted, about 4,096 IDs per millisecond per worker.
- **Ticket server / range allocation**: a central service hands out blocks of IDs (1 to 10,000 to server A). Simple and dense, but the allocator must be highly available.
- **Database sequences with offsets**: server 1 uses odd numbers, server 2 even. Works for a fixed small number of writers.

#### What to consider
- Size (fits in a 64-bit column?), sortability, whether IDs leak information (sequential order IDs reveal your daily volume to competitors), and URL friendliness (Base62 encode for short links).
- **Clock issues**: Snowflake relies on clocks. If a clock goes backwards (NTP adjustment), a worker must wait or refuse to issue IDs.
- **Worker ID assignment**: hand out unique worker IDs via config or a coordinator like ZooKeeper or etcd.

#### Pitfalls
- Exposing sequential IDs in public URLs, making scraping and enumeration trivial.
- Using random UUID v4 as the primary key of a huge, write-heavy MySQL table and suffering index bloat.

You are ready to move on when you can lay out the bits of a Snowflake ID, estimate how many years its timestamp lasts, and choose an ID scheme for orders, short URLs and chat messages.

Key concepts: Auto-increment limits, UUID v4, UUID v7 and ULID, Snowflake IDs, Ticket servers and range allocation, Clock skew handling, Base62 encoding.

Mini project: Implement a Snowflake-style ID generator with configurable epoch and worker ID, generate 1 million IDs across 4 threads, verify uniqueness and ordering, and simulate a backwards clock jump to show your handling.

Self-check: Why do time-ordered IDs like UUID v7 or Snowflake insert more efficiently into a B-tree index than random UUID v4?

Resources:
- [Twitter Snowflake (archived)](https://github.com/twitter-archive/snowflake) (GitHub)
- [RFC 9562: UUIDs](https://datatracker.ietf.org/doc/html/rfc9562) (IETF)
- [ULID specification](https://github.com/ulid/spec) (GitHub)

### Consensus, Leader Election and Coordination

recommended · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/consensus-and-coordination

Understand why distributed nodes need consensus, how Raft elects a leader and replicates a log, and how ZooKeeper and etcd are used for coordination.

Many systems need several machines to **agree** on something: who the leader is, which config is current, whether a transaction committed. Agreement is hard when messages are delayed and nodes crash. Consensus algorithms solve it.

#### The core problems
- **Clocks drift**, so you cannot order events by wall time alone. Logical clocks (Lamport timestamps) and vector clocks capture "happened before".
- **Failure detection** is guesswork. A node that does not reply might be dead or just slow.
- **Split brain**: two nodes both believe they are the leader and accept conflicting writes.

#### Raft in brief
- Nodes are followers, candidates or a leader. A follower that hears no heartbeat starts an **election** for a new **term**.
- A candidate needs votes from a **majority** (a quorum). With 5 nodes, 3 must agree, so the cluster survives 2 failures.
- The leader appends commands to its log and replicates them; an entry is **committed** once a majority has it.
- Because any two majorities overlap, a new leader always has every committed entry.
Paxos solves the same problem; Raft was designed to be easier to understand.

#### Where you use it
You rarely implement consensus yourself. You use systems built on it:
- **etcd** (Kubernetes' brain), **ZooKeeper** (older Kafka, HBase), **Consul**.
- Uses: leader election, distributed locks with **fencing tokens**, service discovery, cluster membership, configuration.
- Databases like CockroachDB, TiDB and Kafka's KRaft mode use Raft internally.

#### Pitfalls
- Running consensus clusters with an even number of nodes (4 tolerates no more failures than 3).
- Putting high-volume data in ZooKeeper or etcd; they are for small, critical metadata.
- Using wall clock timestamps to decide which write wins across machines.

You are ready to move on when you can explain why a 5-node Raft cluster tolerates 2 failures and how it avoids two leaders in the same term.

Key concepts: Why consensus is needed, Quorums and majorities, Raft leader election and log replication, Lamport and vector clocks, Split brain and fencing tokens, etcd and ZooKeeper, Paxos.

Mini project: Run a 3-node etcd cluster in Docker. Use it to elect a leader among three worker processes, kill the leader, and log how long failover takes. Then partition one node and show it cannot accept writes.

Self-check: Why does a cluster of 4 consensus nodes tolerate the same number of failures as a cluster of 3?

Resources:
- [The Raft consensus algorithm](https://raft.github.io/) (Raft)
- [etcd documentation](https://etcd.io/docs/) (etcd)
- [Patterns of Distributed Systems](https://martinfowler.com/articles/patterns-of-distributed-systems/) (Martin Fowler)
- [Lamport timestamp](https://en.wikipedia.org/wiki/Lamport_timestamp) (Wikipedia)

### Distributed Transactions: 2PC and Sagas

core · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/distributed-transactions

Keep data consistent across services and databases with two-phase commit or sagas with compensating actions, and know when each is appropriate.

A single database gives you ACID transactions. Once an order touches the order service, inventory service and payment service, each with its own database, you need another approach.

#### Two-phase commit (2PC)
- A **coordinator** asks every participant to **prepare** (lock resources and promise to commit).
- If all vote yes, it tells them to **commit**; otherwise **abort**.
- Gives atomicity across databases, but it is **blocking**: if the coordinator dies after prepare, participants hold locks until it recovers. It also adds latency and couples availability of all participants. Common inside databases (XA, Spanner style systems), rare across microservices.

#### Sagas
A **saga** splits the business transaction into a sequence of **local transactions**, each with a **compensating action** that semantically undoes it:
1. Create order (compensate: cancel order)
2. Reserve inventory (compensate: release inventory)
3. Charge payment (compensate: refund)
4. Confirm order
If step 3 fails, run compensations for steps 2 and 1. There is no global isolation, so other requests may briefly see intermediate states ("payment pending").

#### Coordinating a saga
- **Choreography**: each service listens for events and emits the next. Fine for 2 or 3 steps.
- **Orchestration**: a saga orchestrator (or a workflow engine like Temporal) drives the steps and tracks state. Easier to reason about, retry and monitor.

#### Design rules
- Every step and every compensation must be **idempotent** and retryable.
- Some actions cannot be undone (an SMS was sent). Order steps so irreversible ones come last.
- Use the **outbox pattern** so each step's state change and event are atomic.

#### Pitfalls
- Using 2PC across services owned by different teams.
- Forgetting compensations can fail too and need retries and alerting.

You are ready to move on when you can write the saga for booking a flight plus hotel, including compensations and what the user sees when the hotel step fails.

Key concepts: Two-phase commit, Blocking and coordinator failure, Sagas and compensating actions, Choreography vs orchestration sagas, Workflow engines (Temporal), Semantic locks and pending states.

Mini project: Build an orchestrated saga for a food order across three toy services (order, restaurant, payment) with compensations. Inject a payment failure and a restaurant timeout and show the final states in each service's database.

Self-check: Why do sagas give up isolation, and how can you stop a user from seeing or acting on a half-finished order?

Resources:
- [Saga pattern](https://microservices.io/patterns/data/saga.html) (microservices.io)
- [Two-phase commit protocol](https://en.wikipedia.org/wiki/Two-phase_commit_protocol) (Wikipedia)
- [Saga distributed transactions pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/saga) (Microsoft)
- [Temporal documentation](https://docs.temporal.io/) (Temporal)

## API Design, Rate Limiting and Idempotency

Design clean, evolvable APIs and protect them with rate limits and idempotent operations so retries and abuse do not break the system.

### API Design: REST, gRPC and GraphQL

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/api-design

Design resource-oriented REST APIs, know when gRPC or GraphQL fits better, and handle pagination, versioning and errors consistently.

The API is the contract between your system and its clients. In interviews, writing the key API endpoints early makes the rest of the design concrete.

#### REST done well
- Model **resources** as nouns: POST /orders, GET /orders/{id}, GET /users/{id}/orders.
- Use HTTP methods and status codes as intended (201 Created, 404, 409 Conflict, 429).
- **Pagination**: offset/limit is simple but slow and unstable on large, changing tables. **Cursor (keyset) pagination** (?after=<last_id>) is the scalable default for feeds and lists.
- **Filtering and sorting** with query parameters; **partial responses** with a fields parameter when payloads are big.
- **Consistent errors**: a machine-readable code, a human message and a request ID.
- **Versioning**: /v1/ in the path or a header. Prefer additive, backward-compatible changes so you rarely need v2.

#### gRPC
Binary Protocol Buffers over HTTP/2, generated clients, streaming in both directions. Excellent for **internal service-to-service** calls where you control both ends and care about latency. Less friendly for browsers and public APIs.

#### GraphQL
Clients ask for exactly the fields they need in one request. Great for apps with many screens over many services (a BFF layer). Costs: harder HTTP caching, risk of very expensive queries (add depth and cost limits), and N+1 resolver problems (use batching like DataLoader).

#### Picking one
- Public or partner API: REST with OpenAPI docs.
- Internal high-throughput calls: gRPC.
- Many client views with varied data needs: GraphQL at the edge, REST or gRPC behind it.
- Server push: WebSockets or SSE alongside any of these.

#### Pitfalls
- Verbs in URLs (/createOrder) and 200 OK with an error body.
- Offset pagination on a feed with millions of rows.
- Breaking changes without versioning.

You are ready to move on when you can write the five core endpoints for a ride-hailing app with request and response shapes, pagination and error codes.

Key concepts: Resource-oriented REST, Cursor vs offset pagination, Error format and status codes, API versioning, gRPC and Protocol Buffers, GraphQL trade-offs, OpenAPI specs.

Mini project: Write an OpenAPI spec for a mini food delivery API (restaurants, menus, carts, orders) with cursor pagination and a standard error schema. Implement two endpoints and the same order lookup as a gRPC service, then compare payload sizes.

Self-check: Why does offset pagination produce duplicates or skipped items on a feed where new posts keep arriving, and how does cursor pagination avoid it?

Resources:
- [Google API design guide](https://cloud.google.com/apis/design) (Google Cloud)
- [Zalando RESTful API guidelines](https://opensource.zalando.com/restful-api-guidelines/) (Zalando)
- [gRPC documentation](https://grpc.io/docs/) (gRPC)
- [Learn GraphQL](https://graphql.org/learn/) (GraphQL Foundation)

### Rate Limiting Algorithms

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/rate-limiting

Protect services from abuse and overload with token bucket, leaky bucket, fixed window and sliding window limiters, applied per user, key or IP.

A **rate limiter** caps how many requests a client can make in a time window. It protects you from abuse (OTP spam, scraping, credential stuffing), keeps one noisy customer from hurting others, and controls cost on paid downstream APIs.

#### Algorithms
- **Token bucket**: a bucket holds up to B tokens, refilled at R per second. Each request takes a token. Allows short **bursts** up to B while enforcing an average rate. The most common choice (used by AWS and Stripe style limiters).
- **Leaky bucket**: requests enter a queue that drains at a fixed rate. Smooths traffic into a steady flow; bursts wait or are dropped.
- **Fixed window counter**: count requests per calendar minute. Simple, but a client can send 2x the limit across a window boundary.
- **Sliding window log**: store each request timestamp and count those in the last N seconds. Exact, memory hungry.
- **Sliding window counter**: blend the current and previous window counts by overlap. Close to exact with tiny memory.

#### What to limit on
User ID, API key, IP address, phone number (for OTP endpoints), or a combination. Different endpoints deserve different limits: login and OTP very strict, product browsing generous.

#### Responding
Return **429 Too Many Requests** with a Retry-After header and, ideally, X-RateLimit-Limit / Remaining headers so good clients can back off.

#### Where it lives
At the API gateway or edge for coarse limits, in services for business limits (5 OTPs per phone per hour). The full distributed version (shared counters in Redis, race conditions, multi-region) is covered as a case study later.

#### Pitfalls
- Limiting only by IP, which punishes everyone behind one college or office NAT.
- Fixed windows that let double bursts through at the boundary.
- No limits on expensive endpoints like search or report export.

You are ready to move on when you can simulate token bucket and sliding window counter by hand for a sequence of requests and explain which one you would use for an OTP endpoint.

Key concepts: Token bucket, Leaky bucket, Fixed window counter, Sliding window log and counter, Choosing limit keys, 429 and Retry-After.

Mini project: Implement token bucket, fixed window and sliding window counter limiters as middleware in a small API. Fire a scripted burst pattern at each and plot allowed vs rejected requests over time.

Self-check: With a fixed window of 100 requests per minute, how can a client send 200 requests within about 2 seconds, and which algorithm prevents it?

Resources:
- [Scaling your API with rate limiters](https://stripe.com/blog/rate-limiters) (Stripe)
- [Token bucket](https://en.wikipedia.org/wiki/Token_bucket) (Wikipedia)
- [Rate limiting pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/rate-limiting-pattern) (Microsoft)

### Idempotency, Retries and Timeouts

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/idempotency-and-retries

Make operations safe to retry with idempotency keys, and retry correctly with timeouts, exponential backoff and jitter.

Networks fail in the worst way: the request succeeded, but the response was lost. The client cannot tell, so it retries. If "create payment" is not **idempotent**, the user is charged twice.

#### Idempotency
An operation is idempotent if doing it many times has the same effect as doing it once. GET, PUT and DELETE are idempotent by design; POST usually is not.

#### Idempotency keys
- The client generates a unique key (a UUID) per logical operation and sends it in a header such as Idempotency-Key.
- The server stores key, request fingerprint, status and response. On a repeat with the same key, it returns the **stored response** instead of executing again.
- Store the key in the **same transaction** as the side effect, or use a unique constraint, so two concurrent retries cannot both run.
- Expire keys after a sensible window (Stripe keeps them for 24 hours).
UPI and card payments rely on this idea: every transaction carries a unique reference so duplicates are detected.

#### Timeouts
Every network call needs a timeout; without one, a slow dependency ties up threads until the whole service hangs. Set timeouts from the dependency's p99 plus margin, and make the overall request budget shrink as it flows downstream (deadline propagation).

#### Retrying well
- Retry only **transient** failures (timeouts, 503, connection resets), not 400s.
- Use **exponential backoff with jitter** (wait 100 ms, 200 ms, 400 ms, each randomised) so clients do not retry in lockstep.
- Cap retries and use a **retry budget** (for example retries may add at most 10 percent load). Retrying at every layer multiplies traffic: 3 retries across 4 layers can mean 81 calls.

#### Pitfalls
- Retrying non-idempotent operations blindly.
- Retries without jitter creating synchronized waves that keep a recovering service down.
- Infinite timeouts in HTTP clients (several popular libraries default to none).

You are ready to move on when you can design an idempotent "place order" API, including what is stored, what a duplicate request returns and how concurrent duplicates are handled.

Key concepts: Idempotent operations, Idempotency keys, Handling concurrent duplicates, Timeouts and deadlines, Exponential backoff with jitter, Retry budgets and amplification.

Mini project: Build a payment-intent API that accepts an Idempotency-Key, stores results in Postgres with a unique constraint, and returns the cached response on replays. Write a client that retries with backoff and jitter while you randomly drop responses, and prove no double charges occur.

Self-check: Two identical requests with the same idempotency key arrive 5 ms apart on different servers. How does your design make sure only one executes?

Resources:
- [Idempotent requests](https://docs.stripe.com/api/idempotent_requests) (Stripe)
- [Making retries safe with idempotent APIs](https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/) (AWS Builders' Library)
- [Timeouts, retries and backoff with jitter](https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/) (AWS Builders' Library)

## Architecture Styles and Service Communication

Monoliths, modular monoliths and microservices, and how services find and talk to each other.

### Monolith, Modular Monolith and Microservices

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/monolith-vs-microservices

Weigh the real costs and benefits of monoliths and microservices, and learn how teams split systems along business boundaries when they need to.

"Should this be microservices?" is one of the most common design questions and one of the most over-answered with "yes".

#### Monolith
One deployable application with one codebase and usually one database. **Simple** to build, test, deploy and debug; transactions are local; no network calls between modules. Scales well horizontally behind a load balancer. Many large Indian products ran as monoliths far longer than people assume.

#### Modular monolith
Still one deployable, but with **strict module boundaries** (separate packages, owned tables, internal APIs between modules). You keep the operational simplicity while preparing clean seams for later extraction. Often the best default.

#### Microservices
Many small services, each owning its data and deployed independently. Benefits:
- **Team autonomy**: 20 teams can ship without coordinating one release.
- **Independent scaling** and technology choice per service.
- **Fault isolation**, if designed for it.
Costs:
- Network calls everywhere: latency, partial failures, retries.
- **Distributed data**: no joins or ACID transactions across services; sagas and eventual consistency.
- Operational load: service discovery, tracing, CI/CD per service, versioned contracts, on-call for each.

#### How to split
Use **domain-driven design** ideas: find **bounded contexts** (catalog, cart, orders, payments, delivery) where language and data are cohesive. Each service owns its data; others access it only through APIs or events. Use the **strangler fig** pattern to extract pieces from a monolith gradually.

#### Pitfalls
- A **distributed monolith**: services that must deploy together and share a database.
- Splitting by technical layer (a "DB service") instead of business capability.
- Five services for a three-person startup.

You are ready to move on when you can argue for a modular monolith for an early-stage startup and for microservices at Swiggy's scale, using team size, deploy frequency and data ownership as reasons.

Key concepts: Monolith strengths, Modular monolith, Microservices benefits and costs, Bounded contexts (DDD), Database per service, Strangler fig migration, Distributed monolith anti-pattern.

Mini project: Take a monolithic e-commerce app (yours or an open-source one), draw its bounded contexts, and write a migration plan that extracts one context (for example notifications) using the strangler fig pattern, including data ownership changes.

Self-check: Name three signs that a set of microservices is actually a distributed monolith.

Resources:
- [Microservices](https://martinfowler.com/articles/microservices.html) (Martin Fowler)
- [MonolithFirst](https://martinfowler.com/bliki/MonolithFirst.html) (Martin Fowler)
- [Microservice architecture patterns](https://microservices.io/) (microservices.io)
- [Strangler fig application](https://martinfowler.com/bliki/StranglerFigApplication.html) (Martin Fowler)

### Service Communication and Discovery

recommended · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/service-communication

Choose synchronous or asynchronous communication between services, and learn how service discovery, service meshes and contracts keep a fleet connected.

Once you have several services, how they talk matters as much as what they do.

#### Sync vs async
- **Synchronous** (REST, gRPC): caller waits for a response. Simple and immediate, but couples availability: if inventory is down, checkout is down. Long synchronous chains multiply latency and failure probability.
- **Asynchronous** (events, queues): caller publishes and moves on. Decoupled and resilient, but eventually consistent and harder to trace.
Rule of thumb: use sync calls when the user needs the answer now (is the coupon valid?), async for everything that can follow later (send invoice, update search index).

#### Service discovery
Instances come and go, so hardcoded IPs fail.
- **Client-side discovery**: the client asks a registry (Consul, Eureka) and picks an instance.
- **Server-side discovery**: the client calls a stable name; a load balancer or platform routes it. In **Kubernetes**, a Service gives a stable DNS name over changing pods.

#### Service mesh
A **sidecar proxy** (Envoy) next to each service handles mTLS, retries, timeouts, traffic splitting and telemetry, configured centrally (Istio, Linkerd). Useful with many services and teams; heavy for small setups.

#### Contracts and compatibility
- Version APIs and event schemas; prefer additive changes.
- Use a **schema registry** for events (Avro or Protobuf with compatibility rules).
- **Consumer-driven contract tests** catch breaking changes before deploy.

#### Pitfalls
- Deep synchronous call chains (A calls B calls C calls D) for one user request.
- Chatty APIs that need 30 calls to render one screen.
- Adopting a service mesh before you have the basics of timeouts and observability.

You are ready to move on when you can mark each call in a checkout flow as sync or async with a reason and explain how a Kubernetes Service finds healthy pods.

Key concepts: Sync vs async communication, Client vs server-side discovery, Kubernetes Services and DNS, Service mesh and sidecars, Schema registry, Contract testing.

Mini project: Deploy three small services on a local Kubernetes cluster (kind or minikube) that find each other through Service DNS names. Make one call sync and one async through a queue, then scale and kill pods while watching that calls keep working.

Self-check: Why does a chain of five synchronous services, each 99.9 percent available, give lower availability than any one of them alone?

Resources:
- [Kubernetes Service](https://kubernetes.io/docs/concepts/services-networking/service/) (Kubernetes)
- [Service discovery patterns](https://microservices.io/patterns/server-side-discovery.html) (microservices.io)
- [Istio documentation](https://istio.io/latest/docs/) (Istio)

## Reliability, Observability and Security

Keep systems up and understandable in production: resilience patterns, monitoring and tracing, availability targets, disaster recovery and security basics.

### Reliability Patterns

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/reliability-patterns

Stop failures from cascading with timeouts, circuit breakers, bulkheads, load shedding, backpressure and graceful degradation.

In a large system something is always failing. Reliability patterns make sure one failure stays small.

#### Core patterns
- **Timeouts** on every remote call (see the idempotency topic).
- **Circuit breaker**: after repeated failures to a dependency, "open" the circuit and fail fast for a cool-down period, then let a few trial requests through (half-open). Prevents threads piling up on a dead service and gives it room to recover.
- **Bulkheads**: isolate resources (separate thread pools or connection pools per dependency) so a slow recommendation service cannot exhaust the threads that serve checkout.
- **Retries with backoff and jitter**, within a budget.
- **Load shedding**: when overloaded, reject low-priority work early (return 503) so high-priority requests still succeed. Better to serve 80 percent well than 100 percent badly.
- **Backpressure**: slow producers down when consumers fall behind, instead of buffering forever.
- **Graceful degradation / fallbacks**: if personalised recommendations fail, show bestsellers; if ratings are down, hide the stars. Keep the core flow (browse, pay) alive.

#### Preventing cascading failure
Cascades usually start with one slow dependency, then exhausted threads, then retries amplifying load, then healthy services falling over. Combine timeouts, breakers, bulkheads and shedding to break each link. Also avoid synchronized behaviour: thundering herds after a cache flush, or every client retrying at the same second.

#### Testing resilience
**Chaos engineering** deliberately injects failures (kill instances, add latency) in controlled experiments to verify these defences actually work. Start in staging with simple fault injection before anything like Chaos Monkey.

#### Pitfalls
- Circuit breakers with thresholds nobody tuned, tripping on normal noise or never tripping.
- Fallbacks that call another fragile dependency.
- Unbounded in-memory queues that turn overload into out-of-memory crashes.

You are ready to move on when you can trace how a slow payment gateway could take down an entire checkout service and name the pattern that breaks each step of that cascade.

Key concepts: Circuit breaker, Bulkheads, Load shedding, Backpressure, Graceful degradation and fallbacks, Cascading failures, Chaos engineering.

Mini project: Wrap calls to a deliberately flaky service with a circuit breaker and a bulkhead (Resilience4j, Polly, opossum or your own). Load test with and without them while the dependency slows to 5 s, and compare the caller's latency and error rate.

Self-check: What problem does a circuit breaker solve that a timeout alone does not?

Resources:
- [CircuitBreaker](https://martinfowler.com/bliki/CircuitBreaker.html) (Martin Fowler)
- [Addressing cascading failures](https://sre.google/sre-book/addressing-cascading-failures/) (Google SRE)
- [Cloud design patterns](https://learn.microsoft.com/en-us/azure/architecture/patterns/) (Microsoft)
- [Principles of Chaos Engineering](https://principlesofchaos.org/) (principlesofchaos.org)

### Observability: Logs, Metrics and Traces

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/observability

Make a distributed system understandable with structured logs, metrics, distributed tracing, dashboards and alerts that point to real user impact.

You cannot fix what you cannot see. **Observability** is the ability to understand what a system is doing from the data it emits, especially for problems you did not predict.

#### The three pillars
- **Logs**: timestamped event records. Make them **structured** (JSON with fields like request_id, user_id, latency_ms) so they can be searched and aggregated. Centralise them (ELK/OpenSearch, Loki, CloudWatch).
- **Metrics**: numeric time series such as request rate, error rate, latency histograms, queue depth, CPU. Cheap to store and great for dashboards and alerts (Prometheus plus Grafana is a common open-source stack).
- **Traces**: follow one request across services. Each hop is a **span** with timing; a shared **trace ID** links them. Shows which service made a request slow. **OpenTelemetry** is the vendor-neutral standard for emitting all three.

#### What to measure
- **RED** for services: Rate, Errors, Duration.
- **USE** for resources: Utilisation, Saturation, Errors.
- **Four golden signals** (Google SRE): latency, traffic, errors, saturation.
- Business metrics too: orders per minute, payment success rate. A drop here is often the first sign of trouble.

#### Alerting
Alert on **symptoms users feel** (error rate above SLO, p99 too high), not on every CPU spike. Every alert should be actionable and link to a runbook. Too many alerts teach on-call engineers to ignore them.

#### Pitfalls
- Logging everything at INFO and paying a fortune to store noise; logging personal data like phone numbers and card details.
- High-cardinality labels (user_id) on metrics, which explode storage.
- Traces that break at every queue because context is not propagated through message headers.

You are ready to move on when you can instrument a two-service app so that one slow request can be found from a dashboard, followed through a trace and matched to its logs by trace ID.

Key concepts: Structured logging, Metrics and histograms, Distributed tracing, OpenTelemetry, RED, USE and golden signals, Symptom-based alerting, Prometheus and Grafana.

Mini project: Instrument two services with OpenTelemetry, export traces to Jaeger, metrics to Prometheus and logs with trace IDs. Build a Grafana dashboard with RED metrics and an alert, then inject latency and find the culprit using only your tools.

Self-check: Why should alerts fire on user-facing symptoms such as error rate rather than on causes such as high CPU?

Resources:
- [OpenTelemetry documentation](https://opentelemetry.io/docs/) (OpenTelemetry)
- [Prometheus overview](https://prometheus.io/docs/introduction/overview/) (Prometheus)
- [Monitoring distributed systems](https://sre.google/sre-book/monitoring-distributed-systems/) (Google SRE)

### Availability, SLOs and Disaster Recovery

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/availability-and-disaster-recovery

Quantify reliability with SLIs, SLOs and error budgets, design redundancy across zones and regions, and plan backups with clear RPO and RTO targets.

"Highly available" means nothing until you put a number on it.

#### Measuring availability
- **SLI** (indicator): what you measure, such as the percentage of successful requests under 300 ms.
- **SLO** (objective): the target, such as 99.9 percent over 30 days.
- **SLA** (agreement): a contractual promise with penalties, usually looser than the SLO.
- **Error budget**: 100 percent minus the SLO. At 99.9 percent you can be down about **43 minutes a month**; at 99.99 percent about **4.3 minutes**. Spend the budget on releases and experiments; when it runs out, slow down and fix reliability.

#### Availability maths
Components in **series** multiply availabilities (two 99.9 percent services in a chain give about 99.8 percent). Components in **parallel** (redundant replicas) improve it. Remove single points of failure by having at least two of everything critical.

#### Redundancy levels
- **Multiple instances** behind a load balancer.
- **Multiple availability zones** (separate data centres in one region, for example Mumbai ap-south-1 zones). The standard baseline for production.
- **Multiple regions**: active-passive (standby region takes over) or active-active (both serve traffic; much harder because of data consistency). Needed for the strictest targets or regulatory resilience.

#### Backups and disaster recovery
- **RPO** (recovery point objective): how much data you can afford to lose (for example 5 minutes).
- **RTO** (recovery time objective): how long recovery may take (for example 1 hour).
These drive the strategy: periodic backups, point-in-time recovery from WAL archives, warm standby, or full active-active. **Test restores regularly**; an untested backup is a hope, not a plan. Keep backups in another account or region.

#### Pitfalls
- Promising 99.99 percent while depending on a single database primary with manual failover.
- Never running a failover or restore drill until a real incident.

You are ready to move on when you can compute the monthly downtime allowed by 99.95 percent, and propose an RPO, RTO and DR setup for a payments service versus a blog.

Key concepts: SLI, SLO and SLA, Error budgets, Series vs parallel availability, Multi-AZ deployment, Multi-region active-passive and active-active, RPO and RTO, Backup and restore drills.

Mini project: Write an SLO document for a ticket booking API: two SLIs, SLO targets, error budget policy, and a DR plan with RPO and RTO. Then practise a point-in-time restore of a Postgres database and record how long it took.

Self-check: Your checkout calls four services in series, each at 99.9 percent availability. What is the rough availability of checkout, and what could you do to raise it?

Resources:
- [Service level objectives](https://sre.google/sre-book/service-level-objectives/) (Google SRE)
- [Google SRE books](https://sre.google/books/) (Google)
- [AWS Well-Architected Framework](https://aws.amazon.com/architecture/well-architected/) (AWS)

### Security Basics for System Design

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/security-basics

Cover authentication, authorization, encryption in transit and at rest, secrets management and the common web threats every design should address.

Interviewers increasingly expect at least a short security pass on every design, and for payments or health data it is central.

#### Identity
- **Authentication**: sessions with secure cookies for web apps, or **tokens** (JWTs) for APIs and mobile. Keep access tokens short-lived with refresh tokens. Use **OAuth 2.0 / OpenID Connect** for "Login with Google" and third-party access.
- **Authorization**: check permissions on every request, server-side. **RBAC** (roles) for most products, attribute or relationship-based checks for fine-grained sharing. Broken object-level authorization (changing /orders/123 to /orders/124) is one of the most common real bugs.
- **Service-to-service**: mTLS or signed service tokens; do not trust traffic just because it is internal.

#### Protecting data
- **In transit**: TLS everywhere, including inside the VPC for sensitive systems.
- **At rest**: disk and database encryption, with keys in a KMS. Encrypt or tokenise especially sensitive fields (card numbers, Aadhaar). Hash passwords with bcrypt or Argon2, never plain SHA.
- **Secrets**: in a secrets manager (Vault, AWS Secrets Manager), never in code or Git.
- **Data minimisation and residency**: store only what you need; know rules like RBI payment data localisation and India's DPDP Act.

#### Common threats to design against
Injection (SQL, command), XSS, CSRF, SSRF, credential stuffing (rate limits plus MFA), DDoS (CDN and WAF), and abuse of business logic (coupon farming, OTP bombing). The **OWASP Top 10** is the standard checklist.

#### Pitfalls
- Trusting client-side checks or IDs sent from the app.
- Long-lived JWTs that cannot be revoked.
- Logging tokens, passwords or full card numbers.

You are ready to move on when you can add a security section to any design covering authn, authz, encryption, secrets and the top three threats specific to that product.

Key concepts: Sessions vs tokens (JWT), OAuth 2.0 and OpenID Connect, RBAC and object-level authorization, Encryption in transit and at rest, Password hashing, Secrets management and KMS, OWASP Top 10, mTLS between services.

Mini project: Take one of your earlier mini-project APIs and write a threat model: list assets, entry points and the top five threats, then implement short-lived JWTs with refresh, object-level authorization checks and secrets loaded from a secrets manager or vault container.

Self-check: A user changes the order ID in GET /orders/{id} and sees someone else's order. What class of bug is this and where should the fix live?

Resources:
- [OWASP Top 10](https://owasp.org/www-project-top-ten/) (OWASP)
- [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/) (OWASP)
- [OAuth 2.0](https://oauth.net/2/) (oauth.net)
- [Introduction to JSON Web Tokens](https://jwt.io/introduction) (jwt.io)

## Low-Level Design (LLD) and Object-Oriented Design

Design clean classes and interfaces with SOLID and design patterns, then practise classic LLD problems and the machine coding round used by Indian product companies.

### OOP Principles and SOLID

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/oop-and-solid

Use encapsulation, abstraction, inheritance and polymorphism well, and apply the five SOLID principles to keep code easy to extend and test.

Low-level design is judged on whether your classes are **easy to change**. Object-oriented principles and SOLID are the vocabulary interviewers use to judge that.

#### The four OOP pillars
- **Encapsulation**: keep state private and expose behaviour (account.withdraw(amount), not account.balance -= amount).
- **Abstraction**: depend on what something does, not how (a PaymentGateway interface).
- **Inheritance**: reuse through "is-a" relationships. Use sparingly.
- **Polymorphism**: one interface, many implementations, chosen at runtime (UpiPayment, CardPayment).
Prefer **composition over inheritance**: a Car has an Engine, rather than Car extends Engine.

#### SOLID
- **S, Single Responsibility**: a class has one reason to change. An Invoice class should not also send emails.
- **O, Open/Closed**: open for extension, closed for modification. Add a new discount type by adding a class, not by editing a giant if-else.
- **L, Liskov Substitution**: subclasses must work wherever the parent is expected. If Square breaks Rectangle's setWidth behaviour, the hierarchy is wrong.
- **I, Interface Segregation**: many small interfaces beat one fat one. A Printer should not be forced to implement fax().
- **D, Dependency Inversion**: high-level code depends on abstractions; concrete classes are injected. This makes testing with fakes easy.

#### Related ideas
DRY, KISS, YAGNI, high cohesion and low coupling, and **dependency injection** as the practical tool for D.

#### Pitfalls
- Deep inheritance trees built to "reuse code".
- Applying every principle everywhere and producing 40 classes for a 200-line problem.
- Anaemic models: classes that are just getters and setters while all logic sits in one manager class.

You are ready to move on when you can refactor a switch statement over payment types into a polymorphic design and name which SOLID principles the refactor satisfies.

Key concepts: Encapsulation and abstraction, Inheritance vs composition, Polymorphism, Single Responsibility and Open/Closed, Liskov Substitution, Interface Segregation and Dependency Inversion, Dependency injection, DRY, KISS, YAGNI.

Mini project: Write a small discount engine for an e-commerce cart (flat, percentage, buy-one-get-one, bank offer) first as one big function, then refactor it to follow SOLID. Add a new discount type to both versions and compare how many lines you had to touch.

Self-check: Give an example where using inheritance breaks the Liskov Substitution Principle and show how composition fixes it.

Resources:
- [SOLID](https://en.wikipedia.org/wiki/SOLID) (Wikipedia)
- [Refactoring.Guru](https://refactoring.guru/) (Refactoring.Guru)
- [Software design and architecture roadmap](https://roadmap.sh/software-design-architecture) (roadmap.sh)

### Design Patterns for LLD

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/system-design/design-patterns

Learn the creational, structural and behavioural patterns that show up most in LLD rounds, and when each one genuinely helps.

Design patterns are named, reusable solutions to recurring design problems. In LLD interviews, using the right pattern (and naming it) shows maturity; forcing patterns everywhere shows the opposite.

#### Creational
- **Singleton**: one shared instance (a config or a parking lot instance). Easy to overuse; it hides dependencies and complicates tests.
- **Factory / Factory Method**: create objects without the caller knowing the concrete class (VehicleFactory.create("CAR")).
- **Builder**: construct complex objects step by step (an Order with many optional fields).

#### Structural
- **Adapter**: wrap an incompatible interface (Razorpay and PayU SDKs behind one PaymentGateway).
- **Decorator**: add behaviour by wrapping (a pizza with toppings, a logging or caching wrapper around a repository).
- **Facade**: one simple interface over a complex subsystem.
- **Proxy**: control access (lazy loading, caching, auth checks).

#### Behavioural
- **Strategy**: swap algorithms at runtime (pricing, parking fee calculation, split types in Splitwise). The most useful pattern in LLD rounds.
- **Observer**: notify subscribers on change (seat availability updates, notification services).
- **State**: behaviour depends on state (a vending machine: Idle, HasMoney, Dispensing; an order: Placed, Preparing, Delivered).
- **Command**: wrap a request as an object (undo, queues).
- **Chain of Responsibility**: pass a request along handlers (ATM cash dispensing by note denomination, middleware).
- **Template Method** and **Iterator** round out the common set.

#### Pitfalls
- Reciting patterns without explaining the problem they solve in this design.
- Singleton for everything, making code untestable and thread-unsafe.
- Confusing Strategy and State: Strategy is chosen by the client; State transitions itself.

You are ready to move on when you can pick and justify a pattern for vending machine states, multiple payment providers and different fare calculation rules.

Key concepts: Singleton, Factory and Builder, Adapter, Decorator, Facade, Strategy, Observer, State, Command and Chain of Responsibility, Proxy and Template Method.

Mini project: Implement a vending machine using the State pattern, an Observer-based low-stock alert, and a Strategy for payment (cash, UPI, card). Write a short README naming each pattern and the problem it solves.

Self-check: What is the difference between the Strategy and State patterns, given that their class diagrams look almost the same?

Resources:
- [Design patterns catalog](https://refactoring.guru/design-patterns) (Refactoring.Guru)
- [Awesome Low Level Design](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [Java design patterns](https://java-design-patterns.com/) (java-design-patterns.com)

### Approaching an LLD Problem: Requirements, Entities and UML

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/lld-approach-and-uml

Follow a repeatable method for LLD rounds: clarify requirements, find entities and relationships, draw class and sequence diagrams, then code the core.

Most LLD failures come from starting to code too early. A repeatable method keeps you calm and makes your design easy to follow.

#### A step-by-step method
1. **Clarify requirements** (5 minutes): which features are in scope? For a parking lot: multiple floors? vehicle types? payments? Write them as a short list.
2. **Identify entities**: nouns in the requirements become candidate classes (ParkingLot, Floor, Spot, Vehicle, Ticket, Payment).
3. **Define relationships**: association, aggregation, composition ("a Floor has Spots"), inheritance only where it is a genuine "is-a".
4. **Define behaviour**: verbs become methods (parkVehicle, unpark, calculateFee). Decide which class owns each method.
5. **Apply patterns** where variation exists (fee rules as Strategy, spot allocation as Strategy, ticket state as State).
6. **Handle concurrency**: two cars grabbing the same spot, two users booking the same seat.
7. **Code the core flow** with clean interfaces and a small driver or tests.

#### UML you actually need
- **Class diagrams**: classes, key fields and methods, relationships with multiplicity (1 to many).
- **Sequence diagrams**: the order of calls for the main use case.
- Optionally an **enum list** and a **state diagram** for objects with a lifecycle.
Draw them quickly; tools like Mermaid, PlantUML or Excalidraw are fine for practice.

#### What interviewers look for
Clear separation of concerns, extensibility for the obvious next requirement, correct handling of edge cases and concurrency, readable naming, and the ability to explain trade-offs.

#### Pitfalls
- God classes (a ParkingLotManager that does everything).
- Modelling every noun as a class, including ones with no behaviour.
- Ignoring concurrency until the interviewer asks.

You are ready to move on when you can take a fresh prompt such as "design a library management system" and produce a requirement list, class diagram and sequence diagram in 20 minutes.

Key concepts: Clarifying LLD requirements, Finding entities and relationships, Class diagrams, Sequence diagrams, State diagrams, Concurrency considerations, Mermaid or PlantUML.

Mini project: Design a library management system end to end: requirements list, class diagram and checkout sequence diagram in Mermaid, then implement the core classes with an in-memory store and a small test suite.

Self-check: What is the difference between aggregation and composition, and which one describes the relationship between a ParkingFloor and its ParkingSpots?

Resources:
- [UML diagrams reference](https://www.uml-diagrams.org/) (uml-diagrams.org)
- [Mermaid class diagrams and more](https://mermaid.js.org/) (Mermaid)
- [Awesome Low Level Design](https://github.com/ashishps1/awesome-low-level-design) (GitHub)

### LLD Case Study: Parking Lot

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/lld-parking-lot

Design the classic parking lot: floors, spot types, vehicle types, tickets, fee calculation and concurrent spot allocation.

The parking lot is the "hello world" of LLD rounds. It looks simple, which is exactly why interviewers use it to test structure and extensibility.

#### Typical requirements
- Multiple floors, each with spots of different sizes (bike, car, truck; maybe EV charging spots).
- Entry and exit gates issue and close **tickets**.
- Fees depend on vehicle type and duration (first hour flat, then per hour; different rules on weekends).
- Show available spots per floor on a display board.

#### Core classes
- **ParkingLot** (holds floors, gates; often a single instance).
- **ParkingFloor** has many **ParkingSpot**s; each spot has a type and an occupied flag.
- **Vehicle** (abstract) with Bike, Car, Truck, or simply a VehicleType enum.
- **Ticket**: id, vehicle, spot, entry time, exit time, status.
- **EntryGate / ExitGate**, **DisplayBoard**, **Payment**.

#### Where patterns help
- **Strategy** for **spot allocation** (nearest to gate, lowest floor first, spread evenly).
- **Strategy** for **fee calculation** (hourly, flat, weekend pricing). New pricing means a new class, not edited code.
- **Factory** for creating vehicles or spots.
- **Observer** for updating display boards when spots change.

#### Concurrency
Two entry gates may try to assign the same spot. Options: synchronise allocation per floor, use atomic compare-and-set on the spot's occupied flag, or keep a concurrent queue of free spots per type. Mention it before you are asked.

#### Pitfalls
- Hardcoding fee logic inside the Ticket or Gate class.
- Using deep inheritance for spot types when an enum plus a size rule is enough.
- Forgetting lost tickets, overstays and full-lot handling.

You are ready to move on when you can code a parking lot in under an hour where adding a new vehicle type or pricing rule touches only one or two new classes.

Key concepts: Floors, spots and vehicle types, Ticket lifecycle, Spot allocation strategy, Fee calculation strategy, Concurrent allocation, Display board with Observer, EV charging spots extension.

Mini project: Implement a parking lot in Java, Python, Go or TypeScript with pluggable allocation and pricing strategies, thread-safe parking from 4 concurrent gates, and tests covering full lot, overstay and a new vehicle type added later.

Self-check: Two gates call park() at the same instant and both see spot 12 as free. Describe two ways to make sure only one gets it.

Resources:
- [Awesome Low Level Design (parking lot and more)](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [Strategy pattern](https://refactoring.guru/design-patterns/strategy) (Refactoring.Guru)
- [Java concurrency tutorial](https://docs.oracle.com/javase/tutorial/essential/concurrency/) (Oracle)

### LLD Case Study: Movie Ticket Booking (BookMyShow)

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/system-design/lld-bookmyshow

Design a seat booking system with cities, theatres, shows and seats, and handle temporary seat locks and concurrent bookings correctly.

Movie or event booking is a favourite LLD problem in India because its hard part, **two people trying to book the same seat**, is a real concurrency problem.

#### Requirements
- Browse movies by city; list theatres and **shows** (a movie on a screen at a time).
- View the seat map with seat types (regular, premium, recliner) and prices.
- Select seats, hold them for a few minutes while the user pays, then confirm or release.
- Cancel bookings and refund per policy.

#### Core model
City, Theatre, Screen, Seat (row, number, type), Movie, Show (movie, screen, start time, pricing), **ShowSeat** (seat status per show: AVAILABLE, LOCKED, BOOKED), Booking (user, show, seats, amount, status), Payment.
Separating Seat from ShowSeat matters: the same physical seat has a different status for every show.

#### Seat locking
1. User selects seats. The system **locks** them atomically for that show with an expiry (say 5 to 10 minutes).
2. Payment succeeds: seats move to BOOKED, booking confirmed.
3. Payment fails or times out: locks are released.
Implementation choices:
- **Database**: a conditional update (UPDATE show_seat SET status = 'LOCKED', locked_until = ... WHERE id IN (...) AND status = 'AVAILABLE') and check the row count; or SELECT ... FOR UPDATE inside a transaction.
- **Optimistic locking** with a version column.
- **In-memory lock service or Redis** with expiries, backed by a DB constraint as the source of truth.
All selected seats must lock together or none should.

#### Patterns
Strategy for pricing (weekend, premium seats, dynamic pricing), State for booking status, Observer to push seat map updates to other viewers, Factory for payment methods.

#### Pitfalls
- Checking availability and then booking in two separate steps (a race).
- Locks without expiry, leaving seats stuck when users abandon payment.
- Partial locks when one of four selected seats is taken.

You are ready to move on when you can explain and code an all-or-nothing seat lock with expiry that stays correct under 100 concurrent attempts on the same seats.

Key concepts: Theatre, screen, show and seat model, Seat vs ShowSeat status, Temporary seat locks with expiry, All-or-nothing locking, Booking state machine, Pricing strategy, Live seat map updates.

Mini project: Build a booking service with an in-memory or Postgres store: lock seats with expiry, confirm on payment, release on timeout. Write a test that fires 100 concurrent requests for the same 2 seats and asserts exactly one booking succeeds.

Self-check: Why should seat status live on a per-show entity rather than on the physical seat, and how do you release locks when a user closes the app mid-payment?

Resources:
- [Awesome Low Level Design](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [PostgreSQL explicit locking](https://www.postgresql.org/docs/current/explicit-locking.html) (PostgreSQL)
- [State pattern](https://refactoring.guru/design-patterns/state) (Refactoring.Guru)

### LLD Case Study: Expense Sharing (Splitwise)

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/lld-splitwise

Design an expense sharing app with groups, multiple split types, balance tracking and debt simplification.

Splitwise is a popular machine coding question at Indian product companies because it mixes clean modelling with a small algorithm.

#### Requirements
- Users, and **groups** of users (a Goa trip, flatmates).
- Add an expense paid by one (or several) users, split among participants.
- Split types: **EQUAL**, **EXACT** amounts, **PERCENT**, and sometimes **SHARES**.
- Show balances: who owes whom and how much, per group and overall.
- Settle up, and optionally **simplify debts** to minimise the number of payments.

#### Model
User, Group, Expense (id, description, amount, paidBy, splits, type, createdAt), Split (user, amount) with subclasses or a type field, and a **BalanceSheet** keyed by pairs of users (or a net balance per user per group).

#### Patterns
- **Strategy** (or Factory plus Strategy) for split types: each validates its input (percentages sum to 100, exact amounts sum to the total) and computes the per-user amounts.
- **Observer** for notifying users when an expense is added.
- Keep money as integer paise (or a decimal type), never floating point. Decide where rounding remainders go (for example to the payer).

#### Debt simplification
Compute each user's **net balance** (total paid minus total owed). Then repeatedly match the largest creditor with the largest debtor and settle the smaller of the two amounts. This greedy approach, using two heaps, is simple and usually what interviewers expect. Finding the absolute minimum number of transactions is NP-hard in general, so mention that and stay with the greedy approach.

#### Pitfalls
- Floating point money: 100 / 3 split three ways leaves a paisa missing.
- Putting split validation in the controller instead of the split strategy.
- Storing only pairwise balances and getting them inconsistent after edits and deletions.

You are ready to move on when you can implement all four split types with validation, show balances, and simplify debts for a group of five people.

Key concepts: Users, groups and expenses, Split types as strategies, Split validation, Balance sheet, Money as integer paise, Greedy debt simplification, Expense edit and delete.

Mini project: Build a command-line Splitwise clone that accepts commands like EXPENSE u1 1000 4 u1 u2 u3 u4 EQUAL and SHOW u2, supports EQUAL, EXACT and PERCENT splits, and includes a SIMPLIFY command that prints the minimal greedy settlement list.

Self-check: Three friends split Rs 100 equally. How do you store the amounts without losing a paisa, and who absorbs the remainder?

Resources:
- [Awesome Low Level Design](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [Strategy pattern](https://refactoring.guru/design-patterns/strategy) (Refactoring.Guru)
- [Factory method pattern](https://refactoring.guru/design-patterns/factory-method) (Refactoring.Guru)

### The Machine Coding Round

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/system-design/machine-coding-round

Prepare for the 90-120 minute machine coding round at Flipkart, Swiggy, Razorpay and similar companies: working, extensible code under time pressure.

Many Indian product companies run a **machine coding round**: you get a problem statement (a cab booking service, a snake and ladder game, an in-memory key-value store, a meeting room scheduler) and 90 to 120 minutes to write **working, runnable code** that you then demo and explain.

#### What evaluators look for
- **It runs** and handles the given test inputs. A beautiful design that does not run usually fails.
- **Modularity and extensibility**: separate models, services and the driver; adding a feature should not require a rewrite.
- **Clean code**: meaningful names, small methods, no copy-paste, sensible exceptions.
- **Correctness on edge cases**: invalid input, empty states, duplicates.
- Often **bonus requirements** (concurrency, a new feature) that reward a flexible design.

#### A time plan for 90 minutes
1. 10 minutes: read carefully, list requirements, ask clarifying questions, sketch entities.
2. 50 minutes: code models, then services with interfaces, then a simple driver (main method or CLI). Keep it running at every step.
3. 15 minutes: edge cases, input validation, bonus features.
4. 10 minutes: tidy up, run through the sample inputs, prepare to explain.

#### Practical habits
- Use **in-memory storage** behind a repository interface; do not set up a real database.
- Use the language you are fastest in; Java, Python, Go, C++ and TypeScript are all common.
- Prepare a mental skeleton: models, repositories, services, strategies, exceptions, driver.
- Practise with a timer on 10 to 15 classic problems: parking lot, Splitwise, snake and ladder, elevator, cab booking, in-memory cache with TTL and LRU, rate limiter, logger, library management, food ordering.

#### Pitfalls
- Over-engineering early and not finishing.
- Everything in one file and one class.
- Not reading the input/output format and losing marks on demo.

You are ready to move on when you can finish two unseen machine coding problems in 90 minutes each with code that runs, passes the sample inputs and handles one new requirement with small changes.

Key concepts: Reading and scoping the problem, Working code first, Models, services, repositories layout, In-memory storage behind interfaces, Time management, Handling bonus requirements, Snake and ladder, elevator, cab booking practice.

Mini project: Do four timed 90-minute machine coding sessions (snake and ladder, in-memory LRU cache with TTL, meeting room scheduler, cab booking) and push each to GitHub with a README, sample input and output, and a note on what you would improve.

Self-check: With 20 minutes left and a bonus requirement unfinished, what do you prioritise, and why?

Resources:
- [Awesome Low Level Design](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [Flipkart Tech Blog](https://blog.flipkart.tech/) (Flipkart)
- [Refactoring.Guru](https://refactoring.guru/) (Refactoring.Guru)

## HLD Case Studies: Core Building Blocks

Classic high-level design problems that exercise one or two building blocks deeply: URL shortener, rate limiter, notifications, distributed cache, crawler and autocomplete.

### Design a URL Shortener (TinyURL, bit.ly)

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/case-url-shortener

Design a service that turns long URLs into short codes and redirects at very high read volume, covering key generation, storage, caching and analytics.

The URL shortener is the most common first HLD question. It is small enough to finish and deep enough to probe estimation, ID generation, caching and data modelling.

#### Requirements
- Functional: create a short link (optionally a custom alias and expiry), redirect to the original URL, basic click analytics.
- Non-functional: very low redirect latency, high availability, read-heavy (100:1 is a fair assumption), short codes must not collide.

#### Estimation
100 million new links a month gives about 40 writes per second and about 4,000 redirects per second, with peaks several times higher. 5 years of 500-byte records is roughly 3 TB.

#### Generating short codes
- **Base62** (a to z, A to Z, 0 to 9): 7 characters give 62^7, about 3.5 trillion codes.
- **Counter plus Base62**: a unique ID (Snowflake, or ranges handed out by a ticket server so each app server encodes its own block) encoded in Base62. No collisions, but codes are guessable; shuffle or add a salt if that matters.
- **Hash (MD5/SHA) and take 7 characters**: needs collision checks and retries.
- **Pre-generated key service**: a pool of unused random codes; servers take batches.

#### Storage and API
POST /urls returns the code; GET /{code} returns **301** (permanent, browsers cache it, fewer hits to you, weaker analytics) or **302** (temporary, every click reaches you, better analytics). A key-value table code to long_url, expiry, owner; a key-value or wide-column store fits naturally, Postgres also works at this scale with sharding by code.

#### Scaling reads
Cache hot codes in Redis (cache-aside, LRU); a small fraction of links gets most traffic. Put a CDN or edge redirect in front for viral links. Record clicks asynchronously through a queue into an analytics store so redirects stay fast.

#### Pitfalls
- Synchronous analytics writes on the redirect path.
- Ignoring abuse: phishing links, spam bots creating millions of links (rate limits, URL scanning).

You are ready to move on when you can present this design in 35 minutes including estimates, code generation choice with trade-offs, data model, cache and the 301 vs 302 decision.

Key concepts: Requirements and read/write ratio, Base62 encoding, Counter vs hash vs key pool, 301 vs 302 redirects, Caching hot links, Async click analytics, Custom aliases and expiry, Abuse prevention.

Mini project: Write a 2-page design doc and build a working prototype: Base62 codes from a range-allocated counter, Postgres storage, Redis cache-aside on redirect, and click events pushed to a queue and aggregated per day. Load test redirects and report p99.

Self-check: Why would choosing 301 over 302 reduce load on your servers but make your click analytics less accurate?

Resources:
- [The System Design Primer (Pastebin and bit.ly solution)](https://github.com/donnemartin/system-design-primer) (GitHub)
- [ByteByteGo System Design 101](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)
- [Awesome System Design Resources](https://github.com/ashishps1/awesome-system-design-resources) (GitHub)

### Design a Distributed Rate Limiter

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/case-distributed-rate-limiter

Design a rate limiting service shared by many API servers, covering algorithm choice, Redis-backed counters, race conditions, rules and multi-region behaviour.

Knowing the algorithms is step one. The case study asks you to make them work across a fleet of servers handling lakhs of requests per second.

#### Requirements
- Limit requests per user, API key or IP, with different rules per endpoint (OTP: 5 per hour per phone; search: 100 per minute per user).
- Very low added latency (a millisecond or two), highly available, accurate enough.
- Clear 429 responses with Retry-After.

#### Where to place it
- In the **API gateway** or as middleware in each service, calling a shared counter store.
- Or as a **sidecar** or library with local counters synced periodically (faster, less accurate).

#### Shared state in Redis
Each server checks and updates a counter in Redis keyed by rule and client (rl:otp:+9198xxxx). Use:
- **Fixed or sliding window counters** with INCR and EXPIRE.
- **Token bucket** storing tokens and last refill time per key.
The read-modify-write must be **atomic**: wrap it in a **Lua script** (or use MULTI/EXEC) so two servers cannot both take the last token.

#### Scaling and failure
- Shard keys across a Redis Cluster; hot keys (a huge customer) may need local pre-aggregation.
- **Fail open or fail closed?** If Redis is down, most APIs fail open (allow traffic) to stay available; sensitive endpoints like login or OTP may fail closed.
- **Multi-region**: per-region limits are simple and fast; global limits need syncing counters across regions (eventually consistent, slightly over-permissive).

#### Rules management
Store rules in config or a rules service, cached in each limiter, so you can change limits without deploys. Log and meter throttled requests to tune them.

#### Pitfalls
- Non-atomic GET then SET races letting bursts through.
- A synchronous network hop to a far-away Redis adding 20 ms to every request.

You are ready to move on when you can draw the architecture, write the Lua logic for a token bucket in pseudocode, and explain your fail-open policy per endpoint.

Key concepts: Rules per endpoint and client, Gateway vs middleware placement, Redis counters, Atomicity with Lua scripts, Fail open vs fail closed, Multi-region limits, Local pre-aggregation for hot keys.

Mini project: Build a rate limiter middleware backed by Redis with a token bucket implemented as a Lua script, configurable rules from a YAML file, and 429 responses with headers. Run two API instances and a load test that proves the limit holds across both.

Self-check: Two API servers check the same user's token count at the same moment and both see 1 token left. What goes wrong and how does a Lua script fix it?

Resources:
- [Scaling your API with rate limiters](https://stripe.com/blog/rate-limiters) (Stripe)
- [Redis documentation](https://redis.io/docs/latest/) (Redis)
- [ByteByteGo System Design 101](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)

### Design a Notification System

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/case-notification-system

Send push, SMS, email and in-app notifications reliably at scale with preferences, templates, priorities, retries and deduplication.

Every product sends notifications: OTPs, order updates, offers, reminders. At Swiggy or Flipkart scale that means crores of messages a day across channels with very different urgency.

#### Requirements
- Channels: **push** (FCM for Android, APNs for iOS), **SMS** (via Indian SMS gateways, with DLT template registration), **email**, **in-app**.
- Transactional (OTP, order status) and promotional (sale alerts) types with different priorities.
- User preferences and opt-outs, quiet hours, templates in multiple languages.
- Reliable delivery with retries, no duplicates, delivery tracking.

#### Architecture
1. Internal services call a **Notification API** with event type, user and data (not raw message text).
2. The service checks **preferences**, rate limits per user, renders a **template**, and picks channels.
3. It enqueues jobs onto **per-channel, per-priority queues** (OTP queue separate from marketing queue, so a 5 crore user campaign never delays an OTP).
4. **Channel workers** call third-party providers (FCM, APNs, SMS and email vendors) with timeouts, retries with backoff, and failover to a backup provider.
5. A **delivery log** records status; provider webhooks update delivered or failed.

#### Reliability details
- **Idempotency**: a notification ID per event so retries do not send the same SMS twice.
- **Dead letter queues** for permanent failures; invalid device tokens get cleaned up.
- **Rate limiting** per user (no one wants 20 pushes an hour) and per provider (respect vendor throughput limits).
- **Scheduling** for reminders and campaigns at a chosen time, spread out to avoid traffic spikes.

#### Pitfalls
- One shared queue for everything, so marketing blasts delay OTPs.
- Sending promotional SMS without consent or DLT-registered templates (it gets blocked in India).
- No dedup, so a retry storm sends five copies of "your order is delivered".

You are ready to move on when you can draw this pipeline, explain how an OTP stays fast during a mega campaign, and describe how duplicates are prevented end to end.

Key concepts: Push, SMS, email and in-app channels, User preferences and opt-outs, Templates and localisation, Priority queues per channel, Retries, DLQs and provider failover, Deduplication, Scheduled campaigns, DLT rules for SMS in India.

Mini project: Write a design doc and build a prototype with a notification API, a preferences table, two priority queues and email plus mock-SMS workers with retries and dedup by notification ID. Fire a 1 lakh message campaign and show OTP latency stays low.

Self-check: How would you guarantee that a marketing campaign to 5 crore users never delays an OTP by more than a few seconds?

Resources:
- [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) (Google)
- [Apple user notifications](https://developer.apple.com/documentation/usernotifications) (Apple)
- [Swiggy Bytes engineering blog](https://bytes.swiggy.com/) (Swiggy)

### Design a Distributed Cache

core · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/case-distributed-cache

Design a Memcached or Redis Cluster style cache: partitioning with consistent hashing, replication, eviction, hot keys and client behaviour.

Here you design the cache itself rather than just using one. It ties together hashing, replication and memory management.

#### Requirements
- get(key), set(key, value, ttl), delete(key) with sub-millisecond latency.
- Hundreds of GB to TB of data across many nodes, millions of operations per second.
- Highly available; losing some cached data is acceptable, losing the whole cache is not.

#### Single node design
A hash map plus a doubly linked list gives **O(1) LRU**. Add TTL handling (lazy expiry on read plus a background sweeper), a memory limit with eviction, and slab or arena allocation to reduce fragmentation. An event loop (as in Redis) or a multi-threaded design with lock striping (as in Memcached) handles concurrency.

#### Partitioning
Spread keys across nodes with **consistent hashing and virtual nodes** (or Redis-style fixed hash slots). Routing can live in:
- the **client library** (knows the ring, talks to nodes directly; fastest),
- a **proxy** layer (twemproxy, Envoy; simpler clients),
- or the **nodes themselves** redirecting clients (Redis Cluster MOVED replies).
Cluster membership comes from a config service or gossip.

#### Replication and availability
Give each shard a primary and one or more replicas with asynchronous replication. On primary failure, promote a replica (via a coordinator or Sentinel-style voting). Reads can go to replicas if slight staleness is fine.

#### Hot keys and big keys
A viral product key can overload one node. Options: client-side local caching for very hot keys, replicating hot keys to several nodes with a random suffix, and splitting big values.

#### Pitfalls
- Using naive mod N hashing so adding a node flushes almost the whole cache.
- Treating the cache as durable storage.
- No protection against stampedes when a node restarts empty.

You are ready to move on when you can explain how a get request finds its node, what happens when a node dies or is added, and how you would handle a key receiving 1 lakh requests per second.

Key concepts: O(1) LRU with hash map and list, TTL expiry strategies, Consistent hashing or hash slots, Client vs proxy vs server routing, Replication and failover, Hot key mitigation, Gossip membership.

Mini project: Build a mini distributed cache: 3 node processes each running an LRU with TTL over a simple TCP or HTTP protocol, and a client library using a consistent hash ring. Add a fourth node live and measure the hit ratio drop and recovery.

Self-check: When a cache node is added to the cluster, which keys miss, and how does consistent hashing limit the damage compared with mod N hashing?

Resources:
- [Scaling Memcache at Facebook](https://www.usenix.org/conference/nsdi13/technical-sessions/presentation/nishtala) (USENIX)
- [Redis Cluster specification](https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/) (Redis)
- [Consistent hashing](https://en.wikipedia.org/wiki/Consistent_hashing) (Wikipedia)

### Design a Web Crawler

recommended · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/case-web-crawler

Crawl billions of pages politely and efficiently with a URL frontier, deduplication, robots.txt handling, distributed workers and storage.

A web crawler (the first stage of a search engine, or a price monitoring tool) downloads pages, extracts links and keeps going. It tests your thinking about queues, dedup, politeness and scale.

#### Requirements
- Start from seed URLs, fetch pages, extract links, store content for indexing.
- Billions of pages, refreshed periodically; some sites much more often than others.
- **Politeness**: respect robots.txt and do not overload any one host.
- Robust to traps, broken HTML, slow servers and duplicate content.

#### Core components
1. **URL frontier**: the to-crawl queue. Usually two levels: **priority queues** (by page importance and freshness need) feeding **per-host queues**, with each host assigned to one worker so you can enforce a delay between requests to the same host.
2. **DNS resolver cache**: DNS lookups are slow; cache them aggressively.
3. **Fetchers**: many async workers downloading pages with timeouts and size limits.
4. **Parser**: extract text and links, normalise URLs (lowercase host, strip fragments, resolve relative paths).
5. **URL seen check**: a large **Bloom filter** or a distributed key-value set of hashes, so each URL is crawled once per cycle.
6. **Content dedup**: hash page content (or use SimHash for near-duplicates) to skip mirrors.
7. **Storage**: raw pages in object storage, metadata (URL, last crawled, hash, status) in a wide-column store.

#### Scaling
Partition the frontier and the seen set by **host hash** so each worker owns a set of hosts. Scale workers horizontally. Re-crawl scheduling uses how often a page changed in the past.

#### Traps and safety
Infinite calendars, session IDs in URLs and auto-generated pages create **crawler traps**. Limit depth per site, URL length and pages per host, and detect repeating patterns.

#### Pitfalls
- A single global FIFO queue that hammers one host with thousands of parallel requests.
- Ignoring robots.txt and getting blocked or worse.

You are ready to move on when you can explain how your frontier enforces politeness per host while keeping thousands of workers busy.

Key concepts: URL frontier with priority and host queues, Politeness and robots.txt, URL normalisation, Bloom filter for seen URLs, Content dedup and SimHash, DNS caching, Crawler traps, Re-crawl scheduling.

Mini project: Build a polite crawler that respects robots.txt, uses per-host queues with a 1 second delay, dedups URLs with a Bloom filter and stores pages to disk. Crawl a few thousand pages from a seed set you are allowed to crawl and report pages per second and duplicates skipped.

Self-check: Why does the URL frontier need per-host queues instead of a single global queue?

Resources:
- [About robots.txt](https://www.robotstxt.org/) (robotstxt.org)
- [How Google Search works](https://developers.google.com/search/docs/fundamentals/how-search-works) (Google)
- [Common Crawl](https://commoncrawl.org/) (Common Crawl)
- [Bloom filter](https://en.wikipedia.org/wiki/Bloom_filter) (Wikipedia)

### Design Search Autocomplete (Typeahead)

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/case-search-autocomplete

Return the top suggestions for a typed prefix within tens of milliseconds, using tries or precomputed prefix tables built from query logs.

As a user types "biry" on Swiggy or "iph" on Flipkart, suggestions must appear in under about 100 ms, updated with every keystroke. That latency budget drives the whole design.

#### Requirements
- Given a prefix, return the top 5 to 10 suggestions ranked by popularity (and maybe personalisation, location, trends).
- Very high read QPS (every keystroke is a request), low latency.
- Suggestions can lag reality by minutes or hours; strict freshness is not needed.

#### Data structure
A **trie** keyed by characters. To make lookups O(prefix length), **store the top K completions at every node**, so a query just walks the prefix and returns the cached list. Without that, you would traverse the whole subtree per keystroke.
An alternative is a **prefix table**: precompute prefix to top K list in a key-value store (Redis or similar), which is simple to shard and cache.

#### Two pipelines
- **Data collection**: log search queries to Kafka; aggregate counts per query in batch (hourly or daily) or in a streaming job for trending terms, with time decay so old popularity fades.
- **Build and serve**: periodically build a new trie or prefix table from the aggregates and swap it in atomically. The serving layer is read-only and heavily replicated.

#### Scaling and latency
- Shard by prefix (careful: "s" is far hotter than "x"; shard by hashed prefix or by prefix ranges sized by traffic).
- Cache popular prefixes at the edge or in the client; debounce keystrokes (wait 50 to 100 ms) and cancel stale requests on the client.
- For product search, engines like Elasticsearch offer completion suggesters with fuzzy matching for typos.

#### Pitfalls
- Updating the trie on every search in real time and locking the read path.
- Ignoring offensive or unsafe suggestions; keep a blocklist filter.
- Forgetting multi-language and transliterated queries common in India ("paneer" vs Hindi script).

You are ready to move on when you can explain why storing top K at each trie node matters, and draw the offline and online pipelines.

Key concepts: Trie with top K per node, Prefix table in key-value store, Query log aggregation, Time decay and trending, Atomic index swap, Client debouncing and caching, Typo tolerance.

Mini project: Build an autocomplete service: generate a fake query log, aggregate counts, build a trie with top 5 per node, serve it over HTTP, and add a front end with 80 ms debounce. Measure p99 latency for 10,000 random prefixes.

Self-check: Why is it better to rebuild the suggestion index periodically and swap it in than to update it on every search query?

Resources:
- [Trie](https://en.wikipedia.org/wiki/Trie) (Wikipedia)
- [Elasticsearch guide](https://www.elastic.co/guide/index.html) (Elastic)
- [ByteByteGo System Design 101](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)

## HLD Case Studies: Large Products

End-to-end designs of the products interviewers love: WhatsApp-style chat, news feeds, Hotstar-style streaming, Uber/Ola ride matching and UPI-style payments.

### Design a Chat App (WhatsApp)

core · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/system-design/case-chat-app

Design one-to-one and group messaging with persistent connections, message storage, delivery receipts, presence and offline delivery.

WhatsApp serves billions of messages a day with famously small teams. Designing it tests real-time connections, storage at scale and delivery guarantees.

#### Requirements
- One-to-one and group chats (groups up to a few hundred or thousand members), text and media.
- Sent, delivered and read receipts; online and last seen presence.
- Offline users receive messages when they reconnect; message order preserved per chat.
- Low latency, very high availability, end-to-end encryption.

#### Connections
Clients keep a persistent **WebSocket** (or MQTT-style) connection to a **chat server**. A **session service** (Redis) maps user_id to the chat server holding their connection. Millions of connections are spread across many servers; servers are stateful, so use consistent routing and handle reconnects gracefully.

#### Message flow (one-to-one)
1. Sender's chat server receives the message, assigns a **message ID** (time-ordered per conversation) and persists it.
2. It acks the sender (single tick).
3. It looks up the recipient's chat server and forwards the message; if the recipient is offline, it stays in their **pending inbox** and a **push notification** is sent.
4. The recipient's client acks delivery (double tick) and later read (blue ticks); these acks flow back as small events.

#### Storage
Messages are write-heavy and read by conversation and time, a natural fit for a **wide-column store** partitioned by conversation_id and clustered by message ID (Cassandra, ScyllaDB, HBase). Media goes to object storage via pre-signed URLs and a CDN; the message carries only a reference.

#### Groups and presence
Small groups: fan out a copy (or a pointer) to each member's inbox on write. Large groups and channels: store once and let members pull. Presence uses heartbeats with a TTL in Redis; broadcast changes only to contacts who are online, and batch them.

#### Pitfalls
- Using HTTP polling for chat at this scale.
- Global ordering across all chats; you only need order per conversation.
- Forgetting idempotent message IDs, so client retries create duplicates.

You are ready to move on when you can trace a message from sender to an offline recipient and back to blue ticks, naming every component and store it touches.

Key concepts: WebSocket connection servers, Session registry (user to server), Message IDs and per-chat ordering, Delivery and read receipts, Offline inbox and push, Wide-column message storage, Group fan-out, Presence with heartbeats, End-to-end encryption basics.

Mini project: Build a chat prototype: two WebSocket servers, Redis for the session registry and pub/sub between servers, Postgres or Cassandra for messages, and sent/delivered/read receipts. Show a message reaching a user connected to the other server and an offline user receiving it on reconnect.

Self-check: User A is connected to chat server 3 and user B to chat server 7. How does A's message reach B, and what happens if B's server crashes mid-delivery?

Resources:
- [How Discord stores trillions of messages](https://discord.com/blog/how-discord-stores-trillions-of-messages) (Discord)
- [The WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) (MDN)
- [High Scalability](https://highscalability.com/) (High Scalability)

### Design a News Feed (Instagram, Twitter, LinkedIn)

core · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/system-design/case-news-feed

Build a personalised feed with fan-out on write, fan-out on read or a hybrid, feed caching, ranking and pagination.

A news feed shows each user recent posts from people they follow, ranked. The core question is **when** to assemble each user's feed.

#### Requirements
- Users post (text, images); users follow others.
- Home feed shows followed users' posts, newest or ranked, with infinite scroll.
- Feed load in a few hundred ms; posting is fast; heavy read ratio.

#### Fan-out on write (push)
When a user posts, push the post ID into every follower's precomputed **feed cache** (a Redis list or sorted set per user). Reading is a simple cache lookup: very fast. Cost: a celebrity with 5 crore followers triggers 5 crore writes per post, and you do work for inactive users.

#### Fan-out on read (pull)
At read time, fetch recent posts from everyone the user follows and merge. No write amplification, but reads are slow and expensive for users who follow thousands.

#### Hybrid (what real systems do)
Push for normal users; for **celebrities** (followers above a threshold), skip fan-out and merge their recent posts in at read time. Also skip pushing to long-inactive users and rebuild their feed on return.

#### Components
- **Post service** stores posts (sharded by post ID or author); media in object storage plus CDN.
- **Graph service** stores follow relationships (sharded by user).
- **Fan-out workers** consume PostCreated events from Kafka and update feed caches.
- **Feed service** reads the cached post IDs, merges celebrity posts, hydrates them (author, counts) from caches, applies **ranking**, and returns a page with a **cursor**.
- Like and comment counts are updated asynchronously and cached; approximate counts are fine.

#### Ranking
Start with reverse chronological. Ranked feeds score candidates on affinity, engagement, recency and content type, often with an ML model. Keep candidate generation and ranking as separate stages.

#### Pitfalls
- Pure fan-out on write and the celebrity problem.
- Offset pagination on a constantly changing feed.

You are ready to move on when you can compare push, pull and hybrid with numbers and explain how a celebrity's post reaches followers' feeds.

Key concepts: Fan-out on write, Fan-out on read, Hybrid and the celebrity problem, Feed cache in Redis, Post hydration, Feed ranking stages, Cursor pagination, Social graph storage.

Mini project: Write a design doc and build a prototype with users, follows and posts in Postgres, a Kafka or queue-based fan-out worker writing post IDs to Redis feeds, and a celebrity threshold that switches to pull. Simulate one celebrity with 1 lakh followers and compare write load.

Self-check: Why does pure fan-out on write break for celebrity accounts, and how does a hybrid approach fix it without slowing everyone's feed?

Resources:
- [Engineering at Meta (Instagram, WhatsApp)](https://engineering.fb.com/) (Meta)
- [TAO: Facebook's distributed data store for the social graph](https://www.usenix.org/conference/atc13/technical-sessions/presentation/bronson) (USENIX)
- [The System Design Primer (Twitter timeline solution)](https://github.com/donnemartin/system-design-primer) (GitHub)

### Design a Video Streaming Platform (YouTube, Hotstar)

core · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/system-design/case-video-streaming

Design upload, transcoding, adaptive bitrate streaming and CDN delivery, including live events with crores of concurrent viewers.

Disney+ Hotstar has served live cricket to more than 5 crore concurrent viewers. Video systems are mostly about moving huge bytes efficiently, and the CDN does most of the work.

#### Requirements
- Upload videos (creator side), process them, and stream to any device on any network.
- Smooth playback on 3G to fibre; start fast; low rebuffering.
- For live: low delay and massive, spiky concurrency at match moments.
- Metadata, search, recommendations, view counts.

#### Upload and processing (VOD)
1. Client uploads to object storage using **resumable multipart uploads** via pre-signed URLs.
2. An upload event triggers a **transcoding pipeline** (a DAG of jobs on a queue): split into chunks, transcode each chunk in parallel into multiple **resolutions and bitrates** (240p to 4K) and codecs (H.264, H.265, AV1), generate thumbnails, run checks.
3. Output is packaged into small **segments** (2 to 6 seconds) with manifests for **HLS** and **DASH**.

#### Playback
The player downloads the manifest, then fetches segments, switching quality per segment based on measured bandwidth: **adaptive bitrate streaming (ABR)**. Segments are static files, perfect for **CDNs**; popular content is pre-positioned at edges (Netflix even places servers inside ISPs).

#### Live streaming
Ingest from the stadium encoder (RTMP or SRT), transcode in real time into ABR ladders, package into short segments, push to CDNs. Trade-off: shorter segments mean lower latency but more requests and overhead. At peak, the hard problems are **CDN capacity**, origin shielding, pre-scaling ahead of predicted spikes (toss, last overs) and degrading gracefully (cap the max bitrate for everyone instead of failing).

#### Other pieces
Metadata in a relational or document DB, view counts aggregated via a stream (approximate is fine), watch history in a wide-column store, DRM for premium content.

#### Pitfalls
- Serving video from your app servers instead of CDN and object storage.
- Transcoding an entire 2-hour file on one machine.
- Autoscaling reactively for live events; you must pre-scale.

You are ready to move on when you can trace a video from upload to a viewer's screen on a weak 4G connection, and explain how live cricket survives a 3x spike in a minute.

Key concepts: Resumable uploads, Transcoding pipeline as a DAG, Segments and manifests (HLS, DASH), Adaptive bitrate streaming, CDN delivery and pre-positioning, Live ingest and low latency, Pre-scaling for live events, DRM.

Mini project: Use ffmpeg to transcode a video into a 3-rung HLS ladder (360p, 720p, 1080p), serve it from object storage or a static server behind a CDN, and play it with hls.js while throttling bandwidth in DevTools to watch quality switch. Write up the pipeline design.

Self-check: Why does adaptive bitrate streaming split video into short segments, and what is the trade-off of making live segments even shorter?

Resources:
- [HTTP Live Streaming](https://developer.apple.com/streaming/) (Apple)
- [Netflix Tech Blog](https://netflixtechblog.com/) (Netflix)
- [Disney+ Hotstar tech blog](https://blog.hotstar.com/) (Hotstar)
- [FFmpeg documentation](https://ffmpeg.org/documentation.html) (FFmpeg)

### Design Ride Matching (Uber, Ola, Rapido)

core · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/system-design/case-ride-matching

Track millions of moving drivers, find nearby ones with geospatial indexing, match riders reliably and manage the trip lifecycle.

Ride hailing combines high-frequency location writes, geospatial queries and a matching process that must never assign one driver to two riders.

#### Requirements
- Drivers send location every few seconds; riders see nearby cabs.
- A rider requests a ride; the system finds and offers it to suitable nearby drivers; one accepts.
- Trip lifecycle: requested, driver assigned, arriving, in progress, completed, paid; plus cancellations.
- ETA and pricing (including surge), live tracking for the rider.

#### Location ingestion
With 10 lakh active drivers sending updates every 4 seconds, that is about 2.5 lakh writes per second. Keep **current location in memory** (Redis or an in-memory location service), not a disk database; stream updates through Kafka for history, analytics and ETA models.

#### Geospatial indexing
You need "drivers within 2 km of this point" fast:
- **Geohash**: encode lat/long into a string; nearby points share prefixes. Query the cell and its 8 neighbours.
- **Quadtree**: recursively split dense areas; good for uneven density (Bengaluru vs rural areas).
- **H3** (Uber's hexagonal grid) or **S2** (Google): cells with uniform neighbours, used widely in production.
Redis GEO commands work well for a prototype. Shard the location index by **city or region**, since matching is local.

#### Matching
1. Find candidate drivers in nearby cells, filter by vehicle type and availability, rank by ETA (road distance, not straight line).
2. Offer to the best driver with a short timeout; if declined or timed out, offer to the next (or offer to a few in parallel).
3. Make assignment **atomic**: a driver's status changes from AVAILABLE to ASSIGNED with a conditional update so two riders cannot get the same driver.
A **trip service** owns the trip state machine; a **dispatch service** runs matching per city.

#### Other concerns
Surge pricing from demand/supply ratios per cell, live tracking pushed over WebSockets, payments after the trip, and handling flaky driver connectivity.

#### Pitfalls
- Writing every location ping to a relational database.
- Straight-line distance for ETA in cities with rivers and one-way roads.
- Race conditions that double-assign drivers.

You are ready to move on when you can explain how a rider's request finds the nearest available driver in under a second and why a geospatial index is needed.

Key concepts: High-frequency location ingestion, Geohash, Quadtree, H3 and S2 cells, Driver offer and timeout flow, Atomic driver assignment, Trip state machine, Surge pricing.

Mini project: Simulate 10,000 drivers moving around a city map and sending locations to Redis GEO every few seconds. Build a request endpoint that finds the 5 nearest available drivers, offers sequentially with timeouts, and assigns atomically. Report p99 matching time.

Self-check: Why is a geohash or H3 cell lookup much faster than computing the distance from the rider to every driver, and what edge case do neighbouring cells solve?

Resources:
- [H3 hexagonal grid system](https://h3geo.org/) (Uber)
- [Uber engineering blog](https://www.uber.com/blog/engineering/) (Uber)
- [Geohash](https://en.wikipedia.org/wiki/Geohash) (Wikipedia)
- [Redis documentation (geospatial)](https://redis.io/docs/latest/) (Redis)

### Design a Payment System (UPI-style)

core · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/system-design/case-payments-upi

Design a payment flow that never loses or double-counts money: idempotency, a double-entry ledger, state machines, reconciliation and PSP or UPI integration.

Payments are the case study where correctness beats everything. A slow feed is annoying; a double debit is a support ticket, a refund and a regulatory problem.

#### Context: how UPI flows work
In UPI, the payer's app (a **PSP** such as PhonePe or Google Pay) sends a request through **NPCI**, which routes it to the payer's bank to debit and the payee's bank to credit. Every transaction carries a unique transaction reference. A merchant usually integrates through a **payment gateway** (Razorpay, PayU, Cashfree) rather than talking to NPCI directly. Responses can be **pending** or delayed, so the design must handle uncertainty.

#### Core components (merchant or gateway side)
- **Payment service**: creates a payment intent with an **idempotency key**, calls the external PSP or bank, tracks state.
- **Payment state machine**: CREATED, PENDING, SUCCESS, FAILED, REFUNDED. Transitions are explicit and only move forward.
- **Ledger service**: a **double-entry ledger**, where every movement is two entries (debit one account, credit another) that sum to zero. Entries are **append-only**; corrections are new entries, never edits.
- **Wallet or balance** views derived from the ledger.
- **Webhook and status poller**: providers notify asynchronously; if no callback arrives, poll the status API.
- **Reconciliation job**: compare your records with bank and gateway settlement files daily and flag mismatches.

#### Correctness rules
- Idempotency at every hop: client to API, API to provider (use the provider's idempotency or reference IDs), and webhook processing.
- Strong consistency (ACID, serialisable or careful locking) for balances; a relational database is the usual choice.
- Never mark SUCCESS without confirmation; treat timeouts as **unknown**, not failed, and resolve them by status checks.
- Store money as integers in paise; record currency explicitly.
- Outbox pattern for events like PaymentSucceeded so order fulfilment is never missed.

#### Non-functional
Audit logs, PCI DSS for card data (tokenise, never store CVV), RBI data localisation, encryption, fraud and velocity checks, and high availability with careful failover.

#### Pitfalls
- Retrying a debit after a timeout without an idempotency key.
- Mutable balance columns updated in place with no ledger.
- Skipping reconciliation and discovering mismatches only through customer complaints.

You are ready to move on when you can walk through a payment that times out, then succeeds via webhook ten minutes later, and show that the user is charged once and the order is fulfilled once.

Key concepts: UPI and PSP flow basics, Payment intent and idempotency, Payment state machine, Double-entry ledger, Handling pending and unknown states, Webhooks and status polling, Reconciliation, PCI DSS and data localisation.

Mini project: Write a design doc and build a mock payment system: a payment API with idempotency keys, a fake PSP that randomly times out or answers late via webhook, a double-entry ledger in Postgres and a reconciliation script that compares your ledger with the PSP's settlement file.

Self-check: A call to the bank times out after 30 seconds. Why must you not mark the payment as failed and retry immediately, and what should you do instead?

Resources:
- [NPCI (UPI operator)](https://www.npci.org.in/) (NPCI)
- [Idempotent requests](https://docs.stripe.com/api/idempotent_requests) (Stripe)
- [Razorpay engineering blog](https://engineering.razorpay.com/) (Razorpay)
- [Zerodha tech blog](https://zerodha.tech/) (Zerodha)

## Cracking System Design Interviews

A repeatable interview framework, how to talk about trade-offs, the mistakes that sink candidates, and how to prepare for Indian product company rounds.

### A Framework for System Design Interviews

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/system-design/interview-framework

Run a 45-60 minute design round with a clear structure: requirements, estimates, API, data model, high-level design, deep dives and wrap-up.

System design interviews are open-ended on purpose. A clear structure keeps you from rambling and shows the interviewer how you think.

#### A 45 to 60 minute structure
1. **Clarify requirements (5 to 8 min)**: functional features (agree on 3 or 4 core ones), non-functional needs (scale, latency, availability, consistency), and what is out of scope. Write them down.
2. **Estimate (3 to 5 min)**: DAU, read and write QPS, peak, storage over a few years. Only as deep as it changes decisions.
3. **API (3 to 5 min)**: the key endpoints with inputs and outputs.
4. **Data model (5 min)**: main entities, keys and the database choice with a reason.
5. **High-level design (10 min)**: draw clients, LB or gateway, services, databases, caches, queues, CDN. Walk through the main read and write flows end to end.
6. **Deep dives (15 to 20 min)**: pick the hardest parts (or follow the interviewer's lead): scaling the hot path, consistency, failure handling, a specific algorithm such as matching or fan-out.
7. **Wrap up (3 to 5 min)**: bottlenecks, monitoring, what you would do with more time.

#### Make it collaborative
Think out loud, check in ("I am planning to focus on the feed generation, does that sound good?"), and adjust when the interviewer nudges you. They are evaluating how you would design alongside them at work.

#### By level
- **SDE-1 / new grad**: solid fundamentals, a working end-to-end design, sensible components.
- **SDE-2**: deeper trade-offs, scaling the bottleneck, failure modes.
- **SDE-3 and above**: drive the conversation, prioritise, discuss operations, cost and evolution.

#### Pitfalls
- Drawing boxes before agreeing on requirements.
- Spending 15 minutes on estimation arithmetic.
- Never walking a request through the diagram.

You are ready to move on when you can run this framework on a fresh problem in 45 minutes with a timer and have time left for at least one real deep dive.

Key concepts: Clarifying requirements and scope, Estimation that drives decisions, API and data model, High-level diagram and request walkthrough, Choosing deep dives, Wrap-up: bottlenecks and monitoring, Expectations by level.

Mini project: Record yourself (video or audio) designing three problems from this track in 45 minutes each using the framework, with a diagram in Excalidraw. Rewatch and score each step against the timings above.

Self-check: The interviewer says 'design Swiggy'. What are the first five questions you ask before drawing anything?

Resources:
- [How to approach a system design interview question](https://github.com/donnemartin/system-design-primer) (System Design Primer)
- [ByteByteGo](https://bytebytego.com/) (ByteByteGo)
- [Excalidraw whiteboard](https://excalidraw.com/) (Excalidraw)

### Talking About Trade-offs

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/system-design/trade-offs-communication

Explain decisions the way senior engineers do: name the options, the criteria, what you give up, and when you would change your mind.

There is rarely a right answer in design, so interviewers judge **how you choose**. Strong candidates make trade-offs explicit; weak ones state choices as facts.

#### A simple pattern for every decision
1. **Options**: "We could use Postgres with read replicas or Cassandra."
2. **Criteria from the requirements**: "We need 50k writes per second, queries by conversation, and no joins."
3. **Choice and cost**: "Cassandra fits the write volume and access pattern; we give up ad hoc queries and multi-row transactions."
4. **Revisit trigger**: "If we later need complex analytics, we stream data into a warehouse."

#### Trade-offs that come up constantly
- **Consistency vs availability and latency**: strong reads for balances, eventual for likes.
- **Latency vs throughput**: batching raises throughput but adds delay.
- **Read vs write optimisation**: denormalisation and fan-out on write make reads cheap and writes expensive.
- **SQL vs NoSQL**: flexibility and transactions vs scale on known access patterns.
- **Sync vs async**: immediate answers vs resilience and decoupling.
- **Push vs pull**: in feeds, notifications and live updates.
- **Build vs buy (managed services)**: control and cost vs speed and less ops.
- **Simplicity vs future scale**: do not build for 100 crore users on day one.
- **Cost**: storage tiering, caching vs compute, egress charges.

#### Language that helps
"It depends on X; given our requirement Y, I would pick Z." "The bottleneck here will be ...; to address it ..." "A simpler alternative is ..., which works until about N QPS."

#### Pitfalls
- Buzzword stacking (Kafka, Kubernetes, microservices) with no reason tied to requirements.
- Defending a choice stubbornly when the interviewer adds a new constraint; adapting is a strength.
- Hedging so much that you never commit.

You are ready to move on when you can justify five decisions in one of your designs using the options, criteria, cost and revisit pattern without notes.

Key concepts: Options, criteria, cost, revisit, Consistency vs latency, Read vs write optimisation, Sync vs async and push vs pull, Build vs buy, Cost awareness, Adapting to new constraints.

Mini project: Pick two of your case study designs and write a decision log (an ADR-style table) with at least six decisions each: options considered, chosen option, what you gave up, and the trigger that would make you change it.

Self-check: Your interviewer says the news feed must now show posts within 1 second of publishing, even from celebrities. Which trade-off from your design changes and how?

Resources:
- [Designing Data-Intensive Applications](https://dataintensive.net/) (Martin Kleppmann)
- [Architecture decision records](https://adr.github.io/) (adr.github.io)
- [AWS Builders' Library](https://aws.amazon.com/builders-library/) (AWS)

### Common Mistakes and Interview Prep for Indian Product Companies

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/system-design/interview-prep-india

Avoid the mistakes that sink most candidates and prepare a realistic plan for LLD, machine coding and HLD rounds at Flipkart, Swiggy, Razorpay and similar companies.

You now know the building blocks and case studies. This last step is about converting that knowledge into offers.

#### Mistakes that sink candidates
- Starting to design before clarifying requirements and scale.
- Memorised answers: reciting "the YouTube design" without adapting to what was asked.
- Single points of failure left in the final diagram (one DB, one LB, one Redis).
- Ignoring failure modes: what happens when the cache, queue or a region is down?
- Hand-waving the hard part ("we will use a queue") without saying how ordering, retries or duplicates work.
- No numbers at all, or only numbers that never influence a decision.
- Not listening to hints, or arguing instead of exploring the interviewer's concern.

#### What the rounds look like
- **Machine coding / LLD** (very common at Flipkart, Swiggy, PhonePe, Razorpay, Meesho, Zomato for SDE-1 and SDE-2): working, extensible code in 90 to 120 minutes, then a review.
- **HLD**: usually from SDE-2 upwards; sometimes a lighter version for strong freshers. Expect India-flavoured problems: food delivery and ETA, UPI payments, flash sales and inventory, IRCTC-style booking, live cricket scores, quick commerce dark stores.
- **Hiring manager or bar raiser**: discussion of past projects with design depth; be ready to explain your own internship or project architecture and its trade-offs.

#### A preparation plan (8 to 10 weeks alongside DSA)
1. Weeks 1 to 3: fundamentals sections of this track, with mini-projects.
2. Weeks 3 to 5: LLD patterns plus 8 to 10 timed machine coding problems.
3. Weeks 5 to 9: two HLD case studies a week, written up as 1 to 2 page docs with diagrams.
4. Throughout: read engineering blogs from Indian companies (Swiggy Bytes, Razorpay, Flipkart, Zerodha, Hotstar) to learn how real systems at Indian scale work.
5. Last 2 weeks: at least 4 to 6 **mock interviews** with peers or seniors, timed, with feedback.

#### Pitfalls
- Watching videos passively instead of designing on paper and getting feedback.
- Skipping LLD because HLD feels more impressive; for early-career roles LLD often decides the outcome.

You have finished this track when you can take an unseen problem, run the full framework in 45 minutes, defend your trade-offs under pushback and finish a machine coding problem with working code.

Key concepts: Common mistakes checklist, Removing single points of failure, Discussing failure modes, India-specific problem themes, Explaining your own projects' design, Engineering blogs from Indian companies, Mock interviews.

Mini project: Design a flash sale system for a Big Billion Days style event (inventory, queueing users, payments, preventing overselling) as a 2-page doc, then present it in a timed mock interview with a peer and write down three pieces of feedback to act on.

Self-check: Look at your last design diagram. List every single point of failure in it and how you would remove each one.

Resources:
- [Swiggy Bytes](https://bytes.swiggy.com/) (Swiggy)
- [Flipkart Tech Blog](https://blog.flipkart.tech/) (Flipkart)
- [Razorpay engineering blog](https://engineering.razorpay.com/) (Razorpay)
- [Awesome System Design Resources](https://github.com/ashishps1/awesome-system-design-resources) (GitHub)

## Related

- [Career roadmaps](https://www.internhack.in/roadmaps)
