Skip to content
Tech Interview Prep
Technical interview guide

Capacity Planning & Load Testing

Knowing how much traffic a system can take before it does, through modeling and deliberate load testing.

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

Scope: Google SRE, Kubernetes, OpenTelemetry, Prometheus, k6, JMeter, PostgreSQL, and IETF guidance current 2026-08-31.

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-7

Explain and prevent coordinated omission.

Answer

Core answer

Coordinated omission is the bias you get when the load generator's request rate is coupled to the system's response rate. A closed-loop generator holds N workers, each sending its next request only after the previous one returns. When the system stalls, the generator stalls with it: the requests that would have arrived during the stall are never sent, so they never produce a latency sample. The stall gets recorded N times, once per worker, instead of once per would-be arrival, and the tail of the distribution is underweighted by orders of magnitude.

The fix is to decouple arrival from completion. Schedule requests on a fixed timeline (open-loop), and measure each request's latency from its intended start time, not from the moment the generator actually got around to sending it.

Worked example

100 closed-loop workers, 10 ms service time, so 10,000 req/s offered. The server stalls for 1 s (GC pause, lock convoy, whatever). Run length 60 s.

closed-loopopen-loop at 10,000/s
requests in the 59 normal seconds590,000 @ 10 ms590,000 @ 10 ms
requests during the 1 s stall100 @ ~1 s10,000 @ ~1 s
total samples590,100600,000
slow fraction0.017%1.67%
p99.910 ms~1 s
p9910 ms~1 s

Closed-loop reports p99.9 = 10 ms. The corrected run reports p99 = 1 s. Same system, same stall, two different stories, and only one of them matches what a user saw.

How tools do it

HdrHistogram has the correction built in: recordValueWithExpectedInterval(value, expectedIntervalBetweenValueSamples). Recording a 1 s sample with an expected interval of 100 µs (10,000/s) makes the histogram insert synthetic samples at 100 µs steps up to 1 s: the ~10,000 arrivals the stall swallowed. That is the arithmetic above, done inside the histogram.

Generators that schedule arrivals independently of completions: wrk2 (-R sets the rate, --latency prints an HdrHistogram), k6's constant-arrival-rate and ramping-arrival-rate executors, Vegeta (-rate, default 50/s), Gatling injection profiles (constantUsersPerSec), JMeter's Precise Throughput Timer.

Failure modes

  • Generator can't hold the rate. At 10,000 req/s the schedule interval is 100 µs; a generator that can't schedule that fast silently under-offers. Detect: k6 dropped_iterations > 0, or achieved rate below the target -R. Cost: you are back to closed-loop without knowing it.
  • Unbounded backlog. If you queue scheduled requests instead of dropping them, the queue grows for the whole stall and you measure queueing delay of a synthetic backlog. Detect: in-flight count or generator RSS climbing monotonically during a stall. Cap in-flight at the concurrency the system is designed for.
  • Silent drops. If you drop, count it. A non-zero drop counter means the reported distribution is conditional on the drop policy, and the tail is truncated.
  • Wrong expected interval. Correcting with the achieved rate instead of the intended rate reintroduces the bias. Detect: intended and achieved rate should agree to within a few percent.
  • Correcting a genuinely closed workload. If production really is 100 users who each wait for a response, closed-loop is the right model and correction overstates latency. Check whether arrivals are independent of completions before you correct.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Interpret p99 latency responsibly in a capacity report.

Answer

Say what the p99 is a p99 of, first. Five things, in this order: the journey (client-observed end-to-end, or server handler only), the success class (2xx only, or including 5xx and timeouts), the population (region, tenant, endpoint, request class), the window, and the sample count. Then name the estimator and say whether the number can be aggregated. A p99 is a claim about the top 1% of a specific population over a specific interval; without those five it is not interpretable, and the first question in the review is which one is missing.

Report it with the distribution, not alone: p50/p90/p99 plus throughput and an error count. Never average p99s across instances: sum the histogram buckets and compute the quantile from the sum.

Why a mix shift moves p99 (this is the mechanism, not a caveat). p99 is an order statistic, so it tracks the composition of the population, not just whether any one class got slower. 1000 requests: 989 cache hits at 10 ms, 11 DB-backed requests at 500 ms. Nearest-rank p99 = the 990th smallest = 500 ms. Move one request from the fast class to the slow class (990 fast, 10 slow) and the 990th smallest is 10 ms. One request in a thousand flips p99 by 50×. That is why cold starts, retries and expensive endpoints get broken out: a mix shift, not a regression, is the most common cause of a p99 move.

Why the estimator matters. Prometheus's default buckets are 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10 s. histogram_quantile(0.99, ...) linearly interpolates inside the bucket that holds the 99th percentile. If p99 lands in the 0.5–1 s bucket, the estimate can be off by up to 500 ms, and the interpolation assumes a uniform spread inside a bucket that latency data never has. With 1000 requests in the window, that bucket may hold three observations. The number is a bucket-shaped guess, not a measurement.

Alternatives and when each wins: t-digest (relative error at the tails, mergeable across instances), HdrHistogram (configurable significant digits, e.g. 3, bounded memory), DDSketch (relative-error guarantee), OpenTelemetry exponential histograms, Prometheus native histograms. Fixed buckets are cheap and summable but coarse; sketch structures give tight tail accuracy but only aggregate if the sketch itself is mergeable. Deciding criterion: aggregating across 200 pods → sum histogram buckets or use a mergeable sketch; one process's tail to 1% relative error → HdrHistogram or DDSketch. Showing percentiles alone is acceptable when the population is homogeneous and the window holds thousands of samples; it stops being acceptable the moment the mix can move.

Failure modes, and how you catch each.

  • Coordinated omission (Gil Tene): a closed-loop generator that waits for each response records one 10 s sample for a 10 s stall instead of the ~100 samples a real user population would have produced. Detect by comparing achieved throughput against attempted throughput; if they diverge, the tail is understated.
  • Averaging p99s across instances: the mean of p99s is not the p99 of the union. Detect by recomputing from summed buckets and comparing.
  • Too few samples: with 100 requests in the window, p99 is the max. Want a few hundred at minimum for a stable p99.
  • Client vs server: server p99 excludes network and client-side queueing, client p99 includes them. They answer different questions: state which one the SLO is written against.

What goes in the report. One row per population: journey, success class, window, sample count, estimator, p50/p90/p99, throughput, error rate, count of observations above the p99 threshold, and breach duration against the objective. Compare runs at equal attempted load, not equal achieved load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Validate the load-test generator and result pipeline.

Answer

The number you report is only as good as the generator that produced it, so I'd validate in three moves: establish the generator's ceiling, prove the pipeline records what the generator actually did, and if either fails, report a bound instead of a capacity figure.

Assumptions I'd state up front: open-loop (arrival-rate) test rather than closed-loop, generator hosts on the same network path as production clients, and the system under test is the only thing I'm trying to characterise.

1. Find the generator's ceiling

Run the same script against a trivial sink, a server that accepts and returns a fixed 200 with no work, and raise the rate until achieved arrivals fall below intended. That rate is the ceiling.

signalhow to read itgenerator-limited if (rule of thumb)
achieved vs intended arrivalsper-second counterachieved < 99% of intended
CPUmpstat -P ALL 1any core pinned at 100%
socketsss -sTIME_WAIT climbing monotonically
scheduling lagintended vs actual send timep99 lag > 10% of target p99

Bandwidth bites before CPU does. A 1 GbE interface moves ~125 MB/s; a 1 KB request/response pair at 100k RPS needs ~100 MB/s each way, ~200 MB/s combined, so the wire saturates first.

2. Why the details matter

Coordinated omission. If the generator stalls (GC, scheduler, a blocking DNS lookup) and then fires the backlog, the slow requests never get timed and p99 looks fine. wrk2 and HdrHistogram exist to correct exactly this; a naive loop does not. Measure the stall directly:

Python
intended = time.perf_counter()
for _ in range(1000):
    intended += 0.001        # 1 kHz intended arrival
    send()
    lag = time.perf_counter() - intended
    record(lag)              # this is the number that matters

If lag's p99 is a meaningful fraction of your target latency, the generator is the bottleneck, not the system.

Ephemeral ports. Linux defaults to net.ipv4.ip_local_port_range = 32768 60999 (28,232 ports) and TIME_WAIT holds a closed connection for 60 s. Against a single destination tuple that caps you near 470 new connections/second per source IP. Sharding generators or adding source IPs is the fix; widening the range buys only a constant factor.

Clocks. If shards timestamp arrivals with unsynchronised clocks, the merged arrival-rate series is wrong by the skew: 200 ms of skew across four shards smears a one-second bucket. Run chrony/NTP and record the measured offset.

DNS and TLS. Resolve once and reuse connections, or account for the resolver. A full TLS handshake costs ~2 RTT, resumption ~1; at 10k new connections/second that is real load you are adding to the target.

3. The result pipeline

Aggregation must preserve counts, labels and histogram semantics. Sum counters, merge histograms, never average percentiles: the mean of two p99s is not a p99 and can land below either input. If all you have is summaries, report the max of the p99s as a bound and say so. Watch label cardinality: a per-request ID label will blow up Prometheus.

Reconcile by sampling N requests at the target, matching IDs, and comparing observed rate to intended. Version the scripts and lockfiles, record placement and network path, and repeat the baseline twice: two runs that disagree mean the harness is unstable, not that the system is.

4. If the generator saturates first

Report the lower bound: "≥ X RPS at p99 ≤ Y ms, generator-limited." Never report the ceiling as target capacity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design a representative load model for an e-commerce event.

Answer

Core answer

Assume a single-region primary, a 4-hour event with a 15-minute peak, and read-dominated traffic. The load model has four axes: arrival shape, journey mix, data shape, and background work. Get the arrival shape wrong and nothing else matters.

Arrival shape. Use an open model: requests arrive at a fixed rate regardless of how long the server takes. A closed model (N virtual users looping) hides tail latency: when the server slows, closed-model users slow down too, so the generator never applies the pressure that caused the slowdown. In k6 that is ramping-arrival-rate:

JavaScript
export const options = {
  scenarios: {
    peak: {
      executor: 'ramping-arrival-rate',
      startRate: 500, timeUnit: '1s',
      preAllocatedVUs: 2000, maxVUs: 40000,
      stages: [
        { target: 5000, duration: '15m' }, // ramp
        { target: 5000, duration: '30m' }, // hold
        { target: 500,  duration: '10m' }, // drain
      ],
    },
  },
};

Journey mix. Split the arrival rate across journeys, each with its own think time and read/write profile. Illustrative mix for a 5,000 RPS peak:

JourneyShareRPSThink timeRead/write
Browse/catalog60%3,0006sread (CDN)
Search20%1,0008sread (search cluster)
Cart12%60010sread+write (session)
Checkout5%25015swrite (inventory)
Payment2%10020swrite (external PSP)
Order status1%505sread (DB)

Concurrency arithmetic. Little's Law separates two numbers people conflate. Server-side in-flight requests = λ × W = 5,000 × 0.05s = 250. Simulated users = λ × (W + think time) = 5,000 × 8.05s ≈ 40,250. Size the generator for the second, the server for the first.

Data shape. Catalog reads are skewed: the top 1% of SKUs take 50%+ of views. Model that explicitly with a Zipf distribution over product IDs, not uniform random: uniform traffic never hits the hot shard that fails in production.

Background work. Add indexing, fulfillment, and analytics as separate scenarios at their real rates; they compete for the same DB and cache.

Trade-offs. Open vs closed: open for the peak, closed for a steady-state soak. Synthetic vs replayed: synthetic to scale past recorded peak and to force hot keys, replay for the baseline mix. One mix vs several: run at least two, because the highest-RPS mix is rarely the most expensive. 100 RPS of payment holds DB connections and calls an external PSP, and can cost more than 3,000 RPS of cached browse.

Failure modes and detection.

  • Coordinated omission: the generator waits for each response before issuing the next, understating latency. Detect by comparing achieved RPS to target RPS; a gap means the generator, not the server, is the bottleneck.
  • Hot-key shard saturation: one SKU pins a shard. Detect by per-key p99 vs aggregate p99.
  • Connection pool exhaustion: p99 climbs from ~40ms to ~180ms once the pool saturates at 20 connections. Detect via pool wait-time metric.
  • Retry amplification: bounded retries at 3 attempts turn a 5% error rate into 15% extra load. Detect via retry rate; cap it and alert above 5%.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Model capacity when request costs vary widely.

Answer

The 90-second answer. Requests-per-second is the wrong unit once request cost varies by more than a small factor. Capacity is set by the scarcest resource, so I model each request class by its service demand on each resource (CPU seconds, DB connection-hold time, bytes, lock time) and compute utilization per resource. The number I report is a workload vector: "at 70% CPU headroom this pool serves 900 rps of the read mix, or 120 rps of the search mix."

Assumptions I'd state up front: I can attribute service demand per class (per-endpoint histograms or a profiler), the mix is forecastable, and the target utilization sits below saturation (say 0.7) so queueing stays roughly linear.

Why RPS fails. Little's Law: L = λW. Concurrency is rate times time. If class A takes 2 ms and class B takes 40 ms, one B holds a worker 20× as long. Same λ, 20× the concurrency. A single rps ceiling is only valid for one fixed mix.

The model. For each resource r: U_r = Σ_c λ_c · D_{c,r} / m_r, where D_{c,r} is per-request demand of class c on resource r and m_r is that resource's capacity (cores, connections). Capacity is the λ vector where max_r U_r hits the target.

Worked arithmetic. Pool of 8 cores, one DB with a 20-connection pool. Two classes:

classCPU/reqDB/req
read2 ms1 ms
search40 ms120 ms

At 1000 rps all-read: CPU = 1000 × 2 ms = 2.0 s/s = 2 cores (25% of 8). DB = 1.0 s/s (5% of the pool).

At 1000 rps, 50/50: CPU = 500 × 2 + 500 × 40 = 21 s/s → 2.6× the 8 cores. DB = 500 × 1 + 500 × 120 = 60.5 s/s → 3.0× the 20-connection pool.

Same 1000 rps. One mix fits with room; the other is 2.6× over CPU and 3× over the DB pool. That is the whole argument for a vector instead of a scalar.

What to do with it. Weighted admission: give each class a concurrency budget proportional to its demand share, so a burst of search can't consume every worker. Separate pools only where isolation is worth paying for: you size each pool for its own peak, so you buy headroom twice. Cache or batch the expensive class when semantics allow: a 40 ms search that becomes a 4 ms cache hit moves the mix, not the code.

Failure modes and detection.

  • Mix shift (launch, retry storm): CPU seconds/sec per class climbs while total rps is flat, and p99 diverges between classes. Detect with per-class CPU accounting (cgroup cpu.stat) or per-endpoint histograms.
  • Head-of-line blocking: cheap-class p99 rises while its own service time is unchanged. That's queue wait, not work. Detect by comparing in-service time to queue time per class.
  • Starvation under weighted admission: a low-weight class never gets scheduled. Detect via per-class admission-reject counters and the age of the oldest queued item.
  • Retry amplification: the expensive class times out and retries double its demand. Detect the attempts/successes ratio per class.

Reporting. State the vector plus the binding resource: "binding resource is DB connections; at 70% we serve 700 rps read-only, or 180 rps at 50/50." That is a number a capacity review can act on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do you derive a capacity estimate from production observability data (metrics, traces, and sampled traffic replay) instead of, or to validate, synthetic load tests?

Answer

Start by naming the saturation signal you will trust, then measure per-request cost and the demand distribution from production, and only then decide whether a synthetic test is needed at all.

Production telemetry answers two things a synthetic model guesses at: what the demand mix actually is, and what each request costs in the resource that saturates first. Pick the resource (CPU, a DB connection pool, a downstream quota) by finding the queue that grows before latency does. In Prometheus that is rate(container_cpu_usage_seconds_total[5m]) against sum(rate(http_requests_total[5m])), plus histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) to locate the knee. Traces split cost per endpoint: a 1% head sample with full span context is usually enough to see that checkout burns 40 ms of DB time while search burns 2 ms.

Then do the arithmetic. A service on 8 pods, 2 vCPU limit each, at 62% CPU serving 4,200 rps:

CPU-seconds per request = (8 × 2 × 0.62) / 4,200 = 2.36 ms.

At a 70% target utilization, capacity = (8 × 2 × 0.70) / 0.00236 ≈ 4,745 rps.

Now check that against the observed knee. If p99 crosses 200 ms at 5,100 rps, the CPU model is optimistic by ~7%, so something other than CPU saturates first. Follow the queue: if each request holds a DB connection for 4 ms and the pool is 20, the ceiling is 20 / 0.004 = 5,000 rps. That is the real constraint and the number to plan against.

signalsourcedecides
saturation queuerate() of queue depth or pool in-usewhich resource to model
per-request costtraces (span duration × resource) or CPU-seconds/requestthe divisor
demand histogramrequest rate by endpoint from metricsthe mix, not the mean
kneehistogram_quantile p99 vs throughputwhether the model holds

Sampled traffic replay validates the model without a synthetic guess. Capture a representative window (a full diurnal peak, not a quiet hour) at the edge, keep the request mix and payload sizes, and replay against staging at a fraction of production. Compare per-endpoint latency and per-request resource cost; if replay cost differs by more than ~20%, the environment is not representative (cold caches, smaller data set, different dependency latency) and the replay validates nothing. If a synthetic test at 5,000 rps shows p99 90 ms while production at 4,200 rps shows 180 ms, the synthetic model is missing data volume or cache hit ratio.

Failure modes worth naming. Production traffic is already shaped by admission control, retries and client timeouts, so it under-represents true demand: the requests you shed never appear in the histogram. Head-based sampling drops exactly the slow traces you need; use tail sampling or a latency-biased sampler. Prometheus histograms are server-side and so avoid the coordinated omission a closed-loop generator suffers, but a client-side metric will not. A replay that hits a shared staging dependency can corrupt it; isolate or mock.

Still run synthetic tests to reach a demand level production has never hit, or a failure mode (zone loss, dependency down) you cannot ethically produce. Use production data to calibrate the synthetic mix and per-request cost, then let the synthetic test push past the observed envelope.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Build a capacity plan for a fast-growing API.

Answer

What I'd say first

I'd clarify three things before sizing anything: the SLO we're protecting (assume p99 < 200 ms), the growth we're planning against (assume 15% month over month, which doubles in ~5 months), and the failure we must survive (assume loss of one availability zone out of three). Then I'd size the 12-month peak and work backwards to triggers.

The plan

Start from today's peak, not average. Assume today's peak is 2,000 rps. At 15%/month, 12 months out is 2,000 × 1.15^12 ≈ 10,700 rps.

Convert rate to resources with Little's Law and per-request cost. If each request burns 10 ms of CPU, today's peak needs 2,000 × 0.010 = 20 cores busy. Running at 60% utilization, 40% headroom, that's 34 cores. In 12 months: 10,700 × 0.010 = 107 cores busy, 178 at 60%.

Zone loss is the multiplier people forget. If one of three AZs dies, the remaining two must carry full peak, so provision 178 × 1.5 ≈ 267 cores.

Storage: at 200 bytes written per request, today is 2,000 × 200 = 400 KB/s ≈ 34 GB/day. At 10,700 rps it's 2.1 MB/s ≈ 185 GB/day, ~67 TB/year before replication. Three-way replication makes that ~200 TB.

Connections: if each request holds a DB connection for 5 ms, concurrency is 2,000 × 0.005 = 10 today, 54 in 12 months. A pool of 20 is fine now and saturates in about 5 months.

Triggers

Set triggers off utilization, not calendar. At 70% sustained for 15 minutes, growth of 15%/month reaches 100% in ln(1/0.7)/ln(1.15) ≈ 2.5 months. That covers a 6-week procurement or quota-increase lead time with margin. Own each trigger: page on 70% CPU, ticket at 60% connection-pool use, quota request at 50% of the provider's limit.

Trade-offs

Vertical vs horizontal: bigger instances are simpler and avoid connection fan-out, but they widen the blast radius of a single node and don't help with AZ loss. Horizontal needs a load balancer and multiplies DB connections.

Autoscale vs pre-scale: autoscaling reacts in 60–90 s for a JVM cold start, too slow for a 3x burst. Pre-scale on a schedule for known peaks and keep autoscale as the backstop.

Headroom costs money: 40% headroom is 1.67x the compute bill. 267 cores at ~$0.04/core-hour is roughly $7,800/month, illustrative. The alternative is breaching p99 during zone loss.

Failure modes

Connection-pool saturation: pool of 20, demand 54. Detect via pool wait-time p99 and connection-timeout errors; p99 goes from 40 ms to 180 ms once the pool queues.

Retry storm: a dependency blip triples load if clients retry without jitter. Detect via retry-rate and 5xx metrics; cap retries at 2 with exponential backoff and a circuit breaker.

Quota exhaustion: provider caps at 10,000 rps per region; you hit it silently as 429s. Detect via dependency 429 rate; request increases at 50% of the cap.

Forecast error: if growth is 25% not 15%, 12 months is 2,000 × 1.25^12 ≈ 29,000 rps, not 10,700. Review actual-vs-forecast monthly and re-run the model when it drifts more than 20%.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Choose headroom for a critical service.

Answer

What I'd say first

Before I pick a number I need three things: which resource saturates first, what the SLO is, and which failure I have to survive. Headroom without those is meaningless: 30% CPU headroom on a service whose real bottleneck is a 20-connection database pool is not headroom. So I size it from measured demand, not a rule of thumb.

Worked sizing (hypothetical service, numbers assumed)

  • steady peak: 1,000 rps
  • p99 90-second burst: 1.6× → 1,600 rps
  • 3 AZs, even spread, must survive one AZ loss → 2/3 of capacity remains
  • autoscaler adds a node in ~4 minutes, so a 90-second burst is absorbed by capacity already running
  • load test: p99 latency flat to 65% utilization of the limiting resource, then a steep knee

Required provisioned capacity:

1,600 rps ÷ (2/3) ÷ 0.65 ≈ 3,700 rps ≈ 3.7× steady peak

That's ~270% headroom over steady peak, and every factor is a measurement: the 1.6× from production traffic, the 2/3 from the failure domain, the 0.65 from the load test. If the autoscaler could add capacity inside the burst window, the 1.6× drops out and you'd need ~2.3× instead. That is the trade you are actually making.

Failure modes and how I'd catch them

  • Autoscaler stalls: quota, image pull, AZ capacity shortage. Detect: pending instances > 0 for more than 2 minutes, or scaling activity failing. Consequence: the burst eats the failure-domain reserve, and the next AZ loss crosses the knee.
  • Retry storm after a partial outage. Detect: request rate above forecast with no matching user traffic; retries amplify the load. Mitigate with retry budgets and jitter.
  • Wrong limiting resource. CPU sits at 40% while the connection pool is saturated. Detect: pool wait-time p99, not utilization.
  • Silent growth. Peak creeps up between reviews. Detect: weekly peak ÷ committed capacity; alert when it crosses 80% of the reserve.

Alternatives

If the service can shed (read-only mode, drop non-critical traffic) you can run with less reserve and a written shedding policy that names what gets dropped first. That is cheaper than 3.7× if the business accepts the degradation. If it cannot shed, you pay for the reserve.

The decision, aloud

Limiting resource is the DB pool; SLO is p99 < 300 ms; I must survive one AZ loss and a 90-second 1.6× burst. The load test puts the knee at 65%, so I provision 3.7× steady peak, alert when consumed headroom passes 80% of the reserve, and keep a shedding policy for the case where the autoscaler cannot keep up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Plan a safe production load test.

Answer

"Safe" here means three things: the blast radius is bounded to a slice of traffic you chose, every effect is reversible, and you walk away with evidence you can defend. If you can't get all three, don't run it in production.

State the assumption up front: staging can't reproduce production's data volume, cache hit ratio, or third-party latency. If it can, the service is stateless and the dependency has a sandbox, test there and save yourself the risk.

Start with shadow traffic. Mirror a copy of live requests with writes suppressed, or replay a captured trace at 1x. That gives you a real latency baseline without touching state. k6's ramping-arrival-rate executor or a GoReplay mirror will do it. Only after shadow shows no surprises do you move to a canary: 1% of real traffic, or a single tenant, with a hard rate ceiling enforced at the load generator, not at the service.

The ramp shape matters because the things that break have time constants. Connection pools fill in seconds, JIT and caches warm in minutes, autoscalers take 60–120 s to react and then overshoot. A step to full rate tests none of that; it just trips the first limit. Ramp in stages (5 min to 10% of target, 10 min to 50%, 10 min to 100%) and hold at target for at least 30 min so the steady state is real.

Saturation looks like throughput flat while p99 climbs, queue depth growing, connection-pool wait time nonzero, and the autoscaler pinned at max replicas. Watch those, not just error rate.

Concrete example. Checkout service, baseline p99 180 ms at 200 rps. Target 600 rps. Abort if p99 > 2× baseline for 2 consecutive minutes, error rate > 1%, or any dependency above 70% of its quota. At 480 rps the HikariCP pool (max 20) saturates: wait time goes 0 → 45 ms, p99 180 → 620 ms. The HPA adds pods but takes 90 s. The controller aborts at the 2-minute mark. That's a useful result: you learned the pool, not the service, is the ceiling.

Trade-offs:

approachwhat it proveswhat it costs
staging clonefunctional correctnessmisses real data volume, cache state, third-party latency
shadow/replaylatency under real traffic shapeno write path, no autoscaling behavior
production canarythe whole system under real loadreal user risk, cleanup debt

Skip the production test when the change is a config you can validate with a single-tenant replay, when there's no kill switch you trust, or when the dependency has no rate-limit headroom: a payment provider at 100 rps will 429 you at 600 and may suspend the account.

Failure modes to plan for:

  • Test traffic contaminates billing or analytics. Tag every synthetic identity and filter downstream; cleanup is a day of reconciliation.
  • Autoscaler masks the bottleneck, then scales down mid-test and oscillates. Pin min replicas or disable scale-down during the window.
  • Third-party quota exhaustion. Check the vendor's limit and your current usage before you start; coordinate a window.
  • Leftover state: test orders, temp IAM roles, feature flags. Script the teardown and verify it, don't eyeball it.

Name one controller with stop authority and a documented abort command. Publish the result with its limits ("600 rps held for 30 min, p99 210 ms, DB pool at 80%") not just "passed."

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Investigate a latency cliff as concurrency rises.

Answer

Assumptions I'd state first: the load generator measures arrival rate and in-flight concurrency independently of the service, and the service reports its own queue wait separately from service time. Without that split you can't tell a cliff from a slow dependency.

Core answer. A latency cliff is a queueing effect, not a code regression. As utilization ρ = λ·S/c approaches 1, wait time grows as ρ/(1−ρ), so the last 5% of headroom costs you 10× the latency of the first 50%. Find the knee, confirm it's queueing by checking that service time is flat while wait time and queue age climb, then either cap admission at the knee or move the constraint.

Why it's nonlinear. Take a single-server view with mean service time S = 50 ms. Queue wait is Wq = ρ/(1−ρ)·S:

utilization ρqueue waittotal latency
0.5050 ms100 ms
0.80200 ms250 ms
0.90450 ms500 ms
0.95950 ms1000 ms

Nothing in the service changed; the same 50 ms of work now sits behind 950 ms of queue. Pooling helps, an M/M/c server with c workers at the same ρ has far less wait than M/M/1, but the shape is identical, and it's why a 20-worker pool at 400 rps capacity looks fine at 300 rps and falls over at 390.

The check that separates queueing from slowness. Apply Little's Law, L = λ·W. If you measure λ = 380 rps and W = 1.0 s, then L = 380 requests are in flight. If the pool has 20 workers, 360 of those are queued, not executing. That gap is the queue, and it tells you the constraint is admission, not the handler. If instead service time itself rose with concurrency, you're looking at contention (a lock, a connection pool, or GC) and the fix is different.

Failure modes to name.

  • Retry storm. Client timeout 1 s, 3 retries, no jitter. At ρ = 0.95, W = 1 s, so roughly half of requests time out and retry, adding ~50% offered load. λ jumps, ρ crosses 1, and the soft degradation becomes a hard cliff. Detect it by comparing server-side request rate against client-side arrival rate, if the server sees more, retries are inflating load. Cost: error rate goes from ~0 to timeout-bound, and recovery needs a retry budget, not more capacity.
  • Pool exhaustion. Connection pool of 20, all held by requests waiting on a slow downstream. Detect via pool wait time and active-connection count pinned at max. Cost: unrelated endpoints sharing the pool also stall.
  • GC pause amplification. Heap pressure under load triggers longer pauses, which lengthen service time, which raises ρ. Detect by correlating pause duration with the latency step.

Remediation trade-offs.

  • Cap admission (limit in-flight to the knee, shed the rest). Use when the constraint can't be expanded this week and you must protect the tail. Cost: you drop requests, so you need priority classes to shed the right ones.
  • Reduce service demand (cache, batch, cheaper query). Use when the work itself is the bottleneck and can be cut without changing semantics. Cost: staleness and cache-invalidation complexity.
  • Expand the constraint (more workers, bigger pool, scale out). Use only when the resource is genuinely the limit and downstream has headroom: otherwise you move the cliff to the database.

Verification. Re-run controlled steps, confirm service time stays flat while wait time tracks ρ/(1−ρ), and check that recovery happens with retries disabled. If latency only recovers once retries stop, you fixed the symptom.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Find a system's real bottleneck from a load test.

Answer

Core answer (say this first).

Pin the objective before touching the tool: which SLO, at what percentile, under what arrival rate. Then run an open-loop test (constant arrival rate, not fixed concurrency) because a closed-loop generator throttles itself when the server slows and hides the tail. Ramp arrival rate in steps and look for the first resource that saturates and leads the degradation, not the one that merely looks hottest.

The bottleneck is the resource whose saturation precedes the latency inflection. Find it with USE per resource (utilization, saturation (queue depth or wait time), errors) then prove it by changing exactly that one constraint and re-running. If the knee moves, you found it. If it doesn't, you were looking at a symptom.

Why latency rises before throughput falls. Little's Law: L = λW. In-flight requests equal arrival rate times time-in-system. Below saturation, capacity exceeds λ, so W stays flat and throughput tracks demand. Once a resource saturates, λ is capped at capacity; extra arrivals queue, so W grows without bound while throughput stays flat. That is the knee: throughput plateaus, p99 climbs. So the diagnostic question is never "what's at 100%?" but "what started queueing first?"

Arithmetic (hypothetical). A service with a 20 ms mean service time behind a connection pool of 10 (HikariCP's default maxPoolSize is 10). Ceiling = 10 / 0.020 = 500 rps. Drive 700 rps and the queue grows at 200 rps: after 10 s, ~2,000 requests are waiting, and p99 is dominated by queue wait, not service time. CPU sits near 30% because threads are blocked in the pool, not computing. That signature (low CPU, rising pool-wait, flat throughput) is pool exhaustion, not a CPU limit.

Discriminating signatures.

LimitSignatureConfirm with
Connection poolLow CPU, pool-wait climbs, threads BLOCKEDpool wait metric, thread dump
CPU quotaHigh CPU, run-queue > cores, throttlingcgroup cpu.stat nr_throttled, load avg
GCp99 spikes aligned to pauses, sawtooth heapGC pause log, allocation rate
Lock contentionThroughput flat at low CPU, threads BLOCKED on a monitorthread dumps, JFR lock events
DownstreamYour latency tracks a dependency's; its errors rise firstdependency RED metrics, its own saturation

Experiment. Change one dimension: raise pool size 10 → 50. If throughput rises toward 2,500 rps, the pool was the limit. If it doesn't move, the constraint is elsewhere: check the downstream or the CPU quota. A shifted knee confirms; an unmoved knee falsifies.

Failure modes. Coordinated omission: a closed-loop generator records latency only when it sends, so a stalled server looks fine. Use constant-arrival tools (k6, wrk2, HdrHistogram). Generator saturation: confirm the load box isn't the limit before blaming the server. And don't call the hottest metric causal if it never saturated or never led the degradation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How do you distinguish between application-level bottlenecks and infrastructure or network saturation during a distributed stress test?

Answer

To isolate whether a stress-test bottleneck stems from the application runtime or underlying infrastructure/network, evaluate correlated signals across three layers simultaneously: load generator vantage, host and kernel telemetry, and distributed request traces.

1. Identify the Point of Divergence

Begin by comparing client-perceived duration against internal service processing time using distributed tracing spans (e.g., OpenTelemetry span durations):

  • If client p99 latency spikes (e.g., 20 ms to 1,200 ms) while internal server-side span execution time remains flat (e.g., 15 ms), time is spent in external network transmission, socket backlog queuing, or connection negotiation (TLS/TCP handshakes).
  • If internal span time tracks client latency directly, inspect down to child spans: internal locks, GC pauses, downstream sync calls, or database query execution.

2. Differentiating Signatures

LayerBottleneck TypeKey Metrics & Telemetry SignaturesRoot Cause Mechanism
Network / FabricBandwidth or Packet Dropsnode_network_transmit_drop_total > 0, TCP retransmits (tcpi_retransmits / netstat -s), RTT inflation on idle probe connections.Buffer bloat in top-of-rack switches, egress bandwidth throttling (e.g., cloud NIC limits), or conntrack table exhaustion (nf_conntrack_count hitting nf_conntrack_max).
OS / Host InfrastructureCPU Steal, CFS Throttling, Disk I/Ocontainer_cpu_cfs_throttled_periods_total rising while host CPU appears low; high iowait (vmstat / node_disk_io_time_seconds_total); hypervisor steal_time > 2%.Linux CFS cgroup quotas starving threads; disk queue saturation blocking synchronous writes/logging; hypervisor noisy neighbors.
App Runtime / PlatformThread / Pool Contention, GC, DB LatencyCPU utilization plateauing below 60% with zero CFS throttling; thread pool queue growth (executor_queue_depth); JVM STW pauses or Go GC sweep times climbing; DB connection pool wait time (hikaricp_pending_threads).Synchronized blocks, thread pool exhaustion, database connection pool exhaustion, or memory allocation pressure triggering frequent GC stop-the-world sweeps.

3. Worked Diagnostic Trace

Suppose an API target exhibits throughput plateauing at 8,500 RPS with p99 response time degrading from 35 ms to 820 ms:

Step 1: Check Client vs Server Duration
Load Gen p99: 820 ms | Edge Proxy p99: 810 ms | App Server Handle() p99: 42 ms
--> Latency is introduced BEFORE the App Server handler executes.

Step 2: Check Kernel & Connection Queues
App host metrics:
- ss -ltn 'sport = :8080' shows Send-Q > 0, Recv-Q near backlog limit (somaxconn: 1024).
- netstat -s: 'times the listen queue of a socket overflowed' increments rapidly.
- Host CPU: 42% (no CFS throttling), Host Memory: 35% utilized.

Step 3: Check Upstream Connection Pooling
Edge proxy connection reuse pool: saturated; proxy is opening new TCP connections per request.
App event loop worker threads are blocked on non-blocking accept() due to worker thread starvation.

Conclusion: The failure is an infrastructure socket configuration & event loop scheduling bottleneck, not network line saturation or backend business logic. Raising net.core.somaxconn, configuring HTTP/2 connection keep-alive on the load generators, and decoupling the I/O accept loop from worker thread execution restores p99 latency to 38 ms at 12,000 RPS.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Capacity-test a database-backed service.

Answer

Assume, then answer. PostgreSQL 16, one primary plus one read replica, HikariCP maximumPoolSize=20, 8 vCPU, SLO p99 under 100 ms at 500 rps with a 1% error budget. Whether the working set fits shared_buffers (default 128 MB) decides whether reads come from memory or disk, so establish that before running anything: it changes every number that follows.

Capacity testing a database-backed service is not "find max TPS." It is finding the load at which p99 leaves the SLO, and what breaks first when it does. Two things make that measurable: drive load open-loop, and read the database's own counters next to the client's.

Drive load open-loop. A fixed client count is closed-loop: each client waits for its previous request before sending the next, so when the database slows the generator slows with it and the stall never appears in your latency numbers. pgbench is exactly this: -c 64 is 64 closed-loop clients; its --rate adds a Poisson arrival schedule, but the worker count stays fixed, and when workers fall behind pgbench reports schedule lag. That lag is the generator, not the database. Use a constant-arrival driver:

JavaScript
import http from 'k6/http';
export const options = {
  scenarios: {
    steady: { executor: 'constant-arrival-rate',
              rate: 800, timeUnit: '1s', duration: '5m',
              preAllocatedVUs: 50, maxVUs: 500 }
  }
};
export default function () { http.get('http://app.internal/orders/42'); }

800 iterations/s for 300 s is 240,000 iterations. VU demand is rate * mean latency: 800 * 0.025 = 20 at the middle step, 1200 * 0.25 = 300 at the top one, inside the 500 cap. Above the cap k6 reports that it could not reach the target rate, and that shortfall is the generator's, not the database's. Hold each step ~5 minutes so checkpoint and autovacuum activity lands inside the window.

Illustrative run (20-connection pool, 8 vCPU):

offeredachievedp50p99errorspool wait p99DB CPU
100 rps1003 ms12 ms00.5 ms12%
400 rps4005 ms40 ms03 ms45%
800 rps79812 ms180 ms0.3%25 ms88%
1200 rps900180 ms900 ms4%600 ms99%

Why the curves bend. In-flight demand is rate * mean latency: 2.8 at 400 rps, 20 at 800 rps, 300 at 1200 rps. The pool holds 20, so at 800 rps every connection is busy and wait starts: p99 moves 40 to 180 ms while p50 barely moves, which is queueing, not a slower query. At 1200 rps achieved stops tracking offered (900 of 1200) and CPU sits at 99%: that is saturation, and because the queue is unstable there the numbers keep worsening with hold time. Pool wait reaching 600 ms means the connection, not the query, is the constraint; DB CPU near saturation means the opposite. p99 "teeth" repeating every checkpoint_timeout (default 5 min) are fsync spikes, not load: raise max_wal_size (default 1 GB) or test again with a longer hold to confirm. Cache miss shows up as blks_read rising against blks_hit in pg_stat_database.

Failure injection, each with a signal and a cost. Kill the replica: pg_stat_replication loses its row and reads either error or serve stale data through promotion; the primary absorbs the read traffic, and the headroom you saw at 400 rps is what decides whether it holds. Kill the primary: a retry storm arrives, and if retries are not idempotent you get duplicate-key violations on the unique index over the idempotency key. Force a deadlock from two sessions locking rows in opposite order: pg_stat_database.deadlocks increments and the app sees SQLSTATE 40P01; deadlock_timeout (default 1 s) is how long the detector waits first. Exhaust the pool: HikariCP connectionTimeout defaults to 30 s, so a starved request fails after 30 s, long past the p99 you are watching, which is why pool timeouts are read separately from query latency.

Finally validate the data, not just the timing: row counts, uniqueness, and idempotency keys after the run. And treat pgbench or synthetic results as comparative evidence for this schema and hardware, never as a prediction of production capacity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you size capacity for a WebSocket or SSE service where held-open connections, not request rate, dominate memory and file descriptors?

Answer

Clarify before sizing: protocol, message rate and size per connection, whether clients actually drain what you send, reconnect policy, and whether connections are sticky to a pod. Then state the model: capacity is the minimum of four budgets. Memory, file descriptors, conntrack/ephemeral ports, and handshake CPU. Request rate is irrelevant; a steady-state idle WebSocket costs almost no CPU.

Per-connection memory is not one number, and the kernel half is the one people forget:

componenttypicalwhere the number comes from
kernel socket buffers208 KiB each way by default; up to 6 MiB with autotuningnet.core.rmem_default/wmem_default = 212992; tcp_rmem max 6291456
app read/write buffer4–64 KiB, chosenyour framing; the send buffer grows if the client stalls
TLS session state~16–40 KiBplus the session-ticket cache
execution stack1 MiB (JVM thread) vs 2–8 KiB (goroutine)this decides the architecture

Thread-per-connection at a 1 MiB stack: 100k connections is 100 GiB of stacks alone. An event loop at ~16 KiB per connection: 100k is 1.6 GiB. The architecture is part of the answer, and any connections-per-node figure that does not name it is meaningless.

Worked arithmetic for 500k connections on an event-loop service: 20 KiB app state + 32 KiB TLS + 8 KiB goroutine = 60 KiB → 30 GiB. Now the kernel: leave autotuning on and 128 KiB of buffers per connection × 500k = 64 GiB, more than the application. Cap tcp_rmem/tcp_wmem at 64 KiB each for a service whose messages are ~1 KiB: you are not moving bulk data, and the default window is sized for throughput, not for half a million idle sockets.

File descriptors: one per connection, plus epoll, plus logs. ulimit -n of 1024 is the classic trap; set LimitNOFILE in the unit file and fs.file-max system-wide. Watch process_open_fds against the limit. EMFILE surfaces as accept: too many open files while existing connections keep serving: a partial outage that looks like a client problem.

Conntrack and ports: every connection through kube-proxy or a NAT is a conntrack entry. nf_conntrack_max defaults around 65536 on small nodes; when it fills, dmesg logs nf_conntrack: table full, dropping packet and new connections disappear with no application-side error. Client-side, the default ip_local_port_range (32768–60999) caps you near 28k connections per (src IP, dst IP, dst port) tuple.

Handshake CPU is bursty, not steady. A deploy that drops every connection makes all clients reconnect at once: 500k TLS handshakes at ~1 ms CPU each is 500 CPU-seconds, roughly 60 s of saturation on 8 cores. Jittered reconnect with exponential backoff is a capacity control, not a nicety. At the connection limit, reject new ones with 429 (RFC 6585) and let existing sessions drain rather than accepting and OOMing.

Load testing: in k6 one VU holds one WebSocket, so VUs ≈ connections; shard generators and watch the generator's own fd limit. Ramp to target, hold past your LB idle timeout and longest backoff, and plot RSS per connection over time: a leak is a slope, not a step. Name the failure modes you are testing for: fd exhaustion, conntrack full, OOM from a stalled consumer's send buffer, idle-timeout churn, reconnect storm.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Plan capacity for asynchronous queues and workers.

Answer

Start by pinning the numbers that decide it: arrival rate per class, service-time distribution, and the SLO on queue age, not throughput. Throughput is easy to satisfy; age is what breaks.

Assume a class arriving at λ = 200 msg/s, each message taking 50 ms of worker time, so one worker does 20 msg/s. Little's Law says L = λW: the number in the system equals arrival rate times time in system. If you want p99 queue age under 2 s, you cannot run workers at 100% utilization: M/M/c waiting time blows up as ρ → 1. At ρ = 0.7 you need 200 / (20 × 0.7) ≈ 15 workers. Ten workers would exactly match arrival and sit at ρ = 1, where age is unbounded.

Drain time is the other half. A 50,000-message burst with arrivals still at 200/s and 15 workers (300/s capacity) drains at 100/s net → 500 s, over 8 minutes. Scale to 30 workers (600/s) and it drains at 400/s net → 125 s. That arithmetic is the capacity plan: recovery capacity must exceed arrival by enough to hit your drain SLO.

For the autoscaling signal, depth alone is ambiguous: 10k messages of 1 ms work is nothing, 10k of 10 s work is a disaster. Age of the oldest unprocessed message maps directly to the SLO.

signalwhat it tells youfailure
queue depthbacklog size, not costambiguous across message classes
age of oldestmaps to the age SLOlags the arrival that caused it
arrival rateleadingnoisy, spikes on retries
in-flight / workersaturationpinned at concurrency during HOL block

Use age-of-oldest as primary, with a fast scale-out and slow scale-in to avoid flapping.

Failure modes and how you see them:

  • Poison message: delivery count climbs, age of one message grows while throughput is fine. Set a redrive policy: SQS maxReceiveCount 5 → DLQ.
  • Head-of-line blocking: p99 processing time diverges from p50, in-flight pinned at concurrency, completions flat. Split slow classes onto their own queue.
  • Dependency throttling: downstream 429s and your retry rate rise together, so effective λ grows. Exponential backoff with jitter plus a circuit breaker.
  • Worker loss: worker count below desired, age slope positive.

Retention and bounds: SQS default retention is 4 days (max 14), visibility timeout default 30 s, max message 256 KB. Set retention to your max tolerable drain time, not the default.

Trade-offs: shed at the edge when work is droppable and freshness matters; backpressure internal producers when they can retry; unbounded queue only when durability beats latency and you have drain capacity. Pick by whether losing a message is worse than serving it late.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design a soak test for a stateful service.

Answer

Assume a sharded, stateful service, say a queue-backed API with a per-shard LSM store and a 20-host fleet, and a workload generator that replays a week of production traffic at 1x. The soak runs at steady p50 load with realistic churn: 5% of keys overwritten per hour, 1% of connections recycled per minute, one credential rotation per 24h, hourly compaction, daily backup.

Run it for at least 72 hours, and longer than the longest periodic cycle you have. If your longest cycle is a 24h credential rotation, 72h gives you three crossings. If you have a weekly compaction, you need 8 days. The point is not duration for its own sake; it is crossing every cleanup, rotation, and refresh boundary at least twice so a one-off failure is distinguishable from a periodic one.

Hold versions fixed: same binary, same config, same data shape. Change one thing and you are testing a different system.

Measure slopes, not endpoints. A final heap of 2 GB is meaningless; a heap slope of +8 MB/h over 72h is a leak that will OOM a 4 GB heap in 250h. Compute slope with a linear fit over a rolling 6h window and alert when the 95% CI excludes zero and the slope exceeds your threshold.

Here is the signal table I would actually run, with illustrative thresholds for a 4 GB heap service:

signalslope thresholddetection
RSS / heap> 2 MB/h over 6hlinear fit, CI excludes 0
file descriptors> 1/minlsof count per host
queue age p99> 5 ms/hrolling median vs baseline
cache hit ratio< 90% of baseline1h average
compaction debt> 100 MB/hLSM pending bytes
connection count> 5% driftpool metrics
error rateany new error classlog clustering

Arithmetic for the heap case: baseline 1.2 GB, cap 4 GB. At +2 MB/h, you hit cap in (4096-1228)/2 ≈ 1434h: fine. At +20 MB/h, 2868/20 ≈ 143h: you OOM in six days. That is the difference between a soak that passes and one that finds the bug.

Alternatives: a stepped soak ramps load every 6h to find the knee; a peak-load soak runs at 2x for 4h to test burst handling. Use stepped when you suspect a nonlinear resource curve, peak when you care about autoscaling. A shorter test suffices if your longest cycle is 1h and you only need leak detection: 12h at 10x churn will surface most leaks.

Failure modes to watch:

  • Leak masked by restart. If a restart resets the slope, you have a leak, not a stable state. Compare RSS before and after a controlled restart.
  • Compaction debt. Queue age rises while CPU stays moderate: the write path is fine, the background merge is not.
  • FD leak from connection churn. lsof count climbs 1/min; after 72h you are 4320 FDs over baseline and hit the 65535 limit.
  • Credential rotation failure. Errors spike exactly at the 24h boundary; the client did not reload the cert.
  • Autoscaler oscillation. Instance count sawtooths because the scaling metric is queue age, which lags.

Recovery: stop the load. Verify queue drains to < 1s p99 within 5 minutes, memory returns to within 5% of pre-soak baseline without a restart, and a controlled restart does not change the slope. If restart fixes it, you have an unresolved leak: file it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Capacity-plan a third-party dependency with a hard quota.

Answer

Assumptions I'd state before sizing anything: the quota is metered per credential (one API key or tenant), it is a hard cap that returns 429 once exceeded, it resets on a fixed window, and every service in our fleet shares that one credential. If any of those is false (per-endpoint quotas, soft limits with overage billing, per-tenant keys) the plan changes, so I'd confirm them first.

The answer. Treat the quota as a fixed capacity budget, not a rate limit to tune. Convert it into the unit the vendor meters, subtract the fan-out and retries that actually consume it, carve out a reserved slice for critical paths, and put a local token bucket in front of every caller so the dependency never sees more than the budget. When the budget runs out, shed low-priority work locally instead of letting the vendor 429 you.

Sizing it. GitHub's REST API allows 5,000 authenticated requests per hour: 1.39 req/s averaged. Suppose a nightly reconciliation fans out one request per repo across 4,000 repos. That is 4,000 of the 5,000 hourly budget in one burst, 80%. Retries at 3 attempts on a 5% failure rate add 4,000 × 0.05 × 2 ≈ 400 more. Now 4,400 of 5,000 is gone, leaving 600/hr: 0.17 req/s: for interactive traffic for the rest of the hour. That number, not the headline 5,000, is what decides whether you need a second credential, a cache, or a schedule change.

Mechanism. A token bucket sized to the reserved interactive budget (capacity 600, refill 600/3600 = 0.167 tokens/s) makes the local limit the binding constraint. Callers block or shed at the bucket, so the vendor's counter never reaches its ceiling and interactive requests never see a 429 caused by batch work. A bounded queue behind the bucket caps memory and converts overload into a fast rejection instead of unbounded latency growth.

Options.

ApproachDeciding criterionWrong when
Cache / batchData tolerates staleness; work is deferrableCaller needs fresh state (payment status, inventory)
Second credential / tenantVendor meters per key and policy allows itVendor meters per account: it buys nothing
Queue + admission controlCallers tolerate added latencySynchronous user-facing path with a tight SLO
Negotiated increaseSustained demand exceeds budgetSpike is transient; you pay for headroom you don't use

Failure modes and detection.

  • Quota exhaustion mid-burst. Detection: 429 rate and a remaining-quota gauge crossing 20% of the window. Cost: interactive requests fail while batch work holds the budget.
  • Retry amplification. Retries consume the same budget as the original call. Detection: retries/requests ratio above 1.1. A 5% failure rate with 3 attempts turns 4,000 calls into 4,400.
  • Window misalignment. Local and vendor windows reset at different instants, so a burst at the boundary double-spends. Detection: 429s clustered in the first seconds of a window.
  • Silent staleness. Fallback serves cached data past its useful life. Detection: age-of-served-data metric, not error rate. Errors stay at zero.

When this is wrong. If the vendor bills overage instead of hard-failing, admission control costs you throughput for no reason; budget for the overage instead. If the dependency is on the critical path with no fallback, the right move is a negotiated quota and a contractual SLA, not a queue.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Run a capacity test with one zone unavailable.

Answer

The 90-second answer

First I'd pin down what "one zone unavailable" is meant to prove, because two different tests hide behind that phrase: proving the surviving zones can carry full peak (N+1 headroom), or proving the failover path itself works. I'd assume a 3-AZ deployment with even spread, peak 30k rps, and each zone provisioned for 15k rps: the classic N+1 where any two zones cover 100% of peak. Steady state each zone carries 10k; lose one and the survivors jump to 15k each, which is exactly their provisioned ceiling. That knife edge is the point of the test.

I'd run it progressively first: drain one zone's traffic in steps (25/50/75/100%) rather than hard-killing it, because progressive removal shows the utilization at which latency bends and it's reversible. A hard kill is the more faithful test (simultaneous connection loss, mass reconnection) but it's the one that can cascade, so I'd save it for a game day with a rollback trigger.

Why the survivors bite

The interesting failures aren't the load, they're the second-order effects:

  • Cache coldness. The dead zone's cache held a slice of the keyspace. Survivors now miss on those keys and hit origin. A hit rate dropping from 90% to 70% can roughly triple origin QPS. Watch cache hit ratio and origin QPS, not just app latency.
  • Connection churn. Killing a zone drops every TCP connection it held. Clients reconnect at once. With exponential backoff and jitter this spreads over seconds; without it you get a retry storm that looks like a traffic spike larger than the zone you lost. Watch SYN rate and retry counters.
  • Quorum. If the datastore is 3 replicas, one per AZ, quorum writes (2 of 3) still succeed after one loss, but with zero fault tolerance left, and commit latency rises because the surviving two are now the entire quorum. Watch write latency and leader-election events.
  • Autoscaling lag. HPA/ASG takes 1–3 minutes to add capacity; the spike arrives in seconds. Watch pending pods and scale-up events against the latency curve.

Failure modes and how I'd catch them

failuresignalcost
retry storm5xx and retry counter climb, p99 uporigin saturation
cascadingthread pools saturate, health checks faila second zone drops
quorum losswrite errors, election churnwrites unavailable
scale-down dipreplicas fall while restored zone warmscapacity dip on recovery

Restore

Bringing the zone back is its own risk: the autoscaler sees low utilization on the two survivors and scales them down while the restored zone is still cold. I'd pin minimum capacity through recovery, verify backlog drains and caches warm, then release scale-down slowly.

What I'd change

If I can't safely reach full peak, I'd test at the highest load I can and label the extrapolation, but flag that nonlinear effects (pool saturation, retries) make that extrapolation optimistic, not conservative.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Test autoscaling for a sudden traffic spike.

Answer

Pin down first

  • Spike shape: a step to 7x in 10 seconds, or a ramp over 5 minutes? Open-loop offered rate, or closed-loop concurrency?
  • Which SLO breaks first: p99 crossing 500 ms, or 5xx above 0.1%?
  • Which autoscaler: HPA on CPU, KEDA on queue depth, a cloud target-tracking policy? Does scale-up need new nodes?
  • Assumption I say out loud: Kubernetes, HPA on CPU, one Deployment behind an ALB, CPU requests set, metrics-server running, pods taking 20-30 s to become ready.

The answer

The test is not whether the HPA fires. It is: how long is the wall-clock gap between offered load and achieved capacity, and what absorbs requests during it. My hypothesis: a 3-6 minute gap is dominated by node provisioning, image pull and readiness, not by the HPA's 15 s loop, so tuning targetCPUUtilizationPercentage rarely fixes it.

The gap budget

StageFloor set byExample measured
Metric visibilitymetrics-server --metric-resolution (60 s default; several published manifests pin 15 s)15-60 s
HPA decisionsync period 15 s; 0.1 tolerance ignores +/-10% of target30-75 s cumulative
Scale-up to Pendinginstant, the HPA writes the ReplicaSet~0 s
Node provisioningcluster-autoscaler --scan-interval=10 s, then bootstrap and join90-180 s managed node group, 50-70 s Karpenter
Image pull and starta 400 MB image at 40 MB/s is 10 s; 20 cold pulls contend10-60 s
ReadinessperiodSeconds=10, failureThreshold=3, so up to 30 s after the process is up10-30 s
Endpoint and LBkube-proxy sync up to 30 s; ALB 30 s interval x 5 healthy = up to 150 s30-150 s

Sum: 2-6 minutes end to end, of which the HPA's own loop is under 75 s.

How I run it

Open-loop, so the offered rate does not collapse when the server slows; a closed-loop tool like ab ends up measuring itself.

JavaScript
// checked against k6 v0.49
import http from 'k6/http';
export const options = {
  discardResponseBodies: true,
  scenarios: {
    spike: {
      executor: 'ramping-arrival-rate',
      startRate: 200, timeUnit: '1s',
      preAllocatedVUs: 4000, maxVUs: 8000,
      stages: [
        { target: 200,  duration: '5m'  },  // baseline: record ready replicas, p99
        { target: 1500, duration: '10s' },  // step to 7.5x
        { target: 1500, duration: '15m' },  // hold past the gap and the 300 s scale-down window
        { target: 200,  duration: '5m'  },  // release: watch scale-down
      ],
    },
  },
};
export default function () { http.get(__ENV.TARGET); }

k6 run -e TARGET=https://api.example.com spike.js

The 15-minute hold is the part people skip: a 10-second smoke test cannot see a 3-minute gap, and the HPA's default scale-down stabilizationWindowSeconds is 300 s.

One run, timed (example figures, metrics-server at 15 s)

  • 0:00 step 200 -> 1500 req/s on six pods; p99 40 ms -> 260 ms.
  • 0:30 HPA evaluates fresh metrics, 88% against an 80% target: 6 -> 12 replicas.
  • 0:40 twelve pods Pending, no node capacity; 2.1% of requests are 5xx.
  • 2:10 node Ready after ~90 s; pulls start. 2:35 containers running.
  • 3:05 readiness passes, Endpoints updated.
  • 3:25 new pods carry traffic, p99 back under 60 ms.

Gap: 3 min 25 s of degraded service from a 10-second step.

Failure modes, with detection

  • HPA idle: ScalingActive=False, message missing request for cpu, when CPU requests are unset. Read Conditions every run.
  • Metrics starvation: a sub-45 s spike is invisible at --metric-resolution=60s. Compare the metric timestamp to the spike start.
  • Pending forever: subnet IP exhaustion (a /24 is roughly 250 pod IPs), pod-count quota, or a node pool the autoscaler cannot grow. Read Pending events.
  • Startup storm: 12 cold pods x 20 connections is 240 against a database sized for 60. Startup latency rises with replica count.
  • Flapping down: after the 300 s window the default policy can drop to minReplicas in one step, utilization spikes, HPA scales back up. Watch replica count after release.

Repeat cold (roll the Deployment first) and with one zone's nodes killed mid-spike.

What the numbers buy: at 1500 req/s, 205 s of gap is roughly 300k degraded requests. Keep baseline at 40% of node capacity so a 2.5x spike needs no new nodes; pre-scale for known events; hold pause pods at a lower priority class so the HPA displaces them in seconds; or shed at the edge with 429 plus Retry-After. Raising the CPU target to 60% buys one 15 s step and does not touch the 90 s node or 30 s probe tail.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Test retry behavior under overload.

Answer

When I test retry behavior under overload, I want to answer three questions: does retry amplify load, do the budgets hold, and does the system recover? I assume the service under test calls a dependency that I can slow down or make fail, and that I can hold the external arrival rate constant. I also assume the retries are for idempotent operations, if they're not, the test is about duplication, not amplification.

The test has three phases. Baseline: measure original attempts, latency, and error rate with retries disabled. Overload: inject a controlled fault (say, add 500ms latency and return 503 for 50% of requests) while holding arrival rate at 1000 RPS. Recovery: remove the fault and measure how long until latency and error rate return to baseline. Throughout, instrument original attempts and retries separately with reason, client, deadline, and correlation ID. The key metric is amplification factor: total attempts divided by original attempts. You also want queue age at the dependency, useful completions (successful responses), and retry budget consumption.

Typical retry defaults you'll see: exponential backoff with base 2, initial delay 100ms, full jitter, max 3 attempts, total deadline 2s, and a shared retry budget of 10% of original requests. For example, with 1000 RPS and a 50% failure rate, without a budget you'd get 1000 original + 500 first retries + 250 second + 125 third = 1875 total attempts, a 1.875x amplification. With a 10% budget (100 retries/s), you cap retries at 100/s, so total attempts = 1100/s, amplification 1.1x. But then only 50 of those 100 retries succeed (if 50% success), so useful completions = 500 original successes + 50 retry successes = 550/s. The other 450/s fail without retry. That's the trade-off: budget protects the dependency but drops requests.

You could retry at the client, at the proxy (Envoy, nginx), or via a queue. Client retries give per-request control and can use the request's deadline, but they amplify. Proxy retries centralize policy and can shed load, but they don't know idempotency unless you configure it. Queueing decouples and smooths, but adds latency and complexity. I'd choose client retries with a budget for idempotent, latency-sensitive calls; for non-idempotent calls, I wouldn't retry automatically: I'd return an error and let the caller decide. When not to retry: if the deadline is already exceeded, if the error is 4xx (except 429), or if the retry budget is exhausted.

Concrete failure modes: retry storm. Amplification > 5x, detected by a spike in total attempts while original attempts stay flat. Thundering herd: synchronized retries from many clients, detected by a spike in retries at fixed intervals; jitter fixes this. Budget exhaustion: fresh requests start failing because retry traffic consumes capacity; detected by a rise in 503s for original attempts. Deadline exceeded: retries continue after the caller has given up; detected by retries with expired deadlines. Non-idempotent duplication: detected by duplicate side effects. To detect, you need metrics: retry rate, amplification, queue age, error rate by reason. For example, if p99 latency goes from 40ms to 180ms once the connection pool saturates at 20 connections, that's a sign retries are filling the pool.

Here's a table of parameters to verify:

ParameterTypical defaultWhat to test
BackoffExponential, base 2Does it double?
Initial delay100msDoes it start at 100ms?
JitterFull jitterAre retries spread?
Max attempts3Does it stop at 3?
Total deadline2sDoes it abort?
Retry budget10% of original RPSDoes it cap?
Retry-AfterHonored for 429Does it wait?

And a trace of a single request with 3 attempts, 100ms initial delay, full jitter: t=0 send; t=100ms timeout, schedule retry with delay = random(0, 100ms) = 50ms; t=150ms send; t=250ms timeout, schedule retry with delay = random(0, 200ms) = 120ms; t=370ms send; t=470ms success. Total time 470ms, 3 attempts.

Finally, abort before harm: if amplification exceeds 3x or queue age exceeds 5s, stop the test. Then tune admission control and retry budgets so retry traffic cannot consume the capacity needed for fresh or recovery work.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Validate graceful degradation and load shedding.

Answer

Core answer

"Validate" here means proving three things under overload: the critical path stays inside SLO, everything else sheds with an explicit signal, and recovery doesn't cause a second incident. You can't validate that without a written overload policy, so the first deliverable is the policy, not the test.

Assumptions I'd state up front: one shared scarce resource (say a 200-connection Postgres pool), a p99 latency SLO of 300 ms on the critical path, multi-tenant traffic, and clients that can retry. If clients can't retry, shedding is the wrong lever: you need queueing or degraded responses instead.

How the shed decision is computed

Two limits, both enforced before the scarce resource:

  1. Concurrency limit. Little's law gives the ceiling: with 200 connections and 300 ms service time, throughput tops out at 200 / 0.3 ≈ 666 rps. Set admission below that, 600 rps, so the pool never saturates and latency stays flat instead of going vertical.
  2. Weighted token bucket per tenant. Refill 100 tokens/s, burst 200. Each request class costs tokens: critical 1, optional 5, expensive 20. When the bucket is empty the request gets 429 with Retry-After, not a queue slot.

The weighting is the point: it makes "shed optional first" a computed outcome rather than a hope. An expensive request consumes 20× the budget of a critical one, so it's the first to fail when the bucket drains.

Trace (hypothetical numbers)

Bucket capacity 200, refill 100/s.

  • t=0.000: bucket=200. Ten expensive requests arrive, 20 tokens each = 200. All admitted, bucket=0.
  • t=0.100: refill 10, bucket=10. One optional (5) admitted → bucket=5. One expensive (20) → 429, bucket stays 5.
  • t=0.200: refill 10, bucket=15. One optional (5) → bucket=10. One critical (1) → bucket=9.

Same arrival mix, but expensive work sheds at t=0.1s while critical work still passes at t=0.2s. That ordering is the property you're validating.

Trade-offs

strategywhen it winswhen it's wrong
reject at admissioncheap, fast, client can retryclient retries are expensive or non-idempotent
bounded queue + deadlineshort bursts, latency-tolerant callersdeadline not propagated → work runs after the caller gave up
degraded response (stale cache, partial result)read paths where staleness is acceptablecorrectness-critical writes; stale reads cause a cache stampede on recovery

Aggressive shedding is wrong when the load is a retry storm: 429s make clients retry harder and you amplify. Fix the client's retry budget first (gRPC retry throttling, Envoy's retry budget) before tightening admission.

Failure modes to test for

  • Retry wave on recovery. After load drops, every shed client retries at once. Detect via a request-rate spike post-recovery; mitigate with jittered Retry-After and a ramp on the admission limit.
  • Feature-flap oscillation. Shedding toggles on and off every few seconds. Needs hysteresis: shed at 90% of budget, restore at 60%.
  • Starved health/control paths. If health checks share the admission budget, the orchestrator kills pods mid-incident. Give them a reserved lane.
  • Fairness collapse. One tenant drains the shared bucket. Per-tenant buckets, verified by running one tenant at 10× the others.

Restoration

Validate the reverse order: restore optional work last, drain the backlog at a bounded rate, confirm no retry wave. Watch p99 of admitted requests and shed rate together, if p99 rises while shed rate falls, you restored too fast.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Evaluate whether caching improved useful capacity.

Answer

Core answer (first 90 seconds). Caching improved useful capacity only if the origin work removed per unit of user-visible throughput exceeds the work the cache adds, and you measure that at equal attempted load, not by hit ratio. So fix the workload: same request mix, same arrival rate, same correctness bar. Run it cache-off and cache-on, and compare origin demand and objective-compliant throughput. Hit ratio is a diagnostic, not the answer.

Why hit ratio lies. Origin relief ≈ 1 − (miss rate × miss cost relative to an uncached request). When the misses are the expensive requests, relief collapses.

Hypothetical arithmetic: 10,000 rps attempted, 90% hit ratio, so 1,000 origin requests. If each miss fans out to 8 shards, origin work is 8,000 baseline-equivalents against 10,000 uncached: 20% relief, not 90%. If misses are cheap single-key reads, relief is close to 90%. Same hit ratio, opposite conclusion.

What to measure.

metriccache offcache onwhat it decides
origin CPU-seconds per 1k user requestsreal relief
p99 latencyuser-visible gain
hit ratio by classn/awhich keys carry it
eviction rateworking set vs memory
origin fills per miss (fill amplification)load the cache adds

Named signals: Redis INFO stats (keyspace_hits, keyspace_misses, evicted_keys), memcached get_hits/get_misses/evictions, nginx $upstream_cache_status, Envoy's cache filter stats.

Failure modes, with detection.

  • Stampede. Synchronized TTL expiry produces a miss burst at the TTL boundary and an origin QPS spike. Detect it as a step in miss rate at TTL multiples plus rising origin queue depth. Mitigate with TTL jitter, request coalescing (nginx proxy_cache_lock, Go singleflight), or stale-while-revalidate.
  • Node loss. With modulo sharding, losing 1 of 10 nodes remaps ~90% of keys; consistent hashing remaps ~1/10. Detect a hit-ratio cliff and origin surge within seconds of a node dropping. Mitigate with consistent hashing, replication, and coalescing.

Trade-offs, and when caching is not capacity. Write-heavy or low-reuse workloads, hit ratio below roughly 50% with a high fill cost, buy memory, invalidation and fill load for little relief. Personalized data that must bypass the cache never helps the hot path. Correctness-critical reads (inventory, balances) may not tolerate staleness, so the throughput gained is not usable. Alternatives that can beat caching: read replicas, materialized or precomputed views, CDN edge for static assets, or request coalescing on its own.

Close. Name which journeys gained sustainable objective-compliant throughput, and what new constraint became limiting: often the origin's miss path or the invalidation pipeline, not the cache itself.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Create performance regression gates for CI.

Answer

The 90-second answer

A perf gate is a statistical test, not a stopwatch reading. Pick two or three operations that are both hot and deterministic (a serialization path, a query-planner call, an HTTP handler on a seeded dataset) pin them to a fixed runner image, and compare the candidate against a stored baseline with a tolerance band. Fail on a metric that maps to a user-visible SLO (p99 latency, throughput, allocations per request), and assert the output is unchanged, because a 40% speedup that returns wrong bytes is a regression. Anything heavier than about five minutes moves to nightly.

What the gate actually runs

  • Workload: fixed seed, fixed dataset (say 1M rows), fixed concurrency, dependency mode pinned. An in-process fake or a container at a pinned image digest, never a shared staging database.
  • Warm-up: JIT and page cache dominate the first seconds. A JVM method goes interpreted → C1 → C2 over the first few thousand invocations, so early iterations can be several times slower than steady state. Criterion.rs defaults to 3 s warm-up and 5 s measurement over 100 samples; a JMH-style harness wants at least 5 warm-up iterations before measurement starts.
  • Statistics: compare distributions, not single runs. Criterion bootstraps the two samples and reports the change with a 95% confidence interval; fail when the interval excludes zero and the point estimate is worse than your tolerance. A single before/after pair on a shared runner flips on noise alone.

Sizing the run

To detect a 5% regression when the metric's run-to-run CV is 2%, per-group n = 2(z₀.₉₇₅ + z₀.₈₀)²(CV/Δ)² = 2(1.96 + 0.84)²(0.02/0.05)² ≈ 2.5, so 3 runs per side. If the runner's CV is 8%, ordinary for a shared cloud VM, the same formula gives n ≈ 40. That is the whole argument for dedicated runners: noise is a sample-size tax.

tierwhenbudgetgate
PR smokeevery push≤ 5 minmicro-benchmark on 2–3 ops; fail on > 5% p50 regression or any correctness diff
Nightly integrationnightly30–60 mink6/vegeta against a seeded service; fail if p99 > 120 ms or > 10% over baseline
Weekly soakweekly8–24 hfail if RSS grows > 5% over 8 h, or FD/connection count climbs monotonically

Failure modes and how I'd catch them

  • Flaky gate blocks merges. Track the rerun-pass rate: if a gate fails and passes on rerun with no code change more than ~2% of runs, it is noise, not a regression. The cost is real: a gate that blocks 1 in 20 merges gets continue-on-error'd within a month and stops existing.
  • Threshold ratchet. Every "just bump it" hides a real regression. Log each threshold change in the repo with a linked issue; if thresholds move more than once a quarter, the gate is decorative.
  • Baseline drift. Comparing a run on a new runner class or a bumped dependency against an old baseline manufactures a regression. Store runner image digest, CPU model and lockfile hash with every result and refuse to compare across a mismatch.
  • Noisy neighbours. Run a fixed canary workload (a known CPU-bound loop) alongside the benchmark; if the canary's own time varies more than 3%, discard the run rather than loosen the threshold.

What it doesn't do: a CI gate detects scoped regressions on the operations you chose. It does not certify production capacity: that is a load test against production-shaped traffic, and a different question.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Capacity-plan a service before a major product launch.

Answer

Assumptions I'd state first: single region, read-heavy API, autoscaling on CPU with a measured ~3-minute scale-out lag, and a launch that is a marketing spike rather than a slow ramp. If any of those is wrong the plan changes, so I'd confirm them before sizing anything.

The answer: size to the high scenario using measured per-instance capacity, pre-scale ahead of the spike, and keep a degradation lever for traffic you can't serve. Don't size to the base case and trust autoscaling to close the gap: the gap arrives faster than the scaler does.

How I get the number. I load-test one instance to find where p99 breaks, not where CPU maxes. Say one instance holds 800 rps at p99 200 ms with CPU at 60%, and past that p99 climbs steeply (hypothetical figures). Current peak is 4,000 rps. The launch forecast is 3x peak, so 12,000 rps. 12,000 / 800 = 15 instances to serve it, and I add 30% because a spike front-loads: 20 instances. Autoscaling needs ~3 minutes to add capacity (boot plus warmup), so I pre-scale to 20 at T-30 min and let the scaler hold it there.

scenariopeak rpsinstances @ 800 rpsaction
base, no launch4,0005steady state
launch base8,00010autoscale
launch high12,00015, +30% = 20pre-scale at T-30
60s spike at 2x high24,00030shed + queue

Trade-offs. Three levers: overprovision, autoscale, degrade. Overprovisioning to 30 instances burns idle money but removes the lag risk entirely. Autoscaling is cheap but the 3-minute lag means the first minutes of a spike hit a saturated fleet. Degradation (serving cached responses, dropping recommendations) keeps the critical path alive when neither of the others is fast enough. The deciding criterion is what a failed launch costs versus what idle capacity costs for a few hours. For a revenue launch I'd overprovision and pre-scale; for a low-stakes one I'd lean on autoscaling and accept the lag.

Failure modes and how I'd see them.

  • Cache cold start: first requests after deploy miss, DB load spikes. Detect via cache hit-ratio and DB connection count. Mitigate by warming the cache before opening traffic.
  • Connection pool exhaustion: a pool of 20 saturates and p99 goes 40 ms → 180 ms. Detect via pool wait-time, not CPU: CPU can look fine while requests queue.
  • Retry storm: a dependency slows, clients retry, load doubles. Detect by reading retry rate and dependency error rate together. Mitigate with capped retries, jitter, and a circuit breaker.
  • Quota exhaustion: a third-party API quota is hit mid-spike. Detect via the vendor's 429 rate. Mitigate by raising the quota in advance and caching responses.

Launch day. Dashboards for rps, p99, error rate, pool wait, cache hit ratio, and dependency 429s, each with a trigger threshold tied to the numbers above and a named owner. Abort lever: a feature flag that turns off the launch surface, plus a config rollback.

Residual risk. After testing I compare measured headroom to the high scenario. If tested capacity is worth 18 instances and high needs 20, that gap is documented and drives the go/no-go call.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Turn a failed load test into an engineering plan.

Answer

Assumptions I'd state before planning. Four pods, each with a Postgres 16 connection pool capped at 5, query p99 around 25 ms, SLO p99 ≤ 300 ms at the 1,200 rps forecast peak, and a 30-minute ramp test. If the pool cap or pod count is wrong the plan changes, so I say them first.

The plan is four moves: freeze the run, find the first objective that broke and the resource that saturated, do the arithmetic that shows the ceiling, then pick remediation by cost per recovered rps and re-run the identical scenario.

Freeze the run. App commit, Postgres version, pool library version, exact load profile, raw percentile time series, pod count. Without the profile you can't reproduce it; without the pod count you can't tell a capacity failure from a scaling failure.

Find the first break. Not the worst number: the first objective to fail, and at what offered load.

metric400 rps600 rps750 rpsSLO
p50 latency28 ms45 ms190 ms—
p99 latency55 ms115 ms380 ms≤ 300 ms
pool wait p9926 ms77 ms355 ms—
query time p9924 ms25 ms25 ms—

Three runs gave p99 360–410 ms at 750 rps, so the breach is real, not noise. The first failure is p99, between 600 and 750 rps.

Do the arithmetic. Query time p99 stayed flat at 25 ms while pool wait exploded. The database isn't slow; the pool is saturated. Little's law: one connection serves 1/0.025 = 40 rps, so 5 connections cap a pod at 200 rps, and four pods cap the cluster at 800 rps. At 750 rps offered, cluster utilization is 750/800 = 0.94: per pod, 187.5/200 = 0.94. Below 1.0, so the queue is stable, but at 0.94 the M/M/c wait tail is long: p99 pool wait 355 ms, which plus 25 ms query time breaches the 300 ms SLO. Correlation alone wouldn't show that; flat query time plus rising wait time separates cause from symptom. The gap to the 1,200 rps target is 400 rps, and at 10% monthly growth from 750 rps the ceiling is crossed in about three weeks.

Choose the work. Four families, deciding criterion for each:

optionwhen it winscost / when not
raise pool to 20/podDB max_connections allows4 × 20 = 80, under the 100 shared limit, but 4× the concurrent DB load
cache the read pathhit rate > 80%staleness budget; useless on write-heavy mixes
admission control + shedprotects p99 for admitted trafficdrops requests; needs a client-visible 429 contract
HPA on pool-wait, not CPUCPU lags saturationneeds the metric exported; risk of flapping

For this run I'd take pool 20/pod plus HPA on pool wait, because the pool cap is the constraint and CPU never crossed 55%.

Failure modes to watch. Connection leak: pool exhausted with idle-in-transaction sessions; detect via pg_stat_activity state counts. Retry storm: clients retrying 429s amplify load; detect via request rate exceeding offered rate. HPA flapping: detect via replica count oscillation.

Verify. Re-run the identical scenario, then adjacent mixes (90/10 and 70/30 read/write), then a recovery test: kill a pod mid-run and confirm p99 returns under 300 ms within 60 s. Update the capacity model with the new per-pod ceiling and set the alert at 70% of it.

Curated: · Written: · Reviewed:

Difficulty: Hard