Experimentation and Validation Questions
Deciding what to test and how to learn it cheaply before committing product investment: identifying the riskiest assumption, writing a falsifiable hypothesis, choosing between a prototype, fake door, concierge test, pilot, beta or live experiment, sequencing validation steps and budgeting effort across assumptions, setting go/no-go criteria and rollback triggers in advance, and combining qualitative and quantitative evidence, including when they disagree. Covers pilot design (participants, comparison group, guardrails, threats to validity), offline checks of a model idea before small online trials, limited trials of vendors or architectures, and validating demand under thin data or privacy limits. Assesses hypothesis-driven product development and evidence-based decisions, including validation of technical and operational bets. Excludes the statistical design of a single online test, interpreting finished experiment results, experimentation platform engineering, user research methods, ordering tests across a program, and non-randomized causal inference.
Your team wants to migrate 50 internal services from REST/JSON to gRPC to cut latency. What is the cheapest credible test of whether the migration is worth it, which result would stop it, and how would you estimate the return?
Sample Answer
The idea in plain words
REST/JSON means services call each other over HTTP and send text (JSON). gRPC is a remote-call framework that runs over HTTP/2 and by default sends a compact binary format (Protocol Buffers). The claim is that switching 50 services will cut latency. The cheapest credible test is not a benchmark of gRPC; it is a measurement of how much of today's latency the protocol can change at all: serialization (turning objects into bytes and back) and wire overhead such as connection setup, headers and the time to move the bytes (a compact encoding sends fewer of them). If that share is small, no protocol can remove more than that share, however fast it is. Only if the share is large does it pay to build a proof of concept (POC) on one real service pair, and only if the POC and the cost model both clear pre-agreed bars does the migration go ahead.
Step 1: find where the time goes (about two days, no new code)
From the existing distributed traces (records of each request's path and timings), take the top call paths and split the time of each hop into network, encode and decode, handler compute, and waiting on downstream systems such as a database. Assumed medians per hop for three representative paths (the numbers are inputs for the example, not facts about any system):
| Path | Time per hop | Of which encode and decode | Share |
|---|---|---|---|
| Small lookups | 12 ms | 0.4 ms | 0.4 / 12 = 3.3% |
| Typical service calls | 30 ms | 1.2 ms | 1.2 / 30 = 4.0% |
| Payload-heavy (about 150 KB JSON) | 40 ms | 9.0 ms | 9 / 40 = 22.5% |
Stop rule for this step: if the encode and decode share, plus any connection-setup and header time you can see in the network part of the traces, plus the byte-transfer time a smaller payload would save, is under 10% on every path that matters, the migration cannot buy much latency, so stop here. In this example connections are reused, so the network part holds no setup cost, and the services share a data-centre link where moving 150 KB takes about 0.12 ms at 10 Gbit/s (150000×8/1010 seconds), so the encode and decode share is the whole protocol share. Across regions or on slow links, transfer time can be a large part of the path and must be counted. Two of the three paths fall below 10%, and the third does not. So the plan narrows from "50 services" to "the services on payload-heavy paths". Assume 6 of the 50 services sit on such paths.
Step 2: the proof of concept on one real pair
Pick one caller and callee from the payload-heavy path and implement the same endpoint in gRPC beside the existing one, with the same business logic. About one engineer for five working days (an assumed estimate).
Hold these equal, or the comparison is not fair. (Terms in the table: TLS is the encryption layer on a connection; a connection pool is a set of already-open connections reused across requests, because opening a new one costs time; keep-alive in HTTP/1.1 keeps one connection open for several requests, while HTTP/2 multiplexing sends many requests at once over one connection; a stubbed callee is a fake downstream service that just waits a fixed time and returns.)
| Item | How |
|---|---|
| Hardware and environment | Same instance types, same region, same resource limits, same runtime version |
| Payloads | Replay one sampled corpus of real requests (identifiers removed) through both versions, covering the median and the largest payloads |
| Compression | Same setting on both sides: if JSON is compressed in production, compress it in the test |
| Connections and security | Same TLS setting, comparable connection reuse and pool sizes (HTTP/1.1 keep-alive against HTTP/2 multiplexing) |
| Downstream | First run with a stubbed callee that waits a fixed time, to isolate protocol cost; second run end to end |
| Load | An open-loop generator that sends requests at a fixed rate regardless of how fast replies come back. A closed-loop generator that waits for each reply slows down when the server does and hides the tail |
| Warm-up and order | Discard the first minutes (runtime warm-up, caches); run in alternating order (REST, gRPC, gRPC, REST) over at least five repeats to cancel drift |
Measure more than latency: latency at p50, p95 and p99 (the time 50%, 95%, 99% of requests finish within; the last is the tail latency), at 50%, 80% and 100% of production peak rate; throughput, meaning the highest request rate at which p99 stays under the latency target; CPU per 1,000 requests; memory use; and bytes on the wire. Throughput and CPU matter because a protocol can leave latency unchanged and still free capacity, which is money.
Present it on one page: the question, what was held equal, one table with the median and range over the repeats for each metric, the decision against the stop rules below, and the caveats (one service pair, one payload shape, a test environment).
Step 3: results that stop it
Agree these before running:
- The protocol share (encode and decode, plus connection and header overhead) under 10% of path time on every path that matters (Step 1).
- At equal load, the POC improves p99 by less than 10% and CPU per 1,000 requests by less than 10%.
- Payback, computed from the POC's measured savings, is longer than the organisation's hurdle (the maximum payback period, or the minimum return, that an investment must meet to be approved; see Step 4).
(Ten percent is an illustrative cut-off for this example; the right number is the smallest improvement that pays for the work.)
Step 4: estimate the return
payback (years)=yearly CPU saving+yearly value of latency savedmigration costAll inputs are assumptions with the ranges that would need checking: engineer time 3 engineer-weeks per service (range 1 to 8); loaded cost 4,000 dollars per engineer-week (salary plus benefits and overhead, not salary alone); 20% extra for running both versions during cut-over, schema management and tooling; 400 dollars per core-year of compute (range 200 to 800).
Option A: migrate all 50. Cost: 50×3×4000=600,000, plus 20% gives 720,000 dollars. Suppose the 50 services use 2,000 cores, 15% of that CPU is encode and decode, and gRPC cuts it by 60%: 2000×0.15×0.6=180 cores, or 180×400=72,000 dollars a year. Payback: 720000/72000=10 years. This counts only the CPU saving because on the two lighter paths from Step 1 encode and decode is only 3.3% to 4.0% of hop time, so a 60% cut saves under 1 ms per hop (for example 0.6 x 1.2 = 0.72 ms of a 30 ms hop), worth very little. Even if the full 16,200 dollars of latency value from option B were added to A, payback would be 720000/(72000+16200)≈8.2 years, which still fails.
Option B: migrate the 6 payload-heavy services. Cost: 6×3×4000=72,000, plus 20% gives 86,400 dollars. Suppose those 6 use 300 cores, 30% of it is encode and decode, and the cut is 60%: 300×0.3×0.6=54 cores, or 54×400=21,600 dollars a year. Latency: if the POC shows the 9 ms encode and decode falling by the same 60%, to 3.6 ms, each hop saves 5.4 ms, which is 13.5% of the 40 ms hop; over 3 such hops that is 16.2 ms. Convert it to money only with a sensitivity (how much the outcome moves per unit of change in an input) measured in this product, for example from a past latency experiment, since slower pages make some visitors give up before they finish: assume 0.5% conversion gained per 100 ms and 20,000,000 dollars a year of revenue through the path, so (16.2/100)×0.005×20,000,000=16,200 dollars. Return: 21600+16200=37,800 a year. Payback: 86400/37800≈2.3 years.
Against a 3-year hurdle (an assumed stand-in for whatever bar the organisation uses), option A fails and option B passes. As a sensitivity check, if only half of that return materialises (18,900 dollars a year), payback is 86400/18900≈4.6 years and B fails the hurdle. So B is a conditional pass: the POC's measured CPU and latency savings, not these assumed ones, decide it. Costs not in the formula: debugging is harder with binary payloads, browsers and outside clients cannot call gRPC directly without a gateway, and load balancers must handle HTTP/2. Benefits not counted: typed contracts and generated clients, and streaming.
What I would recommend
Do Step 1 first. Expect it to say "not 50 services". Run the POC on the one payload-heavy pair, and migrate only the paths where the share, the POC and the payback agree. What would flip it: a goal that is not latency (for example, enforcing typed contracts across teams), which changes what the migration is worth.
Common mistakes
- Benchmarking the protocols in isolation and extrapolating to production latency.
- Comparing uncompressed binary with uncompressed JSON when production compresses JSON, or the reverse.
- Reporting the average only: the claim is about tail latency.
- Closed-loop load and a single run, which hide queueing and noise.
- Counting CPU saved as money when the cluster cannot actually shrink by that amount.
Your team believes adding a cache will cut downstream latency by 20%. What is the minimal prototype you would build first, what baselines and measurements would you capture, and how would you decide whether to expand it?
Sample Answer
The idea in plain words
A cache keeps a copy of a recent answer close to the caller so the next identical request skips the slow call (the downstream call, meaning the other service or database the caller has to wait for). The belief "a cache will cut downstream latency by 20%" can be checked on paper before anything is built, because it reduces to one number: the hit ratio (the share of requests answered from the cache). The cheapest first step is to replay real request logs through a simulated cache, and only then build a minimal prototype behind a switch that turns it off instantly. The claim also needs a definition: 20% of the average, of the median, or of the 99th percentile (p99, the time within which 99% of requests finish)? These behave very differently. In an interview the expected core is turning the claim into a required hit ratio for the average and then checking it against real logs before building anything; the tail calculation is deeper material that shows you know averages and percentiles respond differently to a cache.
Step 1: turn the claim into a required hit ratio
Assume the downstream call averages 120 ms, a cache lookup costs 2 ms, and the cache is read-through (on a miss it does the lookup, then calls downstream, then stores the answer), so a miss costs 2 + 120 = 122 ms and a hit costs 2 ms. With hit ratio h the average latency is
L(h)=h×2+(1−h)×122=122−120hA 20% cut means L≤0.8×120=96 ms:
122−120h≤96⇒h≥12026≈0.217So the average-latency claim needs a hit ratio of at least about 21.7%. All numbers here are assumptions for the example (downstream mean 120 ms with a plausible range of 20 to 500 ms, lookup 1 to 5 ms).
For p99 the answer differs, and the reason is worth working through. A quantile is the value below which a given share of requests fall: the 0.99 quantile is p99, and the 0.975 quantile is p97.5. The traffic after the cache is a mixture, meaning one combined stream of fast hits and slow misses. Assume every hit is faster than every miss (true here: a hit costs about 2 ms, while a miss costs that lookup plus a downstream call that takes tens of milliseconds or more).
Take 1,000 requests with a hit ratio of 0.6: 600 hits and 400 misses. The 99th percentile of all 1,000 requests is the boundary of the slowest 1%, which is the slowest 10 requests. Every hit is faster than every miss, so those 10 slowest requests are all misses. Ten of the 400 misses is 2.5%, so the overall p99 equals the miss path's 97.5th percentile (the point with 2.5% of misses above it).
In general the slowest 1% of all requests is a share 0.01/m of the misses, where m=1−h is the miss share, so the overall p99 is the miss path's quantile at 1−0.01/m. At h=0.217, m=0.783 and the quantile is 1−0.01/0.783≈0.987, almost the same as the original p99, so p99 barely improves. At h=0.6, m=0.4 and the quantile is 1−0.01/0.4=0.975.
To turn a quantile into milliseconds you need the downstream's own latency distribution; in a real project you read the p97.5 and p99 off the baseline logs. Here they are assumed: downstream p99 of 300 ms and p97.5 of 240 ms (a tail about twice the 120 ms mean). The new p99 is the miss-path p97.5 plus the 2 ms lookup, about 240 + 2 = 242 ms, a cut of 1−242/300≈19%. The program below reproduces these numbers:
for h in (0.217, 0.6):
m = 1 - h # share of requests that miss
q = 1 - 0.01 / m # quantile of the miss path that becomes the overall p99
print(f"hit ratio {h}: miss share {m:.3f}, miss-path quantile {q:.3f}")
# the p99 example: downstream p97.5 = 240 ms, p99 = 300 ms (assumed), lookup 2 ms
new_p99 = 240 + 2
print("new p99 ms:", new_p99, "| cut:", round(1 - new_p99 / 300, 3))
Output:
hit ratio 0.217: miss share 0.783, miss-path quantile 0.987
hit ratio 0.6: miss share 0.400, miss-path quantile 0.975
new p99 ms: 242 | cut: 0.193
So a 20% claim about the tail needs a much higher hit ratio than the same claim about the average. Ask which one the team means before building.
Step 2: replay the logs before building (cheapest test)
Take a week of request logs (just the cache keys and timestamps) and run them through a simulator for a cache of the planned size, eviction rule (which stored item to throw out when the cache is full, for example LRU: least recently used items go first) and TTL (time-to-live, after which a cached item is considered too old to serve). Two outputs:
- An upper bound on the hit ratio. Even an infinite cache misses the first request for each key. If a week has 10,000,000 requests and 4,000,000 distinct keys (different values of the cache key, so 4,000,000 different things asked for; assumed), the bound is 1−4/10=60%.
- The simulated hit ratio for the real size and TTL, which is the number to carry forward. If it is below 21.7%, the average-latency claim fails on paper, and the prototype is not worth building as specified.
Also settle how stale an answer may be. A TTL of 60 seconds and a TTL of one hour give different hit ratios and different risk, so the owner of the data must state the tolerance.
Step 3: the minimal prototype
A read-through cache in the calling service (an in-process LRU map, which is a lookup table held in the caller's own memory that discards its least recently used entries when full, or one small shared cache instance) for the single highest-volume endpoint, keyed by the normalized request parameters (the request's parameters put in one canonical form, for example sorted and lower-cased, so that two requests asking for the same thing share a key), with a TTL and a size cap, behind a feature flag (a switch that turns the behaviour on or off at runtime without redeploying). No invalidation protocol beyond the TTL; no other endpoints.
Baselines to capture before turning it on, for at least seven days, by hour: p50, p95 and p99 latency of the call as the caller sees it; request rate; error rate; the share of traffic held by the most popular keys; payload size; and downstream cost per call.
Measurements once it is on: latency split by hit and miss, hit ratio over time, downstream call count, memory used by the cache, extra CPU in the caller, and a staleness check: on a 1% sample of hits, also call downstream and compare, to measure how often the cached answer differed.
Step 4: the production experiment
- Control and treatment. Randomize each request to "use the cache" or "bypass it", with both groups served at the same time by the same instances, so the time of day, deploys and traffic mix hit both equally. Start with a small share of traffic.
- A trap. At a small treated share, each key is seen less often by the treated group, so the hit ratio you measure understates what 100% of traffic would get. Use the replay from Step 2 to extrapolate to full traffic, instead of reading the partial-traffic ratio as final.
- Interference (one group's treatment changing the other group's results). Fewer downstream calls from the treated group may speed up the control group's downstream calls too, which would shrink the measured gap, so the measured difference may understate the benefit.
- Warm-up. A cache starts empty. Report the first minutes separately.
- Cost. Monthly downstream spend is calls times price. Assume 50,000,000 calls a month at 0.0004 dollars per call: 20,000 dollars. A hit ratio of 40% avoids 0.4×20000=8,000 dollars a month. If the cache costs 1,200 dollars a month (assumed), the net is 6,800 dollars, and cost alone breaks even at 1200/20000=6% hit ratio, far below the 21.7% the latency claim needs.
Success and rollback criteria
These are illustrations of the form; the real thresholds come from the service's own objectives, and a real process also needs on-call ownership and alerting wired to the rollback.
| Item | Rule |
|---|---|
| Expand | Treated mean latency at least 20% lower and p99 no more than 5% worse, for three days including a daily peak, with stale answers under the agreed tolerance and the error rate not higher |
| Roll back automatically | Error rate up by more than 0.1 points for 10 minutes, or p99 worse by more than 10% for 15 minutes, or cache memory above 85% of its limit |
Expansion goes in steps (for example 10%, 50%, 100% of traffic), re-checking each step, and other endpoints get their own replay first.
What I would recommend
Ask which latency the 20% refers to, run the replay, and build the prototype only if the simulated hit ratio clears the required one with room. The cache is justified by cost at a hit ratio as low as 6%, but the latency promise needs 21.7% for the average and a much higher hit ratio for the tail. What would flip it: data that must be fresh to the second, which caps the TTL and the hit ratio.
Common mistakes
- Measuring only the average when the objective is a tail percentile.
- Reading a hit ratio from a tiny traffic slice as the production figure.
- Comparing before and after a deploy instead of running control and treatment at the same time.
- Ignoring staleness until a user sees an old answer.
You need to decide between a monolith and a modular-service architecture but want to limit customer risk. How would you validate the choice with a limited trial before committing, and what evidence would settle it?
Sample Answer
The idea in plain words
A monolith is one program that is built, deployed and run as a single unit. A modular-service architecture splits it into separate programs that call each other over the network. Each shape is a bet on specific benefits (a bet here means a choice that only pays off if a stated benefit actually appears): independent deploys, independent scaling, fault isolation, team autonomy. Each also has costs: network calls add delay and failure points, and there is more to operate. Instead of arguing the choice in general, name the benefit you are betting on, split out one piece, serve a small share of real traffic from it with an instant way back, and compare agreed measures before and after. The evidence that settles it is delivery speed, reliability, latency and cost for that piece, measured against the monolith's own baseline.
Step 1: write the bet as a testable statement
For example: "Extracting the notifications module into its own service lets its team deploy at least twice as often, without a meaningful rise in the change failure rate, adding more than 20 ms at p99 (the time within which 99 percent of requests finish), or raising run cost by more than 30 percent. Here a meaningful rise means more than 2 points." All of these numbers are illustrative thresholds you would set with the team. If no one can name the benefit, that is itself the answer: stay with the monolith, perhaps organised into well-separated modules inside it (a modular monolith), which gives much of the structure at a fraction of the operating cost.
Step 2: choose the slice for the trial
Pick a part that has a narrow, well-defined interface (few callers), real traffic (so the numbers mean something), an owning team, and a modest blast radius if it fails (blast radius is how much of the product, and how many customers, are hurt when this one part breaks). Notifications, search indexing or report generation often fit; the payment path usually does not. The slice must own its data. If the new service still reads and writes the monolith's database tables, the boundary is fake and the trial hides the coupling it was meant to expose.
Step 3: limit customer risk while testing
- Contract tests (automated checks that the monolith and the service still agree on what each may send and expect back) that pin the interface between them.
- Shadow (dark) launch: the monolith still answers customers, while the same requests are also sent to the service and the answers and latency compared. Run until the mismatches are explained. The copy must have no customer-visible side effects: for a module that sends messages, charges cards or writes records customers can see, point the service at a stub that records what it would have done (or at internal test recipients), otherwise customers receive every message twice.
- Feature flag with instant rollback: a switch that sends traffic back to the code inside the monolith within minutes. Keep that code in place for the whole trial.
- Ramp by cohort (a cohort is a group of users moved over together): internal users first, then a small share of low-risk customers (for example 5 percent), then widen. Avoid customers with strict service agreements (written promises about uptime or response time) until the later stages.
- Time limit and stop rule fixed before the trial: a customer-visible incident traced to the boundary pauses the ramp, and the on-call engineer (whoever is responsible for responding to alerts out of hours) can trigger the rollback.
Step 4: the evidence that settles it
Compare the trial period (assume 8 weeks) with the same module's recent past:
| Measure | What it tells you | Illustrative pass mark |
|---|---|---|
| Deploys per week by the owning team | Independence | At least twice the baseline |
| Change failure rate (share of deploys that cause a rollback or incident) | Whether speed came with breakage | Not worse than baseline plus 2 points |
| p99 latency added by the new hop (one extra network call from one program to another) | Cost of the network | Within 20 ms |
| Availability of the affected feature (the share of time it works for users) | Cost of the extra dependency | Meets the feature's target (worked example follows) |
| Run cost (infrastructure plus on-call time) | Operating overhead | Within 30 percent of baseline |
| Incidents traced to the boundary | Hidden coupling | None that are customer-visible |
These marks are an illustration of the form. The bet written in Step 1 decides which measures lead: here deploys per week shows whether the benefit arrived, and availability and p99 latency show the price customers would feel; change failure rate, run cost and boundary incidents check for hidden costs. A real trial also covers security review, data consistency, the team's own view of the extra cognitive load (the mental effort of keeping several services and their interactions in your head) and who may declare the trial over.
Worked example: why availability and latency are measured, not assumed. Suppose the monolith meets 99.9 percent availability and the new service also 99.9 percent, with independent failures (one failing does not make the other more likely to fail), and every request needs both. Availability multiplies: 0.999×0.999=0.998001, about 99.80 percent. In a 30-day month (43,200 minutes) that allows (1−0.998001)×43,200≈86.4 minutes of downtime instead of 0.001×43,200=43.2 minutes. Timeouts, fallbacks (serve a degraded result if the service is slow) and retries are how a team claws that back, and the trial tests whether they work. For latency, assume 8 ms at p99 per call and two calls per request, in sequence: a rough estimate of 2×8=16 ms added, inside the 20 ms mark. (Percentiles do not add exactly. For well-behaved latencies the 99th percentile of the total is a little below the sum of the two, because the slowest 1 percent of calls rarely land on the same request. For heavy-tailed latencies, where an occasional call is very slow, the total can even exceed the sum, so the trial measures the added p99 end to end instead of relying on the sum.)
Caution about small samples. Assume the team deploys 1 a week before the trial, which is 8 deployments in 8 weeks, and 2 a week during it, which is 16. Suppose the baseline had 1 failed deploy in 8 (12.5 percent) and the trial has 1 in 16 (6.25 percent). The trial looks half as failure-prone, yet the difference is a single event, and one more failure in the trial would move its rate by 6.25 points, more than three times the 2-point margin in the pass mark (6.25/2≈3.1). So at this volume the rate cannot meet or miss that mark in any reliable way. Do not decide on the rate alone; read each failure and ask whether the boundary caused it.
What I would decide
My default is to stay a modular monolith and make the boundary real inside it first, which is cheap and reversible. Then run the trial for one slice where a concrete benefit is expected. Commit to the full split only if the pass marks are met and the team can describe the next two services it would extract and why. The answer flips toward services if one component needs very different scaling from the rest, if a compliance boundary requires isolation, or if teams are blocked by each other's release schedules. It flips toward the monolith if the added hop breaks the latency mark or the team spends its time on cross-service debugging.
Common mistakes
- Splitting the code but not the data.
- Choosing the most critical module for the trial, so a failure is expensive.
- Comparing against an imagined baseline instead of the module's recent history.
- Agreeing the pass marks after seeing results.
- Counting a handful of deploys or incidents as a rate.
That is every published Experimentation and Validation question for Software Engineer so far. Browse the other topics in this category, or practice this one interactively.