Skip to content
Tech Interview Prep
Technical interview guide

Scalability Fundamentals

Production scalability fundamentals for technical interviews: bottlenecks, scaling, load balancing, autoscaling, capacity, overload control, and failure behavior.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Vendor-neutral fundamentals; Google SRE, AWS Well-Architected, Google Cloud, and IETF references accessed 2026-08-30..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Explain the difference between throughput and latency using a concrete example, and describe a scenario where optimizing one hurts the other.

Answer

First 90 seconds

Throughput and latency are two axes on the same system, and Little's Law ties them: concurrency = throughput * latency. With a fixed number of requests in flight they move in strict opposite directions, so "optimizing one hurts the other" usually just means you moved along that curve. The more interesting case is changing the per-request fixed cost, which shifts the whole curve: that's what batching does. Numbers below are illustrative, not measured.

Assume an event-ingest API in front of Postgres, 8 connections in the pool, one INSERT in flight per connection. Each event row costs 0.1 ms of DB work; a round trip costs 2 ms no matter how many rows it carries. Those two constants drive everything.

Unbatched, one event per INSERT: 2.1 ms each. One connection sustains 1 / 0.0021 s ~ 476 events/s; the pool ~3,810/s. p50 is ~2.5 ms with no backlog; when a burst queues all 8 connections, p99 ~15 ms.

Batched at 100 events per INSERT behind a 20 ms accumulation window: 2 ms + 100 * 0.1 ms = 12 ms per INSERT, so 100 / 0.012 ~ 8,333 events/s per connection and ~66,600/s for the pool. An event arriving just after a flush waits a full window: p50 ~ 10 ms (uniform arrivals, half a window on average) + 12 ms = 22 ms, p99 ~ 32 ms.

configevents per INSERTservice timepool throughputp50p99
unbatched12.1 ms~3,810/s~2.5 ms~15 ms
batch 100, 20 ms window10012 ms~66,600/s~22 ms~32 ms

17.5x the throughput, 8.8x the p50. Same change, opposite directions, because the 2 ms round trip went from covering one event to covering 100: service time per event fell from 2.1 ms to 0.12 ms.

Why this isn't just an accounting identity: at 8 connections Little's Law gives throughput = 8 / latency, so any latency increase at fixed concurrency is a straight throughput loss. Batching escapes that only by cutting service time; the window is the pure added wait you pay for it. The other lever is concurrency: go to 20 connections and you get 20 / 0.0021 ~ 9,524 events/s at ~2.5 ms p50, but DB CPU rises from 8 * 0.1/2.1 ~ 38% to 20 * 0.1/2.1 ~ 95%, so queue wait starts eating the gain. The choice is: spend latency (batch) or spend DB CPU (more connections), and they saturate in different places.

Pipelining is the third option: libpq pipeline mode (added in Postgres 14), or pgx's SendBatch, lets a client send inserts back-to-back without waiting for each response, which removes round-trip serialization with no accumulation window and keeps p50 near 2.5 ms. Batching is the wrong call when the SLO is interactivity (a read path with p99 under 20 ms), when load is too low for the window to amortize anything, and when per-key ordering matters, since a batch can fail or partially apply.

Failure modes I'd watch:

  • Timer restarted on every arrival: at 50 events/s a 100-event batch never fills and the timer never fires, so every event waits 100/50 = 2 s. Detect it with a batch-size histogram sitting below max while p99 tracks a window-derived value. Fix: start the timer on the first arrival in the window.
  • Window too large for the load: at 5 events/s p50 is still ~10 ms despite zero contention. Latency paid for throughput you don't need. Detect: high throughput headroom with latency pinned near window/2.
  • Oversized batch: 1,000 rows is 2 + 100 = 102 ms holding one of eight connections; at 1 MB per event that's 1 GB of in-flight batch memory. Detect: connection wait time and per-slot heap.
  • Poison event: one bad row fails all 100, and a blind retry re-sends the batch. Duplicates if the commit succeeded before a client timeout. Detect: sink-side duplicate counts keyed on event id, plus error rate jumping by roughly the batch factor.

What would change my answer: an ingest SLO of p99 under 10 ms rules batching out. I'd pipeline and shard writes wider instead. A nightly analytics consumer that tolerates seconds would let me batch at 1,000 and bank the throughput.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Why is horizontal scaling generally preferred over vertical scaling for large-scale systems, despite vertical scaling being simpler?

Answer

Short answer: at scale the binding constraint stops being CPU or RAM on one box and becomes the size of the largest box you can buy, the blast radius of losing it, and the cost of the next size up. Horizontal scaling attacks all three; vertical attacks none of them past a point.

The ceiling is real. The largest general-purpose EC2 instance, m7i.48xlarge, is 192 vCPU and 768 GiB; the memory-optimized r7i.48xlarge is 192 vCPU and 1.5 TiB; the biggest single instance AWS sells, u7inh-32tb.480xlarge, is 32 TiB and 480 vCPU. If your working set is 60 TiB, no instance exists. That is the argument in one line: vertical scaling is bounded by a SKU list, horizontal scaling is bounded by your partitioning scheme.

Second, failure domain. One 192-vCPU node is one power domain, one kernel, one NIC. Lose it and you lose 100% of capacity. Eight 24-vCPU nodes lose 12.5% when one dies; with N+1 (nine nodes) you lose 0%. The availability math is why the redundancy argument is not decoration: a single node at 99.9% availability is ~8.8 h/year of downtime. Two replicas behind a load balancer with health checks only reach ~99.9999% if failover is fast and the dependency is not shared.

Third, cost curve. Instance pricing is roughly linear-to-superlinear in vCPU, and the largest classes are not cheaper per vCPU than the mid-range. You also pay for the downtime to resize: changing an EC2 instance type means stop/start, and a Multi-AZ RDS class change fails over, which AWS documents as typically under 60 s of write downtime. Horizontal capacity adds are rolling and can be done one node at a time.

Now the mechanism, because "just add nodes" is where candidates get caught. Throughput scales as long as the work partitions and no shared resource saturates. If 5% of each request is serialized (a single-writer row, a global sequence, a lock) Amdahl caps you at 1/0.05 = 20× no matter how many workers you add. That is the arithmetic behind "coordination eats it."

Shared dependencies are the usual killer. PostgreSQL defaults to max_connections = 100; PgBouncer defaults to default_pool_size = 20 per pool. Going from 8 to 80 app nodes multiplies connection demand 10×, and the DB is the same size. You will see pool wait time climb and p99 follow it before CPU on the app tier moves at all.

Failure modes and how you see them:

  • Hot shard / skew: one shard's p99 is 5–10× the median; a per-shard latency histogram shows it. Fix by re-sharding or splitting the key.
  • Coordination overhead: inter-node bytes per request grows with N (full-mesh gossip is O(N²)); watch network egress per request as node count rises.
  • Shared dependency saturation: DB connection count pinned at max_connections, pool wait > 0, app CPU still low.
  • Retry storm / metastable failure: retry rate and queue depth rise together after a blip; shedding and jittered backoff are the mitigations.

When vertical is the right call: single-writer OLTP with a working set that fits in 1.5 TiB, in-memory joins that would need cross-node shuffles, or a team without the ops maturity to run sharding. Vertical is simpler and often cheaper at small N: the mistake is treating it as a strategy rather than a step.

dimensionverticalhorizontal
ceiling~32 TiB / 480 vCPU (u7inh-32tb.480xlarge)bounded by partition scheme
node loss100% capacity1/N, 0% with N+1
resizestop/start; RDS failover <60 srolling, one node at a time
costsuperlinear at top of rangelinear in node count
complexitylowsharding, coordination, rebalancing

If the interviewer pushes, ask what the serial fraction is and what the shared dependency is. Those two numbers decide the answer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Why does statelessness matter for horizontally scaling an application tier?

Answer

What a strong candidate says first

"Stateless" here means the instance holds no per-request mutable state that must survive the request: no in-process session map, no local file uploads, no in-memory rate-limit counters that other instances have to agree with. The request carries or fetches everything it needs. That makes instances fungible: any instance can serve any request, so the load balancer needs no affinity, autoscaling can add or kill instances at will, and losing a node costs the requests in flight, not the sessions pinned to it.

The state does not disappear. It moves to a shared owner: a Redis/KeyDB session store, the database, a signed cookie or JWT, or an upstream identity service. That owner is now the shared dependency: its capacity, consistency and availability set the ceiling for the whole tier. Statelessness buys horizontal scale of compute; it does not buy horizontal scale of state.

Why it behaves that way

Sticky routing is the alternative, and it is not "no scaling": it is scaling with a coupling. With cookie or IP affinity a session lives on one instance, and two costs follow. Skew: affinity is by hash, not by load, so one NAT'd corporate egress can pin thousands of users to a single instance. Failover: when that instance dies, its sessions die with it.

Arithmetic (illustrative): 12 instances, 10,000 concurrent sessions, evenly hashed. Kill one node and ~833 sessions are lost: those users re-authenticate or lose their carts. With a shared Redis store the same node loss costs only the requests in flight, typically sub-second, and the surviving 11 instances absorb the traffic. The trade is a new hop: a Redis GET is roughly 0.2–0.5 ms on the same VPC versus ~0 for an in-process dict, and Redis now needs its own HA (Sentinel or cluster mode) or it becomes the single point of failure you just removed.

Failure modes and how you detect them

  • Shared store saturation: Redis at maxmemory with the default noeviction policy starts rejecting writes, so sessions silently fail to persist. Watch evicted_keys and rejected-write counters plus p99 on session writes. Size for peak sessions × bytes/session, set a TTL, and run a cluster.
  • Thundering herd on node loss: 833 sessions re-authenticate at once against the auth service. Detect the login-QPS spike and 5xx burst; mitigate with jittered retries and connection pooling.
  • Sticky-session skew: one instance at 90% CPU while peers idle. Detect by comparing per-instance CPU and queue depth: the LB's per-target metrics show it directly.
  • Token bloat: overloading a JWT pushes it past header limits (nginx's default large_client_header_buffers is 8k) and every request pays the parse cost.
state locationscaling propertycost on node lossper-request cost
in-process dictneeds affinitysessions lost~0
Redis session storefungiblein-flight only~0.2–0.5 ms hop, HA needed
signed cookie / JWTfungiblenonesize limit, no revocation without a denylist
DB rowfungiblenonea DB write per request, contention

When not to use it: single-instance services, or workloads where the state is genuinely large and hot. A 2 GB in-memory model per instance is cheaper to keep local with affinity or a partitioned cache than to ship over the network on every request.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Why does a stateless application tier still need to think carefully about where session-related state (like a shopping cart or login session) actually lives?

Answer

"Stateless" means the app process keeps no per-user session data in its own heap between requests. The data still exists: the question is where, and that choice sets your latency floor, your failure modes, and whether you can deploy without logging people out.

Three places it can live, and what each costs:

Client-side (signed cookie / JWT). The server holds only a signing key. No store to scale, no round trip. But browsers cap a cookie at ~4096 bytes, and a 50-item cart (SKU + qty + price) blows past that and gets silently dropped. Revocation is the other problem: a signed token is valid until it expires unless you keep a denylist, which is a store again. Good for small immutable claims (user id, role), bad for a mutable cart.

Sticky sessions. The load balancer pins a user to one node; the session lives in that node's memory. Zero extra latency, nothing to scale. But node loss drops the session, rolling deploys drain users, and autoscaling can't rebalance without evicting someone. Fine for a small fleet where losing a cart is acceptable.

Shared store (Redis, Memcached, a DB table). Any node serves any user. Cost: one network round trip per request on the critical path. Same-AZ Redis GET is p50 ~0.2 ms, p99 ~1 ms; cross-AZ adds ~1-2 ms each way. On a 40 ms p99 API budget that's 0.5-2.5%: cheap, but not free, and it's every request.

The scaling doesn't disappear, it moves. 50k concurrent users at 20 req/s is 1M session reads/s; a hit costs two Redis ops (GET + EXPIRE for the sliding TTL), so 2M ops/s. One Redis node does roughly 100k-200k simple ops/s, so you need ~10-20 shards or read replicas. That's the relocated problem.

Python
# Python 3.12, redis-py 5.x
import redis, json, time
r = redis.Redis(host="sessions.internal", port=6379, socket_timeout=0.05)

def load_session(sid):
    key = f"sess:{sid}"
    raw = r.get(key)                 # RTT 1
    if raw is not None:
        r.expire(key, 1800)          # RTT 2, sliding 30-min TTL
        return json.loads(raw)
    lock = f"lock:{sid}"
    if r.set(lock, "1", nx=True, ex=5):   # one winner rebuilds
        try:
            data = rebuild_from_db(sid)
            r.set(key, json.dumps(data), ex=1800)
            return data
        finally:
            r.delete(lock)
    time.sleep(0.05)                 # loser waits, then re-reads
    raw = r.get(key)
    return json.loads(raw) if raw else None

Trace: a hit is 2 round trips. A miss is SET NX + one DB query + SET + DEL. The loser's sleep-then-read can still return None if the winner is slow: bound it with a retry loop rather than trusting one sleep.

Failure modes worth naming:

  • Stampede on expiry. A popular key expires and every concurrent request misses at once, all hitting the DB. The NX lock above collapses that to one rebuild; jittered TTLs (1800 ± 300 s) spread the rest. Detect it as a sawtooth in DB query rate every TTL period.
  • Store failover. Redis primary failover is typically 10-30 s of connection errors. With no replica, every user is logged out. Set a short socket_timeout so requests fail fast instead of piling up, and decide explicitly whether you fail open (no session) or closed (401).
  • Hot key. One heavy user's session key pegs a single shard. Detect via per-shard latency; mitigate by hashing the session id across shards.
  • Cookie overflow. Cart exceeds 4 KB, browser drops it, user silently loses the cart. Detect via client error reporting.
approachextra latencysurvives node lossrevocationscales by
signed cookie0 (payload on wire)yeshard (denylist)client bandwidth
sticky session0noeasycan't rebalance
Redis~0.2-1 msyes, with replicaeasy (DEL)shard + replica

Pick by what you can't lose: cookies for immutable claims, sticky for tiny fleets that tolerate cart loss, Redis when you need revocation and cross-node balance and can pay the round trip.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Explain why stateless application servers alone don't guarantee a horizontally-scaled system is fully scalable, using the database as a counter-example.

Answer

The 90-second version. Statelessness does not remove state, it relocates it. Once any pod can serve any request, all mutable state and all concurrency concentrate in the shared tiers, and for an OLTP service that is usually one primary database that is not partitioned. Horizontal pod scaling changes the number of clients hitting the primary, not the primary's capacity. Writes do not scale by adding app servers at all: they serialize on a single writer, first at the connection count, then at commit fsync, then at row locks.

Assumptions for the numbers below, stated so they can be argued with: 200 app pods behind an HPA, each holding a 20-connection pool; PostgreSQL 16 primary with default max_connections = 100; one PgBouncer in transaction pooling mode with a 100-server-connection pool; 95% read / 5% write mix; p99 target 200 ms.

Connection layer, the first ceiling. 200 pods x 20 = 4,000 client connections against a default max_connections = 100. Without a pooler the primary rejects the first rollout with SQLSTATE 53300 (too many clients already). Every PostgreSQL backend is a process holding several MB of baseline memory plus work_mem (default 4 MB) per sort or hash node, so raising max_connections to 4,000 trades connection errors for memory pressure and context-switch overhead. PgBouncer in transaction mode multiplexes those 4,000 clients onto ~100 server connections, which is necessary but is a queue, not extra capacity.

Throughput, what the pool actually buys. Little's law: throughput = concurrency / latency. 100 server connections at a 4 ms mean query time cap out near 100 / 0.004 = 25,000 qps. Saturate the pool and let mean latency rise to 40 ms under contention and the same 100 connections give 100 / 0.040 = 2,500 qps: the fleet is now ten times larger and the system is ten times slower.

Write path, the ceiling that decides it. A hot row is the honest example. UPDATE counters SET n = n + 1 WHERE id = 1 takes a row lock held until commit, and commit includes the WAL flush (synchronous_commit = on by default). If lock-to-commit takes 2 ms, the ceiling on that key is 1 / 0.002 = 500 updates/s regardless of pod count. The signature is lock wait time climbing while database CPU stays flat. Add synchronous_standby_names = 'remote_apply' to a cross-region standby and every commit waits a round trip; at 40 ms RTT a single connection is capped at 25 commits/s, and group commit only helps if the commits arrive together.

Read path, and why it does not rescue you. Replicas and caches multiply reads, not writes. A 95% cache hit ratio cuts origin reads 20x. A replica adds read capacity, but every commit still lands on the one primary and is replayed on each replica in WAL order: apply does not parallelize the way read queries do, so replicas fall behind under write bursts.

fixwhat it buyswhat it does notwhen it is the wrong call
Read replicasnear-linear read scalingnothing for write throughputreads must be read-your-writes and lag is unbounded: after a backfill, lag of seconds means a user saves a row, reloads, and does not see it
Read-through cache (Redis)20x fewer origin reads at a 95% hit ratiodoes not touch writes; adds invalidation correctnesslarge or churning working set, or mass expiry causing a thundering herd on the primary
Sharding by tenantwrite scaling across shardsglobal counters, cross-shard joins, distributed transactions, resharding costthe hotspot is one key: sharding by user_id will not split a global counter (fan-out or per-shard counters plus aggregation will)
Transaction-mode poolerprotection from connection stormsthroughput beyond what the primary can servethe app needs LISTEN/NOTIFY, session advisory locks, or server-side prepared statements

Failure modes and how to detect them.

  1. Rolling-deploy connection storm: 200 pods x 20 connections; 53300 errors, pg_stat_activity count pinned at max_connections, rollout stalls. Detect on the connection-count graph and 5xx rate together.
  2. Hot row lock convoy: wait_event_type = 'Lock' in pg_stat_activity, xact_commit flat while request rate doubles.
  3. Replica lag breaking read-your-writes: pg_stat_replication.replay_lag climbing past seconds; a canary that writes then immediately reads the replica fails.
  4. Autoscaling feedback loop: pods scale on latency, more connections make the database slower, latency rises, pods scale further. Detect by connection count and p99 rising together while database CPU is flat.

The useful conclusion is not "fix every layer." It is: find the binding constraint, and if it is the single writer, no amount of stateless capacity above it moves the number. Either partition the write path (shard, per-key counters with coalescing, or a queue in front) or accept the ceiling and shed load at the edge.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Why can scaling out the application tier alone fail to improve overall system throughput?

Answer

The 90-second answer

Scaling the app tier only helps if the app tier is the saturated resource. Throughput of a request path is set by its slowest stage, and for most stateless services that stage is a shared downstream: the primary database, a single-writer lock, a shared cache, or a rate-limited third-party API. Adding app instances adds concurrency, not capacity. Past the point where the downstream is saturated, extra instances convert into queue depth, latency and timeouts rather than completed work.

Assumption to state out loud: the app tier is stateless and horizontally scalable, and the downstream is shared by every instance.

Why it plateaus: the mechanism

Take a Postgres primary behind a connection pool. HikariCP's default maximumPoolSize is 10; PostgreSQL's default max_connections is 100. Each app instance can hold at most 10 concurrent queries, and the whole fleet at most 100 before the server rejects new sessions with FATAL: sorry, too many clients already.

Within one instance the pool is a queue. With c connections and mean service time S, utilization is ρ = λS/c. Response time grows roughly as S/(1−ρ) for a single server and stays directionally the same for c servers: at ρ = 0.5 you pay 2× service time, at ρ = 0.8 you pay 5×, at ρ = 0.9 you pay 10×. Once ρ ≥ 1 the queue is unstable and latency is unbounded.

Worked trace

Query p99 = 5 ms, pool = 10 connections per instance, 8 instances.

  • Per-instance ceiling: 10 / 0.005 s = 2,000 qps. Fleet ceiling if the DB were free: 16,000 qps.
  • The DB's own CPU saturates at ~6,000 qps of this query mix (measure it; don't guess).
  • At 1,800 qps per instance: ρ = 1800 × 0.005 / 10 = 0.9 → wait ≈ 45 ms, total ≈ 50 ms.
  • Scale 8 → 20 instances, same total offered load spread evenly: 3,600 qps per instance → ρ = 1.8. The queue grows without bound; checkout waits hit HikariCP's default connectionTimeout of 30 s and callers get SQLTransientConnectionException.

Total completed work is still ~6,000 qps. You bought 12 more instances and a p99 that went from 50 ms to 30 s timeouts.

What actually breaks, and how you see it

failuresignal
Pool saturationhikaricp_connections_pending rising, hikaricp_connections_timeout_total climbing
Connection storm on deployall instances reconnect together, DB logs too many clients already
Hot-row lock contentionpg_locks waits, deadlock counter, throughput pinned at 1/lock-hold-time
Retry amplificationtimeout → retry → 3× load on an already-saturated DB
Downstream rate limit429s from the third-party API, not from your app

When app scaling is the right call

Scale out the app tier when it is the tier with the highest utilization and the downstream has headroom: CPU-bound serialization, template rendering, TLS termination. Otherwise scale the bottleneck: read replicas for read-heavy paths, partitioning or sharding for write-heavy ones, a cache in front of hot reads, or a queue (Kafka, SQS) to convert synchronous writes into batched async ones. The decision rule is measurement, not reflex: find the tier whose utilization is highest and whose latency is growing superlinearly, and fix that one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How do you identify the bottleneck in a system before deciding what to scale?

Answer

The 90-second answer. Instrument every layer, drive load past the point where latency inflects, and find the resource whose utilization or queue depth rises first. That resource is the bottleneck. Don't infer it from the architecture diagram: it is usually one specific query, lock, or pool, not a whole tier.

Assumptions: a request-path service behind a load balancer, a stateless app tier, a cache, and one primary Postgres. Read-heavy, roughly 10:1.

Mechanism. Two laws do most of the work.

Little's Law: L = λW. In-flight requests equal arrival rate times latency. If p99 triples while throughput is flat, in-flight work tripled: something is queueing.

Queueing: for a single server at utilization ρ, mean queue delay scales as ρ/(1−ρ). At ρ=0.5 the queue adds one service time; at 0.8 it adds four; at 0.9, nine. That is why p99 inflects sharply while throughput is still climbing: you cross the knee well before anything reads 100%. Utilization alone won't show it; queue depth and wait time will.

The USE method (Brendan Gregg) gives the per-resource checklist: Utilization, Saturation, Errors. Saturation is the leading indicator: run-queue length, pool wait time, DB active sessions, GC pause time.

Worked trace (hypothetical numbers, real method). Service at 1,200 rps: p50 12 ms, p99 45 ms. Ramp to 1,800 rps: p50 14 ms, p99 210 ms, throughput plateaus near 1,900 rps.

layersignalreadingverdict
load balancerCPU, conn count8% CPUnot it
app pods (12)CPU, GC pause35% CPU, p99 GC 8 msnot it
RedisINFO commandstats, p994% CPU, p99 0.4 msnot it
Postgres primarypg_stat_statements, pg_stat_activity84% CPU, 160/160 pool connsbottleneck

The Postgres number is arithmetic, not a vibe. pg_stat_statements shows one statement at 1,400 calls/s with mean_exec_time 4.8 ms. 1,400 × 4.8 ms = 6.7 core-seconds of work per wall second; on an 8-vCPU box that is 84% CPU from a single query. EXPLAIN (ANALYZE, BUFFERS) shows a Seq Scan over a 12M-row table. Add the missing index: 0.3 ms mean → 1,400 × 0.3 ms = 0.42 core-seconds/s = 5% CPU. p99 falls back under 60 ms and the plateau moves.

Note what this rules out: the app tier sat at 35% CPU and looked like the obvious place to add pods. Twelve more pods would have added 12 × 20 more DB connections and made it worse.

Trade-offs.

  • Scale up vs scale out. Scale-up is a config change and helps a single-threaded or shared resource (one Postgres, one Redis). Scale-out needs statelessness and multiplies connections to whatever is shared. If 5% of the work is serialized, Amdahl caps you at 20× however many replicas you add.
  • Cache vs capacity. A cache removes read load but adds invalidation, cold-start, and stampede failure modes. It does nothing for a write-bound or unique-key-read bottleneck.
  • Fix the query vs add read replicas. Replicas scale reads, not writes, and add replication lag you now have to reason about.
  • Deciding rule: if the saturated resource is shared (primary DB, single leader, hot key), cut demand per request or scale that resource. If it is a stateless tier, scale out. If it is a lock or a hot partition, shard or restructure: more replicas won't help.

Failure modes and how you catch them.

  • Coordinated omission. A closed-loop generator backs off when the server stalls, so the stall never lands in the histogram. Use a constant-arrival-rate generator (k6 constant-arrival-rate, wrk2) and HdrHistogram-style recording.
  • Averages hide the tail. p50 14 ms with p99 210 ms is a queue, not a slow average. Read p99/p99.9.
  • Utilization lies. Redis is single-threaded: 40% CPU on one core with a hot key is saturated. iostat %util overstates saturation on NVMe because the device handles parallel I/O; use aqu-sz and per-device latency instead.
  • Retry amplification. A 5% error rate with 3 retries adds ~15% load to the already-saturated resource. Cap retries with a budget and jitter.
  • Downstream queueing. Your p99 is their p50 plus their queue wait. Break it out with per-span durations in OpenTelemetry rather than one end-to-end number.
  • Measuring below the knee. At 1,200 rps everything looks healthy. The bottleneck only exists past the inflection point, so the load test has to go there.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How would you identify whether a system's bottleneck is CPU-bound, I/O-bound, or network-bound, and why does the answer change what scaling approach helps?

Answer

First 90 seconds

Don't infer the bottleneck from the architecture: measure it. Use the USE method: for every resource (CPU, memory, disk, NIC) check utilization, saturation, and errors. The bottleneck is the resource whose saturation climbs first as you add load, not the one with the highest utilization. A disk at 100% %util with 0.1 ms service time is healthy; a disk at 55% %util with 40 ms await is the bottleneck.

State your assumptions: steady-state load, host-level telemetry available, one service per node or a homogeneous fleet.

Signals that separate the three

BoundSignal that decides itToolThreshold
CPUrun-queue length, not %usrvmstat 1 (r), mpstat -P ALL 1, runqlatr > vCPU count sustained; runqlat p99 in ms
I/Owait time vs device service timeiostat -x 1 (await, aqu-sz/avgqu-sz, %util)await ≫ service time; aqu-sz > 1
NetworkNIC utilization, retransmits, cwndsar -n DEV 1, ss -ti, netstat -sNIC > 70–80% of line rate; retrans > 0.1%

%iowait alone is a trap: it counts idle time with outstanding I/O, so an async or io_uring workload can be I/O-bound with %iowait near zero. %steal in mpstat means the hypervisor, not your code.

Why the mechanism decides the fix

CPU-bound means requests queue on the run queue: throughput is capped by cores × IPC, and latency grows once r exceeds core count because the scheduler time-slices. More cores help only to the extent the work parallelizes (Amdahl); if 30% is serial, 2× cores buys ~1.5×.

I/O-bound means threads sit in D state. Adding cores adds more threads blocked on the same device, which raises context-switch rate and memory pressure without raising throughput. The lever is in-flight I/O: async I/O, more connections, a faster device, or caching. Little's Law, L = λW: 1,200 rps × 210 ms ≈ 250 requests in flight; if most are blocked on disk, cores are irrelevant.

Network-bound means the NIC or the path saturates. More CPU doesn't add bandwidth; you reduce bytes or round trips (compression, HTTP/2 or gRPC multiplexing, connection reuse, smaller payloads) or buy bandwidth.

Worked trace

8 vCPU node, 1,200 rps, p99 210 ms. vmstat 1: r=14, %usr=38, %iowait=41. iostat -x nvme0n1: await=12.4 ms, aqu-sz=9.8, %util=97. Device service time is ~0.1 ms, so ~12 ms is queueing. Verdict: I/O-bound. Doubling cores moves p99 by single-digit ms; moving to async I/O or a device with 0.05 ms service time cuts the queue term roughly 10×.

Failure modes and detection

  • Misreading %iowait as "disk is fine" when the workload is async: check biolatency and aqu-sz instead.
  • Softirq/ksoftirqd burning CPU on packet processing looks CPU-bound but is network-bound: perf top shows ksoftirqd and __netif_receive_skb.
  • cgroup CPU throttling (cpu.stat nr_throttled) caps throughput below the node's capacity; scaling the node does nothing.
  • Noisy neighbours: %steal > 5% means the fix is a different instance class, not more cores.
  • Scaling the wrong dimension costs real money: doubling cores on an I/O-bound fleet raises the bill ~2× for a few percent of p99.

What to say about scaling

Vertical scaling helps CPU-bound work that parallelizes. I/O-bound work wants concurrency and faster storage, or caching to remove the I/O. Network-bound work wants fewer bytes and round trips, or more bandwidth. Confirm with a load test that ramps past target and watch which saturation signal moves first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How would you determine whether a system's bottleneck under load is the application code itself versus the infrastructure it's running on?

Answer

Assume you can reproduce the load and have request-level latency. The first cut is on-CPU vs off-CPU time. A thread that is runnable but not scheduled, or blocked on a lock, pool, or socket, is not executing application logic. A thread burning CPU inside your frames is. So the question becomes: where is the time, and does adding capacity change service time or only queueing delay?

  1. Pin the SLO and load. Example: 2,000 RPS, 200 concurrent, p99 SLO 40 ms, observed p99 180 ms. Without that, "bottleneck" is undefined.

  2. USE each resource. CPU: mpstat -P ALL 1, vmstat 1. Sustained run-queue length greater than vCPU count, or CPU steal above 5% in a VM, means CPU contention. Disk: iostat -x 1; %util near 100 with await much larger than the device's service time means storage saturation. Network: sar -n DEV 1 for drops and retransmits. Pools: HikariCP maximumPoolSize, active connections, and wait time.

  3. On-CPU profile. perf record -F 99 -g -p PID -- sleep 30, then a flame graph. JVM: async-profiler -e cpu. Go: go tool pprof. Python: py-spy. If leaf frames are your JSON encoder, regex, allocation, or lock code, that is application service time.

  4. Off-CPU profile. bpftrace offcputime, or async-profiler -e wall. If threads are blocked in futex, epoll_wait, recv, or pool wait, they are waiting. Exception: futex can be your own lock contention, which is application code.

  5. Differential test. Double capacity. If p99 falls roughly with queueing math, infra-bound. If p99 barely moves, code-bound.

SignalPoints to
Run queue > vCPU count sustained; CPU steal > 5%Infra/CPU contention
On-CPU flame graph leaves in your serialization, parsing, or algorithm framesApplication code
Off-CPU dominated by epoll_wait, recv, pool waitWaiting on dependency or infra
Off-CPU dominated by futexApplication lock contention
Disk %util ~100, await >> service timeStorage infra
p99 improves ~linearly when capacity doubledInfra-bound
p99 flat when capacity doubledCode-bound

Worked example, hypothetical: 8 vCPU, 200 concurrent, p99 180 ms. perf -F 99 shows 70% on-CPU in JSON encoding; run queue is 12. Double to 16 vCPU: p99 drops to 120 ms, still above the 40 ms SLO. The 70% on-CPU is service time; more CPUs reduce queueing but not service time. If instead off-CPU is 85% waiting on a DB pool with 90 ms pool wait, adding app CPUs does nothing; raise pool size or DB capacity.

Failure modes and detection:

  • Sampling profiler misses short CPU bursts. Use wall-clock profiling (async-profiler -e wall, py-spy --native) when latency is spiky.
  • iowait can be high while CPUs are idle; do not treat it alone as a disk bottleneck. Check iostat -x await and %util.
  • CPU steal in cloud VMs looks like slow code but perf shows no frames. Check %st in top/vmstat.
  • Lock contention appears off-CPU but is application code. Use perf lock or JVM thread dumps.
  • GC safepoints make JVM threads off-CPU. Check GC logs for pause time.
  • Coordinated omission in the load generator understates p99. Use a constant-rate generator and measure from intended send time.

Trade-offs: adding infrastructure is right when a shared resource is saturated, the app is already efficient, horizontal scaling is possible, and the dependency has headroom. Optimizing code is right when on-CPU frames are yours, lock contention is high, allocation churn is visible, or queries are N+1. Deciding criteria: if utilization is above 70-80%, queueing dominates and capacity helps; if service time itself is high, code helps. If p99 improves linearly with capacity, buy time; if it plateaus, fix the code.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Explain the relationship between Amdahl's Law and horizontal scaling: why adding more parallel workers eventually yields diminishing returns.

Answer

The 90-second answer. Amdahl's Law caps speedup by the serial fraction: S(n) = 1 / (s + (1−s)/n), so the ceiling is 1/s no matter how many workers you add. Horizontal scaling is that n. If 10% of a request's work must run one-at-a-time (a single-primary write, a global lock, a serialized token refresh) you can never beat 10×, and you hit most of the wall long before n gets large. The corollary that decides the interview: measure s before you buy servers. If 1/s is below your target speedup, more workers cannot get you there.

The arithmetic. A request with 100 ms of work, 10 ms of it serial (s = 0.1):

workers nspeedup S(n)latency
11.0×100 ms
43.1×32.5 ms
84.7×21.3 ms
166.4×15.6 ms
327.8×12.8 ms
∞10×10 ms

Doubling from 16 to 32 workers buys 2.8 ms. That is the diminishing return, and it is a property of the workload, not the fleet.

Why the real curve is worse than Amdahl. Amdahl assumes the serial fraction is fixed. In a service it usually isn't: it's a shared resource whose service time grows with load. Model the 10 ms serial step as one primary DB with service rate μ = 100 writes/s. At λ = 80 writes/s, ρ = 0.8 and the M/M/1 wait is 1/(μ−λ) = 1/20 = 50 ms. At λ = 95, it is 1/5 = 200 ms. The "serial" term went from 10 ms to 200 ms because you added workers. Amdahl understates the cliff; the Universal Scalability Law adds a coherency term that makes throughput actually fall past the knee.

What to do instead, and when.

  1. Shrink s. Batch the writes, make the serialized step async/fire-and-forget, replace a global lock with per-key locks. Cheapest and usually the biggest win: it moves the ceiling, not just the approach to it.
  2. Shard the serial resource. N primaries make the effective serial fraction s/N, but you pay cross-shard coordination and lose single-shard transactions. Worth it only when s is dominated by one hot key.
  3. Cache to cut λ. Removing read load from the shared resource moves you back down the queueing curve without touching s.
  4. Cap concurrency at the knee and shed. If you can't shrink s, protect the shared resource rather than adding workers to it.

Deciding criteria: if s > 1/target_speedup, fix s first. If the shared resource is already at ρ > 0.7, adding workers makes latency worse: shard or cache instead.

Failure modes, and how you see them.

  • Retry storm on the shared resource. Timeouts on the primary trigger retries, which raise λ on the already-saturated resource, driving ρ → 1 and latency → ∞. Detect with a retry counter and primary queue depth, not just error rate.
  • Connection pool exhaustion. A pool of 20 saturates and p99 goes from 40 ms to 180 ms while CPU looks idle. Detect with a pool wait-time metric; utilization alone hides it.
  • Coordinated omission. A closed-loop load generator waits for responses, so it never records the latency of requests queued during the stall: the cliff reads as a plateau. Detect by driving fixed-rate open-loop traffic and comparing achieved RPS against offered RPS.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

Explain why round-robin load balancing can perform poorly when backend servers have uneven processing times for different requests.

Answer

Round-robin assigns each new request to the next backend in a fixed rotation, ignoring how many requests that backend already holds. That is fine when every request costs about the same. It fails when service times vary: a backend that draws a slow request keeps its slot occupied, and round-robin keeps feeding it new work while the other backends sit idle. The queue that builds behind one slow request is the problem, not the slow request itself.

Mechanism. Each backend sees an M/G/1 queue: arrivals at rate λ, service time S with mean E[S] and second moment E[S²]. Mean wait is

E[W] = λ E[S²] / (2(1 − ρ)), ρ = λ E[S].

The E[S²] term is what punishes variance. With 4 backends at 40 rps total (10 rps each), 95% of requests at 20 ms and 5% at 500 ms: E[S] = 44 ms, E[S²] = 0.01288 s², ρ = 0.44, E[W] = 115 ms. 2.6× the mean service time. The average is already bad; the tail is worse.

Trace. 3 backends A, B, C, rotation A→B→C, one request every 10 ms, service times 20 ms except req3 at 200 ms.

t (ms)requestbackendservice (ms)done (ms)note
0req1A2020
10req2B2030
20req3C200220slow request
30req4A2050
40req5B2060
50req6C20240queued behind req3
60req7A2080
70req8B2090
80req9C20260queued behind req6
90req10A20110

A and B each idle 10 ms out of every 30 ms. C is busy continuously from t=20 to t=260. req6 arrived at t=50 and finished at t=240: 190 ms, 9.5× the normal 20 ms, for a request that itself needed only 20 ms. req9 waited 180 ms. The single 200 ms request cost the two requests behind it almost as much as it cost itself.

Detection. Per-backend p99 latency and in-flight count. If one backend's p99 is 5× the others and its in-flight count is more than 2× the mean, round-robin is the cause. Track max(in-flight)/mean(in-flight); with uneven service times it grows past 2 and stays there. CPU-based autoscaling will not fire, because the busy backend is often I/O-bound on the slow request, not CPU-bound: compare CPU against in-flight count to catch it.

Alternatives. Least-connections is better but not a fix by itself. Under HTTP/2 or gRPC one connection multiplexes many requests, so connection count stops tracking load. Envoy's LEAST_REQUEST with choice_count: 2 (power-of-two-choices) samples two backends at random and sends to the one with fewer in-flight requests; it needs no global state and captures most of the benefit. Nginx least_conn and HAProxy leastconn do the same at the connection level. When service times are homogeneous and ρ is low, round-robin is fine and cheaper.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How would you design a load balancer's health check to avoid both false positives (marking a healthy server unhealthy) and false negatives (missing a genuinely unhealthy server)?

Answer

Assume an L7 HTTP service behind a load balancer: 200 instances across 3 AZs, p99 latency 200 ms, SLO 99.9%. I’d run two health signals: a shallow readiness probe that gates traffic, and deep diagnostics that only alert. The gate must be cheap, fast, and biased against removing healthy instances; the deep checks catch the false negatives the gate misses.

Shallow readiness gate. Use an HTTP GET to /healthz that checks the process is alive and the event loop can serve. Example settings:

settingexamplewhy
interval2 sdetection vs probe load
timeout1 s5× p99, tolerates GC pauses under 1 s
unhealthy_threshold33 consecutive failures before removal
healthy_threshold22 consecutive successes before re-entry
jitter±200 msavoid synchronized probe storms
slow-start30 s rampavoid overwhelming a cold instance

With those numbers, a hard hang is detected in 5–7 s. Worst case: failure just after a successful check, then three timeouts at 2 s intervals plus 1 s timeout = 3×2+1 = 7 s. Best case: failure just before a check = (3−1)×2+1 = 5 s. A 1.5 s GC pause causes at most one timeout, not removal. That is the point of consecutive thresholds: a single packet loss, scheduler stall, or slow query does not flap the instance out of rotation.

Hysteresis and re-entry. After removal, require 2 successes 2 s apart, then ramp traffic over 30 s. Without hysteresis, a marginal instance oscillates: one success re-adds it, one failure removes it, and clients see a burst of 5xx. The healthy threshold plus slow-start makes re-entry deliberate.

Trade-off: shallow vs deep. A shallow check has low false positives but can miss a process that is deadlocked while the socket still accepts. A deep check (query the DB, cache, or a downstream) catches that, but couples fleet health to shared dependencies. If the DB blips, a deep check fails all 200 instances and the LB removes the whole fleet. Decide by asking: can a degraded instance still serve correct responses? If yes, keep it in rotation and shed load; if it returns wrong data, remove it. Run deep checks as metrics and alerts, not as the traffic gate.

Failure modes and detection.

  • False positive removal: timeout too tight. If p99 is 200 ms, 1 s is fine; if p99 spikes to 2 s under load, three consecutive timeouts remove healthy instances. Detect with false-removal rate: removals per hour where the instance recovers within 60 s without intervention. Target < 0.1% of instance-hours.
  • False negative: process deadlocked but TCP accept queue still works. Shallow check passes. Detect with passive outlier detection: if an instance returns 5xx or p99 > 3× fleet median over 30 s, eject it. That catches the deadlock without probing every instance deeply.
  • Probe saturation: 200 instances × 3 LB nodes × 1 probe/2 s = 300 probes/s. If each probe hits the DB, that is 300 QPS of extra load. Use jitter, a central prober, or cached dependency status.
  • Dependency failure: DB down, deep check fails all instances, LB removes all. Mitigation: never gate traffic on a shared dependency; use circuit breakers and keep the shallow gate independent.

Monitor time-to-detect (p99 from failure to removal) and time-to-recover (p99 from recovery to re-entry). Target detection < 10 s for hard failures, recovery < 30 s. Those two numbers, plus false-removal rate, tell you whether the thresholds are tuned for the workload or just copied from a default.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How does a CDN reduce load on an origin server, and what kind of content is it best suited for versus poorly suited for?

Answer

The 90-second answer

A CDN cuts origin load by putting a shared HTTP cache in front of it, in PoPs close to users, so requests terminate at the edge and the origin sees only the misses. The number that measures the offload is the edge hit ratio: at 95%, origin request volume and egress fall by 20x. That ratio, not the CDN itself, is what you tune.

It suits content that is the same for everyone and changes slowly or never: fingerprinted JS/CSS bundles, images, fonts, video segments, public GET responses with a shared body. It suits badly anything specific to one user or changing within seconds: logged-in dashboards, live prices, inventory counts. For those you either cache and risk serving the wrong user's bytes, or send Cache-Control: private, no-store and get no offload at all. Cacheability is a property of the response, not of the CDN.

Mechanism

Anycast or GeoDNS lands the client on the nearest PoP. The edge builds a cache key (by default scheme, host, path and query string, extended by any Vary header) and looks it up. Hit: served from the PoP, single-digit to low-tens of milliseconds for a small object, against 100-300 ms to an origin in another region. Miss: the edge fetches from origin, stores the body if the response allows it, and streams it back.

Response headers decide everything. Cache-Control: public, max-age=31536000, immutable on a fingerprinted asset is the ideal case: the URL changes when the bytes change, so the object never needs revalidation. s-maxage overrides max-age for shared caches, and stale-while-revalidate=60 lets the edge serve a 60-second-stale copy while refreshing in the background, which removes the latency spike at expiry. private, no-store keeps authenticated HTML out of the shared cache.

Revalidation has to be counted honestly: max-age=60 with an ETag means each PoP still sends a conditional GET to the origin once a minute per object, and a 304 saves the body but not the request. Long TTLs on versioned URLs beat short TTLs on mutable ones. Where many PoPs miss the same object, a shield tier (CloudFront Origin Shield, Cloudflare Tiered Cache) collapses those misses into one origin fetch.

Suited versus poorly suited

contentcache?why
fingerprinted bundle, app.4f3c1a.jsyes, max-age=31536000, immutableURL changes with the bytes, so it never revalidates
image, font, WebPyes, daysidentical for every user
HLS/DASH video segmentyes, long TTLimmutable bytes, and video usually dominates egress
public GET API responseyes, s-maxage=10-60only worth it when many users request the same body
logged-in HTML dashboardno, private, no-storeper-user body; Vary: Cookie would key on the whole cookie and drive the hit ratio to roughly zero
live price or inventoryno, or 1-2 s TTLstaleness costs more than the origin capacity it saves
POST, authenticated writenonot cacheable by definition
long-tail unique objectin theory yesone request per object; evicted before reuse, so it thrashes

Arithmetic

Take an origin at peak: 20,000 req/s, 40 KB average object, about 6.4 Gbps egress. At a 90% hit ratio the origin takes 2,000 req/s and 640 Mbps. Get to 95% with long TTLs and fingerprinted filenames and it takes 1,000 req/s and 320 Mbps. The last few points are the cheap capacity: 95% to 99% takes origin requests from 5% of traffic to 1%. Figures hypothetical but sized realistically; substitute your own object size and peak QPS.

Failure modes, and how you see them

  • Stampede at TTL expiry. Hundreds of PoPs miss a hot object at the same instant and origin QPS spikes in alignment with TTL boundaries. Detect by correlating origin request rate against TTL schedules; fix with stale-while-revalidate, request collapsing at the edge, and jittered TTLs.
  • Stale content after deploy. Purge propagation takes seconds to minutes and purge APIs are rate-limited. Detect by comparing the asset hash a canary fetches against the deployed manifest. Versioned filenames remove the need to purge.
  • Poisoning and leakage. Unkeyed inputs (host header, query parameters nobody normalised) let one user's response be served to another, and a per-user endpoint cached on URL alone leaks data. Detect by requesting the same URL from two sessions and diffing the bodies.
  • Origin dependency. With a 95% hit ratio the origin is sized for 5% of traffic, so a CDN misconfiguration or routing outage can hand it 10-20x its capacity within seconds. Detect by alerting on origin ingress QPS, not only on error rate.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Explain how auto-scaling based on CPU utilization can sometimes react too slowly to a sudden traffic spike, and what mitigation strategies address this.

Answer

The 90-second version. CPU is a lagging and clipped signal. It measures work already being done, not work arriving, and it saturates at 100%, so the autoscaler cannot tell 1.1× overload from 3× overload. On top of that, the detect-and-launch pipeline costs minutes. The fix is to scale on a demand signal (queue depth, concurrency, RPS per target), keep headroom or a warm pool, and shed load when the gap exceeds your estimate.

Why CPU lags. Requests arrive faster than the fleet can serve them, so they queue. Latency rises in the first second; CPU rises only as the queue drains into the workers. If the bottleneck is downstream (a saturated database connection pool, a lock, disk I/O) CPU can sit at 40% while p99 climbs, and a CPU-based policy never fires at all. And because utilization is bounded at 100%, the metric is clipped exactly when you need it most.

The pipeline, stage by stage.

  • Metric resolution. 1 minute for EC2 detailed monitoring and Auto Scaling group metrics; 5 minutes on basic monitoring.
  • Alarm. A target tracking policy's scale-out alarm defaults to 3 consecutive 1-minute datapoints, so it fires ~3 minutes after the breach.
  • Policy evaluation. Target tracking computes desired = ceil(current × currentMetric / target). At 100% CPU against a 60% target that is only 1.67× current capacity: the clipped metric caps how much it can add.
  • Launch and warm-up. 90 s for a JVM service, plus ALB health checks before it takes traffic.
  • Second scale-out. Blocked until the estimated instance warmup elapses (target tracking) or the cooldown expires (simple scaling, default 300 s).

Worked example (hypothetical figures). 10 m5.large instances, each serving 300 RPS at 60% CPU, target tracking at 60%. Traffic jumps 2,500 → 8,000 RPS in 30 seconds.

  • Fleet capacity at target: 10 × 300 = 3,000 RPS. At 100% CPU: 5,000 RPS.
  • Each instance now receives 800 RPS: 2.67× its target capacity, 1.6× its hard ceiling. The queue grows at 8,000 − 5,000 = 3,000 RPS.
  • Little's Law: at 5 s latency, 8,000 × 5 = 40,000 requests in flight.
  • T+3:00 the alarm fires. Target tracking asks for ceil(10 × 100/60) = 17 instances → 5,100 RPS at target, still short of 8,000.
  • T+4:30 the 7 new instances are in service. CPU is still pinned, but the policy will not act again until the warmup window passes.
  • p99 goes 200 ms → 5 s and 5xx climbs from 0.1% to 30% as queues overflow.

Detection. ALB TargetResponseTime p99 above SLO, HTTPCode_ELB_5XX_Count climbing, RequestCountPerTarget flat while UnHealthyHostCount rises, and app-side queue depth growing. If CPU is not the bottleneck you see the same latency and queue growth with CPU at 40%: scaling on CPU does nothing.

Mitigations.

MitigationMechanismCostWhen it's wrong
HeadroomRun at 40% average CPU instead of 60%: 2,500/200 = 13 instances instead of 10.~30% higher compute bill.Steady traffic, rare spikes, cost-sensitive.
Demand-signal scalingHPA on RPS-per-pod, or KEDA on SQS queue depth. HPA polls every 15 s and its scale-up stabilization window defaults to 0.Metrics pipeline and instrumentation; risk of scaling on noise.The metric is a poor proxy for load, or you lack the tooling.
Faster detectionPublish a high-resolution (10 s) custom metric and alarm on 1 datapoint: detection in ~10–20 s instead of 3 minutes.Custom-metric charges; more alarm churn.The metric is noisy: 1 datapoint flaps.
Warm poolPre-initialized instances. A running one joins in seconds; a stopped one must be started first, which adds tens of seconds.Full instance charges for running, EBS only for stopped.Traffic is so unpredictable the pool sits idle.
Predictive / scheduledScale before a known event (campaign, batch job).Forecasting effort; a wrong forecast wastes capacity or still spikes.Traffic is ad hoc or genuinely unpredictable.
Graceful degradationLoad shedding, circuit breakers, 503 with Retry-After.Dropped requests and lost revenue.Every request is equally important.

Putting it together. Scale on a demand signal and keep a small warm pool: that removes both the lag and the clipping. If you are stuck with CPU, run headroom, set EstimatedInstanceWarmup to the real warm-up time (it defaults to the group's cooldown, 300 s out of the box), and cut the alarm to fewer datapoints. Use predictive scaling for known events, and keep graceful degradation as the backstop for when the gap exceeds your estimate.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How would you decide between scaling a stateless application tier reactively (auto-scaling based on live metrics) versus proactively (scheduled scaling for known traffic patterns)?

Answer

What I'd say first

This isn't one decision for the tier: it's a decision per traffic component, and it comes down to whether the ramp rate is faster than the control loop's lag. If load is known and rises faster than you can provision, schedule it. If it's unknown, react, but budget the lag explicitly rather than hoping.

Assumptions: stateless tier behind an ALB, horizontal scaling, instances need warm-up before they serve at full speed, and there's a p99 latency SLO.

The reactive lag is a sum, not a single number

On EC2 Auto Scaling with CloudWatch:

stagetypical cost
metric publication60 s standard resolution; 10 s with high-resolution custom metrics
alarm confirmationM-of-N periods, e.g. 3 × 60 s = 180 s
policy cooldowntarget-tracking default 300 s between scale-out actions
instance launch + app warm-up30–60 s boot, more if JIT/cache warm-up
ALB health checkinterval × healthy threshold, e.g. 10 s × 3 = 30 s

Call it 4–8 minutes from demand onset to capacity actually serving. Compare that to your ramp: if traffic doubles in 90 seconds (a campaign email blast), reactive loses and you need scheduled or predictive capacity already running. If it doubles over 15 minutes (the normal daily curve), reactive keeps up and scheduled scaling is just a cost optimization.

Where each wins

Scheduled scaling (ASG scheduled actions, or predictive scaling in forecast-and-scale mode, which fits up to 14 days of history and forecasts 48 hours out) is right when the pattern repeats and the cost of idle capacity is less than the cost of being late. It also removes the human cron-drift problem.

Reactive is right for genuinely unknown load, and it's the safety net under the schedule. In Kubernetes the loop is much faster: HPA syncs every 15 s by default, with a 10% tolerance and a 300 s scale-down stabilization window, but only if node capacity exists; Cluster Autoscaler or Karpenter adds tens of seconds to minutes, so HPA alone doesn't save you on a full cluster.

Failure modes and how I'd catch them

  • Flapping: metric oscillates around the threshold, scale-out and scale-in alternate. Detect by counting scaling activities per hour; fix with a wider tolerance, a longer stabilization window, or step scaling with asymmetric out/in thresholds.
  • Scale-down thrash: a dip removes capacity, demand returns, cold instances again. Detect p99 spikes correlated with scale-in events; fix with the scale-down stabilization window (HPA default 300 s) or an ASG scale-in cooldown.
  • Cold start: new instances serve slow first requests. Detect first-N-requests latency per instance; fix with EC2 warm pools, readiness gates, or ALB slow start (30–900 s, default 30).
  • Wrong metric: CPU is a lagging proxy. For request-driven tiers, ALB RequestCountPerTarget tracks the actual bottleneck better.

A concrete HPA behavior block:

YAML
behavior:
  scaleUp:
    stabilizationWindowSeconds: 0
    policies: [{type: Percent, value: 100, periodSeconds: 15}]
  scaleDown:
    stabilizationWindowSeconds: 300
    policies: [{type: Pods, value: 2, periodSeconds: 60}]

That's fast out, slow in: the asymmetry that stops thrash.

How I'd validate

Load test with a ramp shaped like the real curve, measure time-to-capacity against the lag budget above, and confirm scale-in doesn't break the SLO. Then alarm on capacity-vs-forecast divergence so a scheduled action that silently stops firing is visible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Why is capacity planning based on peak load (not average load) essential for systems with highly variable traffic patterns, like e-commerce during a holiday sale?

Answer

The 90-second answer

Assume a service whose traffic is spiky but whose capacity is fixed or slowly elastic. Provisioning to the average is wrong for two reasons: the relationship between load and latency is not linear, it goes hyperbolic as you approach saturation, and capacity arrives minutes after demand does. So you size for peak, add headroom, and make the system degrade predictably above that.

Why averages fail: the queue is the mechanism

A server is a queue. For a single-server queue, response time W = 1/(μ − λ), where μ is service rate and λ is arrival rate, and utilization ρ = λ/μ. So W = (1/μ)/(1 − ρ):

ρW, in units of service time
0.52
0.85
0.910
0.9520

Going from 45% to 90% utilization multiplies queueing delay by ten. That is the whole answer to "why peak": the last 10% of capacity is where all the latency lives, and average-based provisioning parks you in that region every time traffic spikes.

Worked example

Checkout service. Average 200 rps; Black Friday peak 1,200 rps (6×). Each request holds a DB connection for 20 ms.

  • Peak concurrency by Little's Law: L = λW = 1,200 × 0.02 = 24 connections.
  • A pool sized for average (200 × 0.02 = 4) plus slack, say the HikariCP default maximumPoolSize of 10, gives a service rate of 10 / 0.02 = 500 rps.
  • Arrivals of 1,200 rps against 500 rps of service: the backlog grows at 700 rps. With connectionTimeout at its 30 s default, the pool completes 500 × 30 = 15,000 requests in that window, so anything landing more than ~15,000 deep in the queue fails outright.

The pool does not slow down gracefully; it converts a traffic spike into a hard error cliff.

Overload does not end when the spike does

Sustained 10% overload for 10 minutes at 1,000 rps of capacity builds a 60,000-request backlog (0.1 × 1,000 × 600). Draining it at the 100 rps of spare capacity takes another 600 seconds. A 10-minute spike costs 20 minutes of degraded service, and if clients retry, the backlog grows faster than it drains.

Autoscaling does not save you

EC2 Auto Scaling's default cooldown is 300 s, and a JVM service needs 60–120 s to warm (JIT, pool fill, cache). A sale that doubles traffic in 90 seconds outruns the scaler by minutes. Elasticity handles sustained shifts, not the leading edge of a spike.

Failure modes and how you see them

  • Pool exhaustion: activeConnections pinned at max with threadsAwaitingConnection > 0, then 30 s timeouts. Alert on the gauge, not the error rate.
  • Cache stampede: a hot key expires under peak and N concurrent misses hit the DB. Detect a cache-miss-rate spike correlated with a DB QPS spike; mitigate with jittered TTLs and single-flight.
  • Downstream throttling: the payment provider returns 429s and your retries multiply the load. Cap retries with a budget and circuit-break.
  • Zone loss: with peak spread across 3 AZs, losing one leaves 2/3. Size so that (N−1)/N of peak still meets the SLO.

What to actually do

Size for peak × 1.3–1.5 headroom, verify by ramping production-shaped traffic past target and confirming shedding and recovery, and keep a load-shedding path (admission control, queue-based leveling) for traffic above that. The idle capacity you pay for in March is the premium on not failing in November.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you use a load test to validate a capacity plan before a known high-traffic event, and what specifically would you look for in the results?

Answer

What I'd say first

Assume the event is a known spike, a launch or flash sale, with a target of 5,000 rps at p99 ≤ 200 ms, and that we have both a staging environment and a production canary path. The load test's job isn't to prove the system survives; it's to find the knee and name the resource that bends first, with enough headroom that losing a zone still leaves us under target.

Pick the venue by what you're actually afraid of

venuereproducescan't reproducecost
staging mirroryour code path, config, autoscalingprod data volume, cache warmth, third-party latency, noisy neighboursa full duplicate environment
production shadow (Envoy request_mirror_policies, GoReplay, AWS Traffic Mirroring)real request mix and payload distributionwrite paths (must be suppressed); doubles load on shared dependencies~2× dependency load
canary under real trafficeverything, including interactions you didn't modelsafe only with load shedding and a rehearsed kill switchreal user risk

If the unknown is a dependency you can't reproduce (a third-party API, a 2 TB table) shadow it. If it's your own code path, staging. If it's the traffic mix itself, canary a small percentage behind a kill switch.

Drive it open-loop, or the numbers lie

Closed-loop generators (a fixed VU pool) stop sending when the server stalls, so latency looks flat right up to the cliff: coordinated omission. Use an arrival-rate executor so offered load stays constant:

JavaScript
// k6 v0.49+
export const options = {
  scenarios: {
    ramp: {
      executor: 'ramping-arrival-rate',
      startRate: 1000, timeUnit: '1s',
      preAllocatedVUs: 2000, maxVUs: 6000,
      stages: [
        { target: 5000,  duration: '5m' },  // 1.0x target
        { target: 7500,  duration: '5m' },  // 1.5x
        { target: 10000, duration: '5m' },  // 2.0x
      ],
    },
  },
};

Size the generator with Little's Law. At target: 5,000 rps × 0.12 s mean = 600 in flight. At 2× with mean latency drifting to 0.9 s: 10,000 × 0.9 = 9,000 in flight. Pre-allocate VUs for the worst case, not the target, or the generator becomes the bottleneck.

What the results should look like

Hypothetical run, 3 app instances, HikariCP maxPoolSize=20 per instance, Postgres max_connections=100:

offeredp50p99app CPUpool pendingverdict
5,000 rps22 ms90 ms55%0target met
7,500 rps31 ms140 ms72%0still linear
9,000 rps180 ms900 ms88%340knee: pool saturated

The knee sits near 8,000 rps, so headroom is 1.6×. That is not enough for a zone loss: dropping one of three instances leaves ~5,300 rps, barely above target. Either add instances or raise the pool.

Failure modes and how you'd catch them

  • Coordinated omission: generator reports dropped_iterations > 0, or its own CPU exceeds 70%. Results are void; re-run with more VUs.
  • Staging isn't prod: run a 10-minute 1× baseline in both and compare p50/p99. A gap over 10% invalidates the comparison.
  • Cold cache: flush Redis, restart the app, re-run. Cold p99 is routinely 3-5× warm; if the event follows a deploy, that's the number that matters.
  • Pool exhaustion: hikaricp_connections_pending > 0 sustained, or pg_stat_activity near max_connections. The signature is p99 diverging from p50 while CPU is still under 90%.
  • GC, if p99.9 is more than 5× p99, read the GC logs before blaming the database.

What I'd do with the answer

Ramp past target until something bends, name that resource, then re-run with the required zone or node removed. If the system can't hold target with one zone down, you don't have a capacity plan: you have a hope.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Explain why a system's overall availability can be lower than any individual component's availability, when multiple components are chained together sequentially.

Answer

The 90-second answer

If every component on a request path is mandatory, the request succeeds only when all of them succeed. Measured over the same window, with independent failures, path availability is the product of the component availabilities. Four components at 99.9% each give 0.999^4 = 0.9960, i.e. 99.6%: worse than any one of them. The intuition is that unavailability adds, not availability: for small failure rates, 1 − Π(1 − u_i) ≈ Σ u_i, so four components each unavailable 0.1% of the time produce roughly 0.4% path unavailability.

That is the whole mechanism. Everything else is about when the product is wrong.

Where the arithmetic comes from

Availability is usually MTBF/(MTBF+MTTR). A component with 30 days between failures and 30 minutes to recover is 43,200/(43,200+30) = 0.99931. Chain five of those and you get 0.99931^5 = 0.9965: 99.65%, roughly 3 hours of downtime a year instead of 36 minutes.

components in serieseach at 99.9%each at 99.99%
199.90%99.99%
499.60%99.96%
1099.00%99.90%
2098.02%99.80%

Note the asymmetry: adding a ninth-nine component to a chain already at 99.6% buys almost nothing, because each component contributes its own unavailability additively. The weakest link sets the marginal cost.

When the product is wrong

Two directions.

Optimistic: independence is the big assumption. Components sharing an AZ, a control plane, a DNS resolver, a deploy pipeline, or a config push fail together. The true joint failure probability is then higher than the product, so the product is a floor on optimism, not a bound. Measure joint failures, not per-component ones.

Pessimistic: not every component is strictly serial. A cache hit skips the database; a fallback returns stale data; a circuit breaker sheds a non-critical enrichment; a retry converts a transient failure into a success. Each of those removes an edge from the serial path, and the product over the remaining mandatory edges is what actually applies.

Failure modes and how to see them

  • Retry storms: a dependency at 99% with clients retrying 3 times turns 1% errors into roughly 3% load amplification, which can push the dependency past its own capacity and cascade.
  • Thread or connection pool exhaustion: a slow dependency holds caller threads; once the pool fills, the caller fails requests that never touch the slow dependency. Availability collapses for unrelated traffic.
  • Health checks that test the process, not the dependency: the component reports healthy while every request fails.
  • Availability laundering: a service that returns 500 in 2 ms when its database is down reports high availability by its own metric while being 0% available to callers. Measure at the caller's boundary.

Detection: synthetic canaries at the edge, SLO burn-rate alerts on the user-facing path, and a dependency graph that attributes errors per edge. Compare the predicted product against measured path availability; a persistent gap means correlation, or a non-serial edge you have not accounted for.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Why does over-provisioning capacity beyond the historically observed peak matter for resilience, using a partial-failure scenario as an example?

Answer

What a strong candidate says first

Sizing to the historical peak means the fleet has exactly zero margin for the failure domain it runs in. Resilience is not "some spare capacity": it is the arithmetic of peak load ÷ (1 − fraction of capacity a single failure removes). Run three AZs and lose one, and you lose a third of your capacity, so you need 1.5× peak, not 1.0×. Run N+1 instance redundancy and you need peak × (N+1)/N.

Worked example (hypothetical figures)

A stateless API tier. Observed peak 3,000 rps. Each instance sustains 400 rps at p99 = 150 ms with CPU at 60%. That's 7.5 instances, so you run 8: 3,200 rps of capacity, 6.25% above peak.

Lose one instance to a rolling deploy: 7 × 400 = 2,800 rps. Deficit 200 rps.

Little's law: at 3,000 rps and 150 ms service time, 450 requests are in flight. Once the tier saturates, service time climbs, say to 400 ms, so in-flight demand becomes 3,000 × 0.4 = 1,200. The queue grows at 200 rps, so it fills 1,200 slots in about 6 seconds. p99 crosses the 500 ms SLO shortly after, and the load balancer's health checks start failing on the slow instances, removing them too. A one-instance deploy becomes a full outage.

With 12 instances (4,800 rps, 1.6× peak) the same deploy leaves 11 × 400 = 4,400 rps against 3,000 rps of demand: 47% headroom, no queue growth, no incident.

Production lens

checkworked application
workload3,000 rps peak, 450 concurrent, ~2 KB JSON payloads, SLO p99 < 500 ms
constraintCPU at 60% per instance at 400 rps; saturation shows as p99 150 ms → 400 ms and rising queue depth
failure modeRecompute after losing one AZ: 2/3 × 4,800 = 3,200 rps vs 3,000 rps demand. 6.7% margin, not enough
validationRamp to 3,600 rps in staging with one instance killed; confirm p99 stays under 500 ms and the ASG replaces the instance within 90 s

Failure modes and how you see them

  • Retry amplification. Clients retry 3× on timeout. Detection: compare total request rate to unique-request rate; a gap means retries are inflating load.
  • Hot-spotting. Least-connections LB plus one slow instance concentrates traffic. Detection: per-instance CPU and p99 divergence across the fleet.
  • Autoscaler lag. Scale-out takes 90–180 s (boot + warmup). Detection: scaling activity timestamps against the traffic curve, if the traffic peak is shorter than the boot time, autoscaling never helps.
  • Zone loss. Detection: capacity math per AZ, not per fleet. A fleet that survives one instance loss can still die on one AZ loss.

Trade-offs

Headroom costs money. 12 instances instead of 8 at $0.10/instance-hour is $876/mo vs $584/mo: about $292/mo, or 50% more, for the buffer. Cheap against an outage, but not free, and the wrong tool when:

  • Traffic is spiky and short (a batch job, a marketing blast). Queueing or shedding with a 429 and a Retry-After is cheaper than paying for peak 24/7.
  • The workload is elastic and the SLO tolerates degradation. Autoscaling plus a queue absorbs drift; it just can't absorb an instantaneous loss.
  • The bottleneck is a shared dependency (a database, a third-party API). Adding app instances doesn't add database capacity: you need read replicas, connection pooling, or a cache.

The rule: size headroom to the failure domain, not to the peak. N+1 for instances, N+1 per AZ for zones, and know which one your SLO actually requires.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you use rate limiting to protect a system from being overwhelmed, and what's the tradeoff of setting the limit too conservatively versus too permissively?

Answer

Core answer.

Set the limit from the measured knee of your latency-vs-load curve, enforce it at the edge, key it per identity (API key, IP, tenant), and answer 429 with a Retry-After rather than 503. Load test until p99 starts climbing faster than load; take that throughput and set the sustained limit at roughly 70-80% of it, with a burst bucket sized for the spikes real clients actually send.

Too conservative: you reject work the system would have served. A service holding p99 at 100 ms to 4,000 rps but capped at 500 rps declines 87% of tested capacity, and every rejected client retries, which adds load instead of removing it. Too permissive: you find the collapse point in production, and the cost there is not linear - the last 5% of utilization costs about 4x the latency, because latency consumes the concurrency pool, which cuts throughput, which invites more retries.

Mechanism: the token bucket.

Two parameters: capacity C (largest burst) and refill rate r (sustained rate). Each request takes one token; an empty bucket means reject or queue.

Trace C = 20 tokens, r = 10 tokens/s, offered load 20 requests at t=0 then 20 requests per second for 2 seconds:

  • t=0: bucket is full at 20, the 20 arrivals take 20 tokens, all 20 served, bucket now 0.
  • Each following second: 20 arrive, refill adds 10. So 10 served, 10 rejected with 429.

60 requests offered, 40 served. Steady-state throughput is exactly r = 10/s; the capacity only paid for the first 20.

nginx is this bucket:

limit_req_zone $binary_remote_addr zone=perip:10m rate=100r/s;
limit_req zone=perip burst=200 nodelay;
limit_req_status 429;

nodelay serves the burst immediately instead of delaying it to hold the rate - drop it and nginx queues and paces instead. nginx defaults limit_req_status to 503; override it to 429 so CDNs and clients classify the response as throttling. One 10m zone holds roughly 16,000 addresses by nginx's own sizing.

Alternatives.

Fixed-window counters keep one integer per key and allow 2x the limit across a boundary: 100 requests at 00:59 plus 100 at 01:00 both pass a 100/minute window. A sliding-window log is exact but stores one timestamp per request in the window. Sliding-window counters and GCRA approximate the same shape with O(1) state per key, which is what most gateways ship.

When request cost varies, a request rate is the wrong knob: a /search fanning out to 50 shards is not one /health. A concurrency limit tracks the saturated resource directly: 200 workers at 50 ms service time cap at 200 / 0.05 = 4,000 rps, and if contention pushes service time to 500 ms the same pool does 200 / 0.5 = 400 rps.

Why a permissive limit is not a linear cost.

For a single-server queue at utilization rho = arrival rate / service rate, mean time in system = service time / (1 - rho):

rhomean time in system
0.52x service time
0.85x
0.910x
0.9520x
0.99100x

Moving from 80% to 95% utilization quadruples latency. More servers flatten that curve but not its shape.

Failure modes and detection.

  • Per-node limits multiply: 20 pods at 100 rps each is 2,000 rps reaching the database. With a shared Redis counter, the failure policy is the design decision - fail-open gives no protection during exactly the incident you built it for, fail-closed turns a Redis blip into an outage. Local buckets refilled from the central store every few seconds over-admit by at most the refill interval.
  • Retry storms: a 429 with no Retry-After or jitter tells well-behaved clients to retry immediately. Send Retry-After (RFC 9110) and back off with jitter.
  • Health checks: load balancer probes come from a handful of IPs and will drain an IP-keyed bucket. Exempt the health path or key it separately.
  • Alert on the throttle ratio (429s / total), not just error rate. 0.1% throttled is a healthy limit; 30% means under-provisioned or under attack, and those two runbooks differ.

What would change the decision. Nightly batch traffic wants a large bucket with a low refill rate; steady traffic wants a concurrency limit. Size against degraded capacity, not healthy capacity: lose one of three zones and a limit set at 80% of the healthy knee becomes 120% of what is left.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Explain graceful degradation with a concrete example of a feature you'd disable under heavy load to keep a system's core functionality responsive.

Answer

The answer

Graceful degradation is a pre-decided priority order plus an automatic trigger: when a shared resource saturates, the system stops doing the optional work so the load-bearing work keeps its latency SLO. It is not "the site gets slow for everyone"; it is "the site stays fast and one widget goes empty."

Assumptions I'd state up front: single region, the product detail page is the revenue path, and the recommendations call is a synchronous fan-out from that page rather than something precomputed offline.

Concrete case: "customers who bought this also bought" on the product page. It calls a recs service that does an approximate nearest-neighbour lookup over ~10M product embeddings plus a co-purchase graph traversal. It is the most expensive call on the page and the least important. Under overload I cap its in-flight concurrency and give it an 80 ms deadline; when the cap is full the handler returns an empty list and the page renders without the widget. Search, cart and checkout never see the shed.

Why recs is the right thing to shed

The product page handler fans out to catalog (product + price + inventory, ~12 ms CPU) and recs (~15 ms CPU per call). Recs is the only one whose cost scales with catalog size rather than with the request, and the only one whose absence doesn't stop a purchase.

Illustrative capacity: 40 product-page pods at 200 rps each = 8,000 rps. The recs service has 20 pods × 4 workers = 80 concurrent slots, each search 15 ms, so its ceiling is 80 / 0.015 ≈ 5,300 rps. At 8,000 rps of page traffic, recs demand is 8,000 rps: 1.5× its ceiling. Its queue grows, p99 goes from ~120 ms to seconds, and because the page handler blocks on that call, product-page p99 goes from ~90 ms to over 1 s. Checkout conversion falls with it.

The shed, in code

Go
var recsSem = make(chan struct{}, 50) // 50 in-flight recs calls, max

func Recommendations(ctx context.Context, sku string) []Item {
    select {
    case recsSem <- struct{}{}:
        defer func() { <-recsSem }()
    default:
        recsShedTotal.Inc() // no slot: shed now, don't queue
        return nil
    }
    ctx, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
    defer cancel()
    items, err := recsClient.Fetch(ctx, sku)
    if err != nil {
        recsShedTotal.Inc()
        return nil
    }
    return items
}

Trace at 8,000 rps: 50 slots held ~15 ms each admit 50 / 0.015 ≈ 3,300 rps. The remaining ~4,700 rps take the default branch and return nil in about a microsecond. Recs now sees 3,300 rps against a 5,300 rps ceiling, so it never queues and its p99 stays ~120 ms; the page handler's worst case is the 80 ms deadline, so product-page p99 stays near 90 ms. The widget is empty for ~59% of page views: a visible but bounded loss.

Alternatives, and when they win

  • Cache the widget (Redis, 5-minute TTL). At an 85% hit rate recs load drops to 1,200 rps and you may never need to shed. Costs staleness: fine for "also bought", wrong for price or inventory.
  • Precompute offline into the catalog row. Removes the runtime call entirely, but only if the recommendation doesn't depend on session or real-time signals.
  • Scale recs out. Correct if the spike is sustained and the feature earns its cost: shedding is for the 10-minute spike, not permanent 3× growth.

Deciding criterion: can the feature's output be stale? If yes, cache. If no and it's off the revenue path, shed it.

Failure modes

  • Fallback is expensive. If "no recommendations" means "query the DB for popular items", you've moved load onto the database you were protecting. The fallback must be static or already in memory.
  • Silent degradation. Empty widget, no signal. Emit recs_shed_total and alert when the shed rate exceeds 5% for 5 minutes; otherwise you learn about it from a support ticket.
  • Breaker flapping. An error-rate trigger oscillates. Use a concurrency cap plus hysteresis: open at 90% saturation, probe with 5% of traffic every 30 s, close only after 60 s below 50%.
  • Thundering herd on recovery. When the cap lifts, all 8,000 rps return at once. Ramp the semaphore back over 60 s.
  • Shedding the wrong thing. If the same recs call also powers cart cross-sell, disabling it costs revenue. Tier per call site, not per service.

What would change the decision: if recs turns out to drive a measurable share of add-to-cart, it moves into the core tier and the answer becomes caching plus capacity, not shedding.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Why might a system choose to shed load (deliberately reject some requests) during an overload event rather than trying to serve every request slowly?

Answer

The 90-second answer. Assume a synchronous, user-facing service with a fixed concurrency budget (a thread pool, a connection pool, or an in-flight request cap) and one saturated downstream. The real choice under overload is not "serve everyone" versus "serve no one"; it is whether the system degrades uniformly or selectively. Uniform degradation loses, because queueing latency is convex in utilization: an M/M/1 queue at 90% utilization waits 9× its service time, and at 99% it waits 99×. Past that knee, adding load subtracts throughput. Shedding a fraction of requests at the edge keeps the admitted fraction inside the knee, so those requests get normal latency, and the rejected fraction gets a fast, honest failure it can retry.

Why throughput collapses. Little's Law, L = λW, with L pinned by the concurrency limit. A pool of 200 workers serving 20 ms requests does 200 / 0.02 = 10,000 rps. Let queueing push latency to 2 s and the same pool does 200 / 2 = 100 rps: a 100× throughput loss on identical hardware. That is congestion collapse, and it is why "just serve everything slowly" is not a neutral option.

Retries amplify the load. If clients time out at 1 s and retry twice, a 30% timeout rate turns 1.0× offered load into 1 + 0.3×2 = 1.6×. Shedding with a fast 503 plus a Retry-After header (RFC 9110) turns a 1 s timeout into a ~1 ms rejection, so the client backs off instead of holding a connection open.

What shedding looks like. Reject at the cheapest point that knows the request's cost: an edge rate limiter, a token bucket, or a concurrency limiter. Envoy's retry_budget caps retries at a percentage of active requests (20% by default, with a floor of 3 concurrent retries), which stops retry amplification at the mesh before it reaches the service. Google's SRE practice assigns request criticality (CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS, SHEDDABLE) and sheds from the bottom up.

Request classExamplePolicy under overload
CRITICAL_PLUScheckout submit, payment capturenever shed; shed others first
CRITICALproduct page, searchshed last; may serve stale cache
SHEDDABLE_PLUSrecommendations, personalizationshed at ~80% of the concurrency limit
SHEDDABLEanalytics beacons, prefetchshed first, 503 immediately

When uniform degradation is the right call. Homogeneous batch work with no retry path and no user waiting; or when a slow answer is strictly better than an error, such as a 3 s page load for a user who will not retry. Also when the request is already committed: a payment in flight cannot be un-accepted. The deciding criteria are the cost of a rejected request versus a slow one, whether the client can retry, the request's criticality, and whether the SLO is p99 latency or availability.

How shedding misfires. Putting /healthz behind the same limiter makes the load balancer mark the instance unhealthy, remove it, and push its share onto the survivors: a self-inflicted cascade; exempt health and readiness paths. Shedding on arrival order rather than cost drops 1 ms cache hits while admitting 500 ms misses, which lowers goodput. And rejected clients retry together on recovery, so pair shedding with jittered exponential backoff and a Retry-After value. Shedding below the knee, say at 50% utilization, burns error budget for nothing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you implement backpressure in a system where a fast producer service is overwhelming a slower downstream consumer?

Answer

Clarify first, because it decides the mechanism: is the producer's output replayable, and can the consumer dedupe? If yes, overload becomes a block plus a durable buffer. If it is fire-and-forget telemetry, overload becomes a counted drop. Either way, the invariant is the same: no unbounded buffer sits between mismatched rates.

Recommendation, same-JVM case (producer submits units of work): a bounded queue with a caller-runs rejection policy.

Java
// Java 17
var queue = new ArrayBlockingQueue<Runnable>(200);   // capacity is mandatory here
var pool  = new ThreadPoolExecutor(8, 8, 0L, TimeUnit.MILLISECONDS, queue,
                                   new ThreadPoolExecutor.CallerRunsPolicy());

ArrayBlockingQueue forces you to name a capacity. LinkedBlockingQueue() does not: its default capacity is Integer.MAX_VALUE, the unbounded buffer you are trying to avoid, and Executors.newFixedThreadPool uses exactly that.

Why caller-runs is the backpressure: once all 200 slots are occupied, the submitting thread executes the task inline, so it physically cannot enqueue faster than the consumer drains. The stock handler is AbortPolicy, which throws RejectedExecutionException: correct only if the producer already owns retry logic. Caller-runs instead converts overload into latency on the producer thread, which is the pause the consumer needs.

Size the bound, don't guess it. Little's Law: in-flight = arrival rate * wait. The consumer sustains 200 msg/s and the queue-wait SLO is 1 s, so the bound is 200 messages, not 10,000.

The arithmetic that shows why: a 10,000-slot queue at 1 KB per message holds 10 MB, and with a producer at 5,000 msg/s it fills in 10,000 / (5,000 - 200) = about 2.1 s. Past that, queue wait is depth / 200: 50 s at full depth. Bound at 200 in-flight instead: queue wait caps at 1 s and everything above that arrives as a rejection you can count and alert on.

Across the network you rarely build this. HTTP/2 flow control blocks the producer at the socket until the consumer sends WINDOW_UPDATE, with the per-stream window defaulting to 65,535 bytes (RFC 9113 section 6.9.2); gRPC widens it dynamically via BDP estimation. Above the transport, reactive streams (java.util.concurrent.Flow, Java 9+) inverts control: the subscriber calls subscription.request(64), processes that batch, then requests 64 more, so in-flight never exceeds the prefetch. Choose prefetch so that prefetch / throughput >= RTT, or the window itself becomes the throughput ceiling.

mechanismwhat it boundswrong when
bounded queue + CallerRunsPolicyin-process in-flightthe submitting thread is a Netty or Reactor event loop: unrelated connections stall
pull-based demand, request(n)in-flight end to endthe protocol is push-only; demand has to be enforced at the transport window instead
durable log (Kafka)nothing, but decouples the ratesconsumer lag outlives retention and offsets stop advancing
explicit shed: 429 + Retry-Afterin-flight at the edgeclients retry without jitter and produce a retry storm

Failure modes and how to see them. Caller-runs on an event loop shows up as p99 submit latency climbing while the rejection count is still 0 and queue depth is pinned at capacity: fix with a dedicated bounded executor per downstream or Semaphore.tryAcquire(timeout). A Kafka consumer whose poll loop is slowed past max.poll.interval.ms (default 300,000 ms) is evicted and the group rebalances, replaying from the last committed offset; max.poll.records (default 500) is the knob: watch rebalance rate and poll duration. Cyclic backpressure is a liveness deadlock, not a throughput problem: A blocks on B's full queue while B blocks on A's, visible as a cycle in a thread dump. And a drop with no counter is invisible: work disappears and nothing pages.

Bound at the narrowest point just upstream of the slow consumer, derive the number rather than picking it, expose queue depth and reject count as your two signals, and decide block-versus-429 before the incident. Backpressure bounds damage; it does not add capacity. If offered load is permanently 25x the consumer, the fix is more consumer partitions or admission control at the edge, not a bigger queue.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How would you use a combination of vertical and horizontal scaling pragmatically, rather than treating them as mutually exclusive choices?

Answer

I'd treat vertical scaling as the default first move for any single node, and horizontal as the default for the tier as a whole. Concretely: pick the largest node size that still sits on the flat part of the price/performance curve, then replicate that node until one node's failure leaves headroom.

Assume a stateless API tier, p99 SLO 200 ms, peak 12k rps, three AZs. The mechanism that makes this work is per-node fixed cost. Every node carries an OS, a sidecar, a connection pool, health-check and gossip streams, and a heap that GC has to walk. Doubling node count doubles all of that. A 32 vCPU node with 128 GB RAM holds a 40 GB working set in page cache; eight 4 vCPU nodes each hold 5 GB and miss more. Same cores, different cache hit ratio.

Here's the arithmetic. 64 × 4 vCPU = 256 vCPU across 64 nodes. 8 × 32 vCPU = 256 vCPU across 8 nodes. Same cores. But 64 nodes means 64 health-check streams to the load balancer, 64 connection pools at 20 connections each = 1,280 DB connections versus 160, and 64 × ~1 GB of OS/sidecar overhead = 64 GB versus 8 GB.

The vertical ceiling isn't "the biggest instance exists." It's "the biggest instance whose pause and cost still fit." Price per vCPU on cloud generally rises above ~32–64 vCPU per instance, memory bandwidth per core drops, and GC pause grows with heap: a 64 GB heap under G1 can pause 200–500 ms, blowing a 200 ms SLO.

Hypothetical figures for the knee:

node vCPU$/hrrps at p99<200ms$/M rps
40.179000.19
160.604,2000.14
321.108,0000.14
642.6011,0000.24

32 vCPU is the knee. Pick it. Peak 12k rps → 2 nodes at 8k each = 16k, but N+1 per AZ means 3 nodes = 24k capacity, 50% headroom. Had you picked 4 vCPU nodes you'd need 14 for peak, 21 for N+1, and pay 0.19 $/M rps plus 21× the coordination.

Stateful tiers flip the order. Vertical first for the primary: a 64 vCPU / 512 GB box holds a 300 GB working set, avoiding cross-shard joins. Horizontal only when write throughput exceeds one box's fsync/IOPS ceiling, and then sharding is a one-way door. Resharding a 2 TB shard takes hours and a dual-write migration.

When the blend is wrong: if per-request state is tiny and the workload is embarrassingly parallel (image resize, stateless fan-out), go horizontal from the start. Vertical just buys a bigger bill. If the workload is a single-writer ledger with strong consistency, vertical is the only lever until you shard, and you should exhaust it.

Failure modes, with detection:

  • Vertical hides leaks. A node growing 50 MB/hr RSS looks fine until the box is big enough to hold three days of leak. Detect: RSS slope per node, alert above 10 MB/hr.
  • Horizontal hides hot shards. One shard at 5× median QPS. Detect: per-shard QPS skew, alert above 2× median.
  • The blend hides coordination. Gossip/consensus latency grows with node count. Detect: p99 of the membership protocol and connection count per node.

What would change the decision: tighten the SLO to 50 ms and the 32 vCPU GC pause may not fit. Drop to 16 vCPU nodes and double the count. Make spot instances 70% cheaper and horizontal wins despite the coordination tax.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How would you design a system to gracefully handle a sudden 10x traffic spike without any advance warning, combining several of the techniques discussed?

Answer

Clarify, then assume. Before picking techniques I'd ask three things: is the spike read or write, is the payload cacheable, and what SLO am I defending? Assume a read-heavy public catalog API, p99 target 200 ms, steady state 18k rps across 12 instances, and the spike is 10x, 180k rps, arriving inside a minute with no warning. (These figures are a worked example, not measurements from a specific system.)

The answer: four layers, each sized against a number.

LayerConcrete settingWhat it absorbs
Edge cacheCache-Control: public, max-age=60, stale-while-revalidate=300, stale-if-error=60085–92% of GETs never reach origin
Auto-scalingHPA on CPU target 60%, 15 s sync, scale-up stabilization 0 s12 → 60 pods
Rate limit + concurrencyEnvoy local_ratelimit token bucket 100 rps/tenant, burst 200; adaptive_concurrency gradient controller, min 50 / max 1000caps origin at what it can serve
DegradationPriority shedding: drop recommendations and personalization first, keep search and checkoutpreserves the revenue path

The arithmetic that decides the design. 180k offered × 15% miss = 27k rps hitting origin. Origin capacity is 12 × 1,500 rps = 18k at 45% CPU. So 27k > 18k: something must shed ~9k rps for the whole scale-up window. That window is not 30 seconds. HPA adds at most the greater of 4 pods or 100% of current replicas per 15 s sync, so 12 → 24 → 48 → 60 takes three syncs (~45 s) before pod startup, image pull and readiness are counted. If the cluster has no spare nodes, Cluster Autoscaler adds 2–4 minutes on top. Shedding has to hold for minutes, not seconds.

Why latency, not CPU, is the signal. Little's law: at 1,500 rps and 40 ms, in-flight requests = 1,500 × 0.04 = 60. Let p99 drift to 400 ms at the same arrival rate and in-flight = 600: 10x the threads, on a box whose CPU may still read 70%. A thread-per-request service dies of pool exhaustion before it dies of CPU. So the shed trigger is connection-pool wait time and in-flight count, not CPU.

Failure modes and how each shows up.

  • Retry storm. Clients retry 503s and multiply the load you were trying to shed. Detection: total request rate above 2x baseline while success rate is flat. Mitigation: gRPC retryThrottling with maxTokens: 10, tokenRatio: 0.1, jittered exponential backoff, and a Retry-After header on every shed response.
  • Synchronized cache expiry. Detection: origin rps sawtooths on a fixed period. Mitigation: jitter TTLs ±20% and coalesce concurrent misses for the same key into one origin fetch.
  • Scaler flapping. Detection: replica count oscillating across sync periods. Mitigation: leave HPA's default 300 s scale-down stabilization window alone; lowering it to react faster is how you oscillate.
  • Shedding the wrong traffic. Detection: checkout error rate rising while total shed count is unchanged. Mitigation: make the priority order an explicit config reviewed before the incident, not a decision made during it.

Trade-offs. If the spike is write-heavy, the edge cache layer is worth nothing and you are down to rate limiting plus queueing, which means accepting 503s and saying so to the caller. And rate limiting per tenant only helps if the spike is one tenant; a global spike needs the concurrency limit and the degradation path, because a per-tenant bucket sized for normal traffic will pass all of it.

Curated: · Written: · Reviewed:

Difficulty: Hard