Happy Dussehra! May good always win. Merry Christmas! Warm wishes from Vizag. Happy New Year! Here’s to a great year ahead.

DevOps

System Design, the Complete Picture: Beginner to Expert, a Real Project and the AI Era

System design from first principles to expert level: request path, estimation, caching, databases, replication, sharding, messaging, sagas, consensus, resilience, SLOs, security, multi-region DR and cost, a full HR and payroll SaaS project, five case studies, RAG, LLM serving, AI gateways, agents and AIOps, with 24 animated step-by-step diagrams and an interview playbook.

By Claude86 min read

  • Kubernetes
  • AWS
  • PostgreSQL
  • Redis
  • Kafka
  • vLLM

How to use this guide

This guide is the full map of system design, from “what happens when I type a URL” to multi-region failover, and then into the part interviewers now ask about most: how AI workloads change system design, and how AI is changing the way we design and run systems. It pairs with the DevOps Interview Guide, whose section 10 drills ten classic interview questions (URL shortener, rate limiter, notifications, news feed and more). This post is the foundation under them.

One product runs through the whole guide so the ideas stay concrete: PayFlow, a multi-tenant HR and payroll SaaS for Indian companies. It does payroll runs, payslips, leave, attendance and statutory filings (PF, ESI, PT, TDS). It starts on one VM and grows to millions of employees across two regions, then adds an AI assistant and agents. Every concept is tied back to a decision PayFlow had to make.

Completely new to the subject? Read the gentler System Design for Beginners first, then come back here.

How to read the animated diagrams. Each diagram loops through numbered steps. The active arrow turns orange, a dot travels along it, the receiving box is outlined, and the caption under the picture says what is happening. The numbers on the arrows match the numbered list under each diagram, which carries the fuller explanation. If you prefer to read rather than watch, the list alone tells the whole story.

Levels. Part 1 is for beginners, part 2 intermediate, part 3 advanced, part 4 expert. Part 5 is the PayFlow project end to end, part 6 adds five more case studies, part 7 is the AI era, and part 8 is the interview playbook with a cheat sheet.

1. Foundations (beginner)

1.1 What system design really is, and its dimensions

System design is deciding how the parts of a software system fit together so it meets its requirements: what it must do (functional) and how well it must do it (non-functional), within a budget and a team’s ability to run it. There is no single right answer. There are trade-offs that you can explain.

Every design touches the same dimensions. A strong answer visits most of them on purpose rather than by accident.

Dimension Question it answers PayFlow example
Functional scope What must it do? Run payroll, generate payslips, apply leave
Scale How many users, requests, bytes? 2M employees, about 1.5k requests/s at the payday peak
Performance How fast? Payslip page under 300 ms at p99
Availability How often may it be down? 99.95% (about 22 minutes a month)
Consistency Can readers see stale data? Salaries: never wrong; dashboard counts: a few seconds stale is fine
Durability Can data be lost? Never lose a processed payroll (RPO near zero)
Security and privacy Who can see what? Tenant isolation, PII encryption, DPDP Act duties
Operability Can a small team run it? Managed services, GitOps, good dashboards
Cost What does it cost per tenant? Infra cost under 8% of revenue
Evolvability Can it change safely? Weekly releases with zero downtime
Compliance Which rules apply? Data stays in India; audit trails for payroll changes
AI readiness Can AI features be added safely? Clean data, permission-aware APIs, an AI gateway

Real world: a junior answer to “design PayFlow” jumps to “Kubernetes and microservices”. A senior answer first asks “how many tenants, what is the peak, what can never be wrong?” and lets those answers pick the technology.

Say in the interview: “Before drawing boxes I want to pin down the requirements and the two or three non-functional properties that will drive the design, because they decide the trade-offs.”

1.2 The life of a request

Almost every design builds on one path: name resolution, edge, load balancer, stateless application, cache, database. Learn this path cold. Most “design X” questions are this path plus one or two special components.

Life of one request in PayFlow (animated, 8 steps)Browser / appDNS resolverCDN edgestatic filesLoad balancerTLS ends hereApp server 1App server 2Cache (Redis)Database123456781Browser asks DNS for api.payflow.in and gets an IP.2Static files (JS, CSS, images) come from the nearest CDNedge.3The API call reaches the load balancer over HTTPS.4LB picks a healthy app server (round robin or leastconnections).5The app checks the cache first.6On a cache miss it reads the database.7The result is stored in the cache with a TTL.8The response travels back through the load balancer.All 8 steps done. The flow replays…
Animated diagram: Life of one request in PayFlow. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Browser asks DNS for api.payflow.in and gets an IP. DNS answers are cached by the OS and resolver for the record’s TTL. Low TTLs (60 s) make failover faster; high TTLs cut lookups.
  2. Static files (JS, CSS, images) come from the nearest CDN edge. The heavy, cacheable bytes never touch your servers. Only API calls travel to the origin.
  3. The API call reaches the load balancer over HTTPS. TLS usually terminates here (or at the CDN). The LB only sends traffic to targets that pass health checks.
  4. LB picks a healthy app server (round robin or least connections). Because servers are stateless (sessions live in Redis or a JWT), any server can take any request. The dashed arrow shows the next request may land on server 2.
  5. The app checks the cache first. A Redis GET takes well under a millisecond inside the same zone, so most reads stop here.
  6. On a cache miss it reads the database. The database is the source of truth. An indexed primary-key read is a few milliseconds; an unindexed scan can be seconds.
  7. The result is stored in the cache with a TTL. The next reader gets the cached copy. The TTL bounds how stale it can be.
  8. The response travels back through the load balancer. Total budget for this call might be 200 ms at p99: DNS (cached) ~0, TLS reuse ~0, LB 1 ms, app 20 ms, cache 1 ms or DB 5 ms, network the rest.

What to take from it:

  • Stateless app servers are the key to horizontal scaling. Put session state in Redis or a signed token, never in server memory.
  • Every hop adds latency and a failure mode. Know roughly what each costs (see 1.3).
  • Health checks at the load balancer are what turn “a server died” into “nobody noticed”.

1.3 Requirements and back-of-the-envelope numbers

Functional requirements are features (“employees download payslips”). Non-functional requirements are qualities with numbers (“p99 under 300 ms, 99.95% available, data in India”). Always write both down, and ask which non-functional one matters most. For payroll it is correctness; for a news feed it is latency; for a chat app it is delivery.

Availability in minutes. Each extra nine costs far more than the last.

Availability Downtime per month Typical cost of getting there
99% 7.3 hours One server and backups
99.9% 43.8 minutes Redundant servers, managed DB with failover
99.95% 21.9 minutes Multi-AZ everything, automated deploys and rollback
99.99% 4.4 minutes Multi-region or cells, chaos testing, 24×7 on-call

If service A (99.9%) calls B (99.9%) and C (99.9%) in series, the best A can be is about 99.7%. Dependencies multiply. That is why critical paths should be short and why caches and fallbacks matter.

Latency numbers worth remembering (order of magnitude, not exact):

Operation Rough time
Read from memory (RAM) 100 ns
Read 1 MB sequentially from memory 10-50 µs
Redis GET in the same zone 0.2-0.5 ms
SSD random read 0.1 ms
Round trip within one AWS region (across AZs) 0.5-2 ms
Indexed DB query 1-10 ms
Mumbai to Hyderabad round trip 20-30 ms
Mumbai to US East round trip 180-220 ms
LLM time to first token (hosted model) 300 ms to 2 s

Worked estimate for PayFlow at scale. Assume 2,000 tenants with 2M employees, plus HR admins.

  • Daily active users: about 30% of employees open the app on a normal day, so 600k DAU. Say 20 requests each: 12M requests/day. Divide by 86,400 s: about 140 requests/s on average. Peak is usually 3-5× average for business apps, but payday (the 1st) is spiky: assume 10×, so about 1,400 requests/s at peak, with payslip downloads dominating.
  • Payroll run: 2M employees, mostly in the last 5 days of the month, each needing about 50 calculations and 2 KB of results. 2M × 2 KB = 4 GB of results a month. Easy for one database to store; the challenge is computing it in a few hours, which is a batch problem (part 5).
  • Payslip PDFs: 2M × 100 KB = 200 GB a month, 2.4 TB a year. That belongs in object storage (S3), not the database.
  • Bandwidth at peak: 1,400 requests/s × 50 KB average = 70 MB/s. Fine for a CDN.

The point isn’t precision. It’s spotting which part is hard: here, the monthly payroll batch and the payday read spike, not everyday traffic.

Say in the interview: “Roughly 1.4k requests/s at peak and 2.4 TB of PDFs a year: one well-indexed relational database handles the transactional load, PDFs go to object storage, and the real design work is the month-end batch.”

1.4 Networking and API design

Know when to use which protocol:

Need Use Why
Public CRUD API REST over HTTPS (JSON) Universal, cache-friendly, easy to debug
Service-to-service, high volume gRPC (HTTP/2, protobuf) Smaller payloads, typed contracts, streaming
Flexible reads for many UIs GraphQL Client picks fields; watch for N+1 queries and cost limits
Server pushes to clients WebSocket or Server-Sent Events Chat, live dashboards, streaming LLM tokens (SSE)
Event notifications to partners Webhooks Simple; must be signed, retried and idempotent
Lossy real-time media UDP (WebRTC, QUIC) Late data is useless, so don’t retransmit

API design rules that come up in interviews:

  • Idempotency. GET, PUT and DELETE should be idempotent. POSTs that move money or create resources take an Idempotency-Key header. This is the most important API concept for payments and payroll.
  • Pagination. Use cursor-based pagination (?after=emp_8812&limit=50) for large or changing lists. Offset pagination gets slow and skips rows when data changes underneath it.
  • Versioning. Put the version in the path (/v2/) or a header. Add fields freely, never remove or rename them inside a version.
  • Errors. Consistent error bodies with a machine-readable code, and correct status codes: 400 the client is wrong, 409 conflict, 429 slow down, 503 try later.
  • Rate limits. Per tenant and per API key, returned in response headers so clients can back off (section 10.3 of the DevOps Interview Guide designs the limiter itself).
Idempotency key on a retried payout call (animated, 6 steps)Mobile appPayouts APIIdempotency storekey → status, responsePayment servicemoves the money1,52,6341POST /payouts with header Idempotency-Key: k-123.2API checks k-123: not seen, so it saves it as IN_PROGRESS.3The payout runs exactly once.4The response is lost on a flaky mobile network.5The app retries with the same key.6Key found: the API returns the stored response. No secondpayout.All 6 steps done. The flow replays…
Animated diagram: Idempotency key on a retried payout call. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. POST /payouts with header Idempotency-Key: k-123. The client generates the key once per logical action (a UUID) and reuses it for every retry of that action.
  2. API checks k-123: not seen, so it saves it as IN_PROGRESS. Use an atomic insert (unique constraint or Redis SET NX). Two parallel retries cannot both win.
  3. The payout runs exactly once. The final response is saved against the key, usually for 24 hours to 7 days.
  4. The response is lost on a flaky mobile network. From the client’s side the call simply timed out. It cannot know whether money moved.
  5. The app retries with the same key. Retries use exponential backoff with jitter so thousands of phones do not retry in the same second.
  6. Key found: the API returns the stored response. No second payout. If the key is still IN_PROGRESS the API returns 409 or 202 and the client polls. If the body differs from the original, reject with 422.

Real world: payment gateways such as Stripe and Razorpay require idempotency keys on payment creation for exactly this lost-response case.

1.5 Scaling the first time: vertical, horizontal and load balancing

Vertical scaling means a bigger machine. It is simple and needs no code changes, but it has a ceiling, a single point of failure and a step-change cost. Horizontal scaling means more machines behind a load balancer. It needs stateless services but scales almost without limit and survives machine loss.

Load balancers:

  • L4 (TCP/UDP), for example AWS NLB: very fast, routes by IP and port, can’t see URLs.
  • L7 (HTTP), for example ALB, NGINX, Envoy: routes by path, host or header, terminates TLS, can retry and rewrite.
  • Algorithms: round robin (equal servers), least connections (uneven request cost), weighted (mixed instance sizes), consistent hashing (stickiness for caches), and least outstanding requests or “power of two choices” (good default at scale).
  • Health checks: liveness (is the process alive?) vs readiness (can it take traffic now?). Getting these mixed up in Kubernetes causes restart loops.
  • Connection draining lets in-flight requests finish during deploys.

Rule of thumb: scale vertically until it hurts or until a single failure is unacceptable, then go horizontal. PayFlow’s stage 0 (one VM) to stage 1 (two app servers behind a load balancer) in part 5 is exactly this move.

Say in the interview: “I’d keep the app tier stateless, put it behind an L7 load balancer with readiness checks and draining, and autoscale on request rate. The database is the part that doesn’t scale horizontally for free, so that’s where I’ll spend the design time.”

2. Building blocks (intermediate)

2.1 Caching

A cache keeps a copy of data closer to where it’s needed so you skip slower work. Caches exist at every layer: browser, CDN, API gateway, application memory, Redis, database buffer pool, and now LLM prompt caches.

Patterns:

Pattern How it works Good for Watch out for
Cache-aside (lazy) App reads cache, on miss reads DB and fills cache Most read-heavy APIs First request is slow; stale data until TTL or delete
Read-through Cache library loads from DB itself Simpler app code Tied to a library
Write-through Write goes to cache and DB together Data read right after write Slower writes; caches data nobody reads
Write-behind Write to cache, flush to DB later Counters, very high write rates Data loss if cache dies before flush
Refresh-ahead Refresh hot keys before they expire Predictable hot data Wasted work on cold keys
Cache-aside: read path and write path (animated, 6 steps)App serviceRedis cachePrimary DBTTL + random jitter stops thousands of keys expiring together1,4,623,51Read: GET employee:42 from the cache.2Miss: the cache has nothing (or the entry expired).3The app reads the row from the database.4The app SETs employee:42 with a 10-minute TTL.5Write: update the database first.6Then DELETE the cache key instead of updating it.All 6 steps done. The flow replays…
Animated diagram: Cache-aside: read path and write path. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Read: GET employee:42 from the cache. Key naming carries the tenant: t12:employee:42. That prevents cross-tenant leaks.
  2. Miss: the cache has nothing (or the entry expired). Hit ratio is the KPI to watch. Below roughly 80% for a read-heavy path, question the key design or TTL.
  3. The app reads the row from the database. Under a stampede (a hot key just expired) let only one caller rebuild it: a short lock or request coalescing.
  4. The app SETs employee:42 with a 10-minute TTL. Store what you will read: often a pre-rendered JSON blob rather than raw rows.
  5. Write: update the database first. The database stays the source of truth. Never write only to the cache unless you chose write-behind on purpose.
  6. Then DELETE the cache key instead of updating it. Deleting avoids races where two writers leave an old value in the cache. The next read refills it.

The hard problems:

  • Invalidation. Prefer delete-on-write plus TTL. For multi-service setups, publish change events and let caches evict on them.
  • Stampede (thundering herd). A hot key expires and 5,000 requests hit the database together. Fixes: request coalescing (single-flight), a short lock, serving stale while one caller refreshes, and TTL jitter.
  • Hot keys. One key gets a huge share of traffic (a celebrity, a tenant’s dashboard on payday). Fixes: local in-process cache for a few seconds, key replication (key#1..key#8), or a CDN.
  • Eviction. LRU suits most workloads, LFU suits stable popularity. Size the cache to the working set, not the whole dataset.
  • Consistency budget. Decide per data type how stale is acceptable. PayFlow caches tax rules for hours, dashboard counts for 30 seconds, and never caches the payroll approval state.

CDN. A content delivery network is a geographically distributed cache. Static assets get long TTLs with content-hashed filenames (app.3f9a1c.js), so a deploy changes the name instead of needing a purge. APIs can be cached at the edge too when responses are public or keyed carefully. Modern CDNs also run code at the edge (Cloudflare Workers, Lambda@Edge) for auth checks, redirects and A/B routing.

Say in the interview: “Cache-aside in Redis with delete-on-write and jittered TTLs, single-flight on misses for hot keys, and a CDN in front of anything static. I’d monitor hit ratio and evictions, and I’d never cache anything where staleness changes money.”

2.2 Databases and data modelling

Choose the database from the access pattern, not from fashion.

Type Examples Strong at Weak at
Relational (OLTP) PostgreSQL, MySQL, Aurora Transactions, joins, constraints, mature tooling Horizontal write scaling needs sharding
Key-value Redis, DynamoDB Very fast lookups by key, huge scale Ad-hoc queries
Wide-column Cassandra, ScyllaDB, Bigtable Massive write throughput, time-ordered data Joins; you model per query
Document MongoDB, Firestore Flexible nested records Cross-document transactions (possible but costly)
Search Elasticsearch, OpenSearch Full-text, relevance, aggregations Being the source of truth
Time series Prometheus, TimescaleDB, InfluxDB Metrics, IoT readings General queries
Graph Neo4j, Neptune Relationship traversal Simple high-volume CRUD
Vector pgvector, Qdrant, Milvus, OpenSearch k-NN Similarity search over embeddings Exact filtering and joins (improving fast)
Analytical (OLAP) BigQuery, Snowflake, ClickHouse, Redshift Scanning billions of rows Many small writes

Modelling basics:

  • Indexes turn scans into lookups. Index the columns in WHERE, JOIN and ORDER BY. A composite index (tenant_id, employee_id) serves queries filtered on tenant_id alone too, but not on employee_id alone (leftmost prefix rule). Every index slows writes and uses memory, so don’t index everything.
  • Normalise for correctness (one fact in one place), denormalise for read speed (copy data where it’s read). Typical approach: normalised OLTP schema plus denormalised read models, caches or search indexes fed by events.
  • Transactions and isolation. Read committed is the default in PostgreSQL; repeatable read and serializable prevent more anomalies at a cost. For “two admins approve the same payroll at once”, use a conditional update (UPDATE ... WHERE status = 'PENDING') or SELECT ... FOR UPDATE.
  • Multi-tenancy models: shared tables with a tenant_id column (cheapest, needs row-level security), schema per tenant (middle ground), database per tenant (strong isolation, expensive, used for large enterprise tenants). PayFlow uses shared tables for small tenants and dedicated databases for the largest ones: a hybrid that many SaaS companies end up with.

Real world: “Postgres is enough” is the right default for most new systems, including vector search with pgvector at modest scale. Add specialised stores when a measured access pattern needs them.

2.3 Replication: more copies for reads and survival

Replication keeps copies of the same data on several nodes, for availability (survive node loss) and read scaling.

Leader-follower replication and failover (animated, 5 steps)App (writes)Leader (primary)accepts writesFollower 1sync, same regionFollower 2async, other AZRead API / reports123451Writes go only to the leader.2The leader streams its log; a synchronous followerconfirms first.3The async follower applies changes a little later.4Reads spread over followers.5Leader dies: the most up-to-date follower is promoted.All 5 steps done. The flow replays…
Animated diagram: Leader-follower replication and failover. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Writes go only to the leader. One writer means no write conflicts. It also means the leader is the write bottleneck: scale it vertically or shard.
  2. The leader streams its log; a synchronous follower confirms first. Semi-synchronous replication: the commit waits for one replica, so a leader crash loses nothing that was acknowledged.
  3. The async follower applies changes a little later. That delay is replica lag. It is usually milliseconds, but seconds under heavy load or long transactions.
  4. Reads spread over followers. Read-your-own-writes: after a user saves, route their next reads to the leader for a few seconds, or wait for the replica to reach their write’s log position.
  5. Leader dies: the most up-to-date follower is promoted. Managed services (RDS Multi-AZ, Patroni on-prem) do this in under a minute. Apps reconnect through DNS or a proxy. Fence the old leader so it can’t accept writes if it comes back (split brain).

Three models:

  • Single-leader (PostgreSQL, MySQL, MongoDB replica sets): simple and consistent writes; the leader is the write ceiling.
  • Multi-leader (multi-region active-active writes): low write latency in each region, but conflicting writes need resolution (last-writer-wins loses data; CRDTs or app-level merges are safer). Use sparingly.
  • Leaderless (Dynamo-style: Cassandra, DynamoDB internals): write to W replicas, read from R replicas out of N. If W + R > N, reads overlap the latest write. Typical N=3, W=2, R=2.

Say in the interview: “Single leader with a synchronous standby in another AZ for zero data loss on failover, async read replicas for reports, and read-your-writes routing for the user who just saved.”

2.4 Partitioning (sharding) and consistent hashing

When one machine can’t hold the data or take the writes, split the data. Each partition (shard) holds a subset of keys.

  • Range partitioning (A-F, G-M…): range scans are efficient, but hot ranges are a risk (everyone writes “today”).
  • Hash partitioning: even spread, but range queries hit every shard.
  • Directory or lookup-based: a mapping service says which shard holds which tenant. That’s flexible and great for SaaS, because you can move a big tenant to its own shard.
  • Choosing the shard key is the decision that matters. It should spread load evenly and keep most queries on one shard. For PayFlow, tenant_id is natural: almost every query is within one tenant. The risk is one huge tenant, which is solved by giving that tenant its own shard.
Consistent hashing ring (animated, 5 steps)Node ANode ENode BNode CNode Dkey t12:emp:42hash(key) → point on ringwalk clockwise to the next node123451Hash the key and walk clockwise: it lands on Node B.2Add Node E between A and B.3Only keys in that arc move. Our key now belongs to E.4Node C leaves: its keys move clockwise to D.5Each server owns many virtual points on the ring.All 5 steps done. The flow replays…
Animated diagram: Consistent hashing ring. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Hash the key and walk clockwise: it lands on Node B. With plain hash(key) % N, changing N remaps almost every key. On a ring only neighbours are affected.
  2. Add Node E between A and B. E takes over only the arc between A and E. Everything else stays put, so the cache stays mostly warm.
  3. Only keys in that arc move. Our key now belongs to E. On average just 1/N of keys move when one node joins. That is why Dynamo, Cassandra and Redis-style clients use rings or hash slots.
  4. Node C leaves: its keys move clockwise to D. Replication (store each key on the next 2 nodes too) means D already has a copy, so nothing is lost.
  5. Each server owns many virtual points on the ring. With 100+ virtual nodes per server the load evens out, and a big server can take more points than a small one.

Problems that come with sharding: cross-shard queries (scatter-gather), cross-shard transactions (avoid them; use sagas, 3.2), rebalancing, and global unique IDs. For IDs use UUIDv7 or Snowflake-style IDs (timestamp + machine + sequence), which are unique without coordination and roughly time-sortable, so they index well.

Say in the interview: “Shard by tenant_id through a directory, so most queries hit one shard and I can move a large tenant to dedicated hardware. I’d avoid cross-shard transactions entirely.”

2.5 CAP, PACELC and consistency models

CAP: during a network partition, a distributed data store must choose between consistency (every read sees the latest write or gets an error) and availability (every request gets a non-error answer). Partitions will happen, so the real choice is CP or AP during a partition.

PACELC adds the everyday case: if there’s a Partition choose A or C; Else (normal operation) choose Latency or Consistency. Synchronous replication buys consistency with latency even when nothing is broken.

System Partition Normal
Single-leader Postgres with sync standby CP (minority side stops) EC (waits for standby)
Cassandra / DynamoDB (default settings) AP EL
etcd, ZooKeeper, Consul CP EC
Spanner, CockroachDB CP EC (uses clocks and consensus)

Consistency models from strongest to weakest: linearizable (behaves like one copy), sequential, causal (cause before effect, for example a reply after its message), read-your-writes, monotonic reads, eventual (converges if writes stop).

Real world, mixed in one product: PayFlow’s payroll ledger is strongly consistent (CP, single leader). Employee directory search is eventually consistent (fed by events, seconds behind). Presence (“HR admin online”) is best effort. Picking consistency per feature, not per company, is the senior move.

Say in the interview: “CAP only bites during partitions; day to day it’s latency versus consistency. I’d make money paths linearizable and let read-heavy views be eventually consistent with a clear freshness bound.”

2.6 Asynchronous messaging: queues, streams and the outbox

Use async messaging when the caller doesn’t need the result right now, to absorb spikes, and to decouple services.

Message queue Event stream (log)
Examples SQS, RabbitMQ Kafka, Kinesis, Pulsar, Redpanda
Model Each message to one consumer, deleted after ack Append-only log; many consumer groups read independently
Replay No (once consumed it’s gone) Yes, within retention
Ordering Best effort (FIFO queues exist) Per partition
Good for Task distribution, work queues Event sourcing, CDC, analytics, fan-out to many consumers

Delivery guarantees: at-most-once (may lose), at-least-once (may duplicate, the practical default), exactly-once (only inside a closed system such as Kafka transactions; end to end you build “effectively once” with idempotent consumers).

Transactional outbox with an idempotent consumer (animated, 6 steps)Payroll serviceService DBpayslips + outbox(one transaction)Relay / CDC(Debezium or poller)Kafka topicNotification consumerprocessed_ids tableDead-letter queue1234561Insert the payslip and an outbox row in one localtransaction.2A relay tails the outbox table.3The event is published, then marked sent.4The consumer receives the event, possibly twice.5Check processed_ids: duplicate means skip, new meansprocess.6A poison message goes to the DLQ after N retries.All 6 steps done. The flow replays…
Animated diagram: Transactional outbox with an idempotent consumer. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Insert the payslip and an outbox row in one local transaction. This kills the dual-write bug: no more ‘row saved but event never sent’ or ‘event sent but row rolled back’.
  2. A relay tails the outbox table. Either poll WHERE sent = false, or use CDC on the database log, which has lower latency and no polling load.
  3. The event is published, then marked sent. If the relay crashes between publish and mark, the event goes out twice. That is at-least-once delivery, by design.
  4. The consumer receives the event, possibly twice. Kafka keeps order within a partition, so key by employee or tenant when order matters.
  5. Check processed_ids: duplicate means skip, new means process. Insert the event id and do the work in one transaction. That makes the consumer idempotent, and at-least-once plus idempotent equals effectively once.
  6. A poison message goes to the DLQ after N retries. Alert on DLQ depth. Fix the bug, then replay the DLQ. Never let one bad message block a partition forever.

Other must-knows:

  • Backpressure: when consumers fall behind, the queue grows. Alert on age of oldest message (lag), not just depth, and autoscale consumers on lag (KEDA).
  • Ordering vs parallelism: more partitions mean more parallel consumers but ordering only within each partition. Choose the key that defines “must be in order” (per employee, per account).
  • Schema evolution: use a schema registry (Avro or Protobuf) with backward-compatible changes, or consumers break on deploy.

Say in the interview: “Outbox to avoid dual writes, at-least-once delivery, idempotent consumers keyed by event id, DLQ with alerting, and autoscaling on consumer lag.”

2.7 Other storage you’ll design with

  • Object storage (S3, GCS, Azure Blob, MinIO on-prem): files, backups, PDFs, data lakes. Effectively unlimited, very durable (S3 is designed for eleven nines), cheap tiers for cold data. Upload from clients directly with pre-signed URLs so big files never pass through your servers.
  • Block storage (EBS, persistent disks): disks for VMs and databases. Know IOPS and throughput limits.
  • File storage (EFS, NFS, Filestore): shared POSIX file systems for legacy apps. Usually slower and pricier than object storage.
  • Search index: inverted index (word → documents). Feed it from the database via events or CDC; rebuild it from the source of truth when its mapping changes.
  • Vector index: stores embeddings (lists of numbers that capture meaning) and finds nearest neighbours with approximate algorithms such as HNSW or IVF. Central to RAG (7.2).

3. Distributed systems (advanced)

3.1 Monolith, modular monolith or microservices

Style Good when Cost
Monolith Small team, early product, unclear domain Deploys couple everything together; scaling is all or nothing
Modular monolith Clear modules, one team or a few Needs discipline at module boundaries; still one deploy
Microservices Many teams, domains with different scale or release pace Network calls, distributed data, observability, platform team

Microservices solve an organisational problem (teams blocking each other) more than a technical one. Split along business capabilities (payroll, leave, attendance, billing), with each service owning its data. Shared databases between services bring back all the coupling with none of the benefits.

Pieces that come with microservices:

  • API gateway: one entry point for auth, rate limiting, routing, request shaping. Kong, Envoy Gateway, NGINX Gateway Fabric, AWS API Gateway. On Kubernetes, the Gateway API is the standard way to configure it.
  • Backend for frontend (BFF): a thin API layer per client type (web, mobile) so each gets exactly the data it needs in one call.
  • Service discovery: Kubernetes Services and DNS, Consul or a cloud map. Clients find healthy instances by name.
  • Service mesh (Istio, Linkerd, Cilium): mTLS, retries, timeouts, traffic splitting and telemetry handled outside application code. Worth it with many services and a security need for zero trust; overkill for five services.
  • Contracts: OpenAPI or protobuf definitions, consumer-driven contract tests (Pact), and versioned APIs so teams deploy independently.

Real world: PayFlow stayed a modular monolith until about 40 engineers, then extracted payroll calculation first. It had the most different scaling pattern (idle 25 days, saturated 5) and the strictest correctness rules.

Say in the interview: “I’d start with a modular monolith and extract services where team boundaries or scaling profiles diverge. Each service owns its data; cross-service workflows use events or sagas, not shared tables.”

3.2 Distributed transactions: 2PC vs sagas

When one business action touches several services’ databases, there is no single ACID transaction.

  • Two-phase commit (2PC): a coordinator asks all participants to prepare, then commit. It’s consistent, but blocking: a coordinator crash leaves locks held. It’s rarely used across microservices; more common inside one database system.
  • Saga: a sequence of local transactions, each with a compensating action. If step 3 fails, run the compensations for steps 2 and 1.
    • Choreography: services react to each other’s events. No central brain, but the flow gets hard to see past three or four steps.
    • Orchestration: a coordinator (Temporal, AWS Step Functions, Camunda) drives the steps. It’s easier to reason about, monitor and change. It is the default for anything involving money.
Orchestrated saga with compensation (animated, 6 steps)Saga orchestrator(Temporal / Step Functions)Order servicePayment serviceInventory serviceSaga state store1,52,4361Create the order as PENDING.2Charge the payment: success.3Reserve stock: fails, out of stock.4Compensate: refund the payment.5Compensate: mark the order CANCELLED and tell the user.6Every transition is persisted.All 6 steps done. The flow replays…
Animated diagram: Orchestrated saga with compensation. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Create the order as PENDING. Each step is a local transaction in one service’s own database. No locks are held across services.
  2. Charge the payment: success. The call carries an idempotency key (saga id + step), so a retried step never double-charges.
  3. Reserve stock: fails, out of stock. Business failure, not a crash. The saga now runs compensations in reverse order.
  4. Compensate: refund the payment. Compensation is a new forward action (a refund), not a database rollback. It must also be idempotent and retryable.
  5. Compensate: mark the order CANCELLED and tell the user. Users can briefly see PENDING. Sagas trade isolation for availability; design the UI for it.
  6. Every transition is persisted. If the orchestrator crashes it resumes from the last recorded step. Durable workflow engines give you this for free.

Say in the interview: “Saga with an orchestrator, idempotent steps and compensations, persisted state so it survives crashes, and a UI that shows intermediate states honestly.”

3.3 Consensus, quorums, locks and time

Some decisions need every node to agree: who is the leader, which config is current, who holds a lock. That’s consensus, usually Raft (etcd, Consul, KRaft) or Paxos variants.

Raft: one write reaching a majority (animated, 5 steps)ClientLeaderterm 7Follower AFollower Bslow123451Client sends the write x = 5 to the leader.2The leader appends it to its log and sends AppendEntries.3Follower A acknowledges. 2 of 3 is a majority.4The entry is committed, applied, and the client gets OK.5B catches up later. If the leader dies, a node with thelatest log wins.All 5 steps done. The flow replays…
Animated diagram: Raft: one write reaching a majority. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Client sends the write x = 5 to the leader. Followers that get a write redirect it to the leader. Only the leader appends new entries.
  2. The leader appends it to its log and sends AppendEntries. Entries carry the term number and the index, so followers can detect gaps or a stale leader.
  3. Follower A acknowledges. 2 of 3 is a majority. That’s why clusters are 3 or 5 nodes: 3 tolerates 1 failure, 5 tolerates 2. An even count adds cost without adding tolerance.
  4. The entry is committed, applied, and the client gets OK. etcd (Kubernetes’ brain), Consul and KRaft-mode Kafka all work this way.
  5. B catches up later. If the leader dies, a node with the latest log wins. Election timeouts are randomised (150-300 ms) so two candidates rarely split the vote. A partitioned old leader can’t commit, because it can’t reach a majority.

Related ideas interviewers probe:

  • Quorum: majority = floor(N/2) + 1. With 3 nodes you need 2; with 5 you need 3. A partitioned minority can’t elect a leader or commit, which prevents split brain.
  • Leader election in practice: a Kubernetes Lease object, etcd lease, or a database row with an expiry. Used for schedulers, cron runners, controllers.
  • Distributed locks: Redis SET key value NX PX 30000 is fine for efficiency (avoiding duplicate work). For correctness (two writers must never both act), add fencing tokens: the lock service hands out an increasing number, and the storage rejects writes with an older token. That way a paused process that wakes after its lock expired can’t corrupt data.
  • Time is unreliable: clocks drift and jump (NTP corrections, VM pauses). Never order events across machines by wall-clock time alone. Use sequence numbers from one authority, logical clocks (Lamport, vector clocks), or bounded-uncertainty clocks like Spanner’s TrueTime.

Say in the interview: “Three or five etcd nodes for coordination, leases for leader election, and fencing tokens whenever a lock protects correctness rather than just efficiency.”

3.4 Resilience patterns

In a distributed system something is always failing. Design so partial failure stays partial.

Timeout, retry with jitter, circuit breaker and fallback (animated, 6 steps)Checkout serviceResilient clienttimeout · retrycircuit breakerPricing service(slow today)Fallbacklast known prices12,3,6451The call goes through a resilient client.2Pricing is slow: the call times out at 300 ms.3Retry with exponential backoff and jitter, at most 2times.4Failures cross 50% in 10 s: the breaker opens.5Serve a fallback instead of an error.6After a cooldown, half-open lets one probe through.All 6 steps done. The flow replays…
Animated diagram: Timeout, retry with jitter, circuit breaker and fallback. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. The call goes through a resilient client. Set an explicit timeout on every network call. Defaults are often infinite or 30 s, which is how one slow dependency exhausts every thread.
  2. Pricing is slow: the call times out at 300 ms. Choose the timeout from the dependency’s p99 plus a margin, and within your own latency budget.
  3. Retry with exponential backoff and jitter, at most 2 times. Retry only idempotent calls and only on retryable errors (timeouts, 503). Cap retries per request and add a retry budget across the service.
  4. Failures cross 50% in 10 s: the breaker opens. Open means fail fast with no network call. That frees threads and gives the sick service room to recover.
  5. Serve a fallback instead of an error. Graceful degradation: stale prices with a ‘prices may have changed’ note beat a broken checkout.
  6. After a cooldown, half-open lets one probe through. If the probe succeeds the breaker closes; if not it opens again. Bulkheads (separate pools per dependency) keep one bad dependency from starving the others.

The full toolkit:

  • Timeouts on every call, with a total deadline propagated through the call chain (gRPC deadlines do this).
  • Retries with exponential backoff, full jitter and a cap, only for idempotent operations. Retry at one layer only, or retries multiply (3 layers × 3 retries = 27 calls).
  • Circuit breakers to fail fast and give dependencies room to recover.
  • Bulkheads: separate thread pools, connection pools or even clusters per dependency or tenant, so one problem can’t drain shared capacity.
  • Rate limiting and load shedding: reject or queue excess load early (at the gateway) with 429 or 503 instead of collapsing. Shed low-priority work first (reports before payslips).
  • Backpressure: bounded queues; when full, push back to the producer instead of growing memory until OOM.
  • Graceful degradation: a feature-flagged “lite mode” that turns off non-essential features under stress.
  • Cell-based architecture: split the system into independent copies (cells), each serving a subset of tenants. A bad deploy or poison request hits one cell. AWS uses this widely to limit blast radius.
  • Chaos engineering: inject failure on purpose (LitmusChaos, Chaos Mesh, AWS FIS) to prove the patterns work before a real incident does.

Say in the interview: “Timeouts everywhere with deadline propagation, retries with jitter at one layer only, breakers and bulkheads per dependency, and load shedding at the edge, then chaos tests to prove it.”

3.5 Observability, SLIs, SLOs and error budgets

You can’t run what you can’t see. Observability is the ability to ask new questions about the system’s behaviour from its outputs.

  • Metrics (Prometheus, CloudWatch): cheap, aggregated numbers over time. Use RED for services (Rate, Errors, Duration) and USE for resources (Utilisation, Saturation, Errors).
  • Logs (Loki, OpenSearch, CloudWatch Logs): structured JSON with trace id, tenant id and request id. Never log salaries, PAN or tokens.
  • Traces (OpenTelemetry → Tempo, Jaeger, X-Ray): one request’s path across services with timing per hop. Essential with microservices.
  • Profiles (continuous profiling, for example Pyroscope): which code burns CPU and memory.

Reliability targets:

  • SLI: a measured indicator, for example the share of payslip requests served successfully in under 300 ms.
  • SLO: the target for the SLI, for example 99.9% over 30 days.
  • Error budget: 100% minus the SLO. 0.1% of a month is about 43 minutes. While budget remains, ship features; when it’s burnt, prioritise reliability work.
  • Burn-rate alerts: page when the budget is being consumed fast (for example 14× normal over 1 hour), not on every spike. This cuts alert noise dramatically.

Say in the interview: “OpenTelemetry for traces, metrics and logs correlated by trace id, SLOs on user journeys rather than servers, and multi-window burn-rate alerts so we page on user impact only.”

3.6 Security and multi-tenancy by design

Security is a design dimension, not a final checklist.

Authentication, authorisation and tenant isolation (animated, 6 steps)User browserIdentity provider(Keycloak / Cognito)API gatewayPayroll servicePolicy engine(OPA)Databaserow-level security1234561Login with OIDC (authorization code + PKCE) and MFA.2The IdP returns a short-lived access token (JWT).3API call with a Bearer token; the gateway validates it.4Forwarded over mTLS inside the cluster.5The service asks: can this user approve payroll for tenant12?6The query runs with tenant_id = 12 enforced by thedatabase.All 6 steps done. The flow replays…
Animated diagram: Authentication, authorisation and tenant isolation. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Login with OIDC (authorization code + PKCE) and MFA. The app never sees the password. Enterprise tenants can federate their own IdP through SAML or OIDC (SSO).
  2. The IdP returns a short-lived access token (JWT). Access tokens live 5-15 minutes; a refresh token, stored safely, gets new ones. Short life limits the damage of a stolen token.
  3. API call with a Bearer token; the gateway validates it. Check signature (via the IdP’s JWKS keys), expiry, issuer and audience. Rate limit per tenant here too.
  4. Forwarded over mTLS inside the cluster. Service identity (SPIFFE IDs through a mesh such as Istio or Linkerd) means a compromised pod can’t impersonate another service. That’s zero trust.
  5. The service asks: can this user approve payroll for tenant 12? Authorisation is centralised as policy-as-code (RBAC + attributes). Decisions are logged for audit.
  6. The query runs with tenant_id = 12 enforced by the database. Row-level security is the last line of defence. Even a buggy query can’t read another tenant’s salaries.

Principles to cover:

  • Defence in depth: WAF and DDoS protection at the edge, auth at the gateway, authz in the service, RLS in the database, encryption at rest with KMS.
  • Least privilege: IAM roles per service (IRSA on EKS, Workload Identity on GKE), no long-lived keys, secrets in Vault or a cloud secrets manager with rotation.
  • Data protection: encrypt PII fields at the application level (envelope encryption) so even a DB dump is useless. Tokenise identifiers like PAN and bank accounts.
  • Tenant isolation: tenant id from the verified token only, never from a request parameter. Per-tenant encryption keys for enterprise customers who ask for them.
  • Supply chain: signed images (cosign), SBOMs, vulnerability scanning in CI, admission policies (Kyverno, OPA Gatekeeper) blocking unsigned or privileged workloads.
  • Compliance: India’s DPDP Act (purpose limitation, consent, breach reporting), data residency, audit logs that can’t be edited (append-only, separate account).

Say in the interview: “Zero trust: verify identity at every hop with OIDC at the edge and mTLS inside, authorise with policy as code, enforce tenant isolation in the database itself, and keep PII encrypted at the field level.”

4. Production at scale (expert)

4.1 Multi-region, disaster recovery, RPO and RTO

Start from the business: RPO (recovery point objective) is how much data you can afford to lose; RTO (recovery time objective) is how long you can be down. These two numbers pick the architecture.

Strategy RPO RTO Cost How
Backup and restore Hours Hours to a day Lowest Snapshots copied to another region; rebuild with IaC
Pilot light Minutes Tens of minutes Low Data replicated; minimal core running; scale up on failover
Warm standby Seconds Minutes Medium Smaller full copy running; scale out and switch DNS
Active-active Near zero Near zero Highest Both regions serve traffic; data layer designed for it
Two-region setup and regional failover (animated, 6 steps)Region 1 (Mumbai)Region 2 (Hyderabad)UsersGlobal DNS / GSLBlatency + healthApp clusterDB primaryApp clusterDB replicapromotable1234561Users resolve api.payflow.in. GSLB picks the nearesthealthy region.2Both regions serve traffic.3Writes go to the primary in Mumbai.4Asynchronous replication to Hyderabad.5Mumbai fails: the replica is promoted.6All traffic now goes to Hyderabad.All 6 steps done. The flow replays…
Animated diagram: Two-region setup and regional failover. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Users resolve api.payflow.in. GSLB picks the nearest healthy region. Route 53 latency routing, Cloudflare Load Balancing or Azure Front Door all do this, with health checks every few seconds.
  2. Both regions serve traffic. Stateless app tiers are easy to run active-active. The data tier decides how ‘active’ region 2 can really be.
  3. Writes go to the primary in Mumbai. Single-writer keeps data simple. Region 2 forwards writes across regions (extra 20-30 ms) or stays read-only.
  4. Asynchronous replication to Hyderabad. RPO (data you can lose) equals the replication lag at failure time, usually seconds. Synchronous cross-region replication makes RPO zero but slows every write.
  5. Mumbai fails: the replica is promoted. RTO (time to recover) depends on detection, promotion and DNS. Automate it, but require a human ‘go’ for the database if data loss is possible.
  6. All traffic now goes to Hyderabad. Region 2 must be sized to take 100% (or shed load gracefully). Practise this as a game day each quarter, or it won’t work when you need it.

Expert points:

  • Data is the hard part. Stateless tiers are easy to copy. For data, choose single-writer with fast promotion (simplest), partitioned ownership (each tenant has a home region and writes there), or a globally consistent database (Spanner, CockroachDB, Aurora DSQL, DynamoDB global tables with their own conflict semantics).
  • Partitioned ownership is often the best fit for SaaS. Each tenant is pinned to a home region, which also solves data residency (EU tenants in Frankfurt, Indian tenants in Mumbai).
  • Static stability: the standby region shouldn’t need to call the failed region’s control plane to take over. Pre-provision capacity or be certain you can get it (capacity reservations).
  • Failover is a product decision. Automate detection and preparation; for the database, many teams keep a human “go” because a wrong failover can lose data or cause split brain.
  • Test it. Run game days. An untested DR plan is a hope, not a plan.

Say in the interview: “I’d agree RPO and RTO first. For PayFlow: tenants pinned to a home region for residency, warm standby in the paired region with async replication (RPO seconds, RTO under 15 minutes), DNS failover with low TTLs, and quarterly game days.”

4.2 Changing a live system safely

Most outages are caused by changes. A system design that ignores how it changes isn’t complete.

  • Deploy strategies (section 4.4 of the DevOps Interview Guide covers mechanics): rolling, blue-green, canary with automated analysis (Argo Rollouts, Flagger), and progressive delivery by region or cell.
  • Feature flags separate deploy (code is there) from release (users see it). Flags allow kill switches, per-tenant rollouts and instant rollback without a redeploy. Clean up old flags; they are technical debt.
  • Database migrations must be backward compatible, because old and new code run together during a deploy.
Zero-downtime schema change: expand and contract (animated, 5 steps)ExpandADD COLUMN pan_enc NULLDual writev2 writes old + new columnsBackfillbatched copy, throttledSwitch readsfeature flag, canary 5% → 100%Contractdrop old column next release123451Expand: add the new column as nullable.2Deploy v2 that writes both columns.3Backfill old rows in small batches.4Flip reads to the new column behind a flag.5Contract: stop writing and drop the old column later.All 5 steps done. The flow replays…
Animated diagram: Zero-downtime schema change: expand and contract. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Expand: add the new column as nullable. Additive changes are backward compatible. The running v1 code ignores the new column. Use online DDL tools for big MySQL tables (gh-ost, pt-osc).
  2. Deploy v2 that writes both columns. Old and new pods run side by side during a rolling deploy. Both must work with the schema as it is now.
  3. Backfill old rows in small batches. Throttle by replica lag. A single giant UPDATE locks rows and floods replication.
  4. Flip reads to the new column behind a flag. Canary it. If error rates rise, flip the flag back in seconds, with no redeploy.
  5. Contract: stop writing and drop the old column later. Only after rollback to v1 is no longer possible. Every step on its own was reversible.
  • API changes: additive only within a version; deprecate with telemetry showing who still calls the old field.
  • Config is code: config changes go through review, CI and gradual rollout. Many large outages were a bad config pushed everywhere at once.

Say in the interview: “Every change is gradual, observable and reversible: canaries with automated rollback, flags for release, and expand-contract for schema changes.”

4.3 Performance and capacity

  • Latency percentiles: report p50, p95, p99 and p99.9. Averages hide pain. At scale, the slowest backend call decides the page: if a page fans out to 100 calls, almost every page sees some call’s p99.
  • Tail latency fixes: hedged requests (send a second request after the p95 time and take the first answer), smaller fan-out, timeouts, isolating slow tenants.
  • Little’s law: concurrency = arrival rate × time in system. 1,000 requests/s × 0.2 s = 200 requests in flight. Size thread pools, connection pools and pods from this.
  • Queueing: as utilisation approaches 100%, wait time grows sharply. Run steady-state CPU around 50-70% for latency-sensitive services so spikes don’t push you over the cliff.
  • Connection pools: the database is usually the bottleneck. 200 pods × 20 connections = 4,000 connections, too many for most databases. Use a pooler (PgBouncer, RDS Proxy) and size pools from Little’s law.
  • Autoscaling signals: request rate or concurrency for web services, queue lag for workers (KEDA), schedules for known peaks (payday), and for GPUs, queue depth (7.3). CPU alone is often a lagging or misleading signal.
  • Load testing: k6, Locust or Gatling with realistic traffic mixes, run before peak events, not after.

Say in the interview: “I size from Little’s law, protect the database with a pooler, scale on concurrency or lag rather than CPU, and pre-scale on a schedule before payday because reactive scaling is too slow for a spike that sharp.”

4.4 Cost as a design dimension (FinOps)

Cost is an architecture property like latency. Interviewers increasingly ask “what does this cost and how would you reduce it?”

  • Unit economics: cost per tenant, per payroll run, per 1,000 requests, per AI answer. If you can’t name a unit cost, you can’t tell whether growth is healthy.
  • Big levers: right-sizing (most workloads are over-provisioned), autoscaling to zero for batch, Spot for fault-tolerant work (transcoding, CI, payroll batches with checkpointing), commitment discounts for the steady baseline, Graviton or ARM instances, storage tiering (S3 Intelligent-Tiering, lifecycle rules).
  • Hidden costs: cross-AZ and cross-region data transfer, NAT gateway processing, log ingestion and retention, idle non-production environments, and GPU time.
  • Tagging and showback: every resource tagged with team, service and environment; dashboards per team (OpenCost or Kubecost for Kubernetes).
  • Design choices change cost by multiples: synchronous cross-region replication of everything, keeping all logs for a year at full fidelity, or using the largest LLM for every request can each double a bill.

Say in the interview: “I’d track cost per tenant as a first-class metric, run batch on Spot with checkpoints, put commitments on the baseline, and watch data transfer and logging, which usually surprise people more than compute.”

4.5 Data-intensive systems: batch, stream and CDC

Operational databases serve the app; analytics and ML need the data elsewhere, in other shapes.

  • Batch: process big bounded datasets on a schedule (Spark, dbt, BigQuery). Simple and cheap, but hours stale.
  • Stream: process events continuously (Flink, Kafka Streams, Spark Structured Streaming). Seconds stale, more complex (late events, windows, state).
  • Lambda architecture runs both and merges them; kappa uses only the stream and replays it for reprocessing. Kappa is simpler when the log retains enough history.
  • CDC (change data capture) turns database changes into events without touching application code.
Change data capture feeding stream and batch (animated, 5 steps)OLTP PostgresCDC (Debezium)KafkaStream job(Flink)Lakehouse(S3 + Iceberg)Live dashboardsfraud alertsBatch + BI(Spark, Trino)123451Row changes are read from the database's write-ahead log.2Each change becomes an event keyed by primary key.3Two consumers read the same stream independently.4The stream job computes windowed aggregates withinseconds.5The lakehouse serves nightly batch and ad-hoc SQL.All 5 steps done. The flow replays…
Animated diagram: Change data capture feeding stream and batch. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Row changes are read from the database’s write-ahead log. No application changes and no extra query load. Every insert, update and delete becomes an event.
  2. Each change becomes an event keyed by primary key. Keying by primary key keeps changes for one row in order on one partition.
  3. Two consumers read the same stream independently. Kafka retains events, so a new consumer can start from the beginning. That replay ability is the heart of the kappa architecture.
  4. The stream job computes windowed aggregates within seconds. Example: ‘payroll edits per admin per 5 minutes’ raising a fraud alert. Exactly-once needs checkpoints plus transactional sinks.
  5. The lakehouse serves nightly batch and ad-hoc SQL. Open table formats (Iceberg, Delta) add ACID, schema evolution and time travel on cheap object storage.
  • Lakehouse: object storage plus an open table format (Iceberg, Delta, Hudi) gives warehouse features on cheap storage. Several engines (Spark, Trino, Snowflake) can read the same tables.
  • Data contracts: producers publish schemas and guarantees; breaking changes fail CI instead of breaking dashboards next morning.
  • This is also the AI foundation. RAG, fine-tuning and analytics all depend on clean, fresh, permission-tagged data. Teams with good pipelines ship AI features fastest.

5. Real-time project: designing PayFlow end to end

This section walks one realistic product through its whole life, the way systems are actually built: start small, let real pain trigger each change, and explain the trade-off every time. It’s also a ready-made answer for “tell me about a system you designed” if you’ve worked on HR, payroll or any B2B SaaS.

5.1 Requirements

Functional: tenant onboarding; employee records; attendance and leave; monthly payroll with Indian statutory rules (PF, ESI, professional tax, TDS); payslip generation and download; bank payout files; reports; audit trail. Later: an HR assistant that answers policy questions, and agents that fix payroll exceptions.

Non-functional:

Property Target
Scale (stage 4) 2,000 tenants, 2M employees, peak 1.5k requests/s, payroll for 2M in under 4 hours
Availability 99.95% for employee self-service; payroll run must finish by its cut-off
Correctness Payroll results reproducible and auditable; zero double payouts
Durability RPO near zero for payroll and ledger data
Latency p99 under 300 ms for reads; payslip PDF under 2 s
Security Tenant isolation, PII encryption, SSO for enterprises, full audit
Compliance Data stays in India; retention per labour law; DPDP Act
Cost Infra under 8% of revenue; cost per tenant visible

5.2 How PayFlow evolved

PayFlow: from one VM to an AI-era platform (animated, 6 steps)Stage 0 · one VMapp + MySQL · 200 usersStage 1 · LB + 2 apps + managed DB5k usersStage 2 · cache, queue, read replicas50k usersStage 3 · services on Kubernetes500k usersStage 4 · two regions, cells5M users, enterprisesStage 5 · AI assistant + agentsgateway, RAG, evals1234561Stage 0: one VM is right for an MVP.2Pain: the VM is a single point of failure. Fix: LB + 2apps.3Pain: slow dashboards, payroll runs time out. Fix: cache +queue.4Pain: one deploy breaks everything. Fix: split by domain.5Pain: one outage hits every tenant. Fix: regions andcells.6New need: AI features. Fix: an AI platform layer.All 6 steps done. The flow replays…
Animated diagram: PayFlow: from one VM to an AI-era platform. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Stage 0: one VM is right for an MVP. Cheap, simple, fast to change. Take nightly backups and keep the app stateless from day one.
  2. Pain: the VM is a single point of failure. Fix: LB + 2 apps. Managed MySQL with Multi-AZ, sessions in Redis, deploys via CI/CD with health checks.
  3. Pain: slow dashboards, payroll runs time out. Fix: cache + queue. Read replicas for reports, Redis for hot data, payroll and payslip PDFs as background jobs.
  4. Pain: one deploy breaks everything. Fix: split by domain. Payroll, Leave, Attendance as separate services on Kubernetes with their own data, GitOps, SLOs per service.
  5. Pain: one outage hits every tenant. Fix: regions and cells. Tenants pinned to cells (independent stacks); a bad deploy or noisy tenant only hurts one cell.
  6. New need: AI features. Fix: an AI platform layer. AI gateway, RAG over policies, agents with approvals, evaluations in CI. Built on the same reliability ideas.
Stage Architecture Why this, now Main risk accepted
0 · MVP One VM: Node.js app, MySQL, nightly backups to S3 Speed of learning beats robustness when there are 10 tenants Downtime and data loss up to 24 h
1 · Reliable ALB, 2+ app instances in an Auto Scaling group across AZs, RDS Multi-AZ, Redis for sessions, CI/CD with health checks First paying enterprise customers need uptime Payroll still runs inside web requests
2 · Scalable Read replica for reports, Redis cache, SQS or Kafka for jobs, payslip PDFs as async jobs to S3 + CloudFront Month-end slowness and timeouts More moving parts to monitor
3 · Modular Payroll, leave, attendance, notifications as services on EKS; GitOps (Argo CD); OpenTelemetry; SLOs per journey; outbox + events between services Teams blocking each other; payroll needs its own scaling Distributed data, needs a platform team
4 · Resilient at scale Cells (groups of tenants on independent stacks), Mumbai home region with Hyderabad warm standby, largest tenants on dedicated databases, cost per tenant One bad deploy or noisy tenant shouldn’t hit everyone; enterprise contracts demand DR Higher baseline cost; more complex routing
5 · AI era AI gateway, RAG assistant over policies, agents with approvals, evals in CI, AIOps in operations Customers expect self-service answers; HR teams drown in exceptions New failure modes: hallucination, prompt injection, token cost

On-prem variant. The same design runs on-prem for customers who require it: k3s or RKE2 instead of EKS, MetalLB plus NGINX Gateway Fabric instead of ALB, MinIO instead of S3, CloudNativePG or Percona operators instead of RDS, Strimzi for Kafka, Vault for secrets, and the same Argo CD GitOps flow. Designing against open interfaces (S3 API, Kafka protocol, PostgreSQL, Gateway API) is what makes that portability cheap.

5.3 Deep dive: the monthly payroll run

The payroll run is PayFlow’s hardest workload: large, bursty, deadline-bound and money-moving. It is a batch-processing design question in disguise.

The monthly payroll run (animated, 8 steps)Scheduler25th, 18:00 ISTPayroll orchestratorQueue: 2,000 batchesWorkers × NKEDA scales on queue depthRules cachetax slabs, PF, ESI, PTResults DBupsert (run_id, emp_id)HR approvalvariance reportBank file / APIReconciliation123456781The scheduler starts run R-2026-12 for each tenant.2The run is split into batches of 500 employees.3Workers pull batches; queue depth drives autoscaling.4Workers read cached, versioned tax and statutory rules.5Results are upserted by (run, employee): retries are safe.6HR reviews a variance report and approves.7The bank file is generated once, keyed by the run id.8Bank responses are matched to the ledger.All 8 steps done. The flow replays…
Animated diagram: The monthly payroll run. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. The scheduler starts run R-2026-12 for each tenant. Only one scheduler instance fires (leader election or a DB lock), otherwise payroll runs twice.
  2. The run is split into batches of 500 employees. Small batches mean a failure retries 500 employees, not 1 million. Batches are independent, so they run in parallel.
  3. Workers pull batches; queue depth drives autoscaling. KEDA scales pods from 2 to 200 on the evening of the run, then back to 2. Cost follows load.
  4. Workers read cached, versioned tax and statutory rules. Rules are versioned by effective date, so re-running March uses March’s rules, not today’s.
  5. Results are upserted by (run, employee): retries are safe. A crashed worker’s batch reappears after its visibility timeout. The upsert makes the second attempt harmless.
  6. HR reviews a variance report and approves. Human in the loop for money. ‘Net pay changed by over 20% for 37 employees’ is checked before anything is paid.
  7. The bank file is generated once, keyed by the run id. Signed, encrypted and sent over SFTP or a bank API. Re-sending the same run id is rejected.
  8. Bank responses are matched to the ledger. Every rupee is accounted for: paid, failed (bad IFSC) or pending. Mismatches become tickets.

Design decisions worth saying out loud:

  • Determinism: payroll for a month must give the same answer when re-run. Inputs (attendance, salary structure, rules version) are snapshotted at run start; calculation code is pure, with no “now()” inside.
  • Idempotency everywhere: batch upserts keyed by (run, employee); the bank file keyed by run id; notifications keyed by (run, employee, channel).
  • Checkpointing: progress is per batch, so a crash at 70% resumes at 70%, not 0%.
  • Isolation of big tenants: a 200k-employee tenant gets its own queue partition and worker pool, so it can’t starve 1,900 small tenants with the same deadline.
  • Cost: workers run on Spot nodes (a reclaimed node just returns its batch to the queue), and scale to near zero for the other 25 days.
  • Observability: a run dashboard shows batches done, failed and retrying, ETA vs cut-off, and per-tenant progress, so support can answer “is my payroll done?” without engineers.

5.4 Failure drill: Mumbai region goes down on payroll night

Interviewers love “what happens when…”. Walk the timeline:

  1. 18:40 Health checks and synthetic probes fail for Mumbai cell 3; burn-rate alerts fire. The incident is opened automatically with a summary of signals.
  2. 18:45 The decision is a regional event (cloud status confirms an AZ-wide network fault spreading). The incident commander invokes the DR runbook.
  3. 18:50 The Hyderabad replica is checked for lag (4 s at failure time), promoted, and old-primary fencing is confirmed. GSLB shifts traffic; DNS TTL is 60 s.
  4. 19:00 Workers in Hyderabad resume payroll from checkpoints. Batches upserted twice are harmless thanks to idempotent keys. The bank file hasn’t been generated yet, so there is no payout risk.
  5. 19:30 Payroll is back on schedule because the cut-off had 4 hours of slack designed in. Tenants get a status page update.
  6. Afterwards: a blameless postmortem, the 4 s of potentially lost writes is reconciled from client retries and the audit log, and the runbook is updated.

That drill shows RPO and RTO, fencing, idempotency, checkpointing, capacity in the standby region and communication, all in one story.

6. Five more case studies

The DevOps Interview Guide (section 10) covers the URL shortener, rate limiter, notifications, news feed, image upload, payments, webhooks, caching layer and job queue. These five round out the common question bank. Each follows the same shape: requirements, numbers, design, deep dives, trade-offs.

6.1 Design a chat system (WhatsApp, Slack)

Requirements: 1:1 and group messages, delivery and read receipts, online presence, offline delivery, message history across devices. Non-functional: low latency (under 200 ms to deliver online), no lost messages, ordering within a conversation.

Numbers: 50M daily users, 40 messages each a day = 2B messages/day ≈ 23k/s average, maybe 100k/s peak. At 200 bytes each, about 400 GB/day of messages. Connections: 10M concurrent WebSockets, so 20-50 gateway servers at a few hundred thousand idle connections each.

One chat message from Alice to Bob (animated, 7 steps)Alice's appWS gateway 1Bob's appWS gateway 2Chat serviceMessage store(Cassandra)Session registry(Redis)Push (APNs / FCM)12345671Alice sends over a persistent WebSocket.2The chat service assigns a per-conversation sequencenumber.3The message is stored before delivery.4Look up which gateway holds Bob's connection.5Route the message to gateway 2.6Delivered. Bob's ack updates the delivered and read state.7If Bob is offline, send a push notification.All 7 steps done. The flow replays…
Animated diagram: One chat message from Alice to Bob. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Alice sends over a persistent WebSocket. Each gateway holds hundreds of thousands of idle connections. They’re stateful, so deploys drain them slowly.
  2. The chat service assigns a per-conversation sequence number. Ordering is per conversation, not global. The client sends a message id so a retry isn’t stored twice.
  3. The message is stored before delivery. Partition by conversation_id, cluster by sequence. ‘Sent’ (one tick) means durable.
  4. Look up which gateway holds Bob’s connection. The registry maps user to gateway with a TTL, refreshed by heartbeats. Presence (‘online’) comes from the same data.
  5. Route the message to gateway 2. Through internal RPC or a pub/sub channel per gateway.
  6. Delivered. Bob’s ack updates the delivered and read state. Group chats fan out to each member. Very large groups switch to fan-out-on-read like a news feed.
  7. If Bob is offline, send a push notification. On reconnect his app asks for everything after its last sequence number, so nothing is missed.

Deep dives:

  • Why WebSockets: polling wastes battery and adds latency; one long-lived connection lets the server push.
  • Storage: a wide-column store partitioned by conversation id and ordered by sequence handles the write rate and “load the last 50 messages” efficiently.
  • Large groups: writing a copy per member (fan-out on write) is fine for 50-person groups and wasteful for 100k-member channels, which are read on demand instead.
  • End-to-end encryption: the server routes ciphertext it can’t read (Signal protocol). That rules out server-side search and moderation of content, which is a real product trade-off.
  • Multi-device: each device keeps its own last-seen sequence and syncs the gap.

Say in the interview: “Persistent connections on a stateless-ish gateway tier, a session registry to route, durable write before delivery, per-conversation sequence numbers for ordering, and pull-based sync on reconnect so offline never loses messages.”

6.2 Design a video streaming platform (an OTT service)

Requirements: studios upload titles; viewers browse and play on phones, TVs and browsers; adaptive quality; DRM; resume where you left off; regional catalogues. Non-functional: playback starts in under 2 s, minimal buffering, survive premiere-night spikes.

Numbers: 10M concurrent viewers at 5 Mbps average = 50 Tbps at peak. No origin can serve that, which is why the CDN is the system. A 2-hour title in a ladder of 6 renditions is roughly 15-25 GB stored.

OTT video: from studio upload to playback (animated, 7 steps)Studio uploadmultipart, resumableRaw object storeTranscode queueTranscode workersper chunk, parallelSegment storeHLS / DASH ladderCDN edgePlayer (ABR)Catalog + DRMlicense API12345671The master file is uploaded in parts.2An upload event creates transcode jobs, split into chunks.3Workers encode each chunk from 240p to 4K in parallel.4Segments and manifests are written. The title becomesREADY.5The player fetches the manifest URL and a DRM license.6Popular segments sit at the CDN edge.7The player picks a bitrate per segment (ABR).All 7 steps done. The flow replays…
Animated diagram: OTT video: from studio upload to playback. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. The master file is uploaded in parts. Multipart upload with pre-signed URLs; a dropped connection resumes from the last part.
  2. An upload event creates transcode jobs, split into chunks. Chunking a 2-hour film into 10-second pieces lets hundreds of workers encode it in minutes.
  3. Workers encode each chunk from 240p to 4K in parallel. Spot or preemptible instances fit well: a lost chunk just retries. Per-title encoding saves bits on simple scenes.
  4. Segments and manifests are written. The title becomes READY. Each rendition is a list of 2-6 s segments plus a manifest. DRM encrypts the segments.
  5. The player fetches the manifest URL and a DRM license. Entitlement checks (subscription, region) happen here, not on every segment.
  6. Popular segments sit at the CDN edge. An origin shield tier stops a premiere night’s millions of misses from hitting storage. Pre-warm the CDN for big releases.
  7. The player picks a bitrate per segment (ABR). Bandwidth drops on a train: it switches to 480p for the next segment instead of buffering.

Deep dives:

  • Two separate systems: the control plane (catalogue, auth, recommendations, playback API) is ordinary microservices; the data plane (video bytes) is almost entirely CDN. Large services such as Netflix run their own CDN appliances inside ISPs for this reason.
  • Premiere spikes: pre-position the title’s segments on edge caches before release, scale the playback API on a schedule, and protect entitlement checks with caching.
  • Watch progress: written every few seconds per viewer, a heavy but forgiving write load. Buffer in memory or a stream and store the latest position per (user, title) in a key-value store.
  • Recommendations: offline training on viewing events from the stream, with precomputed rows served from cache. Freshness of minutes is fine.

Say in the interview: “Split control plane and data plane: chunked parallel transcoding into an ABR ladder, segments and manifests on object storage behind a CDN with an origin shield, DRM licences at playback start, and pre-warming for big releases.”

6.3 Design ride hailing or “find nearby” (Uber, Ola, Swiggy delivery)

Requirements: riders see nearby drivers, request a ride, get matched within seconds; both see live location during the trip; fares and payments. Non-functional: matching under 5 s, location updates near real time, no double-booking of drivers.

Numbers: 1M active drivers updating every 4 s = 250k writes/s of tiny payloads. Only the latest point matters for matching.

Ride hailing: tracking drivers and matching a rider (animated, 7 steps)Driver appsGPS every 4 sLocation serviceGeo indexH3 cell → driversLocation streamRider appMatching serviceTrip servicestate machine12345671Drivers send positions every few seconds.2Update cell membership in memory with a short TTL.3Also stream positions to Kafka.4A rider requests a ride.5Query the rider's cell and neighbouring rings for freedrivers.6Offer the trip to the best driver and lock them for 10 s.7Accepted: a trip is created and moves through its states.All 7 steps done. The flow replays…
Animated diagram: Ride hailing: tracking drivers and matching a rider. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Drivers send positions every few seconds. Huge write volume (1M drivers / 4 s = 250k writes/s) but only the latest point matters, so don’t store each one in the main DB.
  2. Update cell membership in memory with a short TTL. Hexagonal cells (H3) or geohashes turn ‘nearby’ into ‘same or neighbouring cell’, a cheap key lookup.
  3. Also stream positions to Kafka. For trip replay, ETA models, surge pricing and analytics, which can tolerate seconds of delay.
  4. A rider requests a ride. The request carries pickup coordinates and an idempotency key (double taps happen).
  5. Query the rider’s cell and neighbouring rings for free drivers. Expand ring by ring until there are enough candidates; rank by ETA on the road graph, not straight-line distance.
  6. Offer the trip to the best driver and lock them for 10 s. The lock (Redis SET NX with TTL) stops two riders being matched to one driver.
  7. Accepted: a trip is created and moves through its states. REQUESTED → ACCEPTED → ARRIVED → ON_TRIP → COMPLETED. Explicit states make retries and support cases sane.

Deep dives:

  • Spatial indexing: geohash (string prefixes for grid cells), quadtrees (adaptive cells, dense cities get smaller cells) or H3 hexagons (uniform neighbour distances). All turn “within 2 km” into a small set of cell lookups.
  • Hot cells: an airport at 11 pm or a stadium after a match. Split cells finer, or shard the geo index by city and cell.
  • Consistency where it matters: location can be a few seconds stale; driver assignment must be exactly one rider per driver (lock or conditional write).
  • Trip as a state machine: each transition is an event, which makes billing, support and analytics straightforward.

Say in the interview: “Latest-position-only in an in-memory geo index keyed by H3 cells, ring search plus road-network ETA for ranking, a short lock to prevent double assignment, and the full location stream to Kafka for everything that tolerates delay.”

6.4 Design search autocomplete (typeahead)

Requirements: suggest the top 5-10 completions as the user types, ranked by popularity, personalised lightly; under 100 ms.

Design in brief:

  1. Collect: search queries stream into Kafka; a batch or streaming job counts frequency per query with time decay.
  2. Build: a trie (prefix tree) where each node stores its precomputed top-k completions, so a lookup is one walk down the prefix with no sorting at request time.
  3. Serve: the trie lives in memory on a fleet of suggestion servers, sharded by first characters if large, rebuilt and swapped atomically every few minutes or hours.
  4. Edge: short prefixes (one or two letters) are the same for everyone, so cache them at the CDN or in the browser.
  5. Client: debounce keystrokes (wait 100-150 ms), cancel in-flight requests when a new letter arrives.
  6. Safety: filter offensive or legally risky suggestions before they enter the trie.

AI-era twist: semantic suggestions (“leave policy” also suggests “casual leave rules”) come from embeddings, but the trie stays for speed. Blend both, with the trie as the fast first answer.

6.5 Design a CI/CD system (a distributed job scheduler)

A DevOps favourite: “design Jenkins, GitHub Actions or a build farm”. It tests queues, leases, leader election, isolation and cost, and you can talk about it from experience.

Requirements: run pipelines triggered by pushes and PRs; dependency graphs between jobs; runners with labels (OS, architecture, GPU); logs streamed live; artifacts; secrets; fair sharing between teams. Non-functional: queue wait under 1 minute at peak, no lost or duplicated jobs, isolation between jobs.

A CI system as a distributed job scheduler (animated, 6 steps)Git webhookCI APIJob DBDAG, state, leasesArtifacts + logsobject storeSchedulerleader electedQueues by labellinux, arm, gpuEphemeral runnerspods, autoscaled1234561Webhook verified (HMAC) and de-duplicated by delivery id.2The pipeline becomes a DAG of jobs in state QUEUED.3The leader scheduler picks jobs whose dependencies aredone.4Jobs are queued by runner label and priority.5A runner leases a job and heartbeats.6Logs stream out, artifacts upload, status goes back to thePR.All 6 steps done. The flow replays…
Animated diagram: A CI system as a distributed job scheduler. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Webhook verified (HMAC) and de-duplicated by delivery id. Git providers retry webhooks. Without de-duplication one push starts two pipelines.
  2. The pipeline becomes a DAG of jobs in state QUEUED. Jobs, dependencies and matrix expansions are rows. The DB is the source of truth, not the queue.
  3. The leader scheduler picks jobs whose dependencies are done. Leader election (Kubernetes Lease or etcd) ensures one scheduler. A standby takes over within seconds.
  4. Jobs are queued by runner label and priority. Fair share per team stops one monorepo from starving everyone else.
  5. A runner leases a job and heartbeats. A missed heartbeat means the lease expires and the job is retried elsewhere. Runners are ephemeral pods: clean, isolated, no leftover secrets.
  6. Logs stream out, artifacts upload, status goes back to the PR. Cache dependencies by lockfile hash; it is the cheapest speed-up in CI.

Deep dives:

  • Leases, not locks: a runner owns a job only while it heartbeats. Crashed runners release work automatically. This is the same pattern as the payroll workers and SQS visibility timeouts.
  • Isolation: one job per ephemeral pod or micro-VM (Firecracker), short-lived credentials through OIDC federation to the cloud, never static keys on runners.
  • Autoscaling: scale runner pools on queue depth per label (Actions Runner Controller, KEDA). Keep a small warm pool so the first job of the morning doesn’t wait for a node.
  • Cost: Spot nodes for most builds, a remote build cache (Bazel, Gradle, Docker BuildKit cache) and test splitting cut both time and money.
  • Supply chain: builds produce signed artifacts with provenance (SLSA), so deploys can verify what they run.

Say in the interview: “The job database is the source of truth, a leader-elected scheduler resolves the DAG, labelled queues feed autoscaled ephemeral runners that hold leases with heartbeats, and every build is isolated and produces signed artifacts.”

7. System design in the AI era

AI touches system design in two directions, and interviews now probe both:

  1. Designing systems that serve AI: RAG assistants, model serving, AI gateways, agents. New components, new failure modes, new cost curves.
  2. Using AI to design and run systems: AI-assisted architecture reviews, infrastructure code generation, incident analysis and automated remediation (AIOps).

The good news: the fundamentals in parts 1 to 4 still apply. Caching, queues, idempotency, timeouts, least privilege and observability carry straight over. What changes is the shape of the workload.

7.1 What’s different about AI workloads

Property Classic web service LLM-backed feature Design consequence
Latency Tens of ms, one number Time to first token (TTFT) plus time per output token; seconds in total Stream responses (SSE); set SLOs on TTFT and tokens/s separately
Unit of cost Requests, CPU-seconds Input and output tokens; GPU-hours Budgets and rate limits in tokens; route cheap tasks to small models
Compute CPU, scale out easily GPUs: scarce, expensive, slow to start Capacity planning, warm pools, queue-based autoscaling
Determinism Same input, same output Outputs vary; can be confidently wrong Evaluations instead of only unit tests; guardrails; human review for high stakes
State Request is stateless KV cache and prompt prefixes make routing matter Cache-aware routing; prompt caching
Inputs Validated forms Free text, documents, web pages (possibly hostile) Prompt-injection defences; treat model output as untrusted
Dependencies Your services Model providers with rate limits and outages Gateway with failover across providers or self-hosted models
Data Rows in your DB Embeddings and indexes derived from documents Pipelines that keep indexes fresh and permission-aware
Change Code deploys Model, prompt and index changes alter behaviour Version prompts and models; evaluate before rollout; canary them

Say in the interview: “I’d treat the model as an unreliable, expensive, rate-limited dependency: put a gateway in front of it, stream responses, budget tokens per tenant, evaluate every prompt or model change before rollout, and never let model output act without validation.”

7.2 Design a RAG assistant (“Ask HR” in PayFlow)

Retrieval-augmented generation answers questions from your own documents: retrieve the most relevant passages, put them in the prompt, and let the model answer with citations. It’s the most common AI system design question today.

Ask-HR: a permission-aware RAG assistant (animated, 7 steps)HR policiesPDF, wiki, ticketsIngest pipelineparse · chunk · embedVector + keywordindex with ACLsEmployeeAsk-HR APIauth, tenantRetrieverhybrid + rerankLLM via AI gatewayTraces + evals12345671Offline: documents are parsed, chunked and embedded.2Chunks are stored with tenant, ACL and source metadata.3An employee asks: 'How many leaves can I carry forward?'4The query is rewritten and the retriever is called withthe user's permissions.5Hybrid search filtered by tenant and ACL, then reranked.6Prompt = rules + 5 chunks + question. The answer citessources.7Everything is traced and a sample is evaluated.All 7 steps done. The flow replays…
Animated diagram: Ask-HR: a permission-aware RAG assistant. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Offline: documents are parsed, chunked and embedded. Chunks of a few hundred tokens with some overlap, split on headings. Re-ingest only changed documents (hash per file).
  2. Chunks are stored with tenant, ACL and source metadata. Metadata makes filtering, citations and deletion possible. Without it you can’t honour ‘remove this document’.
  3. An employee asks: ‘How many leaves can I carry forward?’ Normal auth applies: the assistant acts as this user, never as a super-user.
  4. The query is rewritten and the retriever is called with the user’s permissions. Query rewriting adds context (‘leave policy, Hyderabad office, 2026’).
  5. Hybrid search filtered by tenant and ACL, then reranked. Vector search finds meaning, keyword (BM25) finds exact terms like ‘Form 16’. Take the top 20 and rerank to the best 5.
  6. Prompt = rules + 5 chunks + question. The answer cites sources. Instruct the model to answer only from the context and say ‘I don’t know’ otherwise. Stream the tokens to the UI.
  7. Everything is traced and a sample is evaluated. Track retrieval hit rate, groundedness, latency and cost. Thumbs-down answers become new test cases.

Deep dives:

  • Chunking decides quality more than the model choice. Split on document structure (headings, sections, table rows), keep chunks a few hundred tokens with overlap, and store the parent section so you can expand context.
  • Embeddings: pick one model and version it. Changing the embedding model means re-embedding everything, so plan for a blue-green index swap.
  • Hybrid retrieval plus reranking beats pure vector search, especially for codes and names (“Form 12BB”, “LTA”).
  • Permissions are not optional. Filter by tenant and document ACL inside the search query itself. Filtering after retrieval can leak through summaries, and it starves results.
  • Freshness: an HR policy changed today must be answerable today. Ingest on change events (webhooks or CDC from the document store), and delete chunks when documents are deleted.
  • Vector store choice: pgvector keeps everything in Postgres and is enough for millions of chunks; dedicated engines (Qdrant, Milvus, OpenSearch) suit larger scale or heavy filtering. Index type trades recall for memory and speed (HNSW is the common default).
  • When not RAG: for structured questions (“how many leaves do I have left?”) call an API as a tool instead of searching documents. For style or format, fine-tuning helps; for knowledge, retrieval is better because it’s current and citable.
  • Quality metrics: retrieval recall (did the right chunk appear in the top 5?), groundedness (is every claim supported by a retrieved chunk?), answer relevance, refusal correctness, latency, and cost per answer.

Say in the interview: “Permission-aware hybrid retrieval with reranking, citations in every answer, event-driven ingestion so the index is fresh, and an evaluation set of real questions that gates every change to chunking, prompts or models.”

7.3 Design LLM inference serving at scale

If you self-host models (data residency, cost at high volume, fine-tuned models), you’re designing a GPU serving platform. This is where DevOps and platform engineers are most in demand right now.

Self-hosted LLM serving on Kubernetes (animated, 7 steps)Apps and agentsInference gatewayGateway API + extEndpoint picker(EPP)Autoscalerqueue, KV usePrefill pods (vLLM)compute-boundDecode pods (vLLM)memory-bandwidth-boundKV-cache transfer12345671A request arrives for model 'payflow-chat', priorityinteractive.2The gateway asks the endpoint picker which pod to use.3The picker scores pods and answers.4The prompt goes to a prefill pod.5The KV cache is handed to a decode pod.6Tokens stream back to the caller.7The autoscaler adds decode pods based on queue depth.All 7 steps done. The flow replays…
Animated diagram: Self-hosted LLM serving on Kubernetes. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. A request arrives for model ‘payflow-chat’, priority interactive. OpenAI-compatible API, so apps don’t care whether the model is self-hosted or a provider.
  2. The gateway asks the endpoint picker which pod to use. The InferencePool resource groups model-server pods; the picker is an extension the gateway calls per request.
  3. The picker scores pods and answers. It weighs queue length, KV-cache use, whether the prompt prefix is already cached on a pod, and which LoRA adapters are loaded. Round robin ignores all of that.
  4. The prompt goes to a prefill pod. Prefill processes the whole prompt in parallel and builds the KV cache. It sets time to first token (TTFT).
  5. The KV cache is handed to a decode pod. Decode generates one token at a time and is limited by memory bandwidth. Splitting the phases lets each pool scale and be tuned separately.
  6. Tokens stream back to the caller. Inter-token latency sets how fast text appears. Continuous batching in vLLM keeps the GPU full as requests join and leave.
  7. The autoscaler adds decode pods based on queue depth. GPU utilisation and CPU are poor signals for LLMs. Scale on waiting requests and KV-cache pressure, and keep warm capacity because GPU pods start slowly.

Concepts to explain clearly:

  • Prefill vs decode: prefill reads the whole prompt at once (compute-heavy, sets TTFT); decode produces tokens one by one (memory-bandwidth-heavy, sets tokens per second). Long prompts hurt TTFT; long answers hurt total time.
  • KV cache: the attention keys and values for tokens already processed. It grows with context length and concurrent requests and is usually what fills GPU memory. vLLM’s PagedAttention manages it in pages, like virtual memory, so far less is wasted.
  • Continuous batching: new requests join the running batch at every step instead of waiting for a whole batch to finish. This is the main reason modern servers (vLLM, SGLang, TensorRT-LLM) get much higher throughput than naive serving.
  • Prefix caching: requests sharing a prefix (same system prompt, same RAG context) reuse its KV cache. That is why routing to the pod that already holds the prefix pays off.
  • Model-aware routing on Kubernetes: the Gateway API Inference Extension adds an InferencePool backend and an endpoint picker that routes on model-server metrics. llm-d builds on it, adding KV-cache-aware routing and disaggregated prefill/decode.
  • Making models smaller: quantisation (FP8, INT4) cuts memory and cost with small quality loss; LoRA adapters let one base model serve many fine-tuned variants.
  • Parallelism for big models: tensor parallelism splits each layer across GPUs in one node; pipeline parallelism splits layers across nodes; expert parallelism spreads mixture-of-experts models.
  • Capacity planning: measure tokens per second per GPU for your model, prompt length and latency target, then size from peak tokens per second plus headroom. Keep a warm floor; scaling from zero means minutes of image pull and model load (pre-pull images, cache weights on local NVMe or a shared volume).

Build vs buy: hosted APIs win on time to market, model quality and zero GPU operations. Self-hosting wins on data control, predictable cost at high steady volume and custom models. Most companies run both behind one gateway.

Say in the interview: “vLLM pods behind an inference-aware gateway that routes on queue depth and prefix-cache hits, prefill and decode scaled separately for large deployments, autoscaling on waiting requests and KV-cache pressure, quantised models where quality allows, and a warm floor because GPU cold starts are slow.”

7.4 Design an AI gateway

Once several teams call several models, you need one control point, just as API gateways became necessary for microservices.

AI gateway: one front door for every model call (animated, 7 steps)AI gatewayProduct servicesAuth + budgettokens per tenantGuardrailsPII, injectionSemantic cacheModel routertask · cost · latencyTraces + costper featureSmall self-hostedProvider AProvider B12345671Every model call goes through one gateway.2Input guardrails: redact PII and flag prompt injection.3Semantic cache: was a near-identical question answeredrecently?4On a miss, the router chooses a model.5Simple work goes to a small, cheap model.6Hard reasoning goes to a frontier model, with failover.7Tokens, cost, latency and outcomes are logged.All 7 steps done. The flow replays…
Animated diagram: AI gateway: one front door for every model call. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Every model call goes through one gateway. A virtual key identifies tenant and feature. Budgets are in tokens and rupees, not just requests per second.
  2. Input guardrails: redact PII and flag prompt injection. PAN, Aadhaar, bank account and salary fields are masked before they leave your network.
  3. Semantic cache: was a near-identical question answered recently? Embedding similarity above a threshold returns the cached answer in milliseconds for zero tokens. Scope it per tenant.
  4. On a miss, the router chooses a model. Routing rules: by task type, context length, latency budget and cost. Start with rules; learn routing later.
  5. Simple work goes to a small, cheap model. Classification, extraction and short summaries rarely need a frontier model.
  6. Hard reasoning goes to a frontier model, with failover. On 429 or 5xx, retry on Provider B. Provider outages happen; one dependency is a single point of failure.
  7. Tokens, cost, latency and outcomes are logged. Cost per feature per tenant is the number finance will ask for. Output guardrails and evals hook in here too.

Caching layers to mention:

  • Exact cache: same prompt, same parameters, same answer. Cheap and safe for deterministic settings.
  • Semantic cache: similar meaning returns a cached answer. It’s powerful for FAQs, but risky if answers depend on the user (always scope by tenant and, where needed, by user), and needs a similarity threshold tuned on real data.
  • Provider prompt caching: many providers discount or speed up repeated prompt prefixes. Structure prompts with the stable parts (instructions, tools, policies) first to benefit.

Cost and fairness controls: token rate limits per tenant and feature, monthly budgets with alerts at 50/80/100%, maximum output length per route, and a cheaper fallback model when a budget runs out instead of a hard failure.

Open-source and managed options include LiteLLM, Envoy AI Gateway, Kong AI Gateway, and cloud offerings from the major providers. The pattern matters more than the product.

Say in the interview: “A single AI gateway for keys, budgets, PII redaction, caching, routing and failover, with per-feature cost and quality telemetry. It turns ‘we use LLMs’ from a pile of API keys into a governed platform.”

7.5 Design an agentic system

An agent is a loop: a model decides the next action, the runtime executes a tool, the result goes back to the model, until the goal is met. Agents turn LLMs from answering into doing, which makes them a distributed-systems and security problem.

An HR agent with tools, policy and human approval (animated, 8 steps)HR managerAgent runtimedurable workflowLLMplan / decideMemorystate, historyPolicy + approvalhuman for writesMCP server: HRISread-only scopeMCP server: Payrollwrite, sandboxedAudit log123456781Goal: fix the 12 employees whose PF wasn't deducted inNovember.2The model plans the next action.3Every tool call passes through policy first.4Read calls are auto-approved.5The write call pauses for HR approval.6Approved: the tool runs once, in a sandbox.7Results and decisions are saved to memory.8Every action is audited: who asked, what ran, whoapproved.All 8 steps done. The flow replays…
Animated diagram: An HR agent with tools, policy and human approval. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Goal: fix the 12 employees whose PF wasn’t deducted in November. A clear goal, a scope (this tenant, this month) and a budget (steps, tokens, time).
  2. The model plans the next action. The runtime loops: ask the model, run the chosen tool, feed back the result, repeat until done or out of budget.
  3. Every tool call passes through policy first. Least privilege: which tools, which tenant, which fields, how many calls. Treat model output as untrusted input.
  4. Read calls are auto-approved. MCP gives a standard way to expose tools and data; scope each server’s credentials narrowly.
  5. The write call pauses for HR approval. The workflow sleeps durably (hours if needed) and resumes exactly where it stopped. No polling loops holding memory.
  6. Approved: the tool runs once, in a sandbox. An idempotency key makes a retried step safe, and a dry-run diff is shown before the real write.
  7. Results and decisions are saved to memory. Short-term state for this task; long-term facts only if they are useful and allowed.
  8. Every action is audited: who asked, what ran, who approved. Auditors and incident reviews need this. So do you, the first time an agent does something surprising.

Design principles:

  • Durable execution: agent runs can take minutes or days and wait for humans. Run them on a workflow engine (Temporal, Step Functions, LangGraph with a persistent checkpointer) so crashes and deploys don’t lose progress.
  • Tools are APIs with contracts: clear schemas, narrow permissions, idempotency keys, dry-run modes. The Model Context Protocol (MCP) standardises how agents discover and call tools and data sources; treat each MCP server like any other service, with authentication and least privilege.
  • Risk-tiered autonomy: read-only actions run freely; reversible writes run with logging; irreversible or money-moving actions require a human approval step.
  • Budgets and stop conditions: maximum steps, tokens, wall-clock time and cost per run, so a confused agent can’t loop forever.
  • Untrusted inputs: anything the agent reads (emails, tickets, web pages, documents) can contain instructions. The agent’s permissions, not its prompt, must be what keeps it safe.
  • Multi-agent setups: a planner with specialist sub-agents can help on broad tasks, but every hand-off adds cost and failure points. Start with one agent and good tools.
  • Observability: trace every step (prompt, tool call, result, decision) with OpenTelemetry-style spans so you can replay and debug a run.

Say in the interview: “The agent runs as a durable workflow, calls tools through MCP servers scoped to least privilege, every write goes through a policy gate with human approval for anything irreversible, budgets cap each run, and every step is traced and audited.”

7.6 Evaluation, LLMOps and AI security

You can’t unit-test your way to a good AI feature. You evaluate.

  • Offline evals: a versioned dataset of real questions with expected answers or grading rubrics. Run it in CI on every change to prompt, model, retrieval or tools; block the merge if scores drop. Graders can be exact match, code checks, or an LLM judge calibrated against human labels.
  • Online monitoring: sample live traffic; track user feedback, groundedness, refusal rates, latency, cost; alert on drift.
  • Release like code: version prompts and model choices in Git, canary them to a share of traffic, and compare metrics before full rollout.
  • Security (from the OWASP Top 10 for LLM applications): prompt injection, sensitive information disclosure, supply-chain risk in models and plugins, excessive agency (agents with too much permission), and unbounded consumption (cost blow-ups). Mitigations are mostly classic: least privilege, input and output validation, rate limits, isolation, audit.
  • Data governance: know which data may be sent to which model (contracts, region, retention), redact before sending, log what was sent.

7.7 How AI is changing the design and operations work itself

In design:

  • Faster exploration: an assistant drafts two or three candidate architectures with trade-offs, rough capacity estimates and a failure-mode list in minutes. The engineer’s job shifts to judging, not typing.
  • Design reviews: feed the design doc to a model with your organisation’s standards (well-architected checklists, security rules) to catch missing items before human review.
  • Infrastructure as code: generated Terraform, Helm or Kubernetes YAML must pass the same gates as human code: plan review, policy as code (OPA, Checkov, Kyverno), cost estimation (Infracost), and tests.
  • Documentation: ADRs (architecture decision records), runbooks and diagrams kept current from code and incidents.

In operations (AIOps):

AI in the operations loop (animated, 7 steps)Metrics, logs, tracesAnomaly detectionlearned baselinesCorrelationtopology + changesOn-call (Slack)ExecutorGitOps, SSM, kubectlDecision gaterisk-tieredRCA assistant (LLM)runbooks, incidentsVerify SLO12345671Signals are compared with learned baselines.2500 alerts become 1 incident.3The LLM assembles evidence and a likely cause.4A summary with evidence links goes to on-call.5The proposed action is classified by risk.6Low risk runs automatically; high risk waits for a human.7Verify the SLO recovered, or escalate.All 7 steps done. The flow replays…
Animated diagram: AI in the operations loop. The numbered steps below match the numbers in the picture.

Flow, step by step

  1. Signals are compared with learned baselines. Seasonal baselines know Monday 10 AM is busy. Static thresholds page you for normal peaks.
  2. 500 alerts become 1 incident. Grouped by the service map and recent changes: ‘everything downstream of payroll-db went red after 18:02’.
  3. The LLM assembles evidence and a likely cause. It reads the deploy log, diff, dashboards and similar past incidents: ‘v4.2 raised DB pool wait time’. It proposes; it does not decide.
  4. A summary with evidence links goes to on-call. Minutes of dashboard hunting become one message. The human still owns the incident.
  5. The proposed action is classified by risk. Low risk: roll back a deploy, scale out, restart a pod. High risk: database failover, deleting data.
  6. Low risk runs automatically; high risk waits for a human. Every action goes through the same GitOps or runbook automation a human would use, so it is reviewed, logged and reversible.
  7. Verify the SLO recovered, or escalate. If error budget burn doesn’t drop within 10 minutes, page a human and undo the change. Post-incident, the case feeds the runbook library.

The rule that keeps this safe: AI proposes, policy decides, automation executes, and humans own outcomes. Start with summarisation and correlation (low risk, high value), then low-risk automated actions with automatic verification and rollback, and widen autonomy only with evidence.

7.8 Strategies to adopt in the AI era

A checklist for architects and DevOps engineers:

  1. Make the platform AI-ready before adding AI: clean, documented, permission-tagged data; APIs that enforce authorisation (agents will call them); good event streams. AI amplifies whatever data quality you already have.
  2. Put one gateway in front of all models for keys, budgets, redaction, routing, caching and telemetry. Never let every team integrate providers directly.
  3. Design for model churn: models improve and change price every few months. Keep the model behind an interface, keep evals ready, and expect to switch.
  4. Treat prompts, models and indexes as deployable artifacts: versioned, reviewed, evaluated, canaried, rolled back.
  5. Budget in tokens and GPU-hours, show cost per feature and per tenant, and route by task: small models for routine work, large models only where they earn it.
  6. Keep humans in the loop where actions are irreversible, and widen autonomy with measured evidence, not hope.
  7. Secure by architecture, not by prompt: least privilege for tools, sandboxing, output validation, audit logs.
  8. Plan GPU capacity like any scarce resource: reservations, warm pools, multi-provider fallback, and queue-based autoscaling.
  9. Instrument everything with traces, including model calls and agent steps, so AI behaviour is debuggable like any other service.
  10. Upskill across the boundary: platform engineers who understand inference serving, and application engineers who understand evals and cost, are the people building these systems.

8. Interview playbook

8.1 Running the 45 minutes

Section 10.1 of the DevOps Interview Guide has the six-step framework. Here’s how the time usually splits, and what each level is expected to show.

Minutes Do Output on the whiteboard
0-5 Clarify functional scope and the 2-3 non-functional drivers Bullet list of requirements with numbers
5-10 Estimate load, storage, bandwidth; name the hard part Three or four numbers and “the hard part is…”
10-15 API and data model 4-6 endpoints, main tables or entities, key choice
15-25 High-level design: the request path end to end Boxes and arrows like 1.2
25-40 Deep dive on the hard part, scaling, failure modes One component in detail, with trade-offs
40-45 Bottlenecks, monitoring, what you’d do next SLOs, alerts, cost, v2 ideas
Level What interviewers look for
Junior / mid A working design, correct use of cache, queue, DB, LB; reasonable numbers
Senior Trade-offs stated and chosen; failure modes; data model and consistency choices; operations and cost
Staff / lead / architect Scoping well; evolution over time; organisation and team impact; cross-cutting concerns (security, compliance, cost, migration); knowing what not to build

8.2 Trade-off language and common mistakes

Phrases that show judgement:

  • “We could do A or B. A gives us X but costs Y. Given our requirement for Z, I’d pick A, and revisit if W changes.”
  • “This is the one place I’d pay for strong consistency; everything else can be eventually consistent.”
  • “I’d start simpler and add this when metric M crosses threshold T.”
  • “The failure mode here is F; we detect it with D and recover by R.”

Common mistakes:

  • Drawing microservices and Kafka before asking about scale.
  • No numbers, or numbers that never affect a decision.
  • Ignoring failure: what if this box dies, is slow, or gets duplicated messages?
  • One database for everything, or a different database for everything.
  • Forgetting operations: deploys, migrations, monitoring, on-call, cost.
  • For AI questions: no evaluation plan, no cost model, no permission model for retrieval and tools.
  • Going silent. Think aloud; the interviewer grades your reasoning, not just the final picture.

8.3 Rapid-fire questions

  1. Horizontal vs vertical scaling? Vertical is a bigger box (simple, limited, single point of failure); horizontal is more boxes behind a load balancer (needs statelessness, scales further, survives failures).
  2. L4 vs L7 load balancer? L4 routes TCP/UDP by address, fast and protocol-agnostic; L7 understands HTTP and routes by path, host or header, terminates TLS and can retry.
  3. When would a cache hurt? When data must be fresh (balances), when hit ratio is low (wasted memory and an extra hop), or when invalidation bugs serve wrong data.
  4. Cache-aside vs write-through? Cache-aside fills on read misses and deletes on write; write-through updates cache and DB together on every write, keeping the cache warm at the cost of slower writes.
  5. What is a thundering herd and how do you stop it? Many requests hitting the backend at once after a cache expiry or restart. Use single-flight, locks, stale-while-revalidate and TTL jitter.
  6. SQL or NoSQL? Start with the access patterns: relational for transactions and flexible queries; key-value or wide-column for huge scale with known queries.
  7. How does an index speed up a query, and what does it cost? A B-tree lets the database find rows in logarithmic time instead of scanning; it costs write speed, storage and memory.
  8. What is replica lag and how do you handle it? The delay before a follower applies the leader’s writes. Read from the leader after a user’s own write, or wait for the replica to catch up to that write’s position.
  9. How do you choose a shard key? High cardinality, even load, and most queries served by one shard. For B2B SaaS, usually tenant id, with big tenants given their own shard.
  10. Explain consistent hashing. Keys and nodes map onto a ring; a key belongs to the next node clockwise, so adding or removing a node moves only about 1/N of keys.
  11. CAP in one sentence? During a network partition you choose between consistency and availability; PACELC adds that without a partition you trade latency for consistency.
  12. At-least-once vs exactly-once? At-least-once may deliver duplicates; true exactly-once end to end is impractical, so you make consumers idempotent to get effectively-once.
  13. What problem does the outbox pattern solve? The dual write: saving to the DB and publishing an event can’t be atomic across two systems, so you write the event to an outbox table in the same transaction and relay it.
  14. Saga vs 2PC? 2PC locks across participants and blocks on coordinator failure; sagas use local transactions plus compensations and suit microservices.
  15. Why 3 or 5 nodes in etcd? Majority quorum: 3 tolerates 1 failure, 5 tolerates 2; even numbers add cost without tolerance.
  16. What is a fencing token? An increasing number issued with a lock; storage rejects writes from older tokens, so a paused process can’t act on an expired lock.
  17. How do retries cause outages? Retry storms multiply load on an already struggling service. Use backoff with jitter, retry budgets, and retry at one layer only.
  18. Circuit breaker states? Closed (normal), open (fail fast), half-open (probe to test recovery).
  19. SLI vs SLO vs SLA? SLI is the measurement, SLO the internal target, SLA the contract with penalties. Set SLOs tighter than SLAs.
  20. What is an error budget used for? Balancing release speed with reliability: ship while the budget lasts, focus on reliability when it’s spent.
  21. RPO vs RTO? RPO is how much data you can lose; RTO is how long recovery may take.
  22. Active-active vs active-passive? Active-active serves from multiple regions at once (complex data layer, near-zero RTO); active-passive keeps a standby to fail over to (simpler, minutes of RTO).
  23. How do you change a database schema with zero downtime? Expand and contract: additive change, dual write, backfill, switch reads, then remove the old shape.
  24. What is Little’s law used for? Sizing concurrency: in-flight requests = arrival rate × latency. Use it for pools, pods and queues.
  25. Why is p99 more important than average? Users feel the slow requests, and fan-out makes tail latency the common case.
  26. What are TTFT and TPOT? Time to first token and time per output token: the two latency numbers for LLM serving, driven by prefill and decode respectively.
  27. Why route LLM requests by KV-cache or prefix? A pod that already holds the prompt’s prefix skips recomputing it, cutting TTFT and GPU cost.
  28. How do you stop a RAG assistant leaking data across tenants? Filter by tenant and ACL inside retrieval, act with the user’s permissions, scope caches per tenant, and test it with adversarial evals.
  29. How do you keep an AI agent safe? Least-privilege tools, human approval for irreversible actions, budgets and stop conditions, durable workflows, full tracing and audit.
  30. How would you reduce LLM costs by half? Route simple tasks to small models, cache (exact, semantic, provider prompt caching), trim prompts and outputs, batch offline work, and self-host high-volume steady workloads.

8.4 One-page cheat sheet

If you hear… Reach for…
“Read-heavy”, “slow page” Cache-aside in Redis, CDN, read replicas, denormalised read model
“Spiky traffic”, “slow work” Queue plus workers, autoscale on lag, load shedding
“Must not double charge” Idempotency keys, conditional writes, ledger, reconciliation
“Many services must agree” Saga with orchestrator; avoid 2PC
“Leader”, “only one should run” Lease-based leader election (etcd, Kubernetes Lease) plus fencing
“Huge write volume” Partitioning, wide-column store or log, batch writes, only keep latest where possible
“Global users” CDN, regional deployments, GSLB, data residency by home region
“Never lose data” Synchronous standby, backups tested by restore, outbox, RPO targets
“Real-time updates” WebSockets or SSE, pub/sub, session registry
“Search” Inverted index fed by CDC; hybrid with vectors for meaning
“Nearby” Geohash, quadtree or H3 cells in an in-memory index
“Video”, “large files” Object storage, multipart and pre-signed uploads, chunked processing, CDN
“Analytics” CDC to a stream, lakehouse, OLAP engine
“Zero downtime” Rolling or canary deploys, flags, expand-contract migrations
“Chatbot on our documents” RAG with permission-aware hybrid retrieval, citations, evals
“Self-host a model” vLLM, inference-aware gateway, queue-based GPU autoscaling, quantisation
“Many teams using LLMs” AI gateway: keys, budgets, redaction, routing, caching, telemetry
“Automate operations with AI” Correlation plus LLM summaries, risk-tiered actions through GitOps, verify and roll back

8.5 A study path from beginner to expert

Stage Focus Practice
Weeks 1-2 Part 1: request path, numbers, APIs, scaling Explain 1.2 aloud from memory; do three estimates a day
Weeks 3-4 Part 2: caching, databases, replication, sharding, messaging Design a URL shortener and a notification system (DevOps Interview Guide, section 10)
Weeks 5-6 Part 3: sagas, consensus, resilience, SLOs, security Add failure handling to each earlier design; write SLOs for them
Weeks 7-8 Parts 4 and 5: multi-region, change safety, cost, PayFlow Tell the PayFlow story (or your own product’s) in 10 minutes
Weeks 9-10 Parts 6 and 7: case studies and AI systems Design Ask-HR and an inference platform; mock interviews with a timer
Ongoing Read real postmortems and engineering blogs Rebuild one public outage’s timeline and say how you’d have designed around it

References

Books:

  • Martin Kleppmann, Designing Data-Intensive Applications (O’Reilly). The best single book on replication, partitioning, transactions and streams.
  • Alex Xu, System Design Interview: An Insider’s Guide, volumes 1 and 2.
  • Betsy Beyer et al., Site Reliability Engineering and The Site Reliability Workbook (Google, free online).
  • Chip Huyen, AI Engineering (O’Reilly) and Designing Machine Learning Systems (O’Reilly).
  • Sam Newman, Building Microservices (O’Reilly), 2nd edition.

Papers and specifications:

Websites:

Spotted something wrong or out of date?Suggest a correction. I review every suggestion before changing the page.

EmailRSS