Skip to content
Tech Interview Prep

Top 100 Product Engineer Interview Questions and Answers

The questions most likely to come up in your Product Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.

Curated: · Written: · Reviewed: —

Reviewed 0Review pending 100

100 questions · Flow follows Relevance until this set has a learning order.

Q&A-1Saved views shipped and views created rose 40% in week one, but weekly reuse stayed flat. How do you decide if the feature worked, and what do you check before calling it a success?

The 90-second answer

I would not call it a success on creation volume. I would check whether the pre-registered primary metric moved, whether the lift survived the novelty window, and whether the guardrails held. For saved views in our dashboard, the primary metric was the share of weekly active workspaces applying a saved view at least three times in a week, measured by week four. Creation was a diagnostic, not the decision metric. A 40% rise in week one with flat reuse is the classic novelty pattern, so I would read the week four cohort before deciding anything.

Why creation misleads here

Creating a view costs one click and signals curiosity. Applying it repeatedly signals that the saved filter set replaced manual rebuilding, which was the actual problem. Session replays before launch showed a median of six filter interactions before the chart users wanted. If that interaction count did not fall for treated workspaces, the feature had not changed behaviour, however many views existed.

I would compare two readings of the same launch:

ReadingWhat it countsFailure mode
Views createdOne-off saves, including trials abandoned after one useRewards a prominent save button and a launch announcement
Views applied per active workspaceRepeated reuse by week fourSlower to move, needs event dedupe and a fixed cohort window

The second reading is harder to instrument and slower to report. It is also the one that survives contact with a renewal decision.

What I would check, in order

First, cohort timing. Week one creation in our run was 2.4 times week three creation. I would plot creation and application by days since first exposure for the treated cohort, not calendar days since launch, so a mid-week rollout does not smear the novelty spike.

Second, the experiment contrast. We randomised by workspace, 50/50, for two weeks, with the variant showing the save control. Randomising by user would have contaminated the result, because views are shared inside a workspace and one user applying a view changes what teammates see. The readout I would trust:

GroupWorkspacesApplied 3+ times/week by week 4Dashboard p95
Control1,24011.8%410 ms
Variant1,26119.4%418 ms

That is a 7.6 point lift on the primary metric with p95 inside our 500 ms budget. If creation rose 40% and this table did not move, I would report no effect and look for a UI problem, not ship on the creation chart.

Third, instrumentation quality. view_applied fired from the client on every chart query retry, which produced a 1.3% duplicate rate in week one. I fixed it at the source with a client-generated event_id and server-side dedupe, rather than filtering duplicates downstream in the warehouse.

TypeScript
// TypeScript, React 18 client
type ViewApplied = {
  event_id: string; // uuid, generated once per user action
  event: "view_applied";
  workspace_id: string;
  view_id: string;
  filter_count: number;
  ts: string; // ISO 8601 at fire time
};

Without that, a retry storm could have manufactured the reuse lift I was hoping to find.

Fourth, segments and guardrails. Workspaces under five users lifted only 4.1 points against 7.6 overall, which told me the feature served power users first. I would also check the views endpoints for error rate and the filter interaction count per session. If reuse rose but p95 breached budget or PATCH /views/{id} returned 409 conflicts from two tabs editing the same view, I would treat that as a cost to fix, not a footnote.

The decision rule I would state in the readout

Ship if the week four reuse metric moves, the guardrails hold, and the lift is present outside the first week. Kill or iterate if creation moves and reuse does not, because that pattern means users tried the control and found no recurring value. In our case reuse held after the novelty window and support tickets about rebuilding filters fell by a third the following month, so we kept it. The week one creation spike alone would not have justified that call.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-2What is the first step you would take before writing any code for a new feature?

The 90-second answer

Before writing code I write down the user problem and the one metric that will tell us whether the feature worked. If I cannot state both in a sentence each, I do not start building.

For a saved payment method feature, that looks like this. Problem: repeat buyers re-enter card details at every checkout and abandon at a higher rate. Metric: repeat purchase rate within 30 days for users who check out after launch. Baseline from the last 28 days: 22% repeat purchase, median checkout time of 94 seconds for repeat buyers. Target: a lift we can detect with the traffic we have, and a date when we read the result.

That one page decides the MVP cut. Save one card, reuse it next checkout, delete it in settings. Multi-card management and default card selection stay out, because they add work without testing whether saving a card changes behaviour.

ElementWeak versionVersion I would use
ProblemUsers want saved cards38% of repeat buyers re-enter card details, 120 support tickets a month mention it
MetricImprove checkoutRepeat purchase within 30 days, baseline 22%
GuardrailKeep checkout fastCheckout completion must not fall more than 0.5 percentage points, p95 checkout latency under 2.5 seconds
DecisionSee how it goesRead result after 14 days at 50/50 rollout, ship or remove the flag

Why this comes first

The problem statement forces a check against real data. I pull the baseline from the database and from support tickets before I talk to design. When the numbers do not support the problem, the feature stops there. That check costs an afternoon. Building the wrong feature costs a sprint and leaves code that nobody wants to delete.

The metric matters for the same reason. Without a baseline and a target, any result can be argued as success. With them, the team agrees in advance what evidence would change the decision. I also name the guardrails at the same time, because a feature that lifts repeat purchase by breaking checkout completion has failed in practice.

Instrument the decision before the UI

I define the events that produce the metric in the same document, so instrumentation is part of the first step rather than an afterthought. The schema is small and stable.

TypeScript
// TypeScript, event schema for the saved-card MVP
type SavedCardEvent = {
  name: 'card_save_started' | 'card_saved' | 'card_reused' | 'card_deleted';
  user_id: string;
  treatment: boolean;
  occurred_at: string; // ISO 8601, set server-side
};

function track(event: SavedCardEvent) {
  // Send to the analytics pipeline with user_id as the join key.
  // treatment comes from the experiment assignment, never from the client.
  return analytics.track(event);
}

Every event carries user_id and the experiment assignment. That lets me join exposure to outcome later without rebuilding the funnel from page views. If the event names are still being debated in week two, the metric was never really defined.

What the MVP then looks like

With problem and metric fixed, scoping gets easier. The smallest slice that can move the metric goes in. Everything else goes on a written list with a reason. I put that list in the same doc as the problem statement, so when someone asks for multi-card support during the build, the answer is already recorded: it waits until the saved-card hypothesis is tested.

I ship that slice behind a flag at 1% first, watch payment errors for 48 hours, then move to a 50/50 split. The arithmetic for the split is also in the doc. At roughly 400 eligible checkouts a day, 14 days gives about 2,800 per arm, enough to detect a 3 percentage point lift from a 22% baseline. If traffic were lower, I would extend the window or pick a faster metric and say so before launch.

That sequence, problem with a baseline, one metric with guardrails, events defined up front, then the smallest slice that can move the metric, is the whole approach. Code comes last because the earlier steps decide what code is worth writing.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-3Walk me through how you would push back if product wants exact live stock counts on every product page, refreshed within a second and guaranteed at click, at 40,000 concurrent views, with no extra inventory capacity?

The 90-second answer

I would push back on the mechanism, not the goal. The goal is fewer users reaching checkout for stock we do not have. Exact counts refreshed within a second, guaranteed at click, at 40,000 concurrent product views, with no extra inventory capacity, cannot all hold. I would show the arithmetic and the race, then propose a cached low-stock bucket plus a hard reservation at checkout, shipped behind a flag with events so we can compare oversell rate and conversion.

Assume peak is 40,000 concurrent product views and the inventory service already runs hot during sales. A one second refresh means either a read per view per second, which is 40,000 requests per second, or polling from the client at the same order of magnitude. That saturates inventory before anyone reaches checkout. Even if capacity existed, the count would still be wrong under a race. Two users see "1 left", both click, and only one reservation can win. Display accuracy cannot create a guarantee.

So I would keep the trust signal and move the guarantee to the one place it can hold: a conditional reservation at checkout with a timed hold.

The working I would put on the table

CheckNumbers or traceResult
Refresh cost, hypothetical peak40,000 views, 1 s refresh = 40,000 req/sInventory becomes the bottleneck for browsing
Cached bucket alternative60 s cache, 1 read per SKU per minute, 5,000 SKUs = about 83 req/sTwo orders of magnitude cheaper, bucket may lag by a minute
Race traceUser A and B both read available=1, both attempt reserveRead-then-write lets both proceed, conditional update lets one win
Checkout failureLoser gets insufficient_stock at checkoutFailure is explicit and recoverable, instead of a false promise on the page

The reservation has to be a single conditional update. A read followed by a write passes sequential tests and fails exactly when two carts arrive together.

TypeScript
// TypeScript, checked against Node 20
type Reservation =
  | { ok: true; holdId: string }
  | { ok: false; reason: "insufficient_stock" };

async function reserve(sku: string, qty: number): Promise<Reservation> {
  const result = await db.inventory.updateMany({
    where: { sku, available: { gte: qty } },
    data: {
      available: { decrement: qty },
      reserved: { increment: qty },
    },
  });
  return result.count === 1
    ? { ok: true, holdId: crypto.randomUUID() }
    : { ok: false, reason: "insufficient_stock" };
}

The hold then needs an expiry, for example 10 minutes, and a sweeper that returns reserved to available when the hold lapses or the order is cancelled. Without that, abandoned carts quietly drain sellable stock and the bucket starts lying in the other direction.

Product view Show cached bucket: low stock if under 5 User clicks Buy Checkout calls conditional reserve Hold placed for 10 minutes insufficient_stock shown with alternatives Order confirmed or hold expires

How I would run the disagreement

First I restate the user problem and confirm we share it. Then I price the requested mechanism with our peak figures, labelled as hypothetical where they are estimates. Then I show the race trace. Only then do I propose the alternative, with bucket thresholds, cache age, hold duration and failure copy written into the same ticket. Vague alternatives let the original requirement creep back during implementation.

I would ship behind a flag and emit stock_bucket_shown, reservation_attempted and reservation_failed with SKU and bucket. The decision rule goes in before launch: keep the bucket if oversell incidents fall and checkout completion does not drop beyond the threshold we agree with product. If conversion does drop, the next lever is copy or threshold, not a return to exact counts.

Pushback fails when it is a veto based on elegance. If I cannot attach a number, a trace or a failure rate, I build as asked, instrument it, and push back with results. It also fails when I win on cost and ignore the user. Cheaper is a constraint. The goal stays the one product stated: fewer users blocked at checkout for stock we do not have.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-4How do you define success metrics before building a feature, and how do you know if the metric you picked is the right one?

The 90-second answer

I start from the decision the feature has to change, not from a dashboard. For a checkout change, the decision is whether to ship it to everyone. So I write a metric contract before any code: one primary metric, two or three guardrails, the exact population, the baseline, the target effect, and the rule for shipping or rolling back.

Primary metric: checkout completion rate, defined as completed orders divided by checkout sessions that reached the payment step, over a rolling 7 day window. Guardrails: payment error rate, refund rate within 14 days, and p95 checkout latency. If completion rises because we pushed users into a payment method that fails later, the guardrails catch it.

I also write the instrumentation plan in the same ticket. Every event needs a name, owner, and the properties the metric needs. If we cannot log the denominator reliably, we do not start.

RoleExample for checkoutBaseline (hypothetical)Ship rule
PrimaryCompleted orders / payment-step sessions18.0%+1.5 pp or more, statistically clear
GuardrailPayment error rate2.1%No rise above 2.6%
GuardrailRefund rate, 14 day3.4%No rise above 4.0%
Guardrailp95 checkout latency900 msNo rise above 1,100 ms
CountermetricSupport tickets per 1,000 orders8.0No rise above 10.0

How I size the test

The target has to be detectable with real traffic. With a baseline of 18.0% and a target of 19.5%, alpha 0.05 and 80% power, the usual two-proportion calculation gives about 10,600 sessions per arm. At 2,000 eligible sessions per arm per week, that is roughly five weeks. If the team wants an answer in one week, I either lower the ambition, narrow the population to the segment the feature actually touches, or admit we will only detect a larger effect. Picking a target we cannot measure is how teams ship on noise.

Instrumentation before UI

I define the events the metric depends on, with the experiment assignment joined at event time:

TypeScript
// TypeScript, checked against a standard analytics pipeline
type CheckoutEvent = {
  event: "checkout_payment_step_viewed" | "checkout_order_completed";
  userId: string;
  sessionId: string;
  experiment: "one_click_checkout_v2";
  variant: "control" | "treatment";
  surface: "web" | "ios" | "android";
  occurredAt: string; // ISO 8601, server timestamp
};

The denominator event fires when the payment step renders, not when the page loads. The numerator fires only on a confirmed order, not on a button click. I check both counts in staging against a scripted run before the experiment starts, and I add an alert if either event volume drops by more than 20% week on week. A silent logging break looks exactly like a failed feature.

No Yes User problem Primary metric Guardrails Countermetric Instrumentation check Effect detectable? Rescope or stop Ship, iterate, or roll back

Where this goes wrong

Vanity metrics are the common failure. Page views or clicks can rise while completed orders fall, so I tie the primary metric to revenue, retention, or task completion the business already tracks. Denominator drift is the second failure. If a marketing campaign sends cheaper traffic during the test, completion can fall for reasons unrelated to the feature, which is why I randomise at user level, keep the window fixed, and compare segments separately. The third failure is measuring too early. A new checkout flow often dips in week one while users learn it, then recovers. I pre-register the analysis window and look at novelty effects instead of calling the result on day three.

A metric is the right one when it moves only if the feature works, it cannot be gamed by a side effect, and the team would actually reverse the launch if it missed. If nobody would act on the number, it is decoration.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-5How would you prioritize features with RICE or MoSCoW when engineering capacity covers only half the backlog?

The 90-second answer

I use MoSCoW to decide what the quarter is allowed to contain, and RICE to order the items inside the Should and Could buckets. MoSCoW alone leaves 14 Musts competing for the same engineers. RICE alone gives a precise-looking score to a feature that should not ship this quarter at all, such as a compliance fix or a dependency for a Must. Together they answer different questions: MoSCoW sets the boundary, RICE ranks within it.

Assume a team of 2 engineers for a 6-week quarter, so 12 person-weeks of capacity before bugs and support. I first list Musts and check they fit. If they do not fit, something moves to Should and I say so explicitly. Then I score the remaining candidates with RICE and take them in score order until capacity runs out. The rest become Won't have this time, with a reason and a revisit date.

RICE, worked with real figures

RICE = (Reach x Impact x Confidence) / Effort. Reach is users affected per quarter, Impact is effect per user on a 0.25 to 3 scale, Confidence is a percentage, Effort is person-weeks.

FeatureReachImpactConfidenceEffortRICE
One-click checkout12,000280%63,200
Saved filters4,000150%21,000
Bulk export to CSV9003100%12,700
New onboarding tour20,0000.530%4750

Checkout: (12,000 x 2 x 0.8) / 6 = 3,200. Bulk export scores second despite reaching only 900 users because Impact is high and Effort is one week. That is the point of the formula. It surfaces cheap, high-certainty wins that a Reach-only list would bury. It also exposes the onboarding tour: large Reach, low Confidence, middling score. I would not build it at full scope. I would run a 2-day prototype or a fake-door test to raise Confidence before committing 4 weeks.

MoSCoW applied to the same quarter

BucketItemsPerson-weeksRule
MustCheckout, payment retry fix, audit log for refunds9Ships or the quarter fails its stated goal
ShouldBulk export, saved filters3Fits in remaining capacity, ranked by RICE
CouldOnboarding tour0Deferred until Confidence improves
Won't have this timeMulti-currency pricing0Revisit next quarter, needs finance sign-off

Musts consume 9 of 12 weeks. Shoulds take the remaining 3, in RICE order: bulk export first, then saved filters if time remains. The tour and multi-currency are not "backlog", they are explicit Won'ts. That wording matters in the room. A Won't with a revisit date stops the weekly re-litigation of the same request.

Where each one breaks

RICE fails when the inputs are gamed or guessed. Reach gets double-counted when two features claim the same 12,000 users. Confidence becomes a negotiation, with every owner at 100%. Effort is the classic underestimate: the checkout estimate of 6 weeks excludes the payment provider certification that adds 3. I counter this by scoring in a group, using last quarter's actuals as the Effort baseline, and capping Confidence at 80% unless there is experiment data behind it. If a score depends on Confidence above 80% with no data, I treat the score as provisional.

RICE also misleads for platform and compliance work. A schema migration or an accessibility fix may reach few users directly and score near zero, yet it unblocks three Musts. I handle that by putting such work in Must before any scoring, and labelling it as an enabler rather than pretending the formula ranked it.

MoSCoW fails when everything is a Must. I have seen 11 Musts for a 12-week capacity. The fix is a capacity check in the meeting: add up Must effort in person-weeks and compare it to the 12 available. If Musts exceed capacity, the product owner demotes one in the room. A Must list that cannot fit is a wish list, and engineers will quietly pick their own order, which is prioritisation without accountability.

RICEMoSCoW
Question answeredWhich of these first?What is in scope at all?
OutputA ranked list with scoresFour buckets with a capacity boundary
StrengthMakes trade-offs numeric and comparableForces explicit exclusion
WeaknessPrecision theatre when inputs are guessesNo ordering inside a bucket
Best useRanking Should and Could itemsSetting the quarter's contract with stakeholders

In practice I run MoSCoW first, in a 30-minute session with product and engineering, then score only what survives. The scored list goes into the tracker with Reach, Impact, Confidence and Effort visible, so anyone can see why bulk export outranks saved filters and challenge the input rather than the conclusion.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-6What format do you use for a user story and its acceptance criteria when a request is ambiguous?

The 90-second answer

I use the standard story format and write the criteria in Given/When/Then, because that format forces the ambiguity out before anyone codes.

The story is one sentence: As a [specific user], I want [specific goal], so that [observable benefit]. If I cannot fill all three slots without vague words, the request is not ready. I ask who, what action, and what changes for them, and I record any answer I had to assume.

Take the ambiguous request "make search better." I cannot build that. After checking search logs, the version I would write is:

As a shopper who knows the product name, I want exact-name results ranked first, so that I find the item without scrolling past unrelated products.

Assumption recorded in the ticket: we are fixing ranking for known-item searches, not adding filters or a new search engine. That line matters. It tells the tester what is out of scope.

Acceptance criteria

Each criterion is one Given/When/Then scenario that a tester can pass or fail without asking what I meant. I avoid words like fast, easy, or intuitive unless I attach a number or a named screen.

Ambiguous phraseTestable criterion
Better resultsGiven the query "red running shoes", when results load, the first result is a product whose title contains all three words
FastGiven a query on 4G, when the shopper submits, results render within 1 second at p95
No results handled wellGiven a query with zero matches, when results load, the shopper sees the query echoed and three suggested alternatives

In the ticket I paste the same scenarios in Gherkin so there is no translation between product and QA:

GHERKIN
Feature: Exact-name search ranking

  Scenario: Known product name ranks first
    Given the catalogue contains "Red Runner Shoes"
    When the shopper searches for "red runner shoes"
    Then the first result is "Red Runner Shoes"

  Scenario: No matches
    Given the shopper searches for "zxqv"
    When results load
    Then the page shows "No results for zxqv"
    And it shows three suggested alternatives

If product still cannot name the user or the outcome, I do not write criteria around a guess. I write one story for the smallest check that resolves it, for example instrumenting which queries return zero results for two weeks, with the criterion being that the report lists the top 20 zero-result queries by volume. Once that data exists, the real story takes an hour to write.

The test I apply before starting work: hand the ticket to someone who was not in the meeting. If they can run every scenario and mark pass or fail without a follow up question, the story is ready. If they have to ask what "better" meant, it is not.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-7You have two weeks, no access to the enterprise buyers who requested a feature, and any prototype you ship would mislead them about the data it can actually show. How do you validate the problem and decide whether to build?

The 90-second answer

I would not run the standard interview and fake-door playbook. With no buyer access and a prototype that would show data we cannot actually supply, both methods produce confident noise. I would triangulate from evidence we already own, test commitment with a real but narrow slice for a proxy cohort, and pre-register a stop decision. If those sources disagree, I recommend not building.

Assume the request is an enterprise buyer asking for live cross-system status. We have two weeks, the buyer will not take calls, and our warehouse only refreshes that data every six hours. A prototype showing live data would validate a promise we cannot keep.

No Yes No Yes Buyer claim: need live status Mine existing evidence Support, logs, churn, sales loss notes Pain visible without buyer? Stop: no basis to build Narrow real-data slice for proxy users Proxy users change behaviour? Decision doc with buyer test as gate

Start with evidence that cannot be flattered

Interviews with champions fail here for a specific reason. The buyer is not the daily user, and the daily user we can reach may not have the buyer's escalation pressure. Their answers will describe a workflow, not the purchase trigger. I treat them as context, not validation.

I mine four sources first. Support tickets tagged with status or freshness, filtered to the last 90 days. Product events showing how often users export, refresh, or contact support after viewing stale data. Churn and lost-deal notes where the buyer named this gap. And sales call notes, read for the exact words the buyer used, because a paraphrase by an account executive often upgrades a preference into a requirement.

SQL
-- Checked against our support export and product events, last 90 days
SELECT
  s.category,
  COUNT(*) AS tickets,
  COUNT(*) FILTER (WHERE s.resolution = 'workaround_provided') AS workarounds,
  ROUND(AVG(s.hours_to_first_response), 1) AS avg_first_response_h
FROM support_tickets s
WHERE s.created_at >= now() - interval '90 days'
  AND s.product_area = 'order_status'
GROUP BY s.category
ORDER BY tickets DESC;

I also pull the denominator. If 4,000 target users view order status weekly and 31 tickets mention staleness, the rate is under 1%. That does not kill the idea. It changes the question from "does the problem exist" to "is it concentrated in a segment worth serving." I segment by account size, plan, and whether the account has a named buyer contact.

Name the misleading prototype trap

The subtle failure is a prototype that is honest about the UI and dishonest about the data contract. Users click, praise it, and sign up. We then discover the six-hour refresh, or the missing source system, and the pilot collapses. The click measured the mock, not the feasible product.

So I constrain the prototype to data we can actually deliver today. For this case that might be a status page for one source system, refreshed hourly, with the refresh time printed on the page. I show the limitation in the interface. If users still commit, I have learned something about the feasible version. If they only commit when I hide the limitation, I have learned the live requirement is the whole value, and we cannot meet it without new pipeline work.

That distinction goes in the decision doc as a table, because it is the trade-off the team will argue about later.

Prototype variantWhat users seeWhat a signup provesWhat it cannot prove
Live mock dataReal-time status for all systemsInterest in the conceptThat we can build it in scope
Real data, one system, hourlyTrue status with visible refresh timeWillingness to use the feasible sliceThat the buyer will accept partial coverage
Concierge checkManual status sent by email twice dailyThat the outcome reduces escalationsThat automation cost is acceptable

I pick the second row for proxy users, usually support agents or mid-market ops managers who feel the escalation pain. I recruit 10 to 15 of them, give them the slice for a week, and instrument the behaviour that matters. Not clicks. Escalations avoided, exports replaced, and time from status view to resolution.

Pre-register the stop rule

Before I recruit anyone, I write thresholds tied to the existing evidence. In a worked example: at least 20% of proxy users use the slice on three or more days, at least 30% of their status-related exports drop, and support tickets from their accounts fall by a visible margin over the week. I also set a buyer gate. We build only if the account team can get the buyer, or a delegate with budget authority, to react to the feasible slice within the next sprint. No reaction means no build, even if proxy users like it.

That last rule feels harsh. It prevents the common outcome where a team builds for the reachable user, ships a partial feature, and then spends two quarters negotiating with a buyer who never asked for that version.

What I deliver in two weeks

Day 1 to 3: evidence mining and segmentation, with the SQL above and the ticket sample read manually. Day 4 to 5: hypothesis rewritten around the feasible slice, plus kill criteria. Day 6 to 10: concierge or narrow slice with real data for the proxy cohort. Day 11 to 14: analysis against the pre-set thresholds and a one-page decision.

The decision has three possible outcomes. Build the narrow slice, because proxy behaviour changed and the buyer gate is scheduled. Run a pipeline spike, because the evidence shows the live requirement is the value and the current refresh cannot support it. Or stop, because the pain is rare, concentrated in one account, or only appears when the prototype overpromises.

The most useful sentence in that doc is the one that names what we did not validate. "We validated hourly status for one system with proxy users. We did not validate buyer acceptance of partial coverage or live cross-system status." That keeps the next team from treating a proxy result as a buyer commitment.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-8How do you draw the line between MVP and v1 scope for a feature, and what do you cut first when time runs short?

The 90-second answer

I draw the line at the smallest slice that can falsify the hypothesis the feature exists to test. MVP is not a cheap version of v1. It is a learning instrument with a date attached. v1 is the version we keep if that learning says yes.

So I start by writing the hypothesis in one sentence with a number in it. For example: "Teams that share a saved dashboard view will return within 7 days at a rate at least 15% higher than teams that do not." If product cannot name that sentence, scope has no line to draw against, and every request looks equally urgent.

Then I list the riskiest assumption. Usually it is not the UI. It is whether users will do the behaviour at all, whether the data model survives real usage, or whether a dependency can deliver at the required latency. The MVP must touch that assumption directly. Everything that does not touch it is a candidate for v1, even if it feels like part of the "real" feature.

DecisionMVPv1
PurposeTest one behaviour and one metricServe the users who passed the test, safely at scale
UserInternal or 5% of eligible teams, invitedAll eligible teams, self-serve
PermissionsOwner only, no sharing rolesRole based sharing, audit log, revocation
DataCreate, read, delete own viewEdit, duplicate, move between workspaces, retention rules
Edge casesHappy path plus empty and error statesConcurrent edits, expired links, deleted source data
InstrumentationEvent for create, view, return visitFull funnel, latency, error budget, support tags
Exit criteriaDecision in 3 weeks: kill, iterate, or promoteSLOs and runbook before general rollout

Worked example with real figures

Say we have 2 engineers for 6 weeks, 12 engineer-weeks total. The full v1 list prices out like this in a planning doc I would actually write:

SliceEstimateTests the hypothesis?
Save and load own view2 weeksNo, it is plumbing
Share link, owner only1.5 weeksYes, this is the behaviour
Event instrumentation and experiment split1 weekYes, without it we learn nothing
Role based permissions and audit3 weeksNo
Concurrent edit handling and notifications2.5 weeksNo
Polish, empty states, accessibility pass2 weeksPartly, empty state only

MVP is save/load, share link, instrumentation, and the empty state. That is 5.5 weeks including buffer, and it reaches the metric. Permissions and notifications move to v1 because they matter only if sharing is adopted. If the experiment shows a 4% lift instead of 15%, we have saved 6.5 weeks building roles for a feature nobody wanted. If it shows 22%, we promote the same code and add the v1 slices with evidence to defend the cost.

The cut order when time runs short follows the same logic. I cut in this order: polish, admin tooling, secondary surfaces such as email or Slack, then advanced permissions. I never cut instrumentation, the delete path, or the security check on the share link. A share link that anyone can guess is not a scope saving. It is a leak we will discover in a support ticket.

No Yes Yes No Write hypothesis with a number Name riskiest assumption Smallest slice that touches it Can we measure it in 3 weeks? Ship to small cohort Metric moves? Build v1 slices Kill or iterate

In code, the MVP boundary should be visible at runtime, not just in a doc. I gate the share path behind a flag so promotion and rollback do not need a deploy:

TypeScript
// TypeScript, checked against Node 20
type Flags = { dashboardSharing: boolean };

function canShare(user: User, flags: Flags): boolean {
  return flags.dashboardSharing && user.role === "owner";
}

That looks trivial, and that is the point. The flag records which cohort gets the behaviour, and the experiment assignment records which cohort we compare against.

Two failure modes I watch for. First, an MVP that is too thin to be usable, so the test measures confusion rather than demand. I guard against it by putting the slice in front of 5 real teams and watching them complete the task without help. Second, an MVP that quietly becomes v1 because every stakeholder adds one "small" must-have. I guard against it by requiring each addition to name which assumption it tests. If it tests none, it waits.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-9You need push notifications live in six weeks with no spare platform engineer. How would you decide between building, buying, or partnering, and what would you check first?

The 90-second answer

With six weeks and no spare platform engineer, I would buy push notifications unless we already own the hard parts. Push looks simple until delivery, opt-outs, quiet hours, and device tokens start failing at scale. A vendor has already paid for that pain. Building makes sense only if push is tied to something we need to control, such as personalised messages driven by our own behavioural data that we test every week.

I would state that assumption first, then check three things in order: time to a testable launch, total cost over 24 months including exit, and whether we can swap vendors without rewriting the product code. Partnering only enters if a partner brings distribution or a licence we cannot get ourselves, for example a telco or marketplace app where the message has to live inside their surface.

How I apply it to this case

First, differentiation. Does push make customers choose us, or is it table stakes for onboarding and re-engagement? For most products it is table stakes. That pushes toward buy.

Second, control. We still need our own events for every send, open, and opt-out, because that is how we measure whether the feature worked. If the vendor cannot emit those events in the format our pipeline expects, the vendor is slower than it looks, even if the SDK installs in a day.

Third, reversibility. I put our interface in front of the vendor on day one. Product code calls our Push interface, never the vendor SDK directly. That adapter is small and it is what makes buy a reversible choice.

OptionWhen it wins hereMain costMain risk
BuildPush logic is core and changes weekly8 to 12 weeks upfront, then ongoing token and deliverability workNo owner after launch, delivery rates quietly fall
BuyCommodity sending, stable API, clear SLAMonthly fee plus per-message cost, integration timePrice rises, API changes, export drops fields we need
PartnerPartner owns the channel or the customer relationshipRevenue share, joint roadmapWe cannot run a holdout, so we cannot prove incrementality

Worked cost comparison, figures hypothetical

Assume 2 million pushes a month over 24 months.

Buy: $1,800 per month plus $0.001 per message. That is $1,800 + $2,000 = $3,800 per month, or $91,200 over 24 months. Integration takes about 3 engineer-weeks. Exit takes about 2 weeks to export templates, tokens, and suppressions.

Build: 10 engineer-weeks to ship sending, token refresh, opt-out handling, and basic scheduling. Then about 0.5 engineer-week per month for deliverability, OS changes, and template work. At a loaded $9,000 per engineer-week, that is $90,000 upfront plus $108,000 over 24 months, $198,000 total, before infrastructure.

On those numbers buy wins clearly. Build only wins if we expect to iterate on targeting weekly and that iteration moves a KPI we care about, such as weekly active users. If push is just welcome and reminder messages, the build cost buys us nothing the customer can see.

The adapter I would write

TypeScript
// TypeScript, Node 20
interface Push {
  send(input: { userId: string; template: string; vars: Record<string, string> }): Promise<{ providerId: string }>;
  setOptOut(userId: string, optedOut: boolean): Promise<void>;
}

class VendorPush implements Push {
  constructor(private client: VendorClient) {}

  async send(input: Parameters<Push['send']>[0]) {
    const res = await this.client.push.send({
      audience: input.userId,
      templateId: input.template,
      data: input.vars,
    });
    return { providerId: res.id };
  }

  async setOptOut(userId: string, optedOut: boolean) {
    await this.client.consent.update({ userId, pushOptOut: optedOut });
  }
}

I also log our own event at send time, with user, template, and experiment assignment. That log survives a vendor switch. Without it, switching vendors breaks the KPI history.

Failure modes I check in the trial

For buy: ask for a sample data export during the trial, not a promise of one later. Check that it includes device tokens, suppression state, and delivery status. Check sandbox parity, because a vendor that behaves differently in sandbox hides integration bugs until launch week. Check rate limits against our peak, not our average.

For partner: who owns the suppression list, and can we assign users to a holdout? If the partner stores the only copy of opt-outs, we cannot legally or practically switch. If we cannot run a holdout, we cannot tell whether the partnership is working.

For build: name the owner in the launch doc. Token cleanup, APNs and FCM changes, and deliverability monitoring are monthly work. If the owner is "the team", that work will not happen.

What would reverse the call

I would write the reversal triggers into the decision doc. Revisit build if the vendor price crosses the build line in the model above, if delivery rate falls below the SLA for two months in a row, or if push starts showing up in win-loss interviews as a reason customers stay. Revisit partner if we lose the ability to run experiments. That turns a one-time choice into a decision we can defend and change.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-10What is the first thing you do when you need to explain a technical tradeoff to product and nontechnical stakeholders?

The 90-second answer

I start with the consequence for the user and the business, then I price the options in time, money and risk. I do not start with the technology. The stakeholder can decide between two priced options. They cannot decide between two architectures described in engineering terms.

My opening line sounds like this: "Option A ships in two days and search takes about 800 milliseconds. Option B takes two weeks, search takes about 50 milliseconds, and we pay for a separate search service. I recommend A for launch, and we move to B if search latency shows up in our activation metric." That sentence contains the tradeoff, a recommendation and a revisit trigger.

Worked example: instant search

Product wants search results as a user types. The choice is between querying the main database with a LIKE pattern and running a dedicated search index.

OptionUser experienceLoad and costBuild time
Query main databaseResults in about 800 ms at our current catalogue size of 200,000 productsUses existing database capacity, no new service2 days
Dedicated search indexResults in about 50 ms, typo tolerance includedNew service to run, index rebuilds on every catalogue change, roughly $300 per month at our volume2 weeks

The arithmetic behind the database option matters. At 100 searches per minute, the main database handles about 1.7 queries per second. Each query scans an index on product name, so response time stays near 800 ms until the catalogue grows past roughly one million products. I would label that figure as measured on our staging data, with the catalogue size and query count stated, so product can challenge the assumption.

I then tie the choice to the metric we agreed before building. If activation depends on a user finding a product in the first session, 800 ms may still pass. If our funnel data shows users abandoning after a slow first search, the 50 ms option earns its cost. I ask product to pick based on that metric, and I record the pick in the ticket.

State user impact in plain language Price each option in time and cost Give a recommendation Name the metric that would change the call Record the decision in the ticket

What makes the explanation land

I translate every technical term on the spot. If I mention an index, I say what it buys the user: faster results. If I mention eventual consistency, I say how stale a number can be and for how long. I also avoid presenting options as equal. A list with no recommendation pushes the decision back to the stakeholder without the information needed to make it.

Two checks keep me honest. First, I name the cost that arrives after launch, such as running a new service or rebuilding an index, before anyone approves the option. Second, I name the trigger for revisiting the call, such as catalogue size passing one million products or search latency appearing in support tickets. I write both checks into the ticket with the decision, so the same tradeoff does not return in the next planning cycle.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-11A 5,000-row product grid rerenders on every keystroke and every websocket price tick, and memoizing rows made prices go stale. Walk me through the render mechanism and how you would fix both without losing input responsiveness?

The 90-second answer

A setter does not edit the DOM. It marks the owning component dirty, React re-executes that function, creates a new element tree, diffs it against the previous tree by type and key, and commits only the changed DOM nodes. Descendants rerender because React assumes their output may have changed. memo changes that assumption: it compares the new props with the previous props using Object.is and skips the subtree when every prop is identical.

In your grid the two symptoms have different causes. Keystroke lag comes from state owned too high, so one update re-executes 5,000 rows. Stale prices after memoizing come from a prop that looks stable while the real value travels elsewhere, usually a mutated object passed by the same reference, a price read from context above the memoized row, or a row memoized on id alone. I would fix ownership first, split the price feed from the search feed, and memoize only after props are primitives.

Exact working

React 18 and later batch updates across events, timers and promises, then schedule a render. Render runs the component body, hooks in fixed order, and JSX creation. Reconciliation then walks the new tree. If an element is the same reference as before, React can bail out of that subtree. If a memoized component receives props that are all Object.is equal, it bails out without running its body. If a parent mutates an object and passes the same reference, the comparison sees no change and the UI stays stale. That is the subtle failure behind stale prices: the code looks memoized and correct, but the data path bypasses the prop comparison entirely.

TSX
// React 19
const Row = memo(function Row({ id, name, priceCents }: Props) {
  return <div>{name} {(priceCents / 100).toFixed(2)}</div>;
});

function Grid() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  const prices = usePrices(); // Map<id, priceCents>, new Map on each tick

  const visible = useMemo(
    () => filterProducts(deferredQuery).slice(0, 200),
    [deferredQuery]
  );

  return (
    <>
      <SearchInput value={query} onChange={setQuery} />
      <VirtualList>
        {visible.map(p => (
          <Row
            key={p.id}
            id={p.id}
            name={p.name}
            priceCents={prices.get(p.id) ?? p.priceCents}
          />
        ))}
      </VirtualList>
    </>
  );
}

priceCents is a primitive, so a tick that changes one product changes one row's prop and only that row rerenders. A tick that changes nothing for a row leaves its props identical and the row bails out. If instead I passed product={p} where p was mutated in place, every row would bail out and prices would freeze.

Worked trace, hypothetical figures

Assume a full render of 5,000 rows costs about 120 ms, a virtualized window mounts about 30 rows, and the websocket sends 5 ticks per second.

EventNaive gridIsolated grid
KeystrokeOwner at page root, all 5,000 rows re-execute, input blocks for about 120 msQuery state lives in the search subtree, input rerenders in under 5 ms, list updates once via the deferred value
Price tick, 1 of 5,000 changedAll rows rerender, 5 times per secondOne row prop changes, one row rerenders, the other 29 mounted rows bail out
Price tick, mutated object, same referenceRows bail out everywhere, prices appear frozenNot applicable, prices are primitives from a new Map
Inline prop, filters={{ q }} recreated per renderMemo never bails out, cost of comparison plus full renderFilters are primitives or memoized, memo can bail out

Trade-offs and failure modes

State colocation is the first lever. A setter rerenders the owner and its descendants, never parents or siblings, so moving query state into the input component removes the keystroke problem without memoization. The cost is prop drilling when the committed query must reach the list, which useDeferredValue handles by letting the input stay urgent while the list lags one render behind.

Memoization is second and it is not free. Comparing props on every render costs time, so memoizing a cheap row can be slower than rerendering it. I profile with React DevTools Profiler and memoize only the expensive leaf. The failure I check for is a memoized row that never bails out because a parent passes an inline object or arrow function, or because a context provider above it creates a new value object on every render and every consumer rerenders regardless of memo. Splitting context by update frequency, or passing price as a primitive prop, removes that path.

Virtualization is third. It caps mounted rows at about 30, which bounds both render cost and DOM size, but it complicates find-in-page, keyboard navigation and variable row heights. I accept that cost at 5,000 rows because no amount of memoization makes 5,000 mounted DOM nodes cheap to reconcile.

Batching websocket ticks matters too. Five ticks per second is fine as separate renders when only one row changes each time. At 50 ticks per second I would buffer ticks in a ref and flush them in a requestAnimationFrame or a 100 ms interval, trading up to 100 ms of price freshness for far fewer renders. That trade is acceptable for a grid, and it would not be acceptable for a checkout total, so I would keep the total on its own urgent path.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-12When would you lift state up, use React context, or just pass props down, and how do you decide for a given feature?

The 90-second answer

I start from where the state lives, not from the tool. Keep state in the component that uses it. Lift it only to the lowest common ancestor of its consumers, and pass it down as props while the distance is short and the types are explicit. Reach for context when many distant components need the same value, that value changes rarely, and prop drilling would force unrelated intermediates to know about it.

That gives a practical rule. One or two levels, one consumer, frequent updates: props. Three or more levels, five or more consumers scattered across the tree, updates on navigation or login rather than on every keystroke: context. Anything in between, I check who else breaks when the shape changes.

TSX
// React 18, TypeScript. Props: explicit, refactor-safe.
type Cart = { id: string; qty: number };

function CheckoutPage() {
  const [cart, setCart] = useState<Cart[]>([]);
  const [promo, setPromo] = useState<string | null>(null);
  return (
    <>
      <CartSummary items={cart} />
      <PromoForm onApply={setPromo} />
      <PayButton items={cart} promo={promo} onPay={submit} />
    </>
  );
}

Here lifting to CheckoutPage is enough. CartSummary and PayButton are siblings, the props name the dependency, and a rename of promo fails at compile time in exactly two places. Moving this to context would hide that coupling and make the data flow harder to trace in a code review.

Context earns its place for ambient, stable values: the signed-in user, theme, locale, feature flags. Those are read in dozens of places, written rarely, and drilling them through a layout, a toolbar and a settings panel adds no information.

ApproachFits whenMain costTypical failure
Colocated stateOne consumerNonePremature sharing duplicates logic
Lifted state + props2 to 4 consumers, 1 to 2 levels upCommon ancestor re-renders on changeAncestor grows into a god component
ContextMany consumers, low write frequencyAll consumers re-render when value changesUnstable value object re-renders the whole subtree
External store (Zustand, Redux)High-frequency shared state, selectors neededExtra dependency and sync modelStore becomes a dumping ground for local UI state

The re-render cost is the deciding detail. Context has no selector. If a provider value is a new object on every render, every consumer re-renders even if the field it reads did not change. A concrete case I have hit: a ThemeContext value built inline as { theme, toggle } inside a provider at the app root. Typing in a search box that updated unrelated app state re-rendered 120 table rows under that provider, because the value identity changed. Memoising the value with useMemo, splitting a rarely changing context from a frequently changing one, or moving the high-frequency state into a store with selectors fixed it. The search input itself stayed local state, which is the first move I try.

Who reads and writes this state? One component Keep it local Two or more, close together Lift to common ancestor, pass props Many, far apart, writes are rare Context, memoised value Many, writes on every keystroke or tick External store with selectors

Failure modes I watch for in review: lifted state that couples two features which only coincidentally share a parent, so a change to the filter resets the checkout form; context used for form fields, which turns each keystroke into a subtree render and breaks with large lists; and prop drilling past three levels, where an intermediate component forwards props it never reads and a prop rename touches five files with no compiler help if the code is plain JavaScript.

When I am unsure, I prototype with lifted props. It is the easiest to refactor later. Moving props into context is a one-way door in practice, because consumers start importing the context directly and the explicit contract disappears. I only pay that cost when the tree distance and consumer count make the explicit version unreadable, and I keep the context value stable and narrow so the re-render bill stays small.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-13Your effect keeps showing the previous user's orders after userId changes. How do you debug that stale closure and decide on the fix?

The 90-second answer

I reproduce it with two renders and log the values the effect actually saw, not the values on screen. A stale closure in useEffect almost always means the effect captured a value from the render when it was created, and that value never updated because the dependency array did not include it, or because the effect was created with an empty array on purpose and never re-created.

JSX
// React 18/19, checked against the exhaustive-deps rule
function UserOrders({ userId }) {
  const [orders, setOrders] = useState([]);

  useEffect(() => {
    let cancelled = false;
    fetch(`/api/users/${userId}/orders`)
      .then((r) => r.json())
      .then((data) => { if (!cancelled) setOrders(data); });
    return () => { cancelled = true; };
  }, []); // userId is read inside, but missing here

  return <OrderList orders={orders} />;
}

On first mount userId is u1, so the effect closes over u1 and fetches correctly. When the parent switches to u2, React re-renders, the component body runs with u2, but the effect from the first render is still the one in place. It does not re-run, so the UI keeps u1 orders under a u2 header. The fix in this case is to add userId to the array, which also makes the cleanup run before the next fetch.

How I confirm it, not guess

I add a temporary log inside the effect and in the render body, then switch the prop in React DevTools or a story.

StepRender body seesEffect closure seesFetch URLResult on screen
MountuserId = u1userId = u1/users/u1/ordersu1 orders, correct
Prop change to u2userId = u2userId = u1 (no re-run)nonestill u1 orders, wrong
After adding [userId]userId = u2userId = u2 (cleanup, then re-run)/users/u2/ordersu2 orders, correct

If the log shows the effect did re-run but still used the old value, the cause is different: the value came from a function or object created in the parent and recreated each render, or from state updated asynchronously. I then check whether the dependency is a new object identity every render, which causes the opposite symptom, an effect that fires too often.

Choosing the fix

FixWhen it fitsCost
Add the missing dependencyThe effect genuinely depends on that value, as aboveEffect re-runs when it changes, which is usually the intent
Store the latest value in a refYou need the current value for a callback or timer, but you do not want the effect to re-runYou lose the automatic re-run, so stale data can hide if you forget to read the ref
Move the logic into a custom hook or useCallbackThe dependency is a function recreated each render and triggers the effect in a loopExtra abstraction, but it makes the dependency stable

I avoid silencing the exhaustive-deps lint rule with an eslint-disable comment unless I can state why the effect should not re-run. That comment is where the next stale closure gets introduced six months later, usually after a refactor moves a variable inside the effect.

Two failure modes I check before closing the ticket. First, a race: with [userId] added, a slow u1 response can land after the u2 response and overwrite it. The cancelled flag in the cleanup above, or an AbortController, prevents that. Second, a missing dependency that is not a prop: a value from context, a store selector, or a ref read inside the effect. The lint rule catches most of these, so a clean lint run plus the two-render trace is my bar for done.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-14In React, what makes an input controlled instead of uncontrolled?

The 90-second answer

A controlled input is controlled by React. Its value prop comes from React state, and every keystroke runs onChange to update that state. An uncontrolled input is controlled by the DOM. React renders it once with defaultValue, the browser stores what the user types, and you read the value later through a ref or FormData.

That single difference decides the rest. Because React sees every change in a controlled input, you can format the value, disable submit until it is valid, or show an error as the user types. Because React never sees intermediate changes in an uncontrolled input, you avoid a re-render per keystroke, but you cannot react to typing without extra code.

TSX
// React 18, TypeScript
function ControlledEmail() {
  const [email, setEmail] = useState("");
  return (
    <input
      value={email}
      onChange={(event) => setEmail(event.target.value)}
      type="email"
      name="email"
    />
  );
}

function UncontrolledEmail() {
  const ref = useRef<HTMLInputElement>(null);
  return (
    <>
      <input ref={ref} defaultValue="" type="email" name="email" />
      <button onClick={() => console.log(ref.current?.value)}>
        Read from DOM
      </button>
    </>
  );
}

In the controlled version, removing value or onChange breaks the pattern. If you set value without onChange, React makes the field read-only, because state never changes and React keeps resetting the DOM to the prop. That warning in the console is the tell.

ControlledUncontrolled
Value stored inReact stateDOM node
Set at render withvaluedefaultValue
Updated byonChange handler calling setStateBrowser as user types
Read withState variableRef or FormData
Re-renders on typingYesNo

A worked trace makes the split concrete. Typing a, then n, then a into the controlled input fires onChange three times, calls setEmail three times, and re-renders three times with values "a", "an", and "ana". Typing the same three characters into the uncontrolled input fires no React handler and no re-render. The DOM node holds "ana" silently until the button reads ref.current.value.

Controlled Uncontrolled User types a character Input type onChange fires setState updates value React re-renders input Browser updates DOM node No React work until read

The practical default follows from that trace. Use controlled inputs for fields that need live behaviour, such as a card number mask, an autocomplete, or a dependent field that clears when a country changes. Use uncontrolled inputs for a long settings form where nothing depends on intermediate values and you only need the final values on submit. File inputs are a forced case, since the browser owns the selected file and React cannot set it through value.

One failure mode catches people switching between the two. An uncontrolled input only applies defaultValue on first mount. If you render it before data loads and the value arrives later, the field stays empty. Remounting the form with a key tied to the loaded record, or switching that field to controlled, fixes it. The reverse switch has the opposite trap. Moving a field to controlled without wiring onChange freezes it, which is usually a sign the field was meant to stay uncontrolled.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-15Your activity feed is paginated, sortable and filterable, rows hold expanded state and an optimistic edit, items have no stable id and titles duplicate, and the API cannot change this sprint. How do you choose keys without state jumping or losing edits on refetch?

The 90-second answer

With no stable id, you cannot make row identity perfect. You have to decide which state you are willing to lose, and move the state you cannot lose out of the row. Index keys preserve the wrong thing: they keep the component instance at a position while the item at that position changes. On a sortable, filterable, paginated feed that guarantees expanded rows, focus and in-progress edits attach to a different activity after any reorder, filter or page change. The workable compromise this sprint is to lift the optimistic edit into the parent, key rows by the best available content identity, and force a deliberate remount when the ordering context changes so stale local state does not survive a sort or filter.

Assume the API returns activities with actor, verb, createdAt and text, no id, and two activities can have identical fields. Rows have local expanded state and an edit draft. The draft is the state that must survive a refetch. Expanded state is nice to survive, but surviving it incorrectly is worse than losing it.

TSX
// React 18. Draft lives in the parent, keyed by content identity.
type Activity = { actor: string; verb: string; createdAt: string; text: string };

function Feed({ items, sort, filter }: { items: Activity[]; sort: string; filter: string }) {
  const [drafts, setDrafts] = useState<Record<string, string>>({});
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});

  return (
    // Changing sort or filter remounts the list on purpose. Local row state resets.
    <ul key={`${sort}:${filter}`}>
      {items.map((a) => {
        const k = `${a.actor}|${a.createdAt}|${a.verb}|${a.text}`;
        return (
          <ActivityRow
            key={k}
            activity={a}
            draft={drafts[k] ?? a.text}
            expanded={!!expanded[k]}
            onDraft={(v) => setDrafts((d) => ({ ...d, [k]: v }))}
            onToggle={() => setExpanded((e) => ({ ...e, [k]: !e[k] }))}
          />
        );
      })}
    </ul>
  );
}

Worked trace: sort changes, then a refetch returns the same items in a new order

Items X and Y. User expands X and edits its draft to "edited". Then the user sorts by newest first, so order flips to Y, X. A refetch then returns the same two items.

StepWith key={i} and draft in rowWith lifted draft and content key
InitialRow 0: X, row 1: YX keyed by its content, Y by its content
User expands and edits XInstance 0 holds expanded=true, draft="edited"Parent holds expanded[X]=true, drafts[X]="edited"
Sort flips orderInstance 0 now renders Y but keeps expanded=true and draft="edited"X instance moves with X, Y with Y, both states follow the item
Refetch, same itemsDraft still shown on Y, the wrong activityDraft still on X, because the key is derived from the item, not position
Filter removes X, then re-adds itInstance may be reused for another itemX remounts, draft restored from parent, expanded restored if you kept it in parent

The content key is not a real id. It fails in a specific, bounded way: two truly identical activities (same actor, same second, same verb, same text) collide and React treats them as one item. You cannot distinguish them from the payload alone. That is the point to surface to product. The fix is a server id or a client id assigned at creation and persisted with the item. Until then, identical duplicates will share expanded and draft state, and deleting one of them will unmount only one instance while the other keeps its state. That is a data contract problem, not a key trick.

Trade-offs among the options you actually have

StrategyWhat it preservesWhat it breaks
Index keyNothing reliably once order changesExpanded, focus, uncontrolled input and drafts jump to the wrong row on sort, filter, insert, delete or page change
Content key, state in rowExpanded state follows the item across reorders and refetchesIdentical duplicates collide. A text edit changes the key, so the row remounts and loses its draft mid-edit
Content key, draft lifted to parentDraft survives remounts, refetches and the text-edit key change if you key the draft by a pre-edit identityYou must store drafts for items that may never be saved, and clean them up on save or delete
Index key plus remount on sort, filter and pageNo stale state survives a context change, simple to reason aboutExpanded state and scroll position reset on every sort or filter change, even when the item is still visible
Assign a client id on first render and store it in a Map keyed by contentGives stable identity within a session for distinct contentCollapses on identical duplicates, lost on full reload, and drifts if the server later returns a real id

Two details decide whether this holds up. First, pagination: index keys restart at 0 on page 2, so React reuses page 1 instances for page 2 items. Include the page in the list container key, or use the content key, so page 2 does not inherit page 1 state. Second, the optimistic edit: if the draft lives in the row and the key is content based, saving changes text, changes the key, and unmounts the row while the save is in flight. Lifting the draft and keying it by the identity captured when editing started avoids that self-inflicted remount.

When the API can change, replace the content key with the server id and move expanded state back into the row if you want it to reset on unmount. Until then, be explicit in the PR about the duplicate collision and the reset on sort or filter. Those are the two behaviours a reviewer and a user will actually notice.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-16How would you model loading, success, and error states for an API response in TypeScript so the UI cannot render an impossible combination?

The 90-second answer

Use a single status literal as the discriminator and put only the fields that state can actually have on each variant. The compiler then narrows the type inside each branch, so the UI cannot read data while the request is still loading or render an error and a result at the same time.

TypeScript
// TypeScript 5.x
type ApiState<T> =
  | { status: "idle" }
  | { status: "loading"; requestId: string }
  | { status: "success"; data: T; fetchedAt: number }
  | { status: "error"; code: string; message: string; retryable: boolean };

function render<T>(state: ApiState<T>, renderData: (data: T) => string): string {
  switch (state.status) {
    case "idle":
      return "";
    case "loading":
      return `Loading ${state.requestId}…`;
    case "success":
      return renderData(state.data);
    case "error":
      return state.retryable ? `Retry: ${state.message}` : state.message;
    default: {
      const _exhaustive: never = state;
      return _exhaustive;
    }
  }
}

The never check is the point. Add a fifth variant, say status: "partial", and every switch without a case for it fails to compile until you decide what the UI does with it. That is the mechanism doing the work, not a lint rule.

Why this beats the usual alternatives

ApproachImpossible state it allowsWhat breaks in practice
Discriminated unionNone at the type levelNeeds runtime parsing, see below
Separate booleans (isLoading, error, data)isLoading: true with error set and stale data presentUI picks a precedence order by accident, usually error wins on one screen and spinner wins on another
Nullable fields (data: T | null, error: string | null)data: null and error: null while loading, or both setEvery consumer re-derives what null means, and a failed refetch silently keeps showing old data as if it were fresh

With booleans I have debugged screens where a refetch after a 404 left the previous customer's orders on screen because data was never cleared. The union forces the choice into the type: either you model success with stale data explicitly, for example { status: "success"; data: T; stale: boolean }, or a refetch moves you back to loading and the old data is gone by construction.

The failure mode the type does not fix

TypeScript types are erased at runtime. If the API returns { status: "success" } with no data, or adds status: "rate_limited" next deploy, the union lies. So parse at the boundary and keep the union as the internal contract only.

TypeScript
import { z } from "zod";

const OrderResponse = z.discriminatedUnion("status", [
  z.object({ status: z.literal("success"), data: z.object({ id: z.string(), total: z.number() }), fetchedAt: z.number() }),
  z.object({ status: z.literal("error"), code: z.string(), message: z.string(), retryable: z.boolean() }),
]);

type OrderResponse = z.infer<typeof OrderResponse>;

A payload that fails parsing becomes a thrown error you map to the error variant in one place, instead of a runtime crash in ten components. I also keep server status names and client status names identical. Renaming error to failed on the client while the wire says error is where mapping bugs hide.

Two practical details. First, include a requestId or fetchedAt on loading and success when requests can race. Without it, a slow first request can overwrite a faster second one and the union will happily render the wrong customer's data. Second, do not collapse HTTP errors and domain errors into one error variant if the UI treats them differently. A 401 needs a redirect to login, a 422 needs field messages, a 503 needs retry. Model those as separate variants with their own fields, or keep a code field and branch on it explicitly as above. The union is only as useful as the distinctions you put in it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-17How would you use TypeScript generics to build a reusable API client that stays type-safe across endpoints with different response shapes?

The 90-second answer

I would make the transport generic over the response type, and make each endpoint a typed wrapper around it. The core is one request<T> function that knows how to send, read the status, and throw a typed error. Callers never write as any or cast the JSON. They call getOrder(id) and get back Promise<Order>, or listOrders() and get back Promise<Page<Order>>.

Generics do the compile-time work here. They do not check what the server actually sent at runtime, so I pair them with a runtime parser when the shape matters for rendering or checkout.

TypeScript
// Checked against TypeScript 5.5
type ApiError =
  | { kind: 'http'; status: number; code: string; message: string }
  | { kind: 'network'; message: string };

async function request<T>(
  path: string,
  init: RequestInit = {},
  signal?: AbortSignal,
): Promise<T> {
  let res: Response;
  try {
    res = await fetch(path, { ...init, signal, headers: { 'Content-Type': 'application/json', ...init.headers } });
  } catch (err) {
    throw { kind: 'network', message: err instanceof Error ? err.message : 'request failed' } satisfies ApiError;
  }
  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw { kind: 'http', status: res.status, code: body.code ?? 'unknown', message: body.message ?? res.statusText } satisfies ApiError;
  }
  return (await res.json()) as T;
}

The cast inside request is the one place I accept a cast. Every caller above it stays typed. That containment is the point. If I let each feature file cast its own response, a renamed field slips through in one screen and breaks in production.

Typing the endpoints, not just the transport

A generic transport alone still leaves callers guessing the type argument. I define the contract once, next to the client:

TypeScript
interface Order { id: string; totalCents: number; status: 'open' | 'paid' | 'cancelled' }
interface Page<T> { items: T[]; nextCursor: string | null }
interface CreateOrderInput { customerId: string; lines: { sku: string; qty: number }[] }

const api = {
  getOrder: (id: string, signal?: AbortSignal) =>
    request<Order>(`/orders/${id}`, {}, signal),
  listOrders: (cursor?: string, signal?: AbortSignal) =>
    request<Page<Order>>(`/orders?limit=50${cursor ? `&cursor=${cursor}` : ''}`, {}, signal),
  createOrder: (input: CreateOrderInput, signal?: AbortSignal) =>
    request<Order>('/orders', { method: 'POST', body: JSON.stringify(input) }, signal),
};

const order = await api.getOrder('o_42');
order.totalCents; // number, checked at compile time
// order.total; // error: property does not exist

For methods with a body, I add an overload or a second type parameter so the input is checked too:

TypeScript
function send<Req, Res>(path: string, body: Req, signal?: AbortSignal): Promise<Res> {
  return request<Res>(path, { method: 'POST', body: JSON.stringify(body) }, signal);
}

That gives me send<CreateOrderInput, Order> at the call site. A caller who passes { customer: 42 } gets a compile error before the request leaves the browser.

Where generics stop

TypeScript erases types when it compiles. request<Order> compiles to the same JavaScript as request<any>. If the API returns { id: 'o_42', total: '19.99' } instead of totalCents: 1999, the compiler stays silent and the UI renders undefined or does arithmetic on a string. I treat the generic as a promise about the contract, not proof of it.

For fields that drive money, permissions, or a state machine, I parse the payload with a schema (Zod is the usual choice in our stack) and type the client from the schema output:

TypeScript
const OrderSchema = z.object({
  id: z.string(),
  totalCents: z.number().int().nonnegative(),
  status: z.enum(['open', 'paid', 'cancelled']),
});
type Order = z.infer<typeof OrderSchema>;

async function getOrder(id: string, signal?: AbortSignal): Promise<Order> {
  const raw = await request<unknown>(`/orders/${id}`, {}, signal);
  return OrderSchema.parse(raw); // throws on drift, instead of rendering garbage
}

That costs a parse on every response. For a 50-row page it is measurable but small next to the network cost. For a high-frequency price tick stream I would skip parsing on the hot path and parse only at the boundary where the value is used.

Choosing between the options

ApproachWhat the caller getsFailure mode
request(): Promise<any>No checking anywhereA renamed field compiles, then breaks at runtime in one screen
request<T> with a cast per call siteChecking only if the caller writes the right TCasts scatter, drift is found late, one wrong cast hides a bug
Typed endpoint map over request<T>Checking at the call site, one cast inside the clientStill blind to runtime drift unless I add parsing
Typed map plus schema parseCompile-time and runtime checkingParse cost, and schema and server can still drift if nobody tests them

I land on the last row for order, payment, and inventory data, and the third row for low-risk display data where a wrong field degrades gracefully. The generic is what lets me switch between those two without rewriting callers. The schema is what keeps the generic honest.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-18Which runs first after synchronous code finishes, a Promise.then callback or a setTimeout callback, and why?

The 90-second answer

The promise callback runs first. After synchronous code finishes, the engine drains the entire microtask queue before it runs the next macrotask. Promise continuations are microtasks. setTimeout callbacks are macrotasks. So Promise.resolve().then(...) beats setTimeout(..., 0) even when the timer was scheduled first.

JavaScript
// Checked in Node 20 and current browsers
console.log('sync');

setTimeout(() => console.log('timer'), 0);

Promise.resolve().then(() => console.log('promise'));
OrderOutputQueue
1syncSynchronous code on the call stack
2promiseMicrotask queue, drained first
3timerMacrotask queue, runs after microtasks empty

The rule holds inside event handlers too. A click handler is one macrotask. When it returns, the browser empties the microtask queue, then it can paint, then it runs the next macrotask, which might be a timer or the next click. An await inside an async function resumes as a microtask, so it also runs before a pending timer.

Run one macrotask Drain microtask queue Paint if needed Pick next macrotask

Two follow-ups come up often. First, a chained promise still runs in the same drain. If the first then queues another then, that second one joins the queue before any timer runs. Second, microtasks do not yield to paint. A long chain of promise continuations will delay rendering until the queue empties, while a setTimeout chunk gives the browser a chance to paint between pieces of work. That is why chunking a large list update with timers or scheduler.yield() keeps input responsive, and wrapping the same loop in promises does not.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-19Walk me through how you would build a search input that debounces at 300 ms, never renders results for an older query even when the server ignores aborts, and stays correct under React StrictMode double effects, unmounts, and a cleared query?

The 90-second answer

I would debounce on the trailing edge at 300 ms, abort the previous fetch in the effect cleanup, and gate rendering on a sequence number that only the newest request can pass. Abort alone is not a correctness guarantee. The server may ignore the signal, the response may already be in flight, and React StrictMode in development mounts, cleans up, and remounts the effect. The sequence check survives all three because it answers a different question: is this response still for the query the user is looking at?

TSX
// React 18, TypeScript
function useDebouncedSearch(query: string, delay = 300) {
  const [results, setResults] = useState<Result[]>([]);
  const [status, setStatus] = useState<"idle" | "loading" | "error">("idle");
  const seqRef = useRef(0);

  useEffect(() => {
    const seq = ++seqRef.current;
    if (!query.trim()) {
      setResults([]);
      setStatus("idle");
      return;
    }
    const controller = new AbortController();
    setStatus("loading");
    const timer = setTimeout(async () => {
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
          signal: controller.signal,
        });
        if (!res.ok) throw new Error(String(res.status));
        const data = (await res.json()) as Result[];
        if (seq !== seqRef.current) return;
        setResults(data);
        setStatus("idle");
      } catch (err) {
        if (err instanceof DOMException && err.name === "AbortError") return;
        if (seq === seqRef.current) setStatus("error");
      }
    }, delay);
    return () => {
      clearTimeout(timer);
      controller.abort();
    };
  }, [query, delay]);
  return { results, status };
}

Three details carry the correctness. First, the sequence increments at effect start, not inside the timer. A cleared query therefore invalidates an in-flight request immediately, even though no new fetch will run. Second, cleanup clears the timer and aborts the controller, so StrictMode's first pass never fires a fetch and an unmounted component never receives a late setState. Third, errors from superseded requests are swallowed. Showing an error banner for a query the user abandoned would be a false alarm.

Yes No No Yes Query changes Increment sequence, run prior cleanup Query empty? Clear results, no fetch Start 300 ms timer Fetch with AbortSignal Sequence still current? Discard response or error Render results or error

Worked trace

TimeEventSequenceOutcome
0 msTypes rea41Timer pending, no request
200 msTypes read, cleanup runs42Timer for 41 cleared, nothing aborted yet
500 msTimer fires42Request 42 starts
650 msTypes reads, cleanup runs43Request 42 aborted client side
800 msResponse for 42 arrives anyway, server ignored abort43Discarded, 42 is not current
950 msResponse for 43 arrives43Rendered
1000 msStrictMode remount in dev, effect runs twice44, then 45First timer cleared by cleanup, only 45 can render

The 800 ms row is the case interviews probe. Abort frees the browser connection and usually stops server work, but the client cannot rely on it. The sequence check is the authoritative guard.

Trade-offs I would state unprompted

Trailing debounce fits search because the final query is the one worth paying for. Leading debounce would fire on the first keystroke with an incomplete term. Throttle fits a slider, where intermediate values matter and a steady 200 ms cadence beats waiting for a pause. I fire immediately on Enter by flushing the pending query and skipping the timer, since the user has signalled intent.

Delay is measurable. At 300 ms, a typist pausing between words fires about one request per word. At 150 ms, request volume roughly doubles for the same typing. I keep prior results on screen during loading to avoid layout shift, and I watch p95 latency on /api/search plus the abort rate. A rising abort rate with rising latency usually means the endpoint is slow enough that each keystroke queues behind the last one. The client fix is a shorter debounce or a minimum query length. The server fix is cancelling the index lookup when the client disconnects, which the client cannot do alone.

Caching needs the same discipline as rendering. If I cache by query string only, a tenant or permission filter omitted from the key can serve one user's results to another. I key on query plus user scope, cache only successful responses, and never let a cached entry bypass the sequence check on the way to the screen.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-20Your dashboard has cards of uneven content height that must align in columns, pin footers to the bottom, and reflow from 4 columns to 1 without a stretched last row. How do you lay it out with flexbox and grid, and where does each one break?

The 90-second answer

I would use grid for the card list and flexbox inside each card. Grid gives me shared column tracks, so cards in the same column have the same width and line up across rows even when their content differs in height. Flexbox inside a card gives me a single column where the body can grow and push the footer to the bottom. Neither alone handles both jobs cleanly. Flexbox for the list wraps each row independently, so the last row redistributes its own free space. Grid alone for the card interior forces me to define rows for content I do not control.

Why the list breaks under flexbox

Flexbox lays items along a main axis. With flex-wrap: wrap, each wrapped line is laid out on its own. Suppose the container is 1200px wide and each card has flex: 1 1 260px. Four cards fit on line one and share the free space. If there are six cards, line two has two cards. Those two grow to fill the full 1200px, so each becomes roughly 600px wide while the cards above are 300px. The columns no longer align, and the last row looks stretched. I can stop the growth with flex-grow: 0 and a fixed basis, but then at a narrower width the cards leave ragged space on the right and I am tuning basis values per breakpoint to fake what a track does for free.

Grid avoids this because width comes from the track, not from the items on a line. repeat(auto-fit, minmax(260px, 1fr)) creates as many 260px-or-wider columns as fit, and every card placed in column two gets that column width regardless of which row it sits in. A short last row keeps the same column widths and leaves empty tracks at the end.

CSS
/* List: two dimensions, shared tracks */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 16px;
}

/* Card interior: one dimension, footer pinned down */
.card {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.card__body { flex: 1; }
.card__footer { margin-top: auto; }

Worked trace at three widths

Assume six cards, gap: 16px, and the rule above. Hypothetical figures, but the arithmetic is what the browser does.

Container widthColumns createdCard widthLast row
1200px4(1200 - 3*16) / 4 = 288px2 cards at 288px, 2 empty tracks
800px2(800 - 16) / 2 = 392px2 cards at 392px, aligned under row one
360px1360px6 rows of 1 card, no stretching decision to make

At 800px the flexbox version with flex: 1 1 260px would put three cards on line one at about 256px each and three on line two at the same width, which looks fine until the count changes to seven. Then line three holds one card that grows to 800px. Grid at 800px with seven cards holds 392px columns for every row. That stability when content count changes is the practical reason I pick grid here.

Where grid alone breaks inside the card

A card has an image, a title, a variable-length description, and a footer with a price and a button. If I use grid for the interior I need grid-template-rows: auto auto 1fr auto and I must know the order and count of children. That works until a card has no image or a badge appears above the title. Flexbox column handles it with one rule: the body grows, the footer stays at the bottom. height: 100% on the card matters too. Grid items stretch to the track by default, so cards in a row share the row height, and the flex column inside can then pin the footer to that shared bottom. Without the explicit height, a short card ends where its content ends and the footers sit at different heights.

Choosing in review

NeedLayoutMechanism doing the work
---------
Columns aligned across rowsGridShared tracks
Items distributed along one line, sized by contentFlexboxflex-grow, flex-shrink, flex-basis on the main axis
Footer pinned to bottom of equal-height cardFlexbox column inside a stretched grid itemflex: 1 on the body, margin-top: auto on the footer
Reflow from 4 columns to 1GridChange the minmax() minimum or the repeat count, tracks follow
Toolbar with a spacer pushing actions rightFlexboxflex: 1 on the spacer absorbs free space on one axis

The decision rule I state in a pull request is short. If alignment across rows matters, start with grid. If distribution along a single line matters, start with flexbox. Most product screens need both, nested, with grid owning the page structure and flexbox owning the components inside it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-21Walk me through the browser rendering path from HTML to paint?

The 90-second answer

The browser turns bytes into pixels in a pipeline, and each stage can invalidate the next one. HTML is parsed into a DOM, CSS into a CSSOM, the two are combined into a render tree that drops anything not displayed, then layout computes geometry, paint draws into layers, and the compositor assembles the final frame on the GPU. A change late in that pipeline is cheap. A change early, like a font load or a width change on a parent, can force layout and paint for the whole subtree.

HTML and CSS bytes DOM and CSSOM Render tree Layout Paint into layers Composite to screen

Parsing and the render tree

The HTML parser is incremental. It builds DOM nodes as bytes arrive, so the browser can start rendering before the document finishes downloading. That is why a slow stylesheet in <head> still blocks first paint. CSS is not incremental in the same way. The parser needs the full CSSOM to know which rules apply, so rendering waits for stylesheets, and a synchronous <script> in the head waits for CSS too, because the script might query computed style.

Once both trees exist, the browser builds the render tree. display: none removes a subtree entirely. visibility: hidden keeps it, because it still occupies layout space. Elements with display: contents are the awkward middle case: the box disappears but the children render, which can surprise people debugging layout.

Layout, paint, composite

Layout, also called reflow, walks the render tree and computes the position and size of every box. Paint then records drawing commands, text, borders, backgrounds, into layers. Composite hands those layers to the GPU, which can move or fade a layer without repainting its contents.

That split explains the performance advice you actually use in a product codebase. Changing transform or opacity usually stays in the compositor. Changing width, top, or margin invalidates layout, then paint, then composite. At 60 fps you have about 16.7 ms per frame, and that budget has to cover JavaScript, layout, paint, and composite. A 5,000 row grid that reflows on every keystroke will miss it even if the React render itself is fast.

ChangeLayoutPaintCompositeTypical cost
transform: translateX(10px) on a cardnonoyesunder 1 ms for a small layer
opacity fade on a modalnosometimesyescheap if promoted to its own layer
width change on a sidebaryesyesyescan exceed 16 ms with many descendants
Font swap after font-display: swapyesyesyestext reflows, page jumps
background-color on a buttonnoyesyespaint only, no geometry

Where it breaks in practice

The failure mode I see most is forced synchronous layout. Reading offsetHeight or getBoundingClientRect() right after writing a style forces the browser to run layout immediately, in the middle of your JavaScript, instead of batching it at the next frame. In a loop over rows, that turns one layout pass into thousands.

JavaScript
// Checked against Chrome 126, DevTools Performance panel.
// Bad: read after write, per row. Forces a layout each iteration.
for (const row of rows) {
  row.style.height = row.dataset.h + 'px';
  const h = row.offsetHeight; // sync layout here
  row.dataset.measured = h;
}

// Better: write all, then read all. One layout pass.
for (const row of rows) row.style.height = row.dataset.h + 'px';
for (const row of rows) row.dataset.measured = row.offsetHeight;

The same pattern shows up with images without dimensions. The browser paints text, the image arrives, layout runs again, and content below shifts. That is a Cumulative Layout Shift problem, and the fix is boring and effective: reserve space with width and height attributes or an aspect ratio box, so the first layout already has the final geometry.

Long tasks are the other killer. A 200 ms synchronous script blocks parsing and also blocks the main thread that handles input, so the browser cannot paint the result of a click until the script yields. Splitting work with requestAnimationFrame, yielding between chunks, or moving parsing and filtering to a Web Worker keeps the frame budget intact. I measure this with the Performance panel and look for long tasks over 50 ms, then check whether layout or paint is the dominant slice before reaching for memoization.

For a product engineer, the practical takeaway is to ask which stage a change invalidates before optimizing. If a price tick only changes text color, paint is enough. If it changes row height in a virtualized grid, you are paying for layout on every tick, and the fix is to fix the row height or isolate the ticking cell, not to add more memoization.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-22A flex item with long text keeps overflowing its container on mobile. What single CSS property lets it shrink below its content size?

{"prompt":"A flex item with long text keeps overflowing its container on mobile. What single CSS property lets it shrink below its content size?","answerMd":"The 90-second answer\n\nSet min-width: 0 on the flex item. Flex items default to min-width: auto, which resolves to the item's minimum content size. A long unbroken word, a URL, or an image therefore sets a floor the item will not shrink below, even when the container is narrower. Setting min-width: 0 removes that floor, so the item can shrink to the size the flex algorithm assigns it.\n\ncss\n/* Checked against current CSS Flexbox spec behaviour in Chrome and Firefox */\n.card-row {\n display: flex;\n gap: 16px;\n}\n\n.card-row__body {\n flex: 1;\n min-width: 0; /* the fix: allow shrinking below content size */\n}\n\n.card-row__body p {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n\nThe overflow rules on the paragraph are separate. min-width: 0 lets the box shrink. Without clipping or wrapping inside the box, the text itself will spill out of the shrunken box.\n\nWorked trace\n\nHypothetical figures: a 320px wide phone viewport, a flex row with a 64px avatar and a text block beside it.\n\n| Step | Value | Result |\n| --- | --- | --- |\n| Container width | 320px | Row must fit in 320px |\n| Avatar plus gap | 64px + 16px = 80px | Leaves 240px for the text block |\n| Text block content | One 480px unbroken string | Minimum content size is 480px |\n| Default min-width: auto | Floor is 480px | Row needs 80px + 480px = 560px, so it overflows by 240px |\n| min-width: 0 | Floor is 0px | Flex algorithm gives the text block 240px and the string clips or ellipsises inside it |\n\nThat 560px against 320px is the horizontal scrollbar people see on mobile while desktop looks fine, because at 1280px the 480px floor fits easily.\n\nHow the values compare\n\n| Value | Floor used | When it helps |\n| --- | --- | --- |\n| auto (default) | Minimum content size | Keeps short labels and icons from collapsing, which is why it is the default |\n| 0 | Zero | Lets a text or media block shrink inside a flex or grid row |\n| 100% | Full container width | Rarely what you want here, it forces the item to stay wide and can recreate the overflow |\n\nThe same default applies to grid items, so a grid column with long content can overflow the same way and needs the same treatment on the item.\n\nFailure modes to check after the fix\n\nShrinking the box exposes the next problem if the inner content has no wrapping or clipping rule. Text overlaps the next column, an image keeps its intrinsic width and paints outside the box, or a nested flex row inside the shrunken item overflows again because that inner item also has min-width: auto. I check each nested level, add overflow-wrap: anywhere for URLs and codes that must wrap mid-string, and give images max-width: 100% so they scale with the box.\n\nTo confirm the fix I retest at 320px, 375px and the breakpoint above the mobile layout, and I check that document.documentElement.scrollWidth equals clientWidth at each width."}

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-23Walk me through how you would make a complex filter-and-sort toolbar in a data grid fully accessible with semantic HTML and keyboard navigation, without breaking existing mouse and touch behaviour?

The 90-second answer

Start from the native element that already does the job, then add ARIA only where the native semantics run out. A filter toolbar is a form, a sort control is a button, a results list with tabular data is a table. Those choices give screen readers names, roles and states for free, and they give keyboard users activation with Enter and Space without custom key handlers.

I would build the toolbar as a <form> with labelled controls, the results as a real <table> with <th scope="col"> headers, and sort as <button aria-sort> on the header cell. Focus order follows the visual order, every interactive element is reachable by Tab, and arrow keys are reserved for composite widgets like the grid itself, following the WAI-ARIA Authoring Practices grid pattern. If a filter panel opens as a dialog, focus moves in on open, is trapped while it is open, and returns to the trigger on close.

Semantic structure first

HTML
<form aria-label="Filter orders" onsubmit="return false">
  <label for="status">Status</label>
  <select id="status" name="status">
    <option value="">All</option>
    <option>Open</option>
    <option>Shipped</option>
  </select>
  <button type="button" aria-pressed="false" id="sort-date">
    Sort by date
  </button>
  <p id="result-count" role="status">1,240 results</p>
</form>

<table>
  <caption>Orders</caption>
  <thead>
    <tr>
      <th scope="col" aria-sort="descending">
        <button type="button">Date</button>
      </th>
      <th scope="col">Customer</th>
    </tr>
  </thead>
  <tbody>...</tbody>
</table>

Three decisions matter here. type="button" stops a sort button submitting the form by accident. role="status" on the count announces result changes politely without interrupting, and it is updated once per filter change, not per keystroke. aria-sort belongs on the th, not the button inside it, because that is where the table semantics live. A <div> with onClick and tabindex="0" would need all of this rebuilt by hand and would still miss the table relationships a screen reader uses to announce column and row position.

Keyboard behaviour

Tab moves between toolbar controls and into the grid once. Inside the grid, arrow keys move cell to cell with a roving tabindex, so only one cell is in the tab order at a time. That is the APG grid pattern, and it is the exception to "everything is a Tab stop".

KeyContextBehaviour
Tab / Shift+TabToolbar, then gridEnters grid on the active cell, leaves from the same cell
Arrow keysGrid cellMoves focus one cell, scrolls into view if needed
Home / EndGrid rowFirst or last cell in the row
PageUp / PageDownGridMoves by the visible page of rows
Enter / SpaceButton, link, cell actionActivates, matching native button behaviour
EscapeOpen filter dialogCloses dialog, returns focus to trigger

Visible focus is part of the contract. I would keep the browser :focus-visible outline, test it at 200% zoom and in forced colours mode, and never remove it with outline: none unless I replace it with an equivalent indicator. WCAG 2.2 AA also sets a 24 by 24 CSS pixel minimum target size, so dense grid actions need padding or a larger hit area even if the icon is small.

Failure modes I check for

The common one is focus loss on rerender. Filtering replaces the tbody, the focused cell is removed from the DOM, and focus drops to <body>. The fix is to track the focused row id, restore focus to the equivalent cell after render, and only do that when the grid had focus before the update. A second failure is positive tabindex values, which reorder focus away from the visual order and break the moment layout changes. A third is aria-hidden="true" on a container that still holds focusable elements, which hides them from assistive tech while keeping them in the tab order.

I verify with a keyboard-only pass through the whole flow, NVDA with Chrome and VoiceOver with Safari for the table and live region announcements, and axe or Lighthouse for missing labels and contrast. Mouse and touch behaviour stays intact because none of this replaces pointer handling. It adds a parallel path that uses the same buttons and the same state, which is what makes the feature shippable rather than a separate accessible version.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-24A product page has a slow hero image, janky filter clicks, and content jumping when a banner loads. How would you diagnose which of LCP, INP, or CLS each problem affects and what you would check first for each?

The 90-second answer

Each metric measures a different moment, so I diagnose them separately. LCP is when the largest element becomes visible. INP is how quickly the page responds after a click, tap, or keypress. CLS is how much visible content jumps around while the page loads. If I know which moment is broken, I know where to look.

For the page you described, the slow hero image is an LCP problem, the janky filter clicks are an INP problem, and the banner pushing content down is a CLS problem. I would confirm each one with a specific check rather than guessing from a single Lighthouse score.

LCP: check when the hero image is discovered

LCP is usually the hero image or headline on a product page. I split its time into server response, the delay before the browser starts loading the image, the download itself, and the delay before it paints. A slow hero often has a short server response but a long discovery delay. That happens when the image URL only appears after JavaScript runs, or when a CSS file blocks it.

I check the Network panel for the hero request and see when it starts relative to the HTML. If it starts late, I move the image into the HTML with a preload hint and serve a version sized for the rendered display. Preloading helps when the image is definitely the LCP element on that template. It hurts when the same page has variants where a different element is largest, because the browser then downloads an image it may not need first.

INP: find the long task after the click

INP runs from the input event to the next paint after the browser finishes handling it. A filter click that freezes for 300 ms usually means one synchronous task is doing too much, such as filtering and re-rendering thousands of rows in the click handler.

I reproduce the click with Performance recording on and look for a long task starting right after the input. The fix depends on what that task does. If it renders rows the user cannot see, I virtualize the list so only visible rows are in the DOM. If it filters a large array, I move that work off the main thread or ask the server to return a smaller result set. I retest the same click, because moving work to a worker only helps if the paint after the click actually gets sooner.

CLS: read the shift source

CLS adds up layout shifts that happen without recent user input. A banner inserted above the title at load time will shift everything below it. I use a PerformanceObserver for layout-shift entries and read the sources on each entry. The source names the node that moved, which tells me whether the banner, an image without dimensions, or a font swap caused it.

For the banner, I reserve its height in the layout before it loads, or I place it where it cannot push the main content. Reserving space keeps CLS at zero for that shift, at the cost of empty space on loads where the banner does not appear. Placing it below the fold avoids that empty space, but it may reduce how many users see it.

SymptomMetricFirst checkLikely fix
Hero appears after 4 secondsLCPWhen the hero request starts in the Network panelPreload the hero in HTML and resize the file
Filter click freezes the pageINPLong task right after the click in Performance recordingVirtualize rows or move filtering off the main thread
Title jumps down when banner loadsCLSLayout-shift source nodeReserve banner height or move it below the fold

Measuring it in the page

For ongoing data I use the web-vitals library and send each value to our analytics endpoint with the page path. That lets me see whether the fix moved the value for this template instead of relying on one lab run.

JavaScript
import { onLCP, onINP, onCLS } from 'web-vitals';

function send(metric) {
  navigator.sendBeacon('/rum', JSON.stringify({
    name: metric.name,
    value: Math.round(metric.value),
    path: location.pathname,
  }));
}

onLCP(send);
onINP(send);
onCLS(send);
Before content shows After a click or keypress Content moves on load Symptom When does it happen? LCP: check image discovery INP: find long task CLS: read shift source

I would verify each fix with the same check that found the problem. If the hero request still starts late, the preload did not work. If the long task is still there after the click, the list is still too large. If the shift source is still the banner, the reserved space is the wrong height.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-25Our initial JS bundle is 1.8 MB and LCP is 4.5s on 4G. How would you use code splitting and lazy loading to cut it without breaking the routes users actually hit?

The 90-second answer

Split by route first, then by heavy component, and keep the initial chunk to what the first paint needs. With React and Vite, that means React.lazy plus dynamic import() for each route, and a separate dynamic import for anything only needed after interaction, like a chart editor or PDF exporter. Measure before and after with the bundle analyzer and field LCP, not just the build size.

Assume a 1.8 MB uncompressed initial bundle, about 520 KB gzipped, on a mid-tier Android over 4G. That is roughly 3 to 4 seconds of transfer alone before parsing. Route splitting typically moves 60 to 70 percent of that out of the critical path if most code belongs to pages the user does not visit first.

TSX
// React 18, Vite 5
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';

const Checkout = lazy(() => import('./routes/Checkout'));
const AdminReports = lazy(() => import('./routes/AdminReports'));

// Loaded only on click, not on first paint
const PdfExporter = lazy(() => import('./components/PdfExporter'));

export function App() {
  return (
    <Suspense fallback={<RouteSkeleton />}>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/checkout" element={<Checkout />} />
        <Route path="/admin/reports" element={<AdminReports />} />
      </Routes>
    </Suspense>
  );
}

Home stays in the initial chunk. Checkout and AdminReports become separate chunks that the browser fetches when the route is matched. PdfExporter does not load until the user clicks Export, which is where lazy loading earns its keep.

ChunkContentsGzipped size, hypothetical but labelledWhen fetched
indexReact, router, shell, Home210 KBFirst load
checkoutCheckout form, payment SDK wrapper145 KBNavigating to /checkout
admin-reportsCharts, table virtualization310 KBNavigating to /admin/reports
pdf-exporterpdf-lib, fonts380 KBClicking Export
sharedShared UI, utils used by 2+ chunks65 KBFirst chunk that needs it

Initial load drops from 520 KB to about 275 KB gzipped including shared. On the same 4G profile that moves LCP from roughly 4.5 s to 2.6 s in lab tests. The win is real only if the user actually lands on Home. If 80 percent of traffic lands directly on Checkout from ads, that route needs preloading, not lazy loading.

Where the split points come from

Route boundaries are the safest first cut because they match how users arrive and they rarely create waterfalls inside a single view. Component boundaries come next, but only for code that is large and rarely used. A 12 KB date picker split into its own chunk adds a request, a loading state, and a possible flash for almost no saving. A 380 KB PDF library split the same way is worth it.

/checkout /admin/reports Initial HTML index chunk Home renders User navigates checkout chunk admin-reports chunk User clicks Export pdf-exporter chunk

Failure modes I check for

Waterfalls: a lazy route that imports three more lazy components in sequence fetches them one after another. Fix by importing them in parallel in the route module, or by prefetching on hover and on idle with requestIdleCallback for the next likely route.

Duplicated code: two lazy chunks each bundling the same chart library doubles download. The bundler should extract that into shared. I verify this in the analyzer output, not by trusting the config.

Loading UX: a blank screen while a 310 KB chunk arrives hurts more than a slightly larger initial bundle. I keep a skeleton that matches the layout to avoid CLS, and I preload the chunk when the link enters the viewport. For the primary conversion route, I preload after first paint rather than waiting for the click.

Errors: a failed chunk fetch, often after a deploy when chunk hashes change, needs a retry path. Suspense alone shows the fallback forever. I add an error boundary that offers a reload, and I set long cache headers on hashed chunks so returning users reuse them.

What I would not do

I would not split every component, and I would not chase the smallest possible initial bundle if it pushes work into the interaction path. Splitting the checkout form itself would delay the form the user came to fill. The target is a fast first paint and a fast first interaction on the routes that carry revenue, with the rest deferred and prefetched where it is predictable.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-26What do you save before applying an optimistic update so you can roll it back if the server rejects it?

The 90-second answer

Save the previous value before you change anything on screen. Apply the new value immediately, send the request, and if the server rejects it, put the saved value back. That saved copy is the rollback. Without it you have to reconstruct the old state from whatever the server returns, and on a failed request there is often no useful response to reconstruct from.

I use this for actions the user can undo and that do not cost money, such as liking a post, renaming a saved view, or toggling a setting. I do not use it for a payment or a stock count, where showing a value the server has not confirmed would mislead the user into acting on it.

TSX
// TypeScript, React 18
async function renameView(view: SavedView, nextName: string) {
  const previousName = view.name; // snapshot taken before the optimistic write
  setViews(vs => vs.map(v => v.id === view.id ? { ...v, name: nextName } : v));

  try {
    const saved = await api.renameView(view.id, nextName);
    setViews(vs => vs.map(v => v.id === view.id ? saved : v));
  } catch {
    setViews(vs => vs.map(v => v.id === view.id ? { ...v, name: previousName } : v));
    toast.error('Rename failed. Previous name restored.');
  }
}

The order matters. Snapshot first, then write, then request. If you write first and snapshot second, you have saved the new value and the rollback restores the wrong thing.

Worked trace for a rename the server rejects because the name is taken:

StepEventWhat the user seesServer state
1User submits "Q3 pipeline""Q3 pipeline" at once"Saved views"
2PATCH /views/v_12 returns 409"Q3 pipeline" still shown"Saved views"
3Catch block runs and restores the snapshot"Saved views" plus an error toast"Saved views"
4User submits "Q3 pipeline (2)""Q3 pipeline (2)" at once"Saved views"
5PATCH returns 200 with the saved viewServer copy, same text"Q3 pipeline (2)"
alt [server accepts] [server rejects] submit new name save old name, show new name PATCH request 200 saved view replace local copy with server copy 4xx or 5xx restore saved name error toast User Client state API

The failure mode to watch is a silent rollback. If the catch block restores the old name but shows no message, the user believes the rename worked and may build the next step on a name the server never stored. Restoring state and telling the user are both required. A rollback the user never notices is worse than waiting for the server, because the screen and the server now disagree without anyone knowing.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-27How do you design loading, empty, and error states for a personalized recommendations panel that must avoid flicker and layout shift, never show one user's cached recommendations to another after an account switch, and keep working when personalization fails but generic items succeed?

The 90-second answer

I start from the failure cases, because the happy path is easy. For a personalized recommendations panel I need to handle slow first load without flicker, a user with no history, personalization failing while generic items succeed, and an account switch while a request is still in flight. The last one is the one that causes real harm. If I cache recommendations by panel id alone, user B can briefly see user A's items after logout or account change. I key every cached state by user id and consent state, and I discard any response that arrives for a previous key.

Loading needs two thresholds. Below 200 ms I show nothing, because a skeleton that flashes for 80 ms reads as a bug. Past 200 ms I show a skeleton that reserves the exact height and item count of the final list, so content below does not shift. I set an 8 s timeout for this non critical panel. On timeout I do not blank the page. I replace only the panel.

Empty needs a reason from the API. An empty array alone cannot distinguish a new user, a user who revoked personalization consent, a filter that excluded everything, and an upstream service that returned nothing because it failed. Each reason needs different copy and a different action. Showing browse categories to a user who revoked consent is wrong. Showing clear filter to a new user is meaningless.

Partial failure is the normal case, not an edge case. If personalization times out but generic bestsellers load, I show the generic items labelled as popular right now, with no personalization notice that confuses the user. If personalization returns items but the profile enrichment failed, I show the items and log a degraded flag for analytics. The user gets value either way.

StateTriggerUIAction offeredEvent
loading, under 200 msrequest in flightnothing, reserved spacenonenone
loading, past 200 msrequest in flightskeleton, fixed heightnonerecs_loading
ready, personalized200 with items, no warningslistopen itemrecs_shown, mode personalized
ready, generic fallbackpersonalization failed, generic items presentlist labelled popularopen itemrecs_shown, mode generic
empty, no history200, 0 items, reason: no_historyexplanationbrowse categoriesrecs_empty, reason
empty, consent revoked200, 0 items, reason: consent_revokedprivacy explanationmanage preferencesrecs_empty, reason
empty, filtered200, 0 items, reason: filter_excludednames the filterclear filterrecs_empty, reason
error5xx, timeout, network failurepanel error, prior same-user items kept if presentretryrecs_error, code, attempt

The state model carries the cache key and a generation number. A response is applied only if both still match the current key. That single check prevents the account switch leak and the out of order refresh race.

TypeScript
// Checked against TypeScript 5.5
type RecsState =
  | { status: "idle" }
  | { status: "loading"; key: string; generation: number; startedAt: number }
  | { status: "ready"; key: string; items: RecItem[]; mode: "personalized" | "generic" }
  | { status: "empty"; key: string; reason: "no_history" | "consent_revoked" | "filter_excluded" }
  | { status: "error"; key: string; code: string; attempt: number; retryable: boolean };

function applyResponse(current: RecsState, incoming: RecsState): RecsState {
  if (current.status !== "loading") return current;
  if (incoming.key !== current.key) return current; // account or consent changed
  if (incoming.generation !== current.generation) return current; // newer request won
  return incoming;
}

Worked trace for the account switch. User A loads the panel, request 1 starts with key userA:consent_on, generation 1. Before it returns, the user signs out and user B signs in. The panel resets to idle, cache for userA is evicted, and request 2 starts with key userB:consent_on, generation 2. Request 1 then returns with A's items. The key check fails, the response is dropped, and nothing renders. Without the key check, B sees A's recommendations for a frame and the analytics event attributes them to B.

key and generation match key or generation mismatch yes no Mount or key change Reset to idle, evict old key Start request, generation n Response arrives Render ready, empty, or error Drop response, log stale_drop Error and attempt under 3 Panel error with manual retry

Retry is capped at two automatic attempts, 500 ms then 1,500 ms, then manual. Each attempt is logged with the attempt number, so I can tell whether retries recover or amplify an outage. Stale while revalidate applies only within the same key. If A already saw items and a refresh fails, I keep A's items with a last updated time and a refresh button. I never keep them across a key change.

Accessibility is part of the state design. The skeleton has aria-busy on the panel and is hidden from assistive tech. The error region uses role="alert" only on the final failure, not on each retry, to avoid repeated announcements. Empty and error copy are plain text with the action as a real button, not a clickable div.

The metric I watch is not the empty rate. It is the split of empty by reason, the generic fallback rate, and the stale drop count. A rising empty rate with reason: no_history is a product signal. The same rise with a generic fallback spike is a personalization outage that a bare empty array would have hidden.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-28How would you choose between Redux, Zustand, and React context for state in a React app, and when would you not use any of them?

The 90-second answer

I start by splitting state by who reads it and how often it changes. Local UI state stays in useState. Theme, current user, and feature flags go in React context because they change rarely and are read by many components. Shared client state that changes often, like cart, filters, or a draft form, goes in Zustand by default. I reach for Redux Toolkit when the team needs the ecosystem around it: time-travel debugging, a large existing codebase, middleware for server sync, or strict audit of every action.

The deciding mechanism is subscription granularity. Context notifies every consumer when the provider value changes, unless you split contexts or memoize the value. Zustand and Redux let a component subscribe to a slice, so a price tick does not rerender the whole tree.

Why context rerenders more than people expect

TSX
// React 18. Checked against React 18.3 and Zustand 5.
const CartContext = createContext<Cart>(emptyCart);

function CartProvider({ children }: { children: ReactNode }) {
  const [cart, setCart] = useState(emptyCart);
  // A new object on every cart change. Every useContext(CartContext)
  // consumer rerenders, even the badge that only needs cart.count.
  const value = useMemo(() => ({ cart, setCart }), [cart]);
  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}

useMemo helps only if the value identity is stable. Add a second concern to the same provider, such as user and cart, and a login change rerenders cart consumers too. Splitting into UserContext and CartContext fixes that, but each split is another provider to maintain.

Zustand inverts the subscription:

TSX
import { create } from 'zustand';

type CartState = {
  count: number;
  add: () => void;
};

const useCart = create<CartState>((set) => ({
  count: 0,
  add: () => set((s) => ({ count: s.count + 1 })),
}));

function CartBadge() {
  const count = useCart((s) => s.count); // rerenders only when count changes
  return <span>{count}</span>;
}

The selector returns a primitive here. If the selector returned a new object each time, Zustand would compare by reference and rerender anyway, so I select primitives or use shallow comparison for objects.

Comparison on the trade-offs that matter in an interview

React contextZustandRedux Toolkit
SubscriptionAll consumers of a provider, unless split or memoizedPer selector, outside React tree possiblePer selector via React-Redux
Update modelsetState in provider, value identity drives rendersDirect store set, no actions requiredActions and reducers, serializable state enforced in dev
DebuggingBrowser React DevTools onlyDevTools middleware, optionalTime travel, action log, replay built in
Bundle and setupZero extra dependencyAbout 1 kB gzipped core, one file to startTens of kB with Toolkit and React-Redux, more boilerplate
Failure modeAccidental global rerenders, prop drilling through contextNo enforced shape, teams invent inconsistent patternsOver-engineering for state that is really server cache

Worked trace: one websocket price tick

Assume a product grid with 200 rows, each row reading price from shared state, and a header reading cart count.

ApproachWhat rerenders on one price update
Single context holding prices and cartAll 200 rows plus header, because the provider value changed
Split contexts, one per priceRows subscribed to that price context, still coarse if prices are one object
Zustand with usePrices((s) => s.prices[id])One row, the one whose price changed
Redux with useSelector((s) => s.prices[id])One row, same selector logic, plus dispatch overhead

That trace is why I do not put high-frequency data in context. A tick every 500 ms across 200 rows turns a cheap update into 200 renders per tick, and React has to reconcile each subtree.

When I would not use any of the three

Server state is not client state. Product lists, orders, and user profiles fetched from an API belong in a cache layer such as TanStack Query, with the store holding only the id or the UI selection. Putting fetched data in Redux or Zustand duplicates cache invalidation, loading flags, and retry logic, and the copies drift. I have seen a cart total in Redux disagree with the server cart after a failed optimistic update because both stores owned the truth.

Failure modes I name before choosing

Context fails silently on performance. The app works in development, then a dashboard with context consumers at three levels rerenders on every keystroke in a search box. I detect it with React DevTools profiler and by counting renders in a test, not by guessing.

Zustand fails on discipline. Without actions, any file can call useCart.setState and bypass validation. I keep writes inside the store definition or a small set of exported functions, and I add the DevTools middleware in development so state changes are visible.

Redux fails on cost. A two-person team shipping a marketing site plus a small dashboard pays for middleware, slice boilerplate, and onboarding for a benefit they never use. I would pick Zustand there and revisit if the app grows a complex, auditable workflow such as multi-step checkout with undo.

My default for a product engineer shipping a feature next week: context for rare, global, read-mostly values, Zustand for shared mutable client state, Redux only when the debugging and ecosystem benefits outweigh the boilerplate, and a server cache for anything the API owns.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-29When would you use useMemo, and when is deriving a value during render enough instead of syncing it with useEffect?

The 90-second answer

Deriving during render is the default. If a value is a pure function of props or state you already have, compute it in the body of the component. useMemo is an optimisation for when that computation is expensive, or when you need a stable reference to stop memoised children from rerendering. useEffect is for synchronising with something outside React, such as the network, a subscription, the DOM, or a browser API. Using it to copy props into state adds a second render and a frame where the UI shows the old value.

TSX
// React 18/19. Bad: one render with the old total, then an effect, then a second render.
const [total, setTotal] = useState(0);
useEffect(() => { setTotal(items.reduce((s, i) => s + i.price, 0)); }, [items]);

// Good: derived in the same render, always consistent.
const total = items.reduce((s, i) => s + i.price, 0);

// Good: expensive, so cached across renders where items has not changed.
const visible = useMemo(
  () => filterAndSort(items, query, sort),
  [items, query, sort],
);

Why the effect version fails in practice

React renders, commits, then runs effects. The effect version therefore paints the stale total once, then re-renders. On a fast typing interaction that reads as flicker. It also creates a loop risk: the effect writes state, that state triggers a render, and if the dependency is slightly wrong you get extra renders or a stale closure. The classic bug is a derived flag such as isEmpty or fullName stored in state and updated in an effect. It is always one render behind, and tests that render once will pass while users see the previous value.

Deriving in render removes that class of bug. The value cannot disagree with its inputs because it is computed from them in the same pass.

When useMemo earns its place

Two cases. First, cost. Filtering and sorting 5,000 rows, parsing a large JSON payload, or building a chart series on every keystroke can dominate render time. In a hypothetical profile, say that work takes 18 ms per render. Caching it with useMemo keyed on the real inputs drops repeat renders to a reference check. Second, identity. If you pass an array or object to a child wrapped in React.memo, a new reference every render defeats the memo. useMemo gives that child a stable reference until the inputs change.

Both uses are hints, not guarantees. React may discard the cache under memory pressure and recompute, so never put correctness inside useMemo. If the result must be right, compute it plainly. Also do not memoise cheap work. Wrapping a + b or a short string concatenation adds dependency bookkeeping and makes the code harder to read for no measurable gain. Measure first, or memoise only when the cost or the child boundary is obvious.

SituationChoiceReason
fullName from first and last nameDerive in renderCheap, pure, must match inputs now
Filtered list over 5,000 rowsuseMemoExpensive, inputs change less often than renders
Options object passed to memoised childuseMemoStable reference prevents child rerenders
Fetch orders when userId changesuseEffectSynchronises with the network, outside React
Focus an input on mount, measure a DOM nodeuseEffect or ref callbackSide effect on the browser, not a value
Subscribe to websocket price ticksuseEffect with cleanupExternal subscription, must unsubscribe on unmount

The boundary to state in an interview

Ask what the value depends on and what it costs. Pure function of current props or state, cheap: derive. Pure but expensive, or identity matters to a memoised child: useMemo. Depends on something React does not own, or must happen after paint: useEffect. If you catch yourself writing an effect whose only job is setX(computeFromY), delete the state and compute x during render. That single move removes the stale frame, the extra render, and most of the dependency array bugs that follow from it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-30How do you handle validation and performance in large forms with hundreds of fields?

The 90-second answer

Keep one schema as the source of truth, validate fields when the user leaves them, and keep typing from re-rendering the whole form. I use a schema library such as Zod on the client and the same schema on the server, register fields so each input owns its value, and run full validation only on submit. That gives fast feedback without paying for a 200-field render on every keystroke.

Validation timing

MomentWhat runsWhy
onBlur after first touchThat field only, sync rulesError appears when the user has finished the field
onChange after a field has erroredThat field onlyError clears as soon as the value becomes valid
Debounced 300 ms after typing stopsAsync checks such as username or postcode lookupAvoids a request per keystroke
SubmitWhole schema, sync then asyncCatches cross-field rules and untouched required fields

Cross-field rules belong in the schema, not in component code. A confirmPassword rule, a date range, or "if country is US then state is required" should be a refinement on the schema so the server can reuse it verbatim. Client-only checks that the server cannot trust, such as a client-generated discount code, still need a server check.

TSX
// react-hook-form 7.x with zod 3.x, checked against current docs
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  email: z.string().email(),
  postcode: z.string().min(3),
  country: z.string(),
  state: z.string(),
}).refine(
  (v) => v.country !== 'US' || v.state.length > 0,
  { message: 'State is required for US addresses', path: ['state'] },
);

type Form = z.infer<typeof schema>;

export function CheckoutForm() {
  const { register, handleSubmit, formState: { errors, touchedFields } } = useForm<Form>({
    resolver: zodResolver(schema),
    mode: 'onTouched',
    reValidateMode: 'onChange',
  });
  return (
    <form onSubmit={handleSubmit((data) => submit(data))} noValidate>
      <input {...register('email')} aria-invalid={!!errors.email} />
      {errors.email && <p role="alert">{errors.email.message}</p>}
      {/* postcode, country, state registered the same way */}
      <button type="submit">Place order</button>
    </form>
  );
}

noValidate stops the browser's native bubbles from competing with the schema messages. Each error is tied to its input with aria-invalid and role="alert", and on a failed submit I move focus to the first invalid field and list the errors at the top for screen reader users.

Performance in a large form

The expensive pattern is one controlled state object at the form root. Every keystroke updates that object, React re-renders the form, and all 200 inputs reconcile. With uncontrolled registration, the input holds its own DOM value and only the field component that subscribed to it re-renders.

Worked example, labelled as hypothetical figures for a 200-field form on a mid-range phone:

ApproachRenders per keystrokeApprox. cost
Single controlled state at root200 inputs plus form chrome200 reconciliations, input lag grows with field count
Registered fields, field-level subscription1 input plus its error slot1 reconciliation, typing stays under one frame

Splitting the form into section components helps further when sections have their own submit or draft save. I memoize expensive derived bits such as a computed order total, and I keep async validation cancellable. If the user types ab, then abc, and the first request returns last, the stale response must not overwrite the newer result. I track a request id per field and ignore responses that do not match the latest value, or abort the earlier request with AbortController.

Failure modes I watch for: validation that only runs on submit, which users discover at the end; async checks with no cancellation, which show errors for values the user already replaced; and a schema that drifts between client and server, which produces 422 responses for data the UI called valid. The fix for the last one is importing the same schema package in both places and adding a contract test that submits the schema's valid and invalid fixtures to the API.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-31Design the REST list endpoint for invoices where clients need stable infinite scroll during concurrent inserts, shareable filtered links, an exact header count, and protection against full-table export on 2 million rows. How do you reconcile those constraints?

The 90-second answer

I would ship one flat collection, GET /v1/invoices, with allowlisted filters, a mandatory total sort order, and keyset pagination. The hard part is not the happy path. It is that the four requirements fight each other. Infinite scroll needs a stable position in a changing list. Shareable links need the filter state in the URL. An exact header count needs a COUNT(*) over the filtered set. Protection against export needs a limit cap. A design that pretends all four are free will fail on at least one in production.

My compromise: cursor pagination for traversal, filter state in query parameters for sharing, an exact count only on a separate cheap path, and a hard limit cap with a documented export job for bulk needs. I state that trade-off to product before building, because an exact count on every scroll request is the first thing that will time out.

Naming and filtering

NeedEndpointReason
---------
---------
---------
list, filter, pageGET /v1/invoicesone collection, filters as query params
read oneGET /v1/invoices/inv_8f21opaque id, no sequential leak
line itemsGET /v1/invoices/inv_8f21/line-itemsidentity depends on the parent
exact count for headerGET /v1/invoices/count with same filterscached separately, not per page

I do not nest under /customers/{id}/invoices. That duplicates the list endpoint the moment a client filters across customers. Filters are a closed allowlist. Unknown parameters return 400, because silently ignoring statsu=overdue returns unfiltered data that looks like a bug. Repeated keys mean OR within one filter, different keys mean AND. Ranges use explicit suffixes such as due_before=2026-03-01. Sort keys come from the allowlist only, never from raw client input.

GET /v1/invoices?customer_id=c_91&status=overdue&sort=-due_date&limit=50

Pagination that survives inserts and deletes

Offset pagination asks the database to scan and discard rows. On a 2 million row table, page 2,000 at 50 per page discards 99,950 rows before returning 50. Worse, an insert above the offset shifts every later page, so a scrolling client sees duplicates or misses rows. Keyset pagination asks for rows after a known position.

That only works with a total order. Sorting by due_date alone is not total, because thousands of invoices share a due date. I sort by due_date DESC, id DESC. The id tiebreaker makes every row's position unique. The cursor encodes the last row's sort key, its id, and a fingerprint of the filters and sort it was issued for.

TypeScript
// Node 20, server side
const payload = { due: last.due_date, id: last.id, f: filterFingerprint };
const cursor = Buffer.from(JSON.stringify(payload)).toString('base64url');
// next request: decode, validate shape and fingerprint, then run
// WHERE (due_date, id) < ($1, $2) ORDER BY due_date DESC, id DESC LIMIT 51

Fetching limit + 1 rows sets has_more without a count query. I cap limit at 200, default 50, and reject larger values with 400. Without the cap, one client can set limit=2000000 and turn the list endpoint into a full export.

The fingerprint is the subtle failure mode most designs miss. A client shares a link, changes the status filter, but keeps the old cursor. Without the fingerprint the server applies the old position to the new filter set and returns a page that skips rows with no error. With it, the server returns 400 with code: cursor_filter_mismatch, and the client restarts from the first page. Deletions are handled the same way. Because the cursor stores key values rather than a row number, deleting the row the cursor points at does not break the next page.

The count problem

An exact count over a filtered 2 million row set can take seconds and changes on every insert, so it disagrees with the list by the time the client renders it. I do not put it in the list response. The header calls /v1/invoices/count with the same filters, the server caches the result for 30 seconds keyed by the filter fingerprint, and the UI labels it as the count at load time. If product insists on an exact count on every keystroke, I show the cost with a query plan on real data and offer the alternative: an approximate count from a stats table refreshed every five minutes. That is a product decision, not something to discover in a load test.

Worked trace

StepRequestResult
---------
---------
---------
1GET /v1/invoices?status=overdue&sort=-due_date&limit=2rows inv_9, inv_8, plus one extra row, so has_more: true and a cursor for inv_8
---------
2new invoice inv_10 inserted with a later due datefirst page changes, cursor page does not, because the cursor is a position in key space
---------
3client follows cursor with same filtersreturns rows after inv_8, no duplicate of inv_9
---------
4client changes filter to status=open but reuses cursor400 cursor_filter_mismatch, client restarts at page one
---------
5client requests limit=5000400 limit_exceeded, bulk export goes through a job instead

Before shipping I page through a test set with identical due dates, concurrent inserts, and deletions, and assert no duplicates and no gaps. I also test a forged cursor, which must fail validation rather than become a filter injection, since cursor values are bound as parameters and never interpolated into SQL.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-32You need to change a field type and remove a field on a public API with clients you cannot update quickly. How do you version it without breaking existing clients?

The 90-second answer

First, I avoid a version bump if I can. Most changes clients actually need can ship as additive changes to the current version: add a field, add an optional parameter, add a new endpoint, and keep the old field populated with the same meaning. A version is for a breaking change, meaning a field is removed, renamed, its type or unit changes, an enum value gains a new meaning, or a previously accepted request now fails.

When a break is unavoidable, I run versions in parallel behind the same host. The old version stays live and unchanged, the new version ships as a new contract, and clients migrate on their own schedule. I never change what /v1/orders returns in place and call it v1.1, because a client pinned to v1 has no way to detect that its assumptions changed.

Choosing where the version lives

StrategyExampleTrade-off
URL pathGET /v2/orders/{id}Visible in logs, docs and caches. Easy to route and to keep both alive. Couples the URL to a contract that may outlive the version.
HeaderAccept: application/vnd.shop.v2+jsonKeeps URLs stable and lets one resource negotiate representation. Harder to debug in a browser, and proxies or CDNs must vary on the header.
Query parameterGET /orders/{id}?v=2Simple to add. Pollutes cache keys and gets copied into links and analytics where it drifts from the real contract.

For a product API consumed by web, mobile and partner clients, I default to the URL path. It makes the version visible in an incident, a support ticket and a log line without inspecting headers. Header negotiation is defensible for a small public API with a single resource family, but I would not pick it when several client teams need to debug from a browser.

HTTP
GET /v2/orders/42 HTTP/1.1
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json
Deprecation: true
Sunset: Sat, 31 Jan 2027 23:59:59 GMT
Link: </v2/orders/42>; rel="successor-version"

The Sunset header is defined in RFC 8594. It tells a client when the deprecated version stops answering, so a well-behaved SDK can warn the developer instead of failing on a date nobody announced.

Client pinned to a version Router reads version from path v1 handler v2 handler Shared domain and database Sunset header and usage metrics

Both handlers share the domain logic and storage. The version layer only translates the wire contract. That keeps business rules in one place and makes the difference between versions a mapping problem I can test.

How a migration actually runs

I use expand, migrate, contract. Expand means the server accepts and returns both shapes for a while. Migrate means clients move one by one, driven by the metrics below. Contract means I remove the old shape only after usage reaches zero, or after the published sunset date with a named owner for the remaining callers.

PhaseServer behaviourClient behaviourExit signal
Announcev2 live, v1 unchanged, Sunset on v1SDKs add v2 support behind a flagv2 passes contract tests against recorded v1 traffic
MigrateBoth versions served, per-version dashboardsClients opt in, can roll back to v1v1 traffic below an agreed threshold, for example under 1% of calls for 30 days
Contractv1 returns 410 Gone with a code and a link to the v2 docsRemaining callers get a hard error they cannot missNo production traffic for 14 days, then the handler is deleted

A worked trace for a field change shows why parallel versions matter. Suppose v1 returns price_cents: 1299 and v2 returns price: { amount_cents: 1299, currency: "USD" }. In v1 I add currency as a new field and keep price_cents exactly as before. In v2 the nested object is the only shape. A v1 client that ignores unknown fields keeps working during the expand phase, and a v2 client never has to guess whether price_cents is in dollars or cents.

Failure modes I watch for

Additive changes still break clients. Adding an enum value breaks a client with an exhaustive switch and no default case. Changing a list endpoint from offset to cursor pagination breaks a client that assumes page 2 always follows page 1. Tightening validation on a field that was previously ignored turns a tolerated request into a 422. I treat those as breaking changes even though no field was removed, and I catch them with contract tests that replay real client payloads against the new handler.

The other failure is a version that never dies. If nobody owns the sunset date, v1 accumulates special cases and every new feature pays for two contracts. I put the sunset date in the release ticket, emit a per-version request count, and review it in the same meeting that reviews the migration. When a partner cannot migrate, the conversation is about a dated exception with an owner, not about quietly extending v1 forever.

For the interview, the sentence I would land on is this: versioning is a migration plan with two live contracts and a published end date, and the version number is only the label on that plan.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-33A client retries POST /orders after a timeout and creates duplicate orders. How would you use an Idempotency-Key to make that retry safe?

The 90-second answer

POST /orders is not safe to retry by default. If the server creates the order and the response is lost on the network, the client cannot tell whether the order exists. A blind retry can create a second order.

I fix that with an Idempotency-Key header. The client generates one UUID for one checkout attempt and sends the same UUID on every retry of that attempt. The server stores the first result under that key and replays it on a retry instead of creating another order.

HTTP
POST /orders HTTP/1.1
Idempotency-Key: 7f3c9a1e-4b2d-4c1a-9e8f-123456789abc
Content-Type: application/json

{"customer_id":"c_8f21","items":[{"sku":"sku_1","qty":2}]}

The key is generated per user intent. Clicking Place order once generates a key. A timeout, a 503, or a dropped connection reuses that key. Starting a new checkout, or changing the cart and submitting again, generates a new key. If the client generated a fresh key per HTTP attempt, the server would see each retry as a new order and the header would do nothing.

On the server I store the key in the same transaction that creates the order, with a unique constraint so two concurrent retries cannot both insert it.

SQL
-- PostgreSQL 16
CREATE TABLE idempotency_keys (
  account_id text NOT NULL,
  key text NOT NULL,
  request_hash text NOT NULL,
  status_code int,
  response jsonb,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (account_id, key)
);
TypeScript
// Node 20, Express-style handler
async function createOrder(req, res) {
  const key = req.header('Idempotency-Key');
  if (!key) return res.status(400).json({ code: 'idempotency_key_required' });
  const hash = sha256(req.method + req.path + req.rawBody);

  const existing = await db.findKey(req.user.id, key);
  if (existing) {
    if (existing.request_hash !== hash)
      return res.status(422).json({ code: 'idempotency_key_reused' });
    return res.status(existing.status_code).json(existing.response);
  }
  const order = await createOrderAndStoreKey(req.user.id, key, hash, req.body);
  return res.status(201).json(order);
}

Worked trace for the timeout case:

TimeWhat happensResult
0 msFirst POST arrives with key 7f3cServer inserts key, creates order 42, stores 201 {id: 42}
200 msResponse is lost after commitClient sees a timeout, order already exists
2,000 msClient retries with same key and same bodyServer finds key, hash matches, replays stored response
2,010 msClient receives replay201 {id: 42}, no second order created

Two details make the replay correct. First, I store the full response, status code and body, not only the order id. The retry must see the same shape the first attempt would have returned. Second, I compare a hash of the request body. If the same key arrives with a different cart, that is a client bug, and I return 422 instead of replaying the first order for a different purchase.

For concurrent retries, the primary key on (account_id, key) means only one insert succeeds. The other request fails the insert, reads the completed row, and replays it. I scope keys by account so one customer cannot guess another customer's key, and I expire them after 24 hours. After expiry a retry would create a new order, which is acceptable because clients stop retrying long before then.

I would test this by dropping the connection after the database commit but before the response is sent, then asserting the retry returns order 42 and the orders table still has one row for that checkout.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-34How do you separate authentication from authorization on API endpoints?

The 90-second answer

Authentication answers who is calling. Authorization answers what that caller may do. I put them in separate middleware layers so each can be tested and changed without touching the other.

Authentication runs first. It verifies the credential, usually a bearer token or session cookie, and attaches a principal to the request: user id, tenant id, token scopes. If the credential is missing, expired or invalid, it stops the request with 401 and a WWW-Authenticate header. It never checks whether the user is an admin.

Authorization runs second. It takes the principal already attached and checks a policy for this endpoint and this resource: does this user own order 42, does this token carry orders:read, is this tenant allowed to export reports. If the check fails, it returns 403. The handler then only runs for a caller who is both identified and permitted.

TypeScript
// Express 4, TypeScript. authenticate knows nothing about orders.
app.get(
  '/orders/:id',
  authenticate,                       // 401 if no valid token; sets req.principal
  authorize({ scope: 'orders:read' }), // 403 if principal lacks scope or ownership
  async (req, res) => {
    const order = await orders.findById(req.params.id);
    if (!order) return res.status(404).json({ code: 'order_not_found' });
    if (order.tenantId !== req.principal.tenantId) {
      return res.status(403).json({ code: 'forbidden' });
    }
    res.json(order);
  },
)

The split matters on the client too. A 401 means go to login or refresh the token. A 403 means the user is logged in and should see an access denied state, not a login redirect loop.

CaseStatusClient behaviour
No token, expired token, bad signature401Prompt login or refresh once, then retry
Valid token, missing scope403Show no access for this feature
Valid token, resource belongs to another tenant403 or 404Show no access, or not found if you must hide existence
Valid token, permitted, resource missing404Show not found
invalid valid, attach principal denied allowed Request arrives authenticate: verify token 401 authorize: scope and ownership 403 Handler runs

Where this breaks in practice

Putting role checks inside the auth middleware is the common failure. The middleware grows a branch per endpoint, a new route forgets its branch, and the endpoint ships open. Keeping authorization as a named policy per route makes the missing check visible in review.

The second failure is checking ownership only in the UI. Hiding a delete button for non owners does nothing if DELETE /orders/42 trusts the caller. The ownership check has to live server side, on the resource, every time.

The third is returning 403 for everything. If a tenant can probe ids and learn which orders exist from the difference between 403 and 404, pick 404 for resources outside the tenant and keep 403 for actions on resources the caller can already see, such as exporting an order they own without the export scope. State that choice in the API contract so the frontend can render one consistent state.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-35How would you design rate limiting and quotas for a public API serving 10,000 third-party keys, where one tenant can starve others and free-tier clients retry aggressively on 429s?

The 90-second answer

I would separate three controls and not merge them into one number. A rate limit protects the service in the short term, a quota protects the business over a billing period, and a concurrency limit protects scarce downstream resources. A free key might get 60 requests per minute, 10,000 requests per month, and 5 concurrent requests. A paid key might get 600 per minute, 1,000,000 per month, and 50 concurrent. If I only set a monthly quota, one client can still send 10,000 requests in 30 seconds and saturate the pool. If I only set a per-minute limit, a client can stay under it forever and consume the monthly budget on day one.

I would key limits by API key, not by IP. Public APIs sit behind NATs, corporate proxies and mobile carriers, so an IP limit punishes unrelated users sharing an address and misses a client rotating addresses. IP limits stay as a coarse abuse backstop, for example 5,000 requests per minute per IP, but the product limit is per key and per tenant.

Every response carries the budget so clients can back off before they hit it. On success and on rejection I return RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset, plus Retry-After on a 429. The client contract is explicit: on 429, wait at least Retry-After, add jitter, and do not retry a non-idempotent POST without an idempotency key.

ControlWindowExample, free tierExample, paid tierRejection
Token bucket rate limit60 s60 req, burst 20600 req, burst 100429
Monthly quotaCalendar month10,000 req1,000,000 req429 with quota_exceeded
ConcurrencyInstant5 in flight50 in flight429 or queue with timeout
Weighted costPer endpointSearch costs 5 unitsSearch costs 5 units429

Weighting matters for a product API. A cached GET /products/{id} might cost 2 ms of database time. A POST /search with a full text scan might cost 80 ms. Counting both as one request lets a client buy cheap reads and spend expensive searches. I would charge units per endpoint, publish the cost table, and count units against both the rate limit and the quota.

LUA
-- Redis Lua, checked against Redis 7. Token bucket per key.
-- KEYS[1] = ratelimit:{api_key}, ARGV = now_ms, refill_per_ms, capacity, cost
local key = KEYS[1]
local now = tonumber(ARGV[1])
local refill = tonumber(ARGV[2])
local capacity = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local data = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(data[1]) or capacity
local ts = tonumber(data[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * refill)
if tokens < cost then
  return {0, math.floor(tokens), math.ceil((cost - tokens) / refill / 1000)}
end
tokens = tokens - cost
redis.call('HMSET', key, 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', key, 120000)
return {1, math.floor(tokens), 0}

The Lua script makes check and deduct atomic. Two application servers cannot both read 10 tokens and both spend them. I would run this in middleware before the handler, after authentication, so unauthenticated traffic gets a separate stricter bucket.

No Yes Request arrives Authenticate API key Key valid? 401, no quota consumed Check concurrency Check token bucket Check monthly quota Execute handler Record usage units

Sizing with real figures

Assume 10,000 active keys, 1,200 requests per second at peak, and a p99 handler latency of 120 ms. Little's law gives about 144 requests in flight at peak. If one tenant holds 40% of traffic, a global limit alone lets that tenant consume the connection pool and push p99 for everyone past 1 second. Per-key buckets fix that, but only if the paid tier is not set so high that 50 concurrent requests from each of 200 paid keys equals 10,000 in flight. I would cap aggregate concurrency at the pool size, for example 200 database connections, and reserve headroom by tier. Free keys share a smaller pool than paid keys, so a free-tier burst degrades free p99 first.

Redis cost is manageable at this scale. One Lua call per request at 1,200 rps is well within a single Redis primary, but I would shard by key hash if I passed 10,000 rps, and I would fail open or closed by tier. Fail open for free keys during a Redis outage, with a local in-process bucket as a backstop, because a hard outage blocks all paying customers. Fail closed for keys already flagged for abuse.

Failure modes I would test

Retry storms are the classic one. If 500 clients get a 429 with Retry-After: 60 and all retry in the same second, the bucket refills and they collide again. Jitter in the client guidance and a reset time spread across the window reduce that spike. I would also return 429 early, before expensive work, and measure how many rejected requests still reached the database. The target is near zero.

Quota resets create a second spike at midnight on the first of the month. I would stagger reset times by hashing the key, so resets spread over an hour instead of landing in one second. I would also alert on quota consumption velocity, not just total use. A key that uses 50% of its monthly quota in the first hour is either a launch spike or a leak, and the response differs.

Clock skew breaks token buckets that rely on client timestamps, which is why the script uses server time from Redis. A shared key inside one customer organisation is a product problem, not a technical one. I would allow sub-keys per environment, so a customer's production integration and their test script do not share one budget, and I would show remaining quota in the developer dashboard with an upgrade path before they hit the wall.

Finally, I would instrument the product metrics that tell me the limits are wrong. A rising 429 rate among paid keys that then churn, a free tier where 2% of keys consume 80% of cost, and support tickets that mention Retry-After are signals to retune tiers. Limits are a pricing and capacity decision expressed in code, and they need the same review cycle as pricing.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-36How do you design API error responses, including status codes and a format clients can branch on without parsing human messages?

The 90-second answer

I separate three jobs that a single error string cannot do. The HTTP status carries HTTP semantics: was the request malformed, is the caller unauthenticated, is a retry safe. A stable machine-readable code carries the product decision: what should the client do next. A human message is display text only, and the client never branches on it. I use RFC 9457 Problem Details as the envelope, with application/problem+json, because it is standard, extensible, and already understood by many HTTP clients. Every error also carries a trace_id that matches the server log line, so a user report can be found in seconds.

JSON
{
  "type": "https://api.example.com/problems/validation-failed",
  "title": "Validation failed",
  "status": 422,
  "detail": "Two fields need attention.",
  "instance": "/orders/req_9f21",
  "code": "validation_failed",
  "trace_id": "tr_7c41e2",
  "errors": [
    { "field": "email", "code": "invalid_format", "message": "Enter a valid email address." },
    { "field": "quantity", "code": "out_of_range", "message": "Quantity must be between 1 and 10." }
  ]
}

type is a stable URI for the problem class, title is short and stable, detail can change, and code is the short token the frontend switches on. Field errors live in errors[] so a form can attach each one to an input without parsing prose.

Choosing the status

StatusMeaning I commit toRetryableClient action
400Syntax broken, body is not parseable JSON or a required envelope field is missingNo, until the request changesShow a generic request error, log trace_id
401No valid authenticationAfter re-authenticationSend to login, preserve the intended route
403Authenticated but not allowedNoShow a permission message, do not retry
404The resource named in the path does not existNoShow not-found state, drop cached entity
409State conflict, such as a duplicate email or a stale versionAfter a fresh readRefetch, then let the user reapply the change
422Syntax valid, semantics rejected, such as a field out of range or a referenced entity missingNo, until the payload changesRender errors[] inline on the form
429Rate limited, with Retry-AfterAfter the delayBack off, show a wait message
500Unexpected server faultSometimes, with backoffShow a generic error, report trace_id
503Dependency unavailable, such as a downstream timeoutYes, with backoffShow a temporary outage state

Two rules keep this honest. Validation failures are never 500, because a 500 tells clients and alerting that the server is broken when the input was the problem. Success is never 200 with an error field inside, because load balancers, caches, and monitoring all read the status, and a 200 error defeats retries, circuit breakers, and log filters.

How the frontend consumes it

In TypeScript I model the response as a discriminated union on code, not on the message:

TypeScript
type ApiError =
  | { status: 422; code: "validation_failed"; errors: FieldError[]; trace_id: string }
  | { status: 401; code: "unauthenticated"; trace_id: string }
  | { status: 409; code: "version_conflict"; trace_id: string }
  | { status: number; code: string; trace_id: string };

function handleError(err: ApiError) {
  switch (err.code) {
    case "validation_failed":
      return form.setFieldErrors(err.errors); // map code to i18n key per field
    case "unauthenticated":
      return redirectToLogin();
    case "version_conflict":
      return refetchAndPrompt(err.trace_id);
    default:
      return showGenericError(err.trace_id); // user can quote this ID in support
  }
}

That mapping is also where localisation happens. The server sends invalid_format, the client renders the translated string for the current locale, and a copy change on the server never breaks branching.

Failure modes I design against

Leaking internals is the common one. Stack traces, SQL fragments, and upstream URLs go to logs under trace_id, never into detail. A second failure is code drift: a team adds customer_not_found as a 404 in one service and a 422 in another for the same situation. I keep a short registry of codes with owner, status, and client action, and I treat changing the meaning of an existing code as a breaking change. Adding a new code is safe. Renaming one is not.

A third failure is the well-meaning fallback. When a client receives a status it does not recognise, it should treat it by class: 4xx means do not retry unchanged, 5xx means retry with backoff and jitter. That keeps a new 451 or a future 5xx from crashing the UI.

4xx 5xx Receive error response Status class Do not retry unchanged Retry with backoff if safe Branch on code Render field, auth, conflict, or generic state

If I had to summarise the contract in one line for a new client team: branch on code, display message, debug with trace_id, and let the status decide whether a retry is even allowed.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-37A payment provider sends invoice.paid webhooks that can arrive twice. How would you verify the signature and make your handler safe to run twice?

The 90-second answer

I would make the handler verify first, record the event, and only then act on it. Verification runs over the raw request body, because the provider signed those exact bytes. Recording uses the provider's event ID as a unique key, so a second delivery of the same event finds the existing row and returns 200 without running the business logic again. That gives at-least-once delivery from the provider and exactly-once effect in my system.

The provider owns the retry policy for delivery to me. I cannot control its backoff, so my defence is idempotency. If my handler is safe to run twice, a retry is harmless. If it is not, no retry schedule saves me.

Signature verification

Most providers send a header such as t=1718000000,v1=<hex> where v1 is HMAC-SHA256 over t + '.' + rawBody, keyed with a shared secret. I recompute that value and compare it in constant time. I also reject timestamps more than five minutes from my clock, which limits replay of a captured valid request.

The common bug is parsing JSON before verifying. Re-serialising the parsed object changes whitespace and key order, so the recomputed signature never matches. The raw body parser has to run before the JSON parser, and only for this route.

TypeScript
// Node 20, Express 4. Raw body captured before express.json().
import crypto from 'node:crypto';

function verify(raw: Buffer, header: string | undefined, secret: string): boolean {
  if (!header) return false;
  const [ts, sig] = header.split(',').map((p) => p.trim().split('=')[1]);
  if (!ts || !sig) return false;
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${ts}.${raw.toString('utf8')}`)
    .digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(sig);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

On failure I return 400, log the event ID and timestamp, and drop the request. I do not return 200, because that would tell the provider a forged request was accepted. I also do not return 500, because that invites retries of a request that will never verify.

Making the handler safe to run twice

I store each verified event before processing it. The table has a unique constraint on provider_event_id. The first delivery inserts the row and processes invoice.paid. The duplicate hits the constraint, I catch it, and I return 200 so the provider stops retrying.

DeliverySignatureInsertResponseEffect
1, evt_9f2validsucceeds200invoice marked paid
2, evt_9f2validunique violation200none, already processed
3, evt_9f2invalidskipped400none, dropped

Processing itself also needs to be idempotent, because a crash after the insert but before the update leaves a stored event that was never applied. I mark the row processed in the same transaction as the business update, or I check that flag at the start of processing. Either way, re-running the handler converges on the same state.

Two failure modes are worth naming. First, clock skew. If the provider's clock runs ahead of mine, valid events fall outside the five minute window and get rejected. I alert on a spike in verification failures for one provider, since that pattern usually means a rotated secret or a signing change on their side. Second, a crash between returning 200 and processing. If processing is inline, a slow downstream can also push the response past the provider timeout and trigger a duplicate. Keeping the handler to verify, insert, and return, then processing from the stored row, keeps the response fast and the duplicate harmless.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-38If a screen needs only three fields from a large product resource, which would you pick, GraphQL or REST, and why?

The 90-second answer

I would pick GraphQL for that screen. The rule I use is simple: if the client knows exactly which fields it needs and those fields span more than one resource, GraphQL lets the client ask for just those fields in one request. REST returns the whole resource as the server defined it, so the client either downloads fields it discards or makes extra calls to assemble the screen.

That is the well known trade off. GraphQL solves overfetching and multiple round trips. REST keeps HTTP caching, simpler tooling, and a simpler contract when the client needs the full resource anyway.

Worked example

Say a product card needs a product name, price, and the count of reviews. The product resource has 40 fields, including descriptions, supplier data, and internal flags.

With REST, the client calls one endpoint and receives all 40 fields:

HTTP
GET /products/p_1042

With GraphQL, the client names the three fields it needs:

GRAPHQL
query ProductCard($id: ID!) {
  product(id: $id) {
    name
    price
    reviewCount
  }
}
ApproachRequests for this cardFields returnedFields used
REST1403
GraphQL133

If the card also needs the seller name, REST needs a second call to the seller resource or a new combined endpoint. GraphQL adds one nested field to the same query and still returns one request.

When I stick with REST

I stick with REST when the screen needs most of the resource, when there is only one client, or when HTTP features do the work for free. A GET can be cached by a CDN or browser using ETag and Cache-Control. File uploads, webhooks, and simple create or update operations also map directly to HTTP methods. Adding GraphQL for a single CRUD page adds a schema, resolvers, and client cache to maintain, with no overfetching problem to solve.

So my one step check is: does the client need a selected subset across related resources? If yes, GraphQL. If it needs the whole resource, REST.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-39A shared schema validates your React form and API, yet old mobile builds, concurrent requests, and a direct database import still create invalid invites. Where should each rule live, and how do you keep them from drifting?

The 90-second answer

Put each rule at the last boundary that can still enforce it, and treat the server copy as authoritative. The form gives instant feedback on shape. The API rechecks shape, permission, and business rules against current state before acting. The database holds invariants that concurrent requests or a direct import could break. A shared schema helps the first two layers agree, but it does not make the client trustworthy. TypeScript types disappear at runtime, old mobile builds keep sending the old payload, and anyone can call the endpoint with curl.

The hard cases are the ones a single check misses. A seat limit checked in application code has a race. Two invites arrive together, both read 24 of 25 seats used, both pass, both insert, and the workspace ends with 26. A unique email checked with a lookup has the same race. Only a database constraint makes one of them fail. A direct import or migration bypasses the API entirely, so a NOT NULL column and a foreign key are the only thing standing between that import and orphaned rows.

Split the rules by what can break them

TypeScript
// checked against Zod 3.23, shared package used by React and Node API
import { z } from "zod";

export const InviteSchema = z.object({
  email: z.string().trim().toLowerCase().email(),
  role: z.enum(["member", "admin"]),
  seats: z.number().int().min(1).max(25),
});

// Client: safeParse for inline errors.
// Server: safeParse again, then authorize. The client's result is discarded.
// A request with role: "admin" from a member account fails here even
// if the UI never rendered an admin option.
RuleFormAPIDatabase
------------
------------
------------
Email shape, seats range, required fieldsInline, on blur and submit422 with per-field codesNOT NULL, CHECK (seats BETWEEN 1 AND 25)
Caller may invite to this workspaceHide or disable control403 before any insertNo
Plan seat limitShow remaining seatsRecheck inside transactionCounter row with CHECK (seats_used <= 25)
One active invite per email per workspaceDebounced lookupHandle conflict as 409UNIQUE (workspace_id, lower(email)) where active
Role escalationNo admin option for membersReject or downgrade per contractCHECK (role IN ('member','admin'))

The database column for the seat counter needs care. Incrementing a counter in the same transaction as the insert, with a check constraint on the counter, turns the race into a failed transaction for the loser. That loser gets a 409 or 422 it can show, rather than a silent overage that billing finds a month later.

SQL
-- Postgres 16
ALTER TABLE workspaces
  ADD CONSTRAINT seats_within_plan CHECK (seats_used <= 25);

CREATE UNIQUE INDEX one_active_invite
  ON invites (workspace_id, lower(email))
  WHERE status = 'pending';

Keeping the layers from drifting

Drift is the failure mode that shared schemas are supposed to prevent and often only postpone. The form ships with a new max of 50 seats, the API package in the deploy lags a week behind, and users on the new form get 422s they cannot explain. Three habits keep this honest. Keep one schema package as the source and generate the OpenAPI description from it, so the docs cannot describe a different contract. Add contract tests that send the old mobile payloads, including a renamed field and an extra unknown field, and assert the API response. Decide how unknown fields behave and write it down. Stripping them silently hides a client bug. Rejecting them breaks old clients that send a field you removed. For invites I reject unknown fields on write endpoints, because a silently dropped role field is worse than a loud error.

Error shape matters for the same reason. Return stable codes per field, such as email_invalid, seats_over_plan, and invite_already_pending, with the HTTP status carrying the class. Old clients that cannot render the new message can still branch on the code. A generic 500 for a validation failure gives the client nothing to render and gives you nothing to count.

Form: shape, instant feedback API: schema, authorization, business rules Transaction: recheck limits, increment counter Database: unique, check, foreign keys 201, 422, 403, or 409 with stable codes

The test I apply to any new rule: if I delete the client check, does anything break in production. If the answer is yes, the rule was only living in the browser. If the answer is no, the client check was doing its real job, which is speed of feedback, and the server and database were already carrying the invariant.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-40Your product endpoint takes 900 ms at p95 and the page budget allows 500 ms. How would you set that budget and decide whether caching the endpoint closes the gap?

The 90-second answer

I would work backwards from the 500 ms page budget. The endpoint is on the critical path for the product page, so it gets the full 500 ms at p95, not the 900 ms it takes today. I then ask whether caching can plausibly bring the blended p95 under 500 ms, using the hit ratio I can actually achieve. If the maths does not close the gap, caching is the wrong fix and I optimise the query instead.

Setting the budget

The budget is a p95 target for that one call, measured at the API gateway. I split it only enough to know where time goes: say 50 ms for routing and serialisation, 400 ms for the database, and 50 ms of headroom. The database slice is the problem, because the current query takes about 850 ms at p95. That tells me the fix has to remove database work from most requests, which is exactly what a cache does, or make the query itself faster.

Does caching close the gap?

Assume a cache hit costs 20 ms end to end and a miss costs the full 900 ms. Blended time is:

blended = hit_ratio x 20 + (1 - hit_ratio) x 900

Setting blended to 500 ms gives hit_ratio = (900 - 500) / (900 - 20) = 0.45. So I need at least a 45% hit ratio to meet budget, and in practice I want 80% or more so the p95 stays under budget when the ratio dips. Whether that is achievable depends on how often the product data changes and how concentrated reads are. A popular product read 5,000 times a day and edited twice a day will sit above 95% with a 60 second TTL. A long tail product read once a day will not, and caching it wastes memory for almost no gain.

That gives me the decision rule. Cache when three things hold: reads dominate writes, the business accepts the TTL as the staleness window, and the expected hit ratio clears the threshold from the arithmetic. Product display data usually passes. If the price shown must match the price charged at checkout to the cent, the staleness window is zero, so I would not cache the display value as the source of truth. I would recheck price on the write path.

ApproachEffect on p95Main trade-off
Cache-aside with 60 s TTLFalls to about 20 ms on hits, 900 ms on missesServes data up to 60 s old
Optimise the query, add indexFalls for every request, say 900 ms to 300 msCosts engineering time, no staleness
ETag revalidationSaves bandwidth, not server time on a 304Client still waits for the round trip

Cache-aside in practice

TypeScript
// Node 20, Redis 7
const TTL_SECONDS = 60;

async function getProduct(id: string) {
  const cached = await redis.get(`product:${id}`);
  if (cached) return JSON.parse(cached);

  const product = await db.findProduct(id);
  await redis.set(`product:${id}`, JSON.stringify(product), 'EX', TTL_SECONDS);
  return product;
}

On a product edit I delete the key instead of updating it, so the next read repopulates from the database. I monitor the hit ratio and the endpoint p95 after rollout. If the hit ratio lands at 30% instead of the assumed 80%, blended time stays near 640 ms and the budget is still missed. At that point I keep the cache only if it helps other endpoints, and I go back to the query, because the measurement has rejected the assumption the cache was built on.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-41How would you use SQL joins to fetch feature usage data across users and orders for a dashboard?

The 90-second answer

Start from the grain you need to report at. If the dashboard shows one row per user, do not join users to orders first and aggregate afterwards. That join fans out: a user with 40 orders becomes 40 rows, and any count of users or sum taken on the joined result is easy to get wrong. Aggregate orders to one row per user in a subquery, then join that result to users. You get correct counts, one row per user, and the planner can use an index on orders(user_id) for the aggregation.

Assume this schema, checked against PostgreSQL 16:

SQL
users  (id bigint primary key, plan text, cohort text, created_at timestamptz)
orders (id bigint primary key, user_id bigint references users(id),
        amount_cents int, status text, created_at timestamptz)
SQL
SELECT u.id,
       u.plan,
       u.cohort,
       COALESCE(o.order_count, 0) AS order_count,
       COALESCE(o.revenue_cents, 0) AS revenue_cents,
       o.last_order_at
FROM users u
LEFT JOIN (
    SELECT user_id,
           COUNT(*) AS order_count,
           SUM(amount_cents) AS revenue_cents,
           MAX(created_at) AS last_order_at
    FROM orders
    WHERE status = 'paid'
      AND created_at >= now() - interval '90 days'
    GROUP BY user_id
) o ON o.user_id = u.id
WHERE u.cohort = '2025-q3';

Three choices in that query do the real work. The LEFT JOIN keeps users with no paid orders in the last 90 days, which matters for a feature adoption view: dropping them with an INNER JOIN makes conversion look better than it is because the denominator shrinks. The status and date filters sit inside the subquery, not in a WHERE clause after the join. Putting WHERE o.status = 'paid' after a LEFT JOIN silently turns it into an inner join and removes exactly the zero-order users you wanted to keep. COALESCE then turns the resulting NULLs into zeros the UI can render without a special case.

Why the naive join fails, with a trace

Suppose three users and four paid orders:

users.idplanorders.idamount_cents
1pro1015000
1pro1027000
2free1032000
3pro(none)

SELECT COUNT(*) FROM users u JOIN orders o ON o.user_id = u.id returns 3, not 2. It counts order rows, not users. COUNT(DISTINCT u.id) fixes that specific count, but it does not fix a SUM(u.something) or a per-user row shape, and it gets slower as the fanout grows. The pre-aggregated subquery returns one row per user by construction:

idplanorder_countrevenue_cents
1pro212000
2free12000
3pro00

Choosing the join

NeedJoinEffect
---------
---------
---------
Only users who orderedINNER JOINDrops zero-order users
All users in a cohort, zeros includedLEFT JOIN from usersKeeps zero-order users, NULL on order columns
Only orders, with user attributes attachedINNER JOIN from ordersOne row per order, grain stays at order level
Users with no orders at allLEFT JOIN plus WHERE o.user_id IS NULLAnti-join pattern for churn or never-activated lists

Failure modes I check before shipping the endpoint

Duplicate user rows after the join usually mean a second one-to-many table was joined in the same query, for example orders and order_items. Aggregate each one-to-many source separately, then join the aggregates. A revenue total that is 40% high in a test against the warehouse almost always traces back to that fanout, or to counting pending and refunded orders. I pin the definition in the query itself: status = 'paid', a named 90-day window, and amounts in cents to avoid float rounding in the UI.

For scale, the subquery above scans the 90-day slice of orders. With 250,000 orders in that window and an index on (status, created_at, user_id), it stays a few hundred milliseconds. Past roughly a million rows in the window, or when the dashboard refreshes every minute, I stop querying the raw tables on the request path and materialize the same aggregation into a nightly or hourly summary table keyed by (user_id, day). The join logic does not change, only the source of the aggregate.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-42What is the rule of thumb for normalizing versus denormalizing a database schema?

The 90-second answer

Normalize by default. Store each fact once and link rows with foreign keys. Denormalize only when a specific read is slow enough to matter, by copying a fact to the place that reads it.

Normalization removes duplication. If a customer email lives only in customers, changing it once updates every order that references that customer. Denormalization adds duplication on purpose. It trades extra storage and update work for fewer joins on a read.

A simple order feature shows both:

SQL
-- PostgreSQL 16
CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE
);

CREATE TABLE orders (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES customers(id),
  total_cents INTEGER NOT NULL
);

That is normalized. orders does not repeat the email. To show an order with the email, the query joins orders to customers.

Denormalizing the same feature would add customer_email to orders. The read becomes a single table scan with no join. The cost appears on writes. Every email change must update customers and every matching row in orders, in the same transaction, or the copies disagree.

NormalizedDenormalized
StorageOne copy of each factRepeated copies
Write costLower, update one rowHigher, update every copy
Read costJoins on readDirect read, fewer joins
Main riskSlow joins on hot queriesStale copies if an update is missed

The rule of thumb is to start normalized and denormalize a named query after measuring it. Suppose, as a labelled hypothetical, an account page loads 50 orders and the join costs 15 ms at p95 while a denormalized summary table costs 2 ms. If that page is hit constantly and database CPU is the limit, the summary table earns its keep. If the join costs 1 ms, the extra sync code buys nothing.

One exception is a snapshot. orders.total_cents repeats a calculation from line items because the total must stay fixed after purchase, even if prices change later. That copy is intentional history, not a cache.

So the decision is not normalize or denormalize for the whole schema. Keep the core tables normalized, then copy data only for a proven hot read or for a fact that must be frozen in time.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-43Your orders table has 50M rows, a new dashboard needs filtering by customer and date, and writes are slowing down. How do you design indexes and weigh query performance against write cost?

The 90-second answer

I start from the queries the feature actually runs, not from the columns that look searchable. For each query I write down the filter, the sort, the join and the columns returned, then I design the smallest index that serves that shape. I only add an index when a measured plan shows a sequential scan or a sort that hurts a user-facing endpoint, and I remove or avoid indexes that tax every write for a query that runs once a day.

Assume PostgreSQL 16, an orders table with 50 million rows, and two hot paths: GET /customers/{id}/orders?from=...&to=... sorted by created_at DESC, and a dashboard count of orders by status in the last 7 days. The write path is POST /orders and status transitions, so every extra index is paid on each insert and each status update.

Design for the customer history query

The filter is equality on customer_id, a range on created_at, and a sort on created_at. A composite B-tree in that order serves all three:

SQL
-- Checked on PostgreSQL 16
CREATE INDEX CONCURRENTLY idx_orders_customer_created
    ON orders (customer_id, created_at DESC)
    INCLUDE (status, total_cents);

Equality first, then the range and sort column. Putting created_at first would force the database to scan many customers to find one. INCLUDE makes the index covering for the list endpoint, so the query can be index-only and skip the heap fetch for rows that are still visible. That matters at 50 million rows: an index-only scan over one customer's 200 orders is cheap, while a heap fetch per row adds random I/O.

I would verify with EXPLAIN (ANALYZE, BUFFERS) and look for Index Only Scan and a buffer count in the hundreds, not tens of thousands. If the plan still shows a sort node, the index order is wrong or the statistics are stale.

Design for the dashboard count

Counting by status over a rolling 7 days is a different shape. A full index on status alone has low selectivity if 80% of orders are completed, so the planner may ignore it. A partial index matches the actual question:

SQL
CREATE INDEX CONCURRENTLY idx_orders_open_recent
    ON orders (status, created_at)
    WHERE created_at >= now() - interval '7 days';

A partial index only contains recent rows, so it stays small and writes outside the window pay nothing. The trade-off is that the query must include the same predicate, or the planner cannot prove the index covers it. If the dashboard window changes to 30 days, this index stops helping and I would replace it with a pre-aggregated table updated by a job, because a dashboard that runs every 30 seconds should not scan an operational table at all.

Query patternIndex choiceWhy it winsWhen I skip it
customer_id = ? ORDER BY created_at DESC(customer_id, created_at DESC) INCLUDE (...)Equality, range and sort in one scanIf the endpoint is admin-only and runs hourly
status = ? AND created_at > ? for recent rowsPartial index on (status, created_at)Small, matches the windowIf statuses are evenly spread and the query is rare
Lookup by idPrimary keyAlready clustered by the PKNever add a second index on the same column
Free-text search on notespg_trgm or a search serviceB-tree cannot help LIKE '%...%'If search is a core feature, use a dedicated engine

Weighing write cost with real numbers

Each B-tree index adds work on insert: one more leaf page to find, one more WAL record, and one more page to keep cached. On a typical managed Postgres instance I have measured, hypothetically, insert p99 rising from 6 ms with the primary key alone to about 11 ms with three secondary indexes, and to 19 ms with six. Those figures are workload-specific, so I measure on a copy of production data with pg_stat_statements before and after, rather than trusting a rule of thumb.

The cost is worse when an indexed column is updated often. Updating status breaks HOT updates in Postgres if status is indexed, because the new row version cannot stay on the same page. That turns a cheap update into index maintenance plus vacuum pressure. So I avoid indexing a column that changes on every transition unless a read path needs it, and I prefer a partial index on the values that matter, such as open orders, over a full index on all statuses.

I also check for dead weight. pg_stat_user_indexes shows idx_scan per index. An index with zero scans after a month of production traffic is pure write tax. I drop it with DROP INDEX CONCURRENTLY after confirming no dashboard, cron job or foreign key depends on it. Foreign keys are the trap here: Postgres does not auto-create an index for a foreign key, so deleting a customer can lock the orders table while it scans for referencing rows. I add an index on orders(customer_id) for that reason alone, even if no query filters by customer yet.

Failure modes I watch for

A composite index that starts with a low-selectivity column, such as status before customer_id, looks fine in a schema review and then produces a plan that scans half the table. I catch that by testing the exact query with production-like data, not by reading the DDL.

A second failure is index bloat after bulk updates. If VACUUM cannot keep up, index-only scans degrade because the visibility map stays unset and the database falls back to heap fetches. The symptom is a plan that still says Index Only Scan but buffer counts climb. The fix is fixing the update pattern or the vacuum settings, not adding another index.

My rule in the interview and in production is the same: one index per proven query shape, measured before and after, and a written reason for every index that survives. If I cannot name the query it serves and the plan it changes, it does not ship.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-44Two checkout requests hit the same last item in stock at the same time. How do transaction isolation levels change what each one sees and whether you oversell?

The 90-second answer

Isolation decides which snapshot of committed data a transaction reads, and what happens when it tries to write a row that changed after that snapshot. PostgreSQL defaults to READ COMMITTED. Each statement sees a snapshot taken at statement start, so another transaction can commit between your SELECT and your UPDATE. PostgreSQL REPEATABLE READ takes one snapshot at the first query and holds it for the transaction. If you then try to update a row that a concurrent transaction committed a change to after your snapshot, PostgreSQL raises a serialization failure, SQLSTATE 40001, instead of overwriting it. SERIALIZABLE in PostgreSQL uses Serializable Snapshot Isolation and aborts a transaction when its result could not match any serial order.

For a product feature, the level alone rarely fixes a race. An atomic conditional update fixes overselling at READ COMMITTED. A read-modify-write in application code needs a row lock or a version check, and SERIALIZABLE trades correctness for retries under contention.

Worked trace: last item in stock

Assume stock = 1 for one SKU. Both requests run application code that reads stock, checks stock > 0, then writes stock - 1.

StepT1 checkout AT2 checkout BResult
1BEGIN; SELECT stock returns 1BEGIN; SELECT stock returns 1Same snapshot value, no lock taken by plain SELECT
2UPDATE stock SET stock = 0UPDATE stock SET stock = 0T2 blocks on the row lock held by T1
3COMMITCOMMIT attemptedUnder READ COMMITTED, T2 re-evaluates on the new version and also writes 0. Both succeed, two orders for one unit. Under PostgreSQL REPEATABLE READ, T2 fails with 40001 because the row changed after its snapshot.

That lost update under READ COMMITTED is the failure to design against. The level changed read consistency, but neither transaction held a lock while deciding, so both decisions were based on 1.

The fix that works at READ COMMITTED moves the check into the write:

SQL
-- PostgreSQL, checked against 15
UPDATE inventory
SET stock = stock - 1
WHERE sku = $1 AND stock > 0
RETURNING stock;
-- Zero rows returned means sold out. Create no order.

One statement takes the row lock, tests the current committed value, and decrements only if the unit exists. The second concurrent update blocks, rechecks stock > 0 against the committed 0, and returns no row. No retry loop, no oversell.

What each PostgreSQL level prevents

LevelDirty readNon-repeatable readPhantom readTypical cost
READ COMMITTED (default)PreventedPossible between statementsPossibleRow locks only. Lowest contention.
REPEATABLE READPreventedPrevented within the snapshotPrevented by the snapshot40001 on conflicting row updates, stale reads for long transactions
SERIALIZABLEPreventedPreventedPreventedPredicate locks via SSI. More 40001 aborts under contention, caller must retry.

InnoDB in MySQL also defaults to REPEATABLE READ, but its implementation differs. It uses gap locks to block phantom inserts on indexed ranges, and it does not raise 40001 for the same-row update case above in the same way PostgreSQL does. Do not carry PostgreSQL behaviour across vendors without checking.

Write skew is the case that pushes you to SERIALIZABLE. Example: two on-call engineers, rule says at least one must stay on call. Each transaction reads the rota, sees the other is on call, and removes themselves. Each transaction touches a different row, so REPEATABLE READ in PostgreSQL allows both and leaves nobody on call. SERIALIZABLE detects the overlapping predicate reads and aborts one transaction, which you retry and then see the updated rota.

How I choose per feature

For inventory decrement, seat booking, or balance deduction, I keep READ COMMITTED and use the conditional update above, plus a unique constraint where a duplicate would corrupt data. For a profile edit form, I keep READ COMMITTED and add optimistic concurrency: UPDATE users SET name = $1, version = version + 1 WHERE id = $2 AND version = $3. Zero rows means someone else saved first, so I return 409 with the current version for the UI to merge or prompt. For a reporting export that must total a table consistently while orders insert, I use REPEATABLE READ for a stable snapshot and accept that it will not see rows committed after it started.

Failure modes to name in the interview: deadlocks when two transactions lock rows in opposite order (detect via deadlock errors, fix by locking in a consistent order), serialization failures at REPEATABLE READ and SERIALIZABLE under flash-sale load (detect via 40001 rate, fix by retrying with backoff and reducing transaction scope), and long REPEATABLE READ transactions holding snapshots that block vacuum in PostgreSQL and bloat the undo log in InnoDB. Short transactions, indexes on the rows you lock, and doing the check inside the UPDATE keep all three rare.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-45Your orders list endpoint runs one query for the page and then one per order to load the customer, and p95 climbs as the page grows. How do you diagnose and fix that N+1?

The 90-second answer

I confirm it is an N+1 before I touch the code. An N+1 means query count grows with row count, not with the request. I log the query count for one request at a small page size and again at a larger one. If 10 rows cost 11 queries and 50 rows cost 51, the pattern is confirmed. The fix is to replace the per-row lookup with one batched fetch for the whole page, usually an eager load or a single WHERE id IN (...) query, and to add a test that fails if the count rises again.

Take the orders list. The endpoint loads 50 orders, then for each order it loads the customer to render a name and plan. At 2 ms per lookup on a warm connection, that is roughly 100 ms of serial database time before rendering, and it gets worse as the page grows. It also holds a connection from the pool for the whole loop, so under load the pool saturates long before the database does.

Diagnose it in the open

In development I turn on query logging and count statements per request. In production I use the ORM event hook or the APM trace to record the count as a metric, because latency alone hides the cause. A slow endpoint with a flat query count points elsewhere. A slow endpoint whose count tracks the page size is an N+1.

Python
# SQLAlchemy, checked against 2.0
from sqlalchemy import select
from sqlalchemy.orm import selectinload

# Before: 1 + N queries
orders = session.scalars(select(Order).limit(50)).all()
for order in orders:
    _ = order.customer.name  # lazy load, one query per order

# After: 2 queries total
orders = session.scalars(
    select(Order)
    .options(selectinload(Order.customer))
    .order_by(Order.created_at.desc())
    .limit(50)
).all()

selectinload issues the orders query, collects the customer ids, then runs one WHERE customers.id IN (...) query and stitches the results in memory. The equivalent SQL shape is:

SQL
SELECT * FROM orders ORDER BY created_at DESC LIMIT 50;
SELECT * FROM customers WHERE id IN (101, 102, 103, ...); -- 50 ids, one round trip
Page sizeQueries beforeQueries afterApprox. DB time before*
1011220 ms
50512100 ms
2002012400 ms

*Hypothetical, at 2 ms per lookup, excluding network and rendering. The point is the slope, not the exact figure.

GET /orders Load 50 orders Collect customer ids One IN query for customers Map customers in memory Render page

Where the fix breaks

Eager loading is not free. Loading two collections at once, say customers and line items, with a join can multiply rows and return duplicates, the cartesian product problem. selectinload avoids that by using separate queries, which is why I prefer it for one-to-many relations. For a many-to-many or a nested GraphQL resolver, the same idea appears as DataLoader: batch keys per request, cache within that request only, and never share the cache across requests or one user sees another user's data.

I also check what the page actually needs. If the list only shows the customer name, loading the full customer row wastes bytes on every request. I select the columns the UI renders, or split the endpoint so the list returns ids and a separate call fetches detail. And I keep pagination in the query. Eager loading 10,000 rows to fix an N+1 just moves the cost.

Keep it fixed

I add a regression test that runs the endpoint with a fixed page size and asserts the query count stays at 2. I also alert on the per-request query count metric in production, not just on latency, because a count jump shows up before p95 does. If the count rises again after a new field is added to the serializer, that test names the change that reintroduced it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-46How do you run a zero-downtime database migration with a backfill?

The 90-second answer

Use expand and contract. Never rename, retype or drop a column in one deploy. Add the new shape alongside the old one, write to both, backfill the old rows in small batches, switch reads once the new column is complete, then drop the old column in a later deploy. Each step is reversible on its own, and no step needs a table lock that blocks writes.

Say you are splitting users.full_name into first_name and last_name, or adding a non-null status to a 50M row orders table. The pattern is the same.

SQL
-- Deploy 1: expand. Nullable, no default, no rewrite.
ALTER TABLE orders ADD COLUMN status VARCHAR(20);
CREATE INDEX CONCURRENTLY idx_orders_status ON orders (status);

CREATE INDEX CONCURRENTLY matters on Postgres. A plain CREATE INDEX takes a SHARE lock and blocks writes for the duration. Concurrently builds the index without blocking inserts and updates, at the cost of a longer build and a second scan. It also cannot run inside a transaction block, so run it as its own migration step.

Dual write. From deploy 1, application code writes both columns in the same transaction. New rows get status = 'pending' from the app, not from a database default, so the value is explicit in the request path and easy to log. Reads still use the old column. If dual write fails, the transaction fails, and you do not get silent divergence between the two shapes.

Backfill in batches. A single UPDATE orders SET status = 'pending' on 50M rows holds a transaction open, bloats the WAL, and can starve the primary for minutes. Batch by primary key instead.

SQL
-- Repeat until 0 rows affected.
UPDATE orders
SET status = 'pending'
WHERE id IN (
  SELECT id FROM orders
  WHERE status IS NULL
  ORDER BY id
  LIMIT 5000
);

Run it from a worker, not a migration script, with a short sleep between batches. Hypothetical figures for this example: 50M rows at 5,000 rows per batch is 10,000 batches. At 2 batches per second, that is 5,000 seconds, about 83 minutes. At 20 batches per second the arithmetic gives about 8 minutes, but that rate would likely push replica lag and write latency up on a busy primary, so treat it as an upper bound to test, not a default. Pause the worker if replica lag passes your threshold, say 2 seconds, or if p95 write latency climbs. That pause is the control you do not get from a one-shot update.

StageOld columnNew columnReads use
After expandliveemptyold
During dual writelivenew rows onlyold
During backfilllivefilling in id orderold
After verificationlivecompletenew
After contractdroppedlivenew

Verify before switching. Count nulls, and sample a few thousand rows against the source of truth. For a split name column, check that first_name || ' ' || last_name matches the old value for rows where the split was unambiguous, and list the exceptions instead of guessing. Only switch reads when null count is zero and the sample passes. Keep dual write running for at least one full deploy cycle after the switch, so a rollback is a config flip, not a data recovery.

Contract. In a separate deploy, stop writing the old column, wait until no old code is running, then drop it. Dropping a column on Postgres is fast, but dropping an index on a large table is not, so drop the old index with DROP INDEX CONCURRENTLY and schedule it off peak.

Expand: add nullable column Dual write both columns Backfill in batches Verify nulls and samples Switch reads to new column Contract: drop old column

Failure modes to name in the interview: a backfill that runs as one transaction and locks the table, a new NOT NULL constraint added before the backfill finishes, and dual write added only in the API layer while a background job or admin script still writes the old shape alone. That last one is the common cause of a backfill that never reaches zero nulls. Search the codebase for every writer of the table before you start, not after.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-47Product pages get 40,000 views an hour, prices change hourly, stock changes by the minute, and a stale price at checkout is a refund. How do you choose caching layers and invalidate product data without serving stale prices?

The 90-second answer

I would not cache "product data" as one thing. A product page mixes data with completely different change rates and cost of being wrong: description and images change weekly, price changes hourly and must be exact at checkout, stock changes every minute and can be approximate on the page but not at reservation. I split the response by that, then pick a layer per slice.

Assume 40,000 product page views an hour, about 11 requests per second on average and 80 per second at peak, with a product endpoint at 900 ms p95 against a 500 ms page budget. At 80 rps, uncached, that is 80 concurrent database queries in flight. A CDN hit at 30 ms and a 95% hit ratio drops origin load to 4 rps, which is the difference between needing a bigger database and not.

SliceWhere it livesTTL / freshnessWhy
------------
Description, specs, imagesCDN, Cache-Control: public, max-age=8640024 h, purge on publishRarely changes, safe to be stale for minutes
PriceOrigin or Redis, short TTL60 s, versioned keyMust match checkout, stale price becomes a refund or margin loss
Stock countOrigin, no CDN cacheNo cache, or 5 s with stale-while-revalidateChanges per order, page can show "low stock" but reservation must recheck
RecommendationsCDN per segment, not per user10 minPersonalised per user would fragment the cache and leak across accounts

The rule I apply: cache at the edge only what is identical for every viewer. Anything user-specific, or anything that gates a transaction, stays dynamic and gets a short, explicit freshness window instead of a long one.

Invalidation: version the key, do not hunt for the old one

For price and stock I use a versioned key such as product:sku_123:v42. A write increments the version in the database transaction, then publishes the new version. Readers fetch the current version pointer, so a purge is a pointer swap, not a search through CDN and Redis for every derived key. If a purge misses, the old version simply expires by TTL instead of living forever.

Admin changes price DB transaction: update price, version 42 to 43 Publish product.updated sku_123 v43 CDN purge by tag sku_123 Redis: set current version to 43 Next GET fetches v43 from origin Checkout re-reads price from origin, never cache

On the server I also send validators so a client that does cache can revalidate cheaply:

TypeScript
// Express-style handler, checked against Express 4.19
app.get('/products/:id', async (req, res) => {
  const product = await getProduct(req.params.id); // includes version
  res.set({
    ETag: `"${product.version}"`,
    'Cache-Control': 'public, max-age=60, stale-while-revalidate=30',
    Vary: 'Accept-Encoding',
  });
  if (req.headers['if-none-match'] === `"${product.version}"`) {
    return res.status(304).end();
  }
  res.json(product);
});

A 304 costs a round trip but transfers no body, so a browser or CDN that revalidates every 60 seconds stays correct without paying the full 900 ms origin cost on every view.

Worked trace: price change during a burst

TimeEventWhat the viewer sees
---------
10:00:00Price $49 cached at CDN, TTL 60 s$49
10:00:20Admin sets $54, version increments, purge sent$49, still within TTL
10:00:21Purge reaches edge, next request misses and fetches $54$54
10:00:22User who loaded at 10:00:20 clicks checkoutCheckout re-reads origin, charges $54, shows price-change notice

That last step matters. The page is allowed to be up to 60 seconds stale. The transaction is not. If checkout trusted the cached page price, the stale window becomes a billing bug.

Failure modes I design for

Cache stampede: when a hot product expires, 80 rps all miss at once and hit the origin together. I add request coalescing on the origin (one fetch per key, others wait) and stale-while-revalidate, so the first request refreshes while the rest get the stale copy for up to 30 seconds.

Purge race: a write lands, the purge runs, then a slow reader that fetched the old version before the write repopulates the cache with stale data. Versioned keys fix this, because the slow reader writes to v42, which nobody reads after the pointer moves to v43.

Negative caching: a product created after a 404 was cached will 404 for the full TTL. I keep 404 TTL at 10 seconds, not 24 hours, and purge by tag on create.

I measure hit ratio per slice, stale-served count, and purge lag (time from write to first fresh edge response). If purge lag exceeds the TTL, the TTL is not the real freshness guarantee, the purge is, and I would shorten it until the numbers agree.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-48How do you prevent a cache stampede on a hot product endpoint when thousands of cached entries expire at once?

The 90-second answer

A stampede happens when a popular key expires and every concurrent request misses at the same moment, so the origin gets the traffic the cache was absorbing. Two mechanisms attack different halves of that moment. TTL jitter spreads expiries out in time. Request coalescing collapses concurrent misses for the same key into one origin call. I use both, because jitter alone still leaves a hot key with a burst, and coalescing alone still leaves thousands of keys expiring together.

Assume a product detail endpoint cached for 1 hour, serving a catalogue page where the top 500 SKUs take most traffic. Without jitter, if those entries were written in the same deploy or warm-up pass, they expire in the same second. Hypothetical figures: 5,000 requests in that second all miss, origin QPS jumps from a steady 200 to 5,000, database connections saturate, and p95 goes from 40 ms to over 2 s while the cache refills.

TTL jitter. Add a random spread to each write, for example plus or minus 10% around the base TTL.

TypeScript
// TypeScript, checked against Node 20
function jitteredTtl(baseSeconds: number): number {
  const jitter = Math.random() * 0.2 - 0.1; // -10% to +10%
  return Math.round(baseSeconds * (1 + jitter));
}
// base 3600s becomes 3240s to 3960s, a 720s spread

With that spread, the same 5,000 expiries land over 720 seconds, roughly 7 per second instead of 5,000 in one second. The cost is small. Some entries live 6 minutes longer than intended and some expire 6 minutes early, so hit ratio drops slightly and a few entries are a little staler. That trade is acceptable for catalogue data with a 1 hour freshness budget. It is not acceptable for a price that must change at a fixed moment, where I would keep the TTL exact and rely on explicit invalidation instead.

Jitter has a limit. It does nothing for a single hot key. If one SKU takes 30% of traffic, its one expiry still triggers a burst.

Request coalescing. When a miss happens, the first request becomes the leader and fetches from the origin. Later requests for the same key wait on that in-flight promise instead of calling the origin themselves. This is often called singleflight.

TypeScript
const inflight = new Map<string, Promise<unknown>>();

async function getCached<T>(key: string, load: () => Promise<T>): Promise<T> {
  const hit = await cache.get(key);
  if (hit) return hit as T;
  const existing = inflight.get(key);
  if (existing) return existing as Promise<T>;
  const pending = load()
    .then(async (value) => { await cache.set(key, value, jitteredTtl(3600)); return value; })
    .finally(() => inflight.delete(key));
  inflight.set(key, pending);
  return pending;
}

In the trace above, 5,000 concurrent misses become 1 origin call and 4,999 waiters. Waiters see higher latency for that one refill, typically the origin latency of 80 to 150 ms, but the origin survives. The map is per process, so with 10 app instances I still get up to 10 origin calls for the same key, not 5,000. That is usually enough. If the origin cannot tolerate even 10, I add a short Redis lock around the leader election, at the cost of another dependency and a lock expiry to tune.

yes no yes no Request arrives Cache hit? Return cached value Leader already fetching? Wait on in-flight promise Fetch origin, write with jittered TTL Release waiters with same result
ApproachWhat it spreads or collapsesMain costWhen it fails
TTL jitterExpiries across keys over timeSlightly lower hit ratio, uneven stalenessOne hot key, or a deploy that rewrites all keys at once
Request coalescingConcurrent misses for one keyWaiters queue behind the leaderLeader crashes mid-fetch, waiters need a timeout and retry path
Stale-while-revalidateServes old value during refillUsers see stale data for one cycleStaleness budget is zero, for example inventory at checkout

Failure modes I instrument for. If the leader throws, the promise rejects for every waiter, so I clear the entry in finally and let waiters retry once with a small backoff rather than hammering the origin. If the origin is slow, the in-flight map grows, so I cap wait time and fall back to a stale entry if one exists within a defined window. If jitter is too narrow, say plus or minus 1%, the expiry spike barely moves, so I check the distribution of TTLs in Redis rather than trusting the code. The metrics that tell me this is working are origin QPS during expiry windows, cache hit ratio, number of coalesced waiters per key, and p95 latency for waiters versus normal hits. A stampede shows up first as origin QPS climbing while hit ratio collapses, before users report slowness.

For a product feature, I would ship jitter and coalescing together, set the stale window per data type, and add a dashboard alert when origin QPS exceeds twice the steady state for more than 30 seconds. That turns a cache problem into a visible KPI instead of a surprise during a launch spike.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-49Your product database is hitting CPU limits on reads, writes are fine, and product wants a new dashboard. When would you add a read replica versus sharding, and what breaks with each?

The 90-second answer

Add a read replica when reads are the bottleneck and writes still fit on one primary. Add sharding when one primary cannot take the write load, the storage, or the connection count, even after you remove the reads. The order matters. Replicas are an operational change you can undo in an afternoon. Sharding changes your data model, your queries, and every future migration.

For a product engineer the practical split is usually this. A dashboard, search page, or product listing can tolerate a replica that is 500 ms to 2 s behind. Checkout, inventory decrement, and anything that must read its own write cannot. If the new dashboard is the pressure, a replica solves it. If checkout writes are the pressure, a replica does nothing for the primary and sharding is the only lever left, after indexes and query fixes.

How a replica behaves

The primary applies writes to its WAL. Each replica replays that WAL asynchronously. Reads routed to a replica see state as of the last replayed transaction. Lag is the gap between primary commit time and replica apply time, and it grows under write bursts, long transactions, and DDL.

Python
# Routing rule checked against Postgres 16 behaviour
# Writes and read-your-writes go to primary. Lag-tolerant reads go to replica.
def route(query, session):
    if query.is_write or session.just_wrote:
        return "primary"
    if query.needs_freshness == "strict":
        return "primary"
    return "replica"  # dashboards, listings, analytics

Failure mode to name in the interview: a user updates their address, the write returns 200 from the primary, the next page load hits a replica 1.8 s behind, and the old address renders. Detection is a lag metric per replica plus a canary write that you read back from each replica. Fix is to pin the session to the primary for a short window after a write, or to route that user's reads by primary until lag falls below your threshold.

How sharding behaves

Sharding splits one logical table across N primaries by a shard key, for example customer_id % 16. Each shard is a full primary with its own replicas. Queries that include the shard key go to one shard. Queries that do not must scatter to all shards and merge results, which is where cost and latency explode.

Client Router Primary Read replica Shard 1 primary Shard 2 primary Shard 3 primary

Pick the shard key from the query pattern you must serve, not from the column that looks tidy. If checkout always looks up by customer_id and the dashboard filters by order_date across all customers, sharding by customer makes checkout fast and the dashboard a 16-way scatter gather. That dashboard then needs its own replica or a separate analytical store, which is a common outcome.

Worked figures

Hypothetical but sized like a mid-stage product: 50M orders, primary at 3,200 read QPS and 400 write QPS, CPU at 88% at peak, p95 read latency 210 ms. Moving 2,600 read QPS to one replica drops primary CPU to roughly 35% and p95 on the primary to about 60 ms, because the remaining load is mostly writes and point reads. Lag during the peak in this example is 400 ms median, 2.1 s at p99. That is fine for the dashboard and unacceptable for the post-checkout confirmation page, so that page stays on the primary.

Sharding the same table 16 ways would put about 25 write QPS and 200 read QPS per shard. Latency per shard improves, but a cross-customer report now touches 16 shards. At 50 ms per shard query plus merge, the report p95 lands near 300 ms before network variance, and a reshard from 16 to 32 shards requires moving roughly half the rows while writes continue.

Decision signalRead replicaSharding
BottleneckRead CPU, read connections, long dashboard queriesWrite throughput, storage, single-primary CPU
Consistency costAsync lag, read-your-writes breaksCross-shard transactions and joins largely gone
Query costSame queries, same schemaQueries without shard key scatter to all shards
Operations costOne more instance to monitor for lagN primaries, resharding, shard-aware migrations and backups
ReversibilityRoute reads back to primaryHard to undo once data is split

What I would check before either

I would look at the top queries by total time, not by count. One unindexed dashboard query scanning 50M rows can saturate a primary that a replica would only copy. Adding the right index or pre-aggregating the dashboard hourly often removes the need for both. If reads still dominate after that, replica first. I would only propose sharding when write QPS or table size keeps growing past what one primary plus replicas can absorb, and I would state the shard key, the scatter queries I am accepting, and the reshard plan in the same proposal. Without those three, sharding is a guess with a migration attached.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-50What is the difference between an experiment assignment and an exposure event, and why log them separately?

The 90-second answer

Assignment is the variant the system decided a user belongs to. Exposure is the moment that user actually saw the changed experience. Log them as two different events because a user can be assigned and never exposed, and only exposed users can be affected by the change.

A typical interview answer states that rule directly, then shows the two rows it produces.

SQL
-- PostgreSQL 16
CREATE TABLE experiment_assignments (
  user_id BIGINT NOT NULL,
  experiment_key TEXT NOT NULL,
  variant TEXT NOT NULL, -- control or treatment
  assigned_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (experiment_key, user_id)
);

CREATE TABLE experiment_exposures (
  user_id BIGINT NOT NULL,
  experiment_key TEXT NOT NULL,
  variant TEXT NOT NULL,
  exposed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (experiment_key, user_id)
);

Assignment happens once, when the flag is evaluated. The server hashes the experiment key with the user id, picks a variant, and stores it. That row does not change later, even if the rollout percentage changes.

Exposure happens later, when the client renders the new UI. The client sends an exposure event at that point, and the server stores it. The primary key on user and experiment means a retry or a second visit does not create a second exposure.

StepWhat happenedRow written
1User 42 loads checkout and the flag returns treatmentassignment: checkout_v2, treatment
2User 42 closes the tab before the new button rendersno exposure
3User 42 returns and the new button rendersexposure: checkout_v2, treatment
4User 42 reloads the pageno new exposure, primary key already exists

Analysis then joins exposures to assignments on user and experiment key. The join confirms the exposed variant matches the assigned variant. Metrics compare exposed control users against exposed treatment users.

No Yes Flag evaluated Assignment stored New UI rendered? No exposure stored Exposure stored Compare exposed users by variant

If you log only assignment, you count users who never saw the change as if they had. That dilutes the measured effect. If you log only exposure, you cannot check whether the split itself was correct, because you have no record of users who were assigned but not exposed. Keeping both rows gives you the assigned counts for the split check and the exposed counts for the metric comparison, from the same two tables.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-51Walk me through how you would design an A/B test for a checkout change, from hypothesis and primary metric to sample size and guardrails?

The 90-second answer

I would write the hypothesis before touching the experiment tool, and I would make it falsifiable. For a checkout change, for example: "Moving the promo code field below the payment form will increase completed checkout rate among eligible users from 8.0% to at least 8.8% within 14 days, without increasing payment errors or p95 checkout latency by more than 5%." That sentence names the population, the intervention, the primary metric, the minimum effect worth shipping for, the time window, and two guardrails.

Then I size it from the baseline, not from a round number of users. Then I randomize at the user level, pre-register the analysis, and refuse to peek at p-values until the planned sample is reached.

Hypothesis and metric choice

The primary metric must be the behaviour the change is meant to move, measured per randomized unit. If the unit is a user, the metric is per user, not per session, or repeat visitors inflate the count and break independence. Checkout completion per eligible user works here. Revenue per user is tempting, but it is noisier, skewed by a few large orders, and needs a much larger sample to detect the same relative lift. I would keep revenue per user as a guardrail, not the primary metric.

I also write down what would make me stop. Payment error rate, checkout p95, and support contacts tagged checkout are guardrails with pre-set limits. If the primary metric wins but a guardrail breaches its limit, the result is not a ship.

Sample size, with real numbers

Assume baseline conversion p1 = 0.08, minimum detectable effect of 10% relative, so p2 = 0.088 and delta = 0.008. Two-sided alpha = 0.05, power = 0.80, so Z values are 1.96 and 0.84.

n per arm = (1.96 + 0.84)^2 x [p1(1-p1) + p2(1-p2)] / delta^2 n per arm = 7.84 x [0.0736 + 0.0803] / 0.000064 = about 18,800 users per arm

That is roughly 37,600 eligible users in total. At 5,000 eligible users per day, that is about 8 days, which also covers a full week of weekday and weekend behaviour. I would check the calculation in code rather than trust a calculator in the doc:

Python
import math

def n_per_arm(p1, p2, alpha=0.05, power=0.80):
    z_alpha = 1.96  # two-sided, alpha = 0.05
    z_beta = 0.84   # power = 0.80
    delta = p2 - p1
    return math.ceil((z_alpha + z_beta) ** 2 * (p1 * (1 - p1) + p2 * (1 - p2)) / delta ** 2)

print(n_per_arm(0.08, 0.088))  # 18844

Sensitivity matters more than the single number. Halving the detectable effect roughly quadruples the sample.

Minimum detectable effect (relative)p2Users per arm
20%0.096about 4,900
10%0.088about 18,800
5%0.084about 74,000

If product wants a 5% lift detected in 3 days at current traffic, the honest answer is that the test cannot deliver that precision. The options are a longer run, a larger eligible population, a less noisy metric, or accepting a bigger detectable effect. Pretending otherwise produces an underpowered test that will read as inconclusive or, worse, get stopped early on a lucky spike.

Randomization and the failure modes I check

Control 50% Variant 50% Eligible user hits checkout Hash user_id + experiment salt Bucket Existing layout Promo field moved Log assignment + exposure Analyse per user, intention to treat

Assignment is logged at first exposure, not at checkout completion, and analysis is intention to treat. Dropping users who never reached checkout would bias the result, because the variant itself may change who reaches that step.

Three checks run before I believe any result. First, a sample ratio mismatch check: if the split drifts from 50/50 beyond what chance allows, randomization or logging is broken and the test is invalid. Second, an A/A sanity check on pre-period behaviour: the two arms should look identical on conversion before the change shipped. Third, novelty and primacy effects: a new layout often lifts clicks in week one and fades. Running a full week and comparing week one against week two catches most of that.

Peeking is the quiet killer. Checking the p-value daily and stopping when it dips below 0.05 inflates the false positive rate well above the nominal 5%. I fix the sample size and the end date in advance, and if the business needs interim looks, I use a sequential method with adjusted thresholds rather than repeated naive tests.

One more constraint decides the unit. If users share carts, accounts, or a household, user-level randomization can leak: one person sees the control layout and another sees the variant for the same purchase. In that case I randomize at the account or household level and size the test on that unit, which usually means fewer independent units and a longer run. Ignoring interference does not make the test faster, it makes the estimate wrong.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-52How do you interpret statistical significance and a p-value when an experiment reports p = 0.03, and what would you check before acting on it?

The 90-second answer

A p-value of 0.03 means: if there were truly no difference between variants, we would see a difference at least this large about 3% of the time by chance alone. It is not the probability that the null is true, not the probability the result is real, and not the size of the effect. Statistical significance only says the data are surprising under the null at a threshold, usually alpha = 0.05, that we set before looking.

I would never act on p alone. I would report the effect size with its confidence interval, check that the experiment was valid, and ask whether the effect is large enough to matter for the decision and the cost of shipping.

What the numbers actually say

Take a labelled hypothetical. Control converts at 10.0% on 50,000 visitors per arm. Treatment converts at 10.3% on 50,000 per arm. The absolute lift is 0.3 percentage points, a 3% relative lift. A two-proportion test gives p = 0.03, and the 95% confidence interval for the difference is roughly +0.03 to +0.57 percentage points.

QuestionAnswer from this result
Is it statistically significant at 0.05?Yes, p = 0.03 is below alpha
How large is the effect?Best estimate +0.3 points, plausibly as low as +0.03
Is it practically significant?Depends on cost. At 1 million visitors a month, +0.3 points is 3,000 extra conversions. At +0.03, it is 300
What is the chance the treatment is better?Not 97%. The p-value does not give that

That last row is the common misread. A p-value conditions on the null being true. It says nothing directly about P(treatment better | data). For that you need a Bayesian model with an explicit prior, or you stay with the frequentist statement and lean on the interval.

A quick check I run in Python before quoting a test in a review:

Python
from statsmodels.stats.proportion import proportions_ztest
import numpy as np

count = np.array([5150, 5000])   # conversions: treatment, control
nobs = np.array([50000, 50000])
stat, p = proportions_ztest(count, nobs)
print(f"z={stat:.2f}, p={p:.4f}")

The snippet is a sanity check, not the decision. The decision needs the interval and the validity checks below.

Checks before I act on p < 0.05

First, was alpha and the primary metric fixed before launch, and did we stop at the planned sample size? Peeking daily and stopping when p dips below 0.05 inflates the false positive rate well above 5%. With 20 independent looks, the chance of at least one false alarm is far higher than the nominal rate, which is why sequential methods or a fixed horizon matter.

Second, is randomisation intact? I check the sample ratio mismatch. If we assigned 50/50 but exposures split 52/48, something upstream is broken, such as logging, bucketing, or a variant that crashes before the exposure event fires. A significant result from a broken split is not evidence.

Third, are we testing one primary metric or fishing across many? Twenty metrics at alpha = 0.05 gives roughly a 64% chance that at least one shows p < 0.05 under the null, since 1 - 0.95^20 = 0.64. That is why the primary metric is pre-registered and secondary metrics are treated as exploratory unless corrected.

Fourth, does the interval clear the minimum effect worth shipping? If the team needs at least +0.5 points to justify maintenance cost and risk, an interval of +0.03 to +0.57 does not clear it. The point estimate clears it, the interval does not. I would call that inconclusive for a ship decision, not a win.

How I would phrase it in the room

"p = 0.03, estimated lift +0.3 points with a 95% interval from +0.03 to +0.57. Randomisation checks pass and we hit the planned sample size. The effect is statistically significant but small, and the lower bound is close to zero, so I would not ship on this alone if the change carries meaningful maintenance cost. I would either extend the run to narrow the interval or ship only if the cost of being wrong is low and guardrail metrics are clean."

That phrasing separates three things interviewers probe for: what the p-value means, how big the effect plausibly is, and whether the experiment design lets you trust either number.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-53You are A/B testing one-click checkout against the current multi-step flow, with completed orders per visitor as the success metric. Which metrics would you pick as guardrails, and what result on each would make you stop the rollout?

The 90-second answer

I would keep the success metric as completed orders per visitor, then pick guardrails that would show harm from this specific change before the harm shows up in revenue. For one-click checkout, that is payment failure rate, refund or duplicate order rate, and checkout latency. I would not pick a metric the change cannot plausibly move in two weeks, such as 90-day retention, and I would not pick a metric nobody would act on. Each guardrail gets a threshold written down before launch, for example payment failures rising by more than 0.3 percentage points against control, and a stated action, pause the rollout and investigate.

Why those three

One-click removes steps. That is the mechanism that should lift conversion, and it is also the mechanism that can cause harm. If card details are prefilled incorrectly, payment failures rise. If a double tap or a retry creates two orders, refunds rise a few days later. If the new flow calls an extra fraud or payment service, latency rises and later conversion falls even if the first week looks fine.

That gives a simple test for any candidate metric. Can this treatment move it quickly? If yes, and would a move mean the conversion gain came from a bad mechanism, it belongs on the guardrail list. If the treatment cannot move it, it will only add noise and arguments at decision time.

MetricRoleHypothetical threshold vs controlAction
Completed orders per visitorSuccessShip only if it rises and is stable across mobile and desktopShip decision
Payment failure rateGuardrailUp more than 0.3 percentage points, from a 1.2% baselinePause rollout, check payment flow
Refund rate within 7 daysGuardrailUp more than 0.2 percentage pointsRoll back, do not ship on conversion alone
Checkout p95 latencyGuardrailUp more than 200 msHold at current percentage, investigate
90-day retentionNot a guardrailCannot move meaningfully in a two-week testTrack after launch, do not gate on it

The thresholds are hypothetical, but the form matters. A threshold tied to cost is easier to defend than a threshold picked because it looks round. At 100,000 checkout attempts a week, 0.3 percentage points is 300 extra failed payments. If the conversion gain is smaller than that cost, the launch should stop even though the success metric won.

Instrumentation check

Guardrails fail in practice when they are computed on the wrong population. I compute them only for users who were actually exposed to a variant, and I use the same denominator in both arms. I also log the payment outcome at the time it happens, rather than rebuilding it later from an orders table that refunds and edits can change.

SQL
-- Exposed users only, one outcome window per user
SELECT e.variant,
       COUNT(DISTINCT e.user_id) AS exposed_users,
       SUM(CASE WHEN p.status = 'failed' THEN 1 ELSE 0 END) * 1.0
         / NULLIF(COUNT(p.id), 0) AS payment_failure_rate
FROM experiment_exposure e
LEFT JOIN payments p
  ON p.user_id = e.user_id
 AND p.created_at >= e.exposed_at
 AND p.created_at < e.exposed_at + INTERVAL '1 day'
WHERE e.experiment = 'one_click_checkout_v2'
GROUP BY e.variant;

Two failure modes come up often. First, dilution. If one-click only appears on mobile, averaging payment failures over all users hides the harm. I compute the guardrail for mobile exposed users, where the treatment actually ran. Second, checking too often. Looking every hour and stopping on the first dip creates false alarms. I schedule checks, for example at day 3 and day 7, and treat an early move as a prompt to inspect logs rather than automatic proof.

No Yes Yes No Scheduled check on exposed users Guardrail past threshold? Ship if success metric wins Pause rollout and inspect payment and order logs Cause is the new flow? Roll back Resume with a note in the launch record

The distinction I would state live is that a guardrail is not just another metric to watch. It is a metric with a pre-agreed number and a pre-agreed consequence, chosen because this change could move it through a harmful path.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-54What distinguishes a north star metric from its input metrics, and what rule should you follow when picking them for a feature?

The 90-second answer

A north star metric is the single outcome that captures the core value a user gets from the product. Input metrics are the smaller behaviours that drive that outcome and that a team can directly influence. The rule is to pick one north star, then pick only inputs with a clear causal link to it.

For a feature, I state the north star first and write its definition before I list anything else. Then I work backwards: what must a user do in this feature for the north star to move? Those steps become the input metrics. If a candidate metric does not sit on that chain, I leave it out, even if it is easy to measure.

A concrete example helps. Suppose the feature is a new template gallery in a project tool. The north star could be weekly active workspaces that create a project from a template and return the next week. That captures value received, not clicks on the gallery. The inputs would be template views, template used to create a project, and first project created within 24 hours of signup. Each input is earlier in the chain and moves before the north star does.

MetricRoleWhy it qualifies
Weekly workspaces creating a project from a template and returning next weekNorth starOne outcome, tied to retained value
Template used to create a projectInputDirectly controlled by the gallery design
First project created within 24 hoursInputLeading indicator, visible days before retention
Gallery page viewsNot an inputActivity only, rises with promotion even if no project is created

The test I apply to each input is simple. Can the feature change it within the experiment window, and does moving it plausibly move the north star? Page views fail the second test. A banner that doubles views without changing template use tells me nothing about value.

Instrumentation follows the same chain. I emit one event per step, with the workspace id and the template id, so the funnel can be checked in order.

SQL
-- funnel check for the template gallery, one row per workspace
SELECT
  COUNT(DISTINCT CASE WHEN event = 'template_viewed' THEN workspace_id END) AS viewed,
  COUNT(DISTINCT CASE WHEN event = 'template_used' THEN workspace_id END) AS used,
  COUNT(DISTINCT CASE WHEN event = 'project_created' THEN workspace_id END) AS created
FROM product_events
WHERE event IN ('template_viewed', 'template_used', 'project_created')
  AND created_at >= CURRENT_DATE - INTERVAL '7 days';
Template viewed Template used Project created in 24 h Workspace returns next week North star

If the inputs move and the north star stays flat, the chain is broken somewhere. In this example that usually means projects are created but abandoned, so I would check project activity in week two before calling the feature a success. If the north star moves and an input does not, I would suspect a definition change or a tracking bug, because the inputs are supposed to explain the movement.

I also add one guardrail per input where gaming is possible. For template use, that guardrail is the share of created projects that get a second session. It stops the team from optimising for empty projects that inflate the input and never reach the north star.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-55How do you instrument analytics events with a naming taxonomy that stays queryable across web, mobile and server without leaking PII or breaking dashboards when you rename an event?

The 90-second answer

I name events as object_action in past tense, with the object first and no UI location in the name: checkout_payment_method_selected, not button_clicked or payment_page_v2_click. The name answers what happened in the product. Where it happened goes in a property, surface: "checkout", so a redesign does not force a rename and break every funnel that references the old name.

Every event goes through one typed wrapper, never a raw analytics.track("whatever") call scattered through components. The wrapper enforces the taxonomy at compile time, adds the envelope fields the warehouse needs, and strips anything that looks like PII before it leaves the browser.

PieceRuleExample
Event nameobject_action, past tense, snake_case, max about 40 charscart_item_added, invoice_paid
Propertiessnake_case, typed, no free-form strings for values you will group byitem_id, quantity, price_cents
Envelopeadded by the wrapper, not by callersevent_id, occurred_at, schema_version, session_id
Forbiddennever in name or propertiesemail, raw URL with query string, user-entered text

Why this shape survives contact with a real team

A taxonomy fails in predictable ways. First, cardinality. If a developer writes track("search_performed", { query: userText }), the warehouse gets a distinct value per search and no query can group it. The fix is to split the event from its payload: search_submitted with result_count and has_results as typed properties, and the raw query only if there is a stated analysis need, hashed or truncated, and never as an event name.

Second, duplication. A track call inside a React effect fires twice in StrictMode development and again on retry or remount in production. The wrapper generates event_id as a UUID at the moment the user action happens, not at flush time, and the ingestion layer deduplicates on (event_id) within a 24 hour window. That also makes offline queueing safe: the client can retry a batch after a network drop without double counting a purchase.

Third, silent renames. Renaming cart_viewed to cart_opened looks harmless in a pull request and orphans six months of funnel history. I treat event names as a public contract. A rename ships as a new event plus a mapping table in the warehouse (new_name aliases old_name for reporting), and the old event stays emitted for one release so dashboards can be compared side by side. Deleting an event is a breaking change that needs the same review as an API field removal.

TypeScript
// analytics.ts, checked against TypeScript 5.x
type EventMap = {
  cart_item_added: { item_id: string; quantity: number; price_cents: number };
  checkout_payment_method_selected: { method: "card" | "wallet" | "bank" };
  invoice_paid: { invoice_id: string; amount_cents: number };
};

type Envelope = {
  event_id: string;
  occurred_at: string; // ISO 8601, client clock
  schema_version: 1;
  session_id: string;
};

function track<K extends keyof EventMap>(name: K, props: EventMap[K]) {
  const payload = { ...props } as Record<string, unknown>;
  for (const key of Object.keys(payload)) {
    if (/email|token|password|ssn/i.test(key)) delete payload[key];
  }
  const event: Envelope & { name: K; props: EventMap[K] } = {
    name,
    props: payload as EventMap[K],
    event_id: crypto.randomUUID(),
    occurred_at: new Date().toISOString(),
    schema_version: 1,
    session_id: getSessionId(),
  };
  queue.push(event); // batched flush, retry with same event_id
}

The EventMap is the taxonomy in code. Adding an event means adding a type, which forces a review of the name and its properties. A CI check can diff EventMap against a checked-in registry file and fail if an event is removed or a property changes type, which catches the rename problem before it ships.

What I would check before calling it done

I would run the funnel end to end on a staging build: click add to cart, confirm exactly one cart_item_added row in the warehouse with the right item_id and no email field, then reload the page and confirm the count does not double. I would also check the server side. invoice_paid should be emitted by the payment service, not the browser, because a client can close the tab after paying and the revenue event would be lost. Client events describe intent and interaction. Server events describe money and state changes that must be true. Mixing them is how a dashboard shows 1,000 checkouts and 940 payments with no way to tell whether the gap is abandonment or a dropped event.

Sampling is the last decision. At 40,000 product page views an hour, product_viewed is cheap to keep at 100 percent and useful for funnels. A high volume, low value event like scroll_depth_changed should be sampled at the client, with the sampling rate recorded as a property so analysts can weight it. Sampling silently in the warehouse makes every rate wrong by an unknown factor.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-56How do you use funnel analysis to find drop-off in a feature flow?

The 90-second answer

Define the flow as an ordered set of events a user must pass through, then count how many distinct users reach each step in order within a fixed window. The drop between steps is the signal. I would start with the steps the feature was designed to have, not the pages it happens to render, and I would check the instrumentation before I trust any number.

Take a concrete flow: a new user creates a workspace, invites a teammate, and creates their first saved view. I would instrument three events with a shared session_id and a distinct_id that survives login, so anonymous and authenticated activity join up.

TypeScript
// TypeScript, client + server events share this shape
type FunnelEvent = {
  event: 'workspace_created' | 'teammate_invited' | 'saved_view_created';
  distinct_id: string;      // stable across login
  session_id: string;       // one attempt at the flow
  ts: string;               // ISO 8601, server clock
  properties: Record<string, string | number | boolean>;
};

Then run the funnel with a 24 hour conversion window per session. A user who invites a teammate on day three did not convert in that attempt, even if they eventually did. Without the window, slow users inflate the later steps and hide the real drop.

StepUsers reaching stepStep conversionCumulative
workspace_created10,000100%100%
teammate_invited3,20032%32%
saved_view_created2,88090%28.8%

The arithmetic points at step one to two. Losing 68% before the invite is a different problem from losing 10% after it. I would segment that step by platform, plan, and entry source before writing code. If mobile web converts at 12% and desktop at 48%, the drop is likely a form or permission issue on mobile, not a product idea issue.

yes no workspace_created teammate_invited within 24h? saved_view_created drop: inspect segment, error, and time to next event compare step conversion by segment

What I check before calling it a drop-off

First, event integrity. I would sample raw events for a few sessions and replay them by hand. Common failures: the invite event fires on button click instead of on successful send, so the funnel counts intent as completion; the event fires twice on retry, which a distinct-user count absorbs but an event count does not; and the client clock skews ordering, which is why I order by server receipt time.

Second, step definition. If users can reach saved_view_created without inviting, the funnel as defined will show zero for that path and overstate the drop. I would run a path view alongside the funnel for one week to see the actual sequences. Funnel answers "how many survived this order", path answers "what did people actually do". When they disagree, the path wins and I redefine the steps.

Third, denominator. A funnel built on all sessions mixes users who never intended to invite anyone with users who tried and failed. I would add a qualifying event, such as opening the invite dialog, and compare conversion from dialog open to invite sent. That separates "never tried" from "tried and hit an error", and the fix differs completely.

QuestionFunnelPath analysis
Main useConversion between defined stepsDiscovering actual sequences
Blind spotAssumes the order you definedHard to compare rates across segments
Use it whenSteps are known and orderedSteps are uncertain or branching

From drop to fix

Once a step is isolated, I look at the distribution of time between steps and the error rate on the transition. A long tail with no errors suggests confusion or a missing prerequisite. A spike in 4xx or validation failures on the submit call suggests a fixable defect. I would then ship the smallest change that targets that step, keep the same funnel definition for the comparison, and watch step conversion rather than the final cumulative number. Changing the definition mid-test makes the before and after incomparable.

I would also set a guardrail. If the fix lifts invite conversion but raises workspace creation abandonment or support tickets tagged with invites, it moved the problem rather than solving it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-57How would you use cohort analysis to measure retention after launching a new feature, and what would you conclude from the pattern?

The 90-second answer

I would group users by the week they first became eligible for the feature, then track what share of each group is still active at fixed intervals after that week. That gives a retention table, not a single blended retention number. A blended number hides whether a launch changed behaviour or whether a later, larger cohort simply diluted the average.

The cohort date matters more than the chart. For a launched feature I would use first exposure to the feature, not account creation, if existing users could adopt it later. New signups and existing users who first try the feature in week 3 belong in different cohorts, because their starting point differs.

Building the table

First I need two events logged consistently: feature_exposed (or first successful use, if exposure is noisy) and a recurring activity event that defines retention, such as session_started or a core action the product expects weekly. Retention is not "opened the app once" if the feature was meant to change a weekly workflow.

A SQL sketch for weekly cohorts, checked against our warehouse:

SQL
-- Postgres, illustrative
WITH first_seen AS (
  SELECT user_id, MIN(created_at) AS cohort_at
  FROM events
  WHERE event_name = 'feature_first_used'
  GROUP BY user_id
),
activity AS (
  SELECT user_id, DATE_TRUNC('week', created_at) AS active_week
  FROM events
  WHERE event_name IN ('session_started', 'core_action')
)
SELECT
  DATE_TRUNC('week', f.cohort_at) AS cohort_week,
  COUNT(DISTINCT f.user_id) AS cohort_size,
  COUNT(DISTINCT CASE WHEN a.active_week = DATE_TRUNC('week', f.cohort_at) + INTERVAL '1 week' THEN a.user_id END) AS w1,
  COUNT(DISTINCT CASE WHEN a.active_week = DATE_TRUNC('week', f.cohort_at) + INTERVAL '4 weeks' THEN a.user_id END) AS w4
FROM first_seen f
LEFT JOIN activity a ON a.user_id = f.user_id
GROUP BY 1
ORDER BY 1;

In the dashboard I would show percentages of the original cohort, with the raw counts beside them. Percentages alone make a 40-user cohort look as reliable as a 40,000-user cohort.

Worked example, hypothetical figures for a feature launched in week 0:

Cohort weekUsersWeek 1 retainedWeek 4 retainedWeek 8 retained
-1 (no feature)10,0005,200 (52%)3,100 (31%)2,600 (26%)
0 (launch)12,0006,600 (55%)4,200 (35%)3,600 (30%)
111,0005,720 (52%)3,520 (32%)2,970 (27%)
29,0004,140 (46%)2,520 (28%)incomplete

Reading that table: week 0 is 4 points above the pre-launch cohort at week 4 (35% vs 31%). Week 1 falls back to 32%, and week 2 to 28%. That pattern points to launch-week selection, for example a campaign or power users trying first, rather than a durable lift. I would not call the feature a retention win from week 0 alone.

What I check before concluding

Incomplete cohorts are the most common error. A cohort from 2 weeks ago has no week 8 value, and averaging only the cohorts that have reached week 8 biases the result toward older, possibly different users. I would grey out or exclude immature cells and compare cohorts at the same age, for example week 4 retention for the pre-launch cohort against week 4 retention for each post-launch cohort.

Second, composition. If week 0 came from a paid campaign, its users may retain worse regardless of the feature. I would split the table by acquisition channel, plan, and new versus existing user, and check whether the lift survives inside each segment. If it only appears in the blended total, it is a mix shift.

Third, the shape of the curve. A curve that drops steeply then flattens suggests a retained core. A curve that keeps falling at the same rate suggests the feature delayed churn by a week rather than creating a habit. In the example, week 0 stays above the baseline at week 8, but the gap narrows from 4 points to 4 points on a smaller base, so I would want week 12 data before claiming a habit effect.

Fourth, definition drift. If the activity event changed, or tracking was fixed at launch, retention can jump because measurement improved. I would check event volume per active user and any instrumentation release in the same window, and keep the retention definition frozen across the comparison.

Cohort analysis shows whether behaviour changed for comparable groups over time. It does not prove the feature caused the change. If launch coincided with pricing, onboarding, or a competitor outage, I would say so and, where possible, compare exposed users with a holdout or a matched unexposed group from the same cohort week before attributing the lift to the feature.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-58Why must a feature flag rollout use sticky bucketing based on a stable user ID instead of random assignment on each request?

The 90-second answer

Sticky bucketing means the same user always lands in the same variant for a given experiment, no matter how many times the flag is evaluated. You get that by hashing a stable identifier, usually the user ID, together with the experiment key, then comparing the hash to the rollout percentage. Random assignment on each request breaks the experiment. A user would flip between control and treatment inside one session, the UI would change under them, and your metrics would mix two experiences for the same person.

The hash has to be stable across deploys, machines, and percentage changes. FNV-1a or a similar non-cryptographic hash works. MD5 or SHA-256 also work, but they cost more for no benefit here. What matters is that bucket 3 today is bucket 3 next week.

TypeScript
// TypeScript, checked against a generic flag service contract
function bucket(userId: string, experimentKey: string): number {
  let hash = 0x811c9dc5;
  const input = `${experimentKey}:${userId}`;
  for (let i = 0; i < input.length; i++) {
    hash ^= input.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193);
  }
  return (hash >>> 0) % 100;
}

function inTreatment(userId: string, rolloutPct: number): boolean {
  return bucket(userId, "one_click_checkout") < rolloutPct;
}

Worked trace for one user, user_4821, whose hash lands in bucket 7:

RolloutTestResultWhat the user sees
1%7 < 1falseControl
5%7 < 5falseControl
10%7 < 10trueTreatment
50%7 < 50trueTreatment
100%7 < 100trueTreatment

That monotonic property is the point. Raising the percentage only ever adds users. Nobody who saw the treatment drops back to control, and nobody in control at 5% is guaranteed to stay there at 50%. With random assignment per request, that user would see treatment on roughly 10% of page loads at the 10% stage, including two variants in the same checkout.

Yes No Request arrives Hash user ID plus experiment key Bucket below rollout percentage? Serve treatment Serve control Log assignment and exposure

Where this breaks in practice

Anonymous users have no stable ID. A logged-out visitor gets a new bucket on each device and after each cookie clear, so the same person can appear in both variants. Either restrict the experiment to signed-in users, or persist the bucket in a first-party cookie and accept that cross-device users count twice. State the choice in the experiment doc, because it changes the sample size.

Client and server must agree. If the browser evaluates the flag and renders the new button while the API still runs the old pricing logic, the user sees a treatment UI backed by control logic. Evaluate once on the server, return the variant in the API response, and have the client render from that value. Cache the result for the session so a percentage change mid-checkout does not flip the UI halfway through.

Log assignment separately from exposure. Assignment is the bucket result at evaluation time. Exposure is when the user actually sees the variant. If you log only exposure, users assigned to treatment who never reached checkout disappear from the denominator and conversion looks better than it is. Log both with the experiment key, user ID, variant, and rollout percentage, so an analyst can rebuild the eligible population.

When the flag service is unreachable, fall back to control for anything money-related. A failed flag fetch should never block checkout, and it should never default to the untested variant. Test that fallback before you move past 1%.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-59You have 47 flags, a 100%-on checkout flag overlapping a live experiment, old mobile builds still sending the old variant, and a flag-service outage next week. How do you sequence cleanup without breaking checkout or invalidating the experiment?

The 90-second answer

I would freeze new flags, then sequence cleanup by risk, not by age. The 100% checkout flag cannot be deleted this week if it overlaps a live experiment and old mobile builds still send the old variant. Deleting it now would either invalidate the experiment or break clients that cannot be updated. The order is: inventory every flag with owner, type, evaluation volume and expiry, separate release flags from experiment and ops flags, fix defaults before any deletion, and only then remove dead branches in an order that keeps checkout working during a flag service outage.

A flag is a temporary code path with an owner and a deletion date. Release flags live for days to weeks. Experiment flags live until the decision is read. Ops kill switches can live indefinitely but are reviewed quarterly. Permission flags that encode entitlement belong in the database, not in a flag.

Flag typeDefault on evaluation failureLifetimeSafe deletion condition
ReleaseOff, meaning old path1 to 4 weeks100% for 14 days, bake period passed, minimum client version no longer sends old variant
ExperimentControl variantUntil readout, max 8 weeksWinner chosen, analysis locked, exposure logs retained
Ops kill switchDepends on which path is safeIndefinite, reviewed quarterlyRisky path removed from code
PermissionOffUntil moved to data modelEntitlement check in database with audit trail

Sequencing for the constraints you named

First, stop the overlap from corrupting the experiment. If the checkout release flag and the experiment flag both gate the same step, the experiment must be analysed only on traffic where the release flag was on. I would check the evaluation logs for the joint distribution. If the experiment started before the release ramp finished, assignment is confounded with time and with the new path. The honest options are to restart the experiment on the released path or to discard the pre-ramp period and accept a smaller sample. Deleting either flag before that decision destroys the ability to reconstruct who saw what.

Second, fix the outage default before touching code. During a flag service outage, evaluators fall back to a cached or declared default. If web defaults to on and the API defaults to off, the UI shows one-click checkout and the API rejects it. I would declare one default per flag in the flag definition and use it in every evaluator, frontend and server.

TypeScript
// TypeScript, checked against a LaunchDarkly style SDK pattern
type FlagDef = {
  key: string;
  owner: string;
  expiresAt: string;
  defaultVariant: 'on' | 'off';
  minClientVersion?: string;
};

function evaluate(def: FlagDef, served: 'on' | 'off' | null): 'on' | 'off' {
  // null means the flag service was unreachable or the flag expired.
  // Never reuse the last served variant silently.
  return served ?? def.defaultVariant;
}

For checkout, the safe default during an outage is the old multi-step flow, because it does not depend on the new payment path. That choice is a product decision, not a technical default, and it should be written in the flag definition where an on-call engineer can find it at 3 a.m.

Third, handle old mobile builds as a hard constraint. A flag evaluated on the client can be cached in an app version you cannot force upgrade. The server must accept both variants until the minimum supported version moves past the flag. I would check the variant distribution by app version in the evaluation logs. If version 4.2 still sends off at 2% of traffic, deleting the off branch breaks those users even though the flag reads 100% on in aggregate.

Yes No Yes No Freeze new flags, inventory all 47 Fix one default per flag Experiment still reading? Keep experiment flag, analyse only on released path Old clients still send losing variant? Wait for readout, then delete loser Keep server branch, raise min version, recheck weekly Delete losing branch, ship with no flag Monitor checkout conversion and payment errors 7 days

Clearing the 47 flags

The stale query is mechanical. Weekly, list flags with zero evaluations in 30 days, flags past expiry, and flags where one variant took 100% of traffic for 14 days. Send each to its owner with the code search attached. In an inherited codebase this usually surfaces about half the flags in the first run, mostly permission flags and experiments nobody read.

Signal in logsMeaningAction
Zero evaluations in 30 daysNo caller, or caller removedConfirm with code search, delete flag
100% one variant for 14 daysRamp finishedDelete losing branch if no old client sends it
Past expiry, still evaluatingCleanup ticket missedFail to declared default, page owner, set new expiry or delete
Two flags gating same stepCombination explosionMerge into one decision, keep experiment inside released path

For the checkout flag, the deletion pull request removes the off branch, keeps the on path as the only path, and ships with no flag. I would watch completed orders per visitor and payment error rate for a week. If the off branch was the old flow, that is the cleanup. Keeping the flag just in case recreates the debt.

The review rule that prevents recurrence: a pull request adding a flag links a cleanup ticket with a date, and a pull request ramping to 100% includes the branch deletion or a ticket dated within one sprint. Without that link, the flag is not done.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-60Your A/B test finishes with a result that is neither statistically significant nor clearly negative. How do you decide whether to ship, kill, or iterate on it?

The 90-second answer

I do not treat "not significant" as a verdict. I compare the confidence interval for the primary metric against two thresholds set before launch: the minimum effect worth shipping, and the maximum harm I will tolerate on guardrails. If the interval clears the ship threshold, I ship. If the whole interval sits below that threshold, I kill it, even if the point estimate is positive. If the interval straddles both, the test was underpowered for the decision I need, so I extend it once or iterate on the variant, and I state which one and why before anyone looks again.

That framing only works if the thresholds were set before launch. I also check for a sample ratio mismatch, novelty effects, and whether the treatment changed who counts as a visitor.

Worked example: what "inconclusive" actually means

Hypothetical figures, labelled as such. Baseline checkout conversion is 10.0%. The team needs a 5% relative lift, which is 0.5 percentage points, to justify maintenance cost. With 80% power and a two-sided alpha of 0.05, the required sample per arm is:

n = (1.96 + 0.84)^2 * [0.10*0.90 + 0.105*0.895] / 0.005^2 = 57,695

So about 57,700 visitors per arm. Suppose the test stops at 20,000 per arm with treatment at 10.2% versus control at 10.0%. The observed lift is +0.2 points, with a 95% confidence interval of roughly -0.39 to +0.79 points. The pre-set harm guardrail is -0.5 points, so the lower bound does not breach it.

Interval positionReadingDecision
Lower bound above 0 and point estimate at or above +0.5Benefit is real and large enoughShip
Upper bound below +0.5, even if point estimate is +0.2Even the optimistic case does not pay for the featureKill
Interval spans 0 and +0.5, as aboveCannot rule out harm or a worthwhile gainExtend or iterate
Lower bound below -0.5, the pre-set harm guardrailPlausible harm beyond toleranceKill or roll back, do not extend

Extending is only valid if traffic will reach the required sample in a reasonable window and the effect is stable over time. If the interval is wide because the variant is weak, extending burns weeks to confirm a small effect. Iterating is better when a secondary metric or segment points to a specific fix, for example the new checkout helps returning users but hurts first-time users who miss the guest path.

Python
# Python 3.11, normal approximation for two proportions
import math

def decide(p_c, p_t, n_c, n_t, ship_pp=0.005, harm_pp=-0.005):
    diff = p_t - p_c
    se = math.sqrt(p_c * (1 - p_c) / n_c + p_t * (1 - p_t) / n_t)
    lo, hi = diff - 1.96 * se, diff + 1.96 * se
    if lo < harm_pp:
        return "kill: plausible harm beyond guardrail", (round(lo, 4), round(hi, 4))
    if lo > 0 and diff >= ship_pp:
        return "ship", (round(lo, 4), round(hi, 4))
    if hi < ship_pp:
        return "kill: even optimistic case below ship threshold", (round(lo, 4), round(hi, 4))
    return "extend or iterate: interval straddles decision thresholds", (round(lo, 4), round(hi, 4))

print(decide(0.100, 0.102, 20000, 20000))
# ('extend or iterate: interval straddles decision thresholds', (-0.0039, 0.0079))
yes no above ship below ship straddles yes no Check SRM, exposure logging, novelty window Guardrail breached? Kill or roll back CI vs ship and harm thresholds Ship Kill Traffic can reach powered n in time? Extend once, pre-register stop date Iterate variant or kill

Failure modes I check before deciding

Repeated peeking inflates false positives, so if the team looked daily and stopped on a good day, I discount that result and require a holdout or a fresh run. A sample ratio mismatch, for example a 52/48 split when randomisation promised 50/50, points to broken assignment or logging, and no decision is safe until that is explained. Novelty effects show up as a strong week one lift that decays, so I compare the first 7 days with the later period rather than pooling blindly. Finally, a flat primary metric with a large move in a guardrail, such as refund rate or page load time, is a kill even if conversion ticks up, because the cost lands after the experiment window closes.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-61How do you trade off roadmap delivery against paying down technical debt when both compete for the same engineering capacity?

The 90-second answer

I treat technical debt as work with an interest rate, not as a separate category that always loses to features. The question for each item is: what does deferring it cost per sprint, in slower delivery, incidents, or blocked work, and when does that cost expire?

I would not apply a fixed 80/20 split blindly. I would reserve capacity based on the debt register. If the register shows items that are actively taxing every feature, that reserve rises. If the debt is mostly cosmetic or isolated, it falls. The reserve is reviewed each planning cycle against evidence, not defended as a permanent policy.

Three tests decide whether an item gets paid now:

  1. Interest rate. Does it slow the next feature, increase defect rate, or force workarounds in code reviewers already see?
  2. Expiry. Is there a date after which deferral becomes much more expensive, such as a scaling limit, a compliance change, or a dependency reaching end of life?
  3. Coupling. Does paying it now unlock two or more roadmap items, or does it only improve one isolated module?

If an item fails all three, it stays in the register with a named owner and a trigger for revisiting it. That is a deliberate deferral, not neglect.

A worked example

Hypothetical figures for one quarter, labelled as such: a team of 6 engineers has 60 engineer-weeks in a 10-week quarter. The checkout retry path has a known defect. It causes 0.4% of attempted orders to fail and needs a 2-week fix plus 1 week of testing.

OptionCapacity usedCost if deferred one quarter
Pay now3 engineer-weeksRemoves the failure source before peak season
Defer0 nowAt 20,000 orders per week, 0.4% is 80 failed orders per week, plus support tickets and manual reconciliation
Partial fix1 engineer-weekAdd idempotency key and alerting, defer the refactor of the retry state machine

The partial fix often wins. It cuts the interest rate (failed orders, manual work) without paying the full principal (the clean refactor) during a delivery crunch. I would ship that, measure failed order rate for two weeks, and keep the refactor in the register with the measured rate as its justification.

How I score the register

I score each item 1 to 5 on interest rate and expiry, and I require a concrete signal for the score. "Code is messy" scores nothing. "Every API change in this module takes 2 extra days because of duplicated validation, measured over the last 3 changes" scores high.

SignalInterest rateTypical action
Blocks a committed feature or launch date5Pay now, or descope the feature explicitly
Causes incidents or data loss in production5Pay now, treat as reliability work
Adds days to each change in a hot module4Pay the slice that removes the tax, defer the rest
Slows onboarding or local development3Schedule when it does not collide with a launch
Duplication in a cold module with no planned changes1Defer, revisit when the module is touched

The last row matters. Paying debt in code nobody will change for a year has a near zero return. When that module is next touched for a feature, the cost of cleaning it then is usually lower than cleaning it now, because the feature work gives context for what the clean design should be.

Yes No Yes No Yes No Debt item proposed Blocks a committed date or causes incidents? Pay now, descope something else High interest rate in a hot module? Pay the slice that cuts the tax Expiry within one quarter? Schedule before expiry, track trigger Defer with owner and revisit trigger

Failure modes I watch for

The first is an invisible register. Debt that lives only in engineers' heads never competes fairly with roadmap items, because roadmap items have dates and owners. I keep the register in the same planning doc as the roadmap, with the same fields: cost of delay, owner, trigger.

The second is the big bang rewrite disguised as debt repayment. A 6-week rewrite of a working module pauses feature delivery and usually reintroduces bugs the old code had already fixed. I prefer incremental slices behind the existing interface, each one shippable and measurable.

The third is paying debt with no before and after measure. If I claim a refactor will speed delivery, I record cycle time for changes in that module before and after. Without that, the next planning cycle has no way to tell whether the reserve was well spent, and the argument becomes opinion against opinion.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-62What is technical debt interest, and how do you use it to decide which debt to fix first?

The 90-second answer

Technical debt has a principal and interest. The principal is the cost to fix it now. The interest is the extra cost you pay every sprint while it stays, in slower changes, bugs, and incidents. I prioritize by interest, not by how messy the code looks. The item charging the most interest per month goes first, provided the fix cost is reasonable.

That is the rule product can use. If a fix costs 10 engineer days and the debt costs 30 engineer hours a month in rework and support, payback is under three months. If another item costs 2 days to fix and costs nothing measurable, it waits. I state both numbers in the same units, hours or days, so the trade is visible.

ItemPrincipal to fixInterest per monthPayback
Checkout retry can create duplicate orders10 engineer days, about 80 hours30 hours in tickets, incident response and rework80 / 30 = 2.7 months
Slow admin report nobody uses2 engineer days, about 16 hours0 hours, no tickets and no feature blockedNo payback
Product search rerenders on each keystroke5 engineer days, about 40 hours20 hours of extra testing on every search change40 / 20 = 2 months

How I explain it to product

I translate interest into a delivery cost. "This checkout path adds two days of manual testing to every pricing change and caused one incident last month. Fixing it takes ten days. Keeping it costs about six days a quarter and delays the next checkout feature by the same amount." That framing lets product choose between paying now or paying repeatedly.

I also name the smallest fix that removes the interest. For duplicate orders, that is an idempotency key on the create endpoint, not a checkout rewrite. Smaller principal means faster payback and less risk.

Find debt item Estimate principal: hours to fix Estimate interest: hours or incidents per month Payback = principal / interest Fix first if payback is short Defer if interest is near zero

What I do when interest is unclear

I do not ask for sprint time on a guess. I add basic instrumentation or a ticket tag for a few weeks, such as counting duplicate order reports or time spent testing pricing changes. Once I can quote a monthly figure, I can rank it against other work. If the figure stays near zero, I leave the code alone and revisit it when it starts charging rent.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-63During an incident, how do you decide whether to roll back a feature launch or fix forward, and what evidence would make you pull the plug?

The 90-second answer

I separate two questions that get merged in an incident: is the new feature causing this, and can I stop it faster than I can fix it. If I cannot attribute the regression to the feature within about 15 minutes, I do not roll back on a hunch. I check the guardrails I set before launch, compare the flagged cohort against control at the same traffic share, and look for a mechanism that ties the symptom to the code path. If attribution is clear and the blast radius is growing, I kill the flag first, not the deploy. A flag flip reaches users in seconds and preserves the option to re-enable. A deploy rollback takes minutes, can fail on a migrated schema, and often reintroduces the bug you just fixed.

I roll back when three conditions hold together: a guardrail has breached its pre-agreed threshold for two consecutive windows, the flagged cohort is materially worse than control, and continuing to serve the feature risks data corruption, incorrect charges, or a support backlog that grows faster than the fix. I fix forward when the failure is narrow, the flag already contains it, and the fix is a config change or a small patch with a known blast radius.

What I check before I decide

Before launch I write down the rollback triggers in the launch doc, with numbers. For a checkout change at 5% rollout, for example: payment success rate down more than 0.5 percentage points versus control, p95 checkout API latency above 800 ms for 10 minutes, or 5xx rate above 1% on the new endpoint. Without those numbers, the incident becomes an argument about whether the dashboard looks bad.

During the incident I run a quick attribution trace. Hypothetical figures, labelled as such: baseline 5xx on /checkout/confirm is 0.2%. At 5% rollout the flagged cohort shows 1.8% and control shows 0.21%. That gap, sustained over 20 minutes and concentrated in the new one-click path, is attribution. If both cohorts rise together, the cause is probably a shared dependency, and rolling back the feature will not help and will cost you the control group you need to diagnose it.

Signal at T+20 minFlagged 5%Control 95%Reading
5xx on new endpoint1.8%0.21%Feature-specific
Payment success-0.9 pp-0.05 ppGuardrail breached
p95 latency, shared DB620 ms610 msNot the feature
Orders created with duplicate idempotency keys140Data risk, escalate

That last row changes the decision. A latency regression I can fix forward. Duplicate orders or double charges I cannot undo by fixing the code later, so I stop exposure immediately even if the fix is ready.

How I stop it, in order

First, flip the flag to 0% for the affected cohort and confirm the flag service has propagated. I check the client-side evaluation, because a cached flag in a mobile build or a service worker can keep serving the new path for an hour after the server flip. Second, I freeze further rollout and stop the experiment, so no new users are assigned. Third, I decide whether the deploy itself must go back. That depends on reversibility. If the launch added a column, backfilled rows, or changed the meaning of an existing field, rolling back the code can break reads against the new schema. In that case I keep the code and disable the behaviour behind the flag, then fix forward.

YAML
# feature_flags/one_click_checkout.yaml
key: one_click_checkout
default: false
rollout:
  percentage: 0        # flipped from 5 during incident
  sticky_bucket: user_id
kill_switch: true      # server evaluates on every request, no client cache

Sticky bucketing matters here. If assignment were random per request, users would flip between old and new flows mid-checkout, and my cohort comparison during the incident would be meaningless.

No Yes Yes No Yes No Guardrail breach detected Flagged cohort worse than control? Investigate shared dependency, keep flag Data corruption or incorrect charge risk? Kill flag to 0%, freeze rollout Fix is config or small patch under 30 min? Fix forward behind flag, watch guardrails Kill flag, schedule fix, keep deploy if schema changed

Failure modes I watch for

The common one is rolling back the deploy while leaving the flag on, so the old code still evaluates the new path and the incident returns. The reverse also happens: flag off, but a background job or webhook handler reads the new table directly and keeps writing bad rows. I check those consumers before I declare the rollback done. Another is declaring victory on error rate while the KPI instrumentation is still broken. If the new feature changed the event name or dropped the exposure event, conversion will look like it recovered because the denominator vanished. I verify event volume for both cohorts before I re-enable anything.

I re-enable in steps, 1% then 5%, with the same guardrails armed, and I keep the incident channel open until the flagged cohort matches control for a full traffic cycle. If it does not, the fix was not the cause.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-64A checkout feature fails only for users on a new flag, and the logs just show a 500. How would you use a trace ID and structured logs to find which step failed?

The 90-second answer

I would start with the trace ID, not with the error message. A 500 log line tells me a request failed. A trace ID tells me which request, which user session, and which steps that request took across the browser, the API, and any downstream service. If every log line and span for that request carries the same trace ID, I can pull one request out of millions and read it end to end.

For a flag-gated checkout bug, I would filter logs to the new flag variant, take one failing trace ID, and check each span in order. The span that errors, or the span after which no further span appears, is where the failure happened. The structured fields on that span then tell me why, such as the payment provider response code or the validation rule that rejected the cart.

What has to be in place

The browser creates a trace ID for the checkout attempt and sends it as a header. The API reads that header, uses it as the parent context for its own spans, and writes it on every log line for that request. If the API enqueues a job, the trace ID goes in the message attributes so the worker continues the same trace.

TypeScript
// API handler, Node 20 with OpenTelemetry JS SDK 1.9
app.post('/checkout', (req, res) => {
  const traceId = req.header('traceparent')?.split('-')[1] ?? randomUUID();
  logger.info({
    event: 'checkout.started',
    trace_id: traceId,
    flag: 'one_click_checkout',
    variant: req.user.variant,
    cart_total_cents: req.body.total,
  });
  // downstream calls inherit traceId via the active OpenTelemetry context
});

Logs and traces answer different questions, and I use both. Logs are cheap to search and good for counting. Traces show sequence and timing across services.

QuestionUse logsUse traces
How many checkouts failed on the new variant?Count event: checkout.failed grouped by variantHard to count across sampled traces
Which step failed for this user?Search by trace_id, read the last log lineOpen the span waterfall for that trace_id
Was the payment service slow or down?Log line shows provider status codeSpan duration and error status on the provider call

Sampling is the trade-off. Keeping 100% of traces at 40,000 requests an hour costs storage and ingestion for spans most users will never need. Keeping 5% risks losing the exact failing request. I keep 100% of traces for errors and for the flagged path, and sample normal traffic, and I record the sampling decision on the span so a missing trace is not mistaken for a missing request.

Working one failing request

Suppose the dashboard shows a 500 rate of 3% on one_click_checkout=on and 0.2% on off. I pull logs for checkout.failed with the new variant and take the first trace_id.

TimeSpan or logDetail
10:02:14.100Browser: POST /checkouttrace_id: 4bf92f3577b34da6a3ce929d0e0e4736
10:02:14.180API: auth and flag check12 ms, variant on
10:02:14.210API: validate cart8 ms, passed
10:02:14.260API: charge payment41 ms, provider returned card_declined
10:02:14.265API: checkout.failed logcode: card_declined, trace_id matches
Browser POST /checkout API auth and flag check API validate cart Payment provider charge API returns 500

The trace shows the failure is not in the new checkout code at all. The provider declined the card, and the new flow maps that decline to a 500 instead of a 402 with a message the UI can show. The old flow handled the same provider code correctly. That is why the bug only appears on the new variant, and the fix is in the error mapping for the new path, not in payment processing.

If the trace had ended after validate cart with no payment span, I would suspect the request died between validation and the provider call, and I would check the API log for that trace_id for an exception or a timeout field. If the payment span existed but the worker span for a confirmation email was missing, I would check whether the queue message carried the trace context.

The check that closes the loop is a rerun of the first query. After the fix, checkout.failed grouped by variant should show the same provider decline rate on both variants, with the new variant returning the correct status code. If the 500 rate on the new variant does not drop, the trace will show the next failing request in the same way.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-65How do SLOs and error budgets change what you ship, sequence, or delay when a feature is ready but reliability is slipping?

The 90-second answer

An SLO turns reliability into a budget that product and engineering spend together. Without it, feature delivery and reliability argue from preference. With it, the argument becomes arithmetic: how much failure have users already absorbed this window, and how much is left for the risk this feature adds?

Take a checkout SLO of 99.9% successful requests over a rolling 30 days, measured at the API edge as 2xx responses divided by all checkout attempts. The error budget is the allowed 0.1%. On 10 million attempts a month that is 10,000 failed attempts, or about 43 minutes of full outage. A feature that touches checkout, adds a dependency, or raises latency does not get approved or blocked by gut feel. It gets checked against burn rate, the speed at which the budget is being spent, and against a policy agreed before the incident.

Python
# Checked against Python 3.12
def budget_status(total_requests: int, failed: int, slo: float = 0.999) -> dict:
    allowed = total_requests * (1 - slo)
    remaining = allowed - failed
    return {
        "allowed_failures": round(allowed),
        "remaining": round(remaining),
        "pct_consumed": round(100 * failed / allowed, 1) if allowed else 0.0,
    }

print(budget_status(10_000_000, 6_200))
# {'allowed_failures': 10000, 'remaining': 3800, 'pct_consumed': 62.0}

That 62% consumed with 12 days left in the window changes delivery in concrete ways. A low risk change behind a flag, with a one click rollback, can still ship. A schema migration on the checkout path, a new synchronous payment call, or a 100% rollout of a redesigned flow waits, or ships to 1% with a guardrail that auto rolls back. The policy, not the loudest stakeholder, makes the call.

Budget stateBurn rate (30d)Delivery decision
More than 50% leftUnder 1xShip normally, standard review and staged rollout
25 to 50% left1x to 2xShip low risk work only, flag gated, no new synchronous dependencies on the SLO path
Under 25% leftOver 2xFreeze risky features, capacity moves to reliability and the top error source
Budget exhaustedOver 14x for 1 hourStop feature releases to that service until the window recovers or the SLO is renegotiated

Burn rate matters more than the raw percentage. Spending 60% of the budget in the first week because of one bad deploy is different from spending it evenly. Google's SRE workbook uses a 14.4x fast burn alert, which would exhaust a 30 day budget in about 2 days, to page immediately, and a slower 6x alert over 6 hours to ticket. I use the same idea at product level: a feature that doubles burn rate for a week is not a small delay, it is a decision to spend next month's reliability now.

No Yes Measure SLO at user facing edge Compute remaining budget and burn rate Policy threshold crossed? Ship with staged rollout and guardrails Gate, shrink, or delay feature Fund fix for top error source

Three failure modes show up in product teams. First, the SLO measures the wrong thing. A 99.99% uptime SLO on the load balancer can be green while checkout fails 2% of the time on a downstream timeout. The budget then protects infrastructure, not the user outcome the feature depends on. I measure success where the user feels it, and keep infrastructure metrics as diagnostics. Second, one incident eats the month. A single 4 hour outage consumes about 5,500 of the 10,000 allowed failures in the example above if traffic is steady. If the team then ships risky work anyway, the budget has no teeth. The policy needs a pre agreed consequence, such as no new releases to that path until burn rate returns under 1x for 48 hours. Third, teams game the window. Delaying a risky deploy by 3 days to land in a new 30 day window spends the same user trust. A rolling window, plus a longer 90 day view for planning, removes most of that incentive.

The trade off is real. A strict budget policy slows delivery and can frustrate product when the SLO was set too tight for the stage of the company. Early products with low traffic often set a looser SLO, such as 99.5%, or use an error budget on a single critical journey rather than the whole platform, and tighten it as traffic and revenue grow. What does not work is keeping the SLO as a reporting number with no delivery consequence. If nothing changes when the budget is gone, it is not a budget. It is a dashboard.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-66What is the primary defence against SQL injection in a customer-facing API, and why does it work?

The 90-second answer

Use parameterized queries for every value that comes from the client. The database driver sends the SQL structure and the values separately, so a value can never be parsed as SQL.

That separation is the whole mechanism. In a concatenated query, the input becomes part of the grammar. In a parameterized query, the grammar is fixed before the value arrives.

JavaScript
// Vulnerable: the input changes the query structure
const rows = await db.query(
  `SELECT id, name FROM users WHERE id = ${req.query.id}`
);

// Safe: the driver binds the value as data, not code
const rows = await db.query(
  'SELECT id, name FROM users WHERE id = ?',
  [req.query.id]
);

Checked against Node.js 20 with a standard MySQL or PostgreSQL driver. The placeholder syntax differs by driver, ? for MySQL and $1 for PostgreSQL, but the rule is the same.

Worked trace

Suppose the client sends id = 1 OR 1=1.

ApproachSQL the database parsesRows returned
---------
---------
ConcatenationSELECT id, name FROM users WHERE id = 1 OR 1=1Every user, because the condition is always true
ParameterizedSELECT id, name FROM users WHERE id = ? with value 1 OR 1=1No rows, because no user has that literal id

The second query does not fail or need the input to be cleaned first. The value is compared as a string or number, so the payload loses its special meaning.

Input validation still has a place. I validate type, length and range so the API returns a clear 422 for a malformed id instead of an empty result. Validation is a usability and contract check. It is not the injection defence, because a value can pass a length check and still contain SQL syntax.

The same rule applies inside an ORM. Its query builder is safe when I pass values through its parameterized methods. It becomes unsafe when I drop to a raw query and interpolate a value into the string. If I see string interpolation in a raw query in review, I block it and ask for the parameterized form.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-67Your app needs a live provider feed over WebSockets for 40,000 concurrent users, the provider issues only one account-wide secret key with no per-user tokens, and product wants the browser to connect directly for sub-second updates. How do you ship this without exposing the key?

The 90-second answer

I would tell product the direct browser call is not shippable as specified, and I would show the arithmetic that forces a different architecture. A secret key in a JS bundle, a WebSocket URL or a client env var is readable by anyone. If the provider only issues one account-wide key and offers no per-user token, there is no safe way for 40,000 browsers to hold that key. The choice is then between changing the provider contract and moving the fan-out to my servers.

My default is server fan-out. One or a few server processes hold the provider WebSocket, and browsers connect to my own WebSocket or Server-Sent Events endpoint. The server subscribes once per channel, not once per user, and broadcasts updates to the browsers that asked for that channel. The key stays in the server secret store and never reaches the client.

one WebSocket per channel, secret key my WebSocket or SSE, session cookie my WebSocket or SSE, session cookie my WebSocket or SSE, session cookie Provider API Server fan-out Browser 1 Browser 2 Browser 3

Why the obvious alternatives fail here

OptionWhat happens at 40,000 usersVerdict
Browser holds account keyKey is public on first page load. Anyone can call the provider as the account, exhaust quota and read other users' dataReject
Server mints short-lived provider tokensProvider has no token endpoint, so there is nothing to mint. Inventing a signed token the provider does not verify does nothingNot available
One server WebSocket per browser40,000 provider connections. Most providers cap connections per key at 100 to 1,000, and the bill scales with connectionsReject
Server subscribes per channel, broadcasts to browsersProvider connections equal channel count, often tens. Browser connections are mine to scaleDefault

The per-channel design is the step that makes the numbers work. Suppose the live map has 50 regions and updates arrive every 2 seconds. Direct per-browser connections would be 40,000 provider sockets. Per-channel fan-out is 50 provider sockets, plus 40,000 sockets to my own servers, which a load balancer and a few Node or Go processes can hold. If the provider charges per message rather than per connection, fan-out also cuts that cost, because the provider sends each update once and I replicate it.

What the server endpoint must enforce

Browsers can send any channel name, so the server checks the session, checks that the user may see that channel, and only then subscribes. It validates the channel against an allowlist rather than passing a raw string to the provider. It also caps how many channels one user can subscribe to, because an unauthenticated client could otherwise subscribe to every channel and turn my fan-out into a free relay.

TypeScript
// Server fan-out, simplified. Runs only on the server.
import WebSocket from "ws";

const provider = new WebSocket("wss://api.provider.example/feed", {
  headers: { Authorization: `Bearer ${process.env.PROVIDER_API_KEY}` },
});

const subscribers = new Map<string, Set<WebSocket>>();

provider.on("message", (raw) => {
  const msg = JSON.parse(raw.toString()) as { channel: string; payload: unknown };
  const targets = subscribers.get(msg.channel);
  if (!targets) return;
  const out = JSON.stringify({ channel: msg.channel, payload: msg.payload });
  for (const ws of targets) {
    if (ws.readyState === WebSocket.OPEN) ws.send(out);
  }
});

The client connects to wss://myapp.example/feed with its session cookie, sends { action: "subscribe", channel: "eu-west" }, and receives only the fields the UI renders. I strip provider metadata such as account IDs and internal error text before forwarding, and I never log the Authorization header.

Failure modes that bite in production

Reconnect storms are the first. If the provider drops the connection, 50 server sockets reconnect, which is fine. If my server restarts, 40,000 browsers reconnect at once and can overwhelm the auth check. I add jittered backoff on the client, a connection limit per user, and a resume token so a browser that reconnects within a few seconds gets the latest snapshot instead of replaying the whole feed.

The second is a slow consumer. One browser on a poor connection that never reads will buffer updates in memory until the server runs out. I set a per-socket send buffer limit, drop that socket when it exceeds it, and let the client resync on reconnect. Without that, one bad client degrades the channel for everyone.

The third is quota abuse through my own endpoint. Because the key is shared, one scripted user subscribing to all channels and reconnecting rapidly can hit the provider rate limit for the whole product. Per-user subscription caps, rate limits on subscribe messages, and an alert on provider 429 responses keep one abuser from taking the feed down for the rest.

When I would change the answer

If the provider later offers scoped, short-lived tokens, I would move to direct browser connections for the users who need the lowest latency, with the server minting a token limited to that user and channel and expiring in 5 to 15 minutes. If the provider offers a public key that is safe to expose, scoped by domain and rate limited per origin, I would use that and drop the fan-out. If neither is available and the channel count explodes into the thousands, fan-out stops being cheap and the honest answer is to renegotiate the provider contract or drop the live requirement. Shipping the account key to the browser is never the fallback, because rotating it later does not undo the calls made with the leaked copy.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-68How would you choose between blue-green, canary, and rolling deployments for a feature rollout, and when would each be the wrong choice?

The 90-second answer

I separate deploying code from releasing the feature. Deployment decides how fast new binaries reach servers and how fast I can pull them back. Release, usually a feature flag, decides which users see the behaviour. For a feature, I pick the deployment that matches the blast radius I can tolerate and the signal I need before going wider.

Rolling is the default when the change is backward compatible and I have no spare capacity. Blue-green is for changes where instant rollback matters more than the cost of running two stacks for an hour. Canary is for changes where I need production evidence from a small slice of real traffic before committing, and I have the routing and metrics to read that slice cleanly.

No, old and new cannot coexist Yes Yes, product or KPI risk No, risk is code correctness Yes No Feature ready to deploy Is the change backward compatiblewith the old version? Blue-green, or rollingwith a compatibility shim Do I need live trafficevidence before full rollout? Canary behind a flag:1%, then 10%, then 50% Can I afford 2x capacityfor the switch window? Blue-green for instant rollback Rolling, 1-2 instances at a time

Comparison on the trade-offs that decide it

RollingBlue-greenCanary
How it shipsReplaces instances in batches, for example 2 of 10 at a timeBuilds a full second stack, then flips the load balancer in secondsSends 1% of traffic to the new version, then steps up
RollbackRe-run the rollout in reverse, often 15 to 30 minutesFlip the balancer back, usually under a minuteShift traffic back to 0%, under a minute if routing is ready
Extra capacityNoneRoughly double for the window, so 20 pods instead of 10Small, one canary pool or a weighted route
Versions live at onceYes, for the whole rolloutNo, one version takes all traffic after the flipYes, by design, old and new split traffic
Signal before full rolloutHealth checks and error rate per batchSmoke tests on the green stack before the flipReal KPI and error comparison between cohorts
Main failure modeA bad batch reaches every host before anyone noticesDatabase or cache state that only one colour understands1% is too small to read, so noise gets mistaken for signal

Rolling: when it fits a feature

Rolling suits a stateless API or worker change where old and new code can read the same data. With 10 instances and 2 per batch, a 5 minute bake per batch means about 25 minutes to full rollout. If batch 3 fails health checks, the rollout pauses and 4 instances run new code while 6 run old. That coexistence is the constraint. The new code must not write a field the old code chokes on, and a schema change needs the expand and contract pattern: add the column, deploy code that writes both, backfill, then stop writing the old one.

I would not use rolling for a feature whose risk is product behaviour rather than a crash. A checkout change can pass every health check and still cut conversion by 8%. Rolling gives me no clean control group to see that.

Blue-green: when instant rollback wins

Blue-green suits a risky release where the cost of being wrong for 20 minutes exceeds the cost of double capacity for an hour. The green stack gets full traffic in one flip, and rollback is the same flip in reverse. That speed only holds if state is shared or compatible. Two stacks writing to one database with an incompatible migration breaks the promise, because flipping back does not undo rows the new code already wrote.

It also gives no partial exposure. At 09:00 the feature is off for everyone, at 09:01 it is on for everyone. For a feature I want to ramp by user segment, I still need a flag on top, and the flag, not the colour, does the ramping.

Canary: when I need evidence, not just safety

Canary fits a feature with measurable product risk: a new recommendation panel, a changed pricing display, a rewritten onboarding step. I route by a stable user ID, not by random per request, so the same user stays in one cohort and the KPI comparison is not polluted by users flipping between variants.

The arithmetic matters. At 40,000 page views an hour, 1% is 400 views. If the baseline conversion is 5%, that is about 20 conversions in the canary hour, far too few to detect a 10% relative drop. I would start at 1% for error and latency signals, then move to 10% (4,000 views, about 200 conversions) for a KPI read, and only then 50% and 100%. Each step needs a named guardrail and a stop rule agreed before the rollout, for example error rate above 0.5% or p95 latency up 100 ms against control.

A canary also fails quietly when the slice is unrepresentative. Routing only internal accounts, or only one region, or only desktop, will hide a mobile rendering bug. I check cohort composition in the dashboard before I trust the numbers.

What I would actually propose for a feature

For most product features I combine them: rolling or blue-green to deploy the code to all servers, with the feature flag at 0%, then a canary style flag ramp at 1%, 10%, 50%, 100%. That keeps deployment simple and puts the risk control where the product risk lives. If the code change itself is the risk, for example a new payment path with no flag, I pick blue-green for the instant rollback and keep the old path warm until the new one has a clean bake.

I would state the rollback trigger in the launch plan: which metric, which threshold, who can call it, and how long the old version stays available. A deployment choice without that trigger is just a preference.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-69Your team debates running full end-to-end checkout tests on every pull request or only after merge. How would you decide, and how would you structure the pipeline around that choice?

The 90-second answer

I would not run the full end-to-end suite on every pull request. I would run fast tests on the PR, run the full checkout E2E suite on merge to main, and use a feature flag to make the merge safe to release. The PR gate would be lint, typecheck, unit tests for pricing and order state, and contract tests for the checkout API. That gate needs to finish in about 4 minutes. The merge gate can take 10 to 15 minutes because it runs once per merge, not per push. It runs integration tests against real Postgres and the payment sandbox, plus the E2E tests for the happy path, card declined, and out of stock. If those pass, we build one artifact and deploy it with the flag off. Then we ramp the flag 1%, 10%, 50%, 100% while watching payment errors and checkout conversion.

The reason is feedback cost. A PR that waits 25 minutes for E2E tests gets pushed less often, so changes get bigger and harder to review. A merge that skips E2E tests lets a broken checkout reach main, where it blocks everyone else. Splitting the gates gives fast feedback where it changes behaviour and full confidence where it is cheaper to pay for it.

Pull request Fast gate: unit, contract, typecheck Merge to main Full gate: integration + E2E Deploy with flag off Flag ramp 1% to 100%

The trade-off, with numbers

ApproachTime per runFeedbackMain risk
Full E2E on every PR20 to 30 min for 40 testsLate, so engineers batch changesFlaky tests train the team to ignore red builds
Full E2E only on merge4 min on PR, 12 min on mergeFast on PR, slower to find integration bugsBroken main blocks merges until fixed
Path-filtered E2E on PR4 min, plus 6 min only when checkout files changeFast for most PRs, covered for risky onesA change outside the filter breaks checkout indirectly

I would start with the second row and add the third as a refinement. The path filter is a list of directories that can affect checkout: the API checkout module, the frontend checkout route, the payment webhook handler, and the shared pricing library. A PR that touches any of those also runs the 5 critical E2E tests, not all 40. A PR that only touches a marketing page skips them.

YAML
jobs:
  fast:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dorny/paths-filter@v3
        id: checkout
        with:
          filters: |
            checkout:
              - 'src/checkout/**'
              - 'src/pricing/**'
              - 'src/payments/**'
      - run: npm run test:unit
      - run: npm run test:contract
      - if: steps.checkout.outputs.checkout == 'true'
        run: npm run test:e2e -- --grep @critical

What each gate actually tests

Unit tests cover the logic that is cheap to test and expensive to get wrong: total with discount and tax, currency rounding, and the order state machine from cart to reserved to paid to failed. I would add property-based tests for rounding, because a 15% discount on a 3-item cart with a capped coupon is the kind of combination hand-picked cases miss.

Contract tests pin the checkout API response the frontend expects. If the backend renames a field, the PR fails in 2 minutes instead of a user seeing a blank total.

Integration tests on merge cover the seams unit tests cannot: POST /checkout with an Idempotency-Key returns the same payment intent on retry, a payment.succeeded webhook arriving twice creates one order, and a stock reservation expires after 10 minutes if payment never completes. Those run against Testcontainers with Postgres 16, using the same migrations as production.

E2E tests stay narrow on purpose. Five tests at about 30 seconds each is 2.5 minutes. I would keep the happy path, card declined, out of stock mid-checkout, back button after payment, and account switch. The other 35 tests I would push down to API or component level. Any E2E test that fails more than 2% of runs in a week gets quarantined and fixed or deleted, because a flaky gate stops being a gate.

Failure modes the split creates

The merge-only E2E gate means a bug can sit on a branch for a day before anyone runs it. The path filter and the critical subset on risky PRs shrink that window without paying the full cost on every push.

The flag ramp is the other safety net. If the merge gate misses a bug, the flag is still off in production. At 1% of 40,000 daily checkouts, that is 400 orders a day, enough to see a payment error rate move from 0.8% to 3% within a day. I would hold each step for a full day before doubling. Rollback is flipping the flag, not redeploying, which only works if the database migration is backward compatible. So the migration ships one release ahead: add the column, deploy code that writes both old and new, backfill, then stop writing the old column. Without that, turning the flag off still leaves data the old code cannot read.

If the flag service is unreachable, checkout should not make a live call on every request. The server caches the last known flag state for 5 minutes and defaults new users to off. That keeps a flag outage from becoming a checkout outage.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-70How do you do capacity planning and load testing for a traffic spike?

The 90-second answer

Start from the spike you expect, not from the servers you have. Take baseline traffic, multiply by the launch factor, add headroom, then prove the system holds that load in staging before the spike hits production. If you cannot name peak requests per second, the bottleneck resource, and the load test that reproduced it, you do not have a capacity plan.

For a product launch I work in four steps: forecast peak, size each tier against that peak at a safe utilisation, load test at and above the forecast, and set production guardrails so the spike degrades gracefully if the forecast is low.

Forecast and size

Use product data, not a guess. Baseline for a checkout or product page might be 2,000 requests per second. A marketing email or launch announcement that historically gives a 10x lift puts the forecast at 20,000 rps. Label that 10x as an assumption and test above it.

Size each tier separately, because the bottleneck is rarely the web tier alone. A simple worked example, with hypothetical figures: one app instance sustains 800 rps at 65% CPU and p95 under 300 ms. Instances needed = 20,000 / 800 = 25. Add 30% headroom for uneven load balancing, deploys and a slow instance, and you provision 33. Do the same arithmetic for the database connections, cache, and any third party you call. If the pool is 20 connections per instance and each request holds a connection for 50 ms, 33 instances offer 660 connections, which supports far more than 20,000 rps in theory. In practice the database CPU or a downstream rate limit saturates first, which is why you test the whole path.

Target 60 to 70% utilisation at forecast peak. At 90% a small burst queues, latency climbs non linearly, and autoscaling reacts after the queue has already formed.

Load test in staging

Mirror production data volume and configuration. A test against an empty database proves nothing about index behaviour at 50 million rows. Run four test shapes, each answering a different question:

TestShapeQuestion it answersPass criteria
BaselineSteady at current peakWhat is normal p95 and error rate?p95 within budget, errors under 0.1%
LoadSteady at forecast peak for 30 minDoes the forecast hold?p95 under 500 ms, no saturation above 70%
SpikeJump from baseline to 1.5x forecast in 60 sDoes autoscaling and queueing survive a sudden jump?No 5xx spike, recovery within 2 min
SoakForecast peak for 4 to 6 hoursDo leaks, connection drift or cache growth appear?Flat memory and connection counts

A k6 script for the spike shape, checked against k6 0.50:

JavaScript
import http from 'k6/http';
import { check } from 'k6';

export const options = {
  stages: [
    { duration: '2m', target: 200 },   // baseline
    { duration: '1m', target: 1500 },  // spike to 1.5x forecast
    { duration: '10m', target: 1500 }, // hold
    { duration: '1m', target: 0 },
  ],
  thresholds: {
    http_req_failed: ['rate<0.001'],
    http_req_duration: ['p(95)<500'],
  },
};

export default function () {
  const res = http.get('https://staging.example.com/products/featured');
  check(res, { 'status 200': (r) => r.status === 200 });
}

A worked trace from a spike run might look like this. Figures are illustrative:

TimeVirtual usersrpsp95Error rateBottleneck
0:002002,000180 ms0.0%none
3:001,50019,500420 ms0.05%app CPU 68%
3:101,50020,1001,900 ms2.4%DB connection pool full
5:001,50020,000460 ms0.0%pool raised, CPU 71%

That trace tells you the fix was pool size and queue timeout, not more app instances. Without the test you would have scaled the wrong tier.

Failure modes to watch

Connection pools saturate before CPU does, so watch pool wait time, not just pool size. Autoscaling lags a spike by minutes, so pre scale before the announcement and keep a manual override. Third parties impose their own limits, for example a payment or email provider at a fixed requests per minute cap, so queue or shed non critical work such as recommendations and analytics beacons when the core path is hot. Cache expiry at launch can stampede the database, so warm the hot keys and stagger TTLs before the spike.

In production

Ship with dashboards for rps, p95, error rate and saturation per tier, alerts on pool wait and queue depth, and a pre agreed degradation order: serve cached product data, disable personalisation, then return 429 with Retry-After on the lowest priority endpoints. Compare actual peak against the forecast after the launch and update the model. The next launch then starts from evidence.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-71Tell me about a conflict with a designer over UX using STAR, where auto-saving a shared dashboard view had to work offline, across two editors, and on old mobile builds that cannot send version headers, without losing either person's changes?

The 90-second answer

Design wanted a shared dashboard view to auto-save on every filter change. I agreed with the speed goal and blocked the first version because it used last writer wins. With two editors, an offline laptop, and old mobile builds that cannot send an If-Match header, last writer wins silently discards one person's work. We shipped auto-save with server-side versioning carried in the request body, a three-way merge for disjoint filter fields, and an explicit conflict prompt only when both editors touched the same field. Overwrites fell to near zero in the experiment and the designer got the instant behaviour.

Situation

Our team dashboards were shared. A product manager and an analyst often edited the same view during a weekly review. Design proposed removing Apply and Save. Every change would apply and persist immediately. I had already seen a support ticket where a user lost a curated date range after a refresh, and our view_saved event only fired on explicit save, so we could not count overwrites.

The constraints made a simple fix unsafe. The web client could send If-Match, but mobile builds in the field, roughly 18% of traffic in our data, sent no version at all. Users also edited offline on trains and reconnected minutes later. A header-only check would protect web and leave mobile unprotected.

Task

I owned the client state, the view API contract, and instrumentation. My task was to keep auto-save, protect both editors, and prove with data that we had not traded a visible annoyance for invisible data loss.

Action

First, I moved the version out of the header and into the body, where every client could send it. The server, not the client, decided whether a save was safe.

TypeScript
// TypeScript, React 18 client and Node 20 API
type SaveViewRequest = {
  base_version: number;      // version the editor started from
  filters: Record<string, string>;
  client_op_id: string;      // idempotency key for offline retries
};

The server stored each version and compared three states on save: the base the client started from, the current server version, and the incoming filters. If the fields changed since base were disjoint from the incoming fields, the server merged them and returned the new version. If both sides changed the same field to different values, the server returned 409 with both values and kept the server version unchanged. The client then showed a conflict prompt naming the field, not a generic error.

Yes No No Yes Client sends base_version and filters Server version equals base Save, increment version Changed fields overlap Merge disjoint fields, increment version Return 409 with both values Client prompts editor to pick one

Second, I handled offline retries. The client queued operations with client_op_id and sent them in order on reconnect. The server stored client_op_id to response for 24 hours, so a retry after a timeout replayed the original result instead of creating a second version. A trace from the experiment looked like this:

TimeActorActionResult
10:00Analyst, webLoads view at version 7Edits region
10:01PM, mobile, offlineLoads version 7, edits date_rangeQueues op op_91
10:02AnalystAuto-saves region=EUServer accepts, now version 8
10:05PM reconnectsSends base_version: 7, date_range=Q3, op_91Fields disjoint, server merges, now version 9
10:05PM clientRetries after timeout with same op_91Server replays version 9 response, no version 10

Third, I instrumented before rollout. Assignment and exposure were logged separately. Every save carried base_version, result_version, trigger, and merge_outcome as clean, merged, or conflict. The decision rule, agreed with design before building, was: ship auto-save only if conflict prompts stayed under 1% of saves and merged saves did not raise view abandonment.

Result

Hypothetical figures from that rollout, labelled as such: over three weeks, saves per weekly active user rose 29% against the explicit-save control. Merged saves were 6.4% of saves, conflict prompts were 0.7%, and undo use fell after we added the merge because most apparent conflicts were disjoint edits. Support tickets about lost filters dropped from 11 in the prior month to 2.

The subtle failure mode I still watch is a merge that is technically disjoint but semantically wrong, for example one editor sets region=EU while another sets a date range that only covers US data. The server cannot judge that. We added a preview line in the conflict and merge toast, "Your view now includes EU data for Q3," so the user sees the combined meaning. If conflict prompts had exceeded 1%, my fallback was to keep auto-save for personal views and restore explicit save for shared views, rather than forcing a merge users did not understand.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-72Using STAR, tell me about a missed feature deadline where a 5,000-row grid rerendering on every keystroke forced a choice between fixing rendering and cutting scope. How did you decide?

The 90-second answer

I missed the committed date for a filterable admin grid by six working days. The grid held 5,000 rows in React state and rerendered on every keystroke and every websocket price tick. Input lag hit 240 ms on a mid-range laptop, which made the filter unusable. I had estimated the work as a table plus a search box. I had not priced the render cost. At day 8 I told product the date would slip, showed them a profile trace, and offered two options: ship server-side filtering in the original window with a simpler grid, or slip six days and keep client-side filtering with virtualization. They chose the slip. We shipped on day 21 instead of day 15, and p95 input latency fell to 38 ms.

Situation

I owned the internal operations console. The new page needed to show 5,000 SKUs, filter by text and category, sort by price, and reflect live price changes from a websocket. The deadline was tied to a warehouse migration. My first plan kept all rows in the browser, filtered with Array.filter, and rendered the result directly.

Task

Ship the grid in three weeks with filtering that stayed responsive while typing and while prices updated. The acceptance bar I wrote was a keystroke-to-paint time under 100 ms on our test laptop.

Action

The first build passed on my machine with 800 rows. With the full 5,000 rows it failed. Each keystroke created a new filtered array, React reconciled 5,000 row components, and the websocket tick did the same thing again. Profiling showed 180 ms in render and 60 ms in layout. Memoizing rows helped the websocket case but broke price updates, because the memoized row received the same props object reference when I mutated the row data in place.

I re-estimated at day 8 and put the choice in writing:

OptionDate impactWhat users getMain risk
A. Server-side filtering, simple tableOn timeFilter latency 120 to 300 ms per keystroke, no live tick on filtered-out rowsDebounce and race handling, plus a new endpoint
B. Client-side filtering, virtualized grid+6 daysInstant filtering, live ticks, scroll stays smoothMore code, needs a windowing library and careful state shape

Product picked B because the warehouse team filtered by SKU text constantly and a 300 ms delay on every keystroke would have slowed them more than the slip cost. I cut the column-resize feature and the saved-filter feature to protect the core path. Both were in the original scope and neither blocked the migration.

The fix had three parts. First, I stopped storing the full row objects in component state and kept them in a normalized map keyed by SKU. Second, I virtualized the list so only about 30 rows mounted at a time. Third, I split the urgent input state from the deferred filter state, so typing painted immediately and the expensive filter ran as a transition.

TSX
// Checked against React 18 and TypeScript 5
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);

const visible = useMemo(
  () => filterRows(rowsById, deferredQuery, category),
  [rowsById, deferredQuery, category]
);

Rows received primitive props (sku, priceCents) instead of the whole row object. That made React.memo correct. A price tick updated one entry in the map, and only the mounted row for that SKU rerendered.

Day 8: profile shows 240 ms input lag Present option A vs B with dates Cut column resize and saved filters Normalize rows, virtualize, defer filter Measure keystroke to paint on test laptop

Result

We shipped six days late. After the change, typing a character painted in 38 ms at p95 in our manual trace, and a websocket tick for one SKU rerendered one mounted row instead of 5,000. The warehouse team used the page daily during the migration. Column resize shipped two sprints later, after we confirmed the core filter was stable.

What I changed afterwards: I now profile with production-sized data before I commit to a date for any grid or list. A demo with 800 rows tells you nothing about render cost at 5,000, and the estimate has to include the mechanism, not just the features.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-73Tell me about a bug you shipped to users and what you changed using STAR?

The 90-second answer

I shipped a localized pricing change that displayed the right number in the wrong currency for European users. The API returned amount_cents and currency correctly. The frontend ignored currency and formatted with the browser locale only, so a German user saw €49.00 rendered as $49.00 in the header while checkout charged EUR. I caught it from a guardrail we had added for the rollout, a mismatch alert between price_displayed and checkout_started amounts, rolled the flag back in 12 minutes, fixed the formatter to use the API currency, and added a contract test plus a dashboard panel so the mismatch could not ship silently again.

Situation

We were launching a new pricing page for our SaaS product. The old page hardcoded USD. The new API returned per-user currency from billing, for example { amount_cents: 4900, currency: "EUR" }, and the frontend was supposed to render it with Intl.NumberFormat. In staging I tested with a US account and a German account, and both looked correct because my browser locale matched the account currency in the second test by coincidence. I missed that the code path used locale without currency.

Task

I owned the frontend for the rollout, which was behind a flag at 10% then 50%. My job was to confirm the launch was safe, not just that the page loaded. The guardrails were conversion on the pricing page, checkout completion, and support contacts tagged pricing. I had also instrumented price_displayed with amount_cents, currency, and locale, and checkout_started with the charged amount, specifically so we could compare what users saw with what they paid.

Action

The alert fired 38 minutes after the 50% step. The mismatch rate for EUR sessions went from 0% to 100% of displayed prices, while USD sessions stayed clean. That pattern pointed at formatting, not billing. I checked the trace in the table below, confirmed the API payload was correct, and rolled the flag to 0% for non-USD currencies while keeping USD at 50% so we did not lose the whole experiment.

TimeSignalAction
09:12Flag raised to 50%Watch guardrails for 30 min
09:50price_displayed vs checkout_started mismatch alert, EUR onlyInspect payloads, confirm API correct
10:02Flag set to 0% for non-USDStop new exposures, keep USD cohort
10:40Fix deployed to 1% canaryVerify mismatch rate back to 0%
Next dayContract test and panel addedRe-enable in steps

The bug was this:

TypeScript
// Before: locale decides the symbol, API currency is ignored
const label = new Intl.NumberFormat(locale).format(amountCents / 100);
// de-DE locale with no currency option renders 49,00 with no symbol,
// and the surrounding UI added a hardcoded $ prefix.

The fix made currency explicit and came from the server response, not from guessing locale:

TypeScript
// After: currency is part of the contract
const label = new Intl.NumberFormat(locale, {
  style: "currency",
  currency, // "EUR" from the API, validated against an allowlist
  currencyDisplay: "symbol",
}).format(amountCents / 100);

I also added a test that renders the same payload under en-US, de-DE, and fr-FR locales and asserts the symbol and amount match currency. That test would have failed on the old code for de-DE plus EUR.

Result

About 3,200 EUR sessions saw the wrong symbol during the window. 412 of them started checkout, and the charged amount was correct, so no one was overcharged, but the display error undermined trust and pricing page conversion for that cohort fell 18% relative to USD in the same period. After the fix and staged re-enable, mismatch rate stayed at 0% across 40,000 sessions over two days, and conversion recovered to within 2% of the USD cohort.

Two changes stuck. First, price_displayed now carries a display_currency field, and the alert compares it to the billing currency on every checkout, not just in aggregate. Second, any new money display has to pass the locale-by-currency matrix test in CI. The lesson I took from it: a flag rollback is only fast if the instrumentation tells you which segment is broken. Without the currency field on the display event, I would have been guessing from support tickets for another hour.

Yes No price_displayed event Compare display_currency vs billing currency checkout_started event Mismatch rate > 0.5% for 5 min? Alert owner and suggest flag rollback Continue rollout

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-74Tell me about mentoring a junior engineer on a feature using STAR?

The 90-second answer

I mentored a junior engineer, Priya, through her first end-to-end feature: saved filters for the orders list. She owned the React toolbar, the GET /orders filter parameters, and the analytics events. I owned the checkpoints, not the keyboard.

Situation. Priya had six months of ticket work on small UI changes. This was her first feature with an API change, a flag, and a launch date three weeks out. She could write components, but she had never designed a contract or instrumented an event.

Task. Ship saved filters behind a flag to 10% of workspace admins, with saved_view_created and saved_view_applied events firing correctly, and no regression to the existing filter performance. I told her the definition of done on day one and left the implementation to her.

Action. We paired for 30 minutes each morning and I reviewed every PR the same day. I set three checkpoints. Day 2: API contract agreed before code. Day 5: clickable prototype with fake data. Day 10: instrumented build on staging with real data. At each checkpoint she demoed, I asked what she would check next, and we wrote the next test together. When she proposed storing the whole filter object as a JSON string in the URL, I did not rewrite it. I asked her to write the contract test for a shared link and let the test show the encoding problem.

Result. She shipped on the planned date. Saved views were created by 18% of admins in the first week, and the events matched the server logs within 2%. She presented the launch review herself. Two months later she ran the same checkpoint pattern for an intern.

STAREvidence from the feature
SituationFirst solo feature, 3 week deadline, no prior API or instrumentation experience
TaskShip saved filters to 10% of admins behind a flag, with two named events and no filter regression
ActionDaily 30 minute pairing, 3 checkpoints, contract test written before the endpoint, same day PR reviews
ResultShipped on date, 18% adoption in week one, event counts within 2% of server logs, Priya later mentored an intern
Day 2: contract review Day 5: prototype with fake data Day 10: instrumented staging build Flag at 10% Launch review led by Priya

The contract test was the turning point. Before coaching she would start with the component and ask the backend to fit it. After the checkpoint she wrote this first:

TypeScript
// savedFilters.contract.test.ts
it('round-trips a shared filter link', async () => {
  const url = buildSavedViewUrl({ status: 'open', owner: 'me', sort: '-created_at' });
  const parsed = parseSavedViewUrl(url);
  expect(parsed).toEqual({ status: 'open', owner: 'me', sort: '-created_at' });
});

That test failed on her first attempt because the URL builder dropped the sort field. She found the bug in 20 minutes instead of discovering it in QA. My feedback pattern stayed the same in reviews: name the risk, point to the test or log that would expose it, and ask her to propose the fix. When she was stuck for more than an hour I would type a small example, then hand the keyboard back and ask her to extend it.

Two failure modes I watch for now. Taking over the keyboard feels helpful and removes the learning. Vague comments such as "make this cleaner" leave a junior guessing what to change. I replace both with a specific question and a checkpoint date. If a checkpoint slips, we cut scope at the checkpoint, for example shipping saved filters without sharing links, rather than letting the whole feature drift.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-75How would you design a feature flag service for multiple teams that need independent rollouts, auditability, and fast evaluation without a single point of failure?

The 90-second answer

I would separate the control plane from the evaluation plane. The control plane is an admin API and UI where teams create flags in their own namespace, target them, and ship changes with an audit trail. The evaluation plane is what production code calls, and it must keep working when the control plane is down. That split decides most of the design.

A flag has a stable key, a type (boolean or multivariate), a default variant, and ordered targeting rules. Each rule matches on context attributes such as plan, country, or app version, and returns a variant. A percentage rollout is a rule with a sticky bucket. I hash flagKey + userId (or a device id for anonymous users) and compare the result to the rollout percentage, so a user stays in the same bucket across requests and services. Random assignment per request would make the same user flip variants mid-session and would corrupt experiment analysis.

SDKs in each service poll for flag updates or receive them over a stream, cache the full flag set locally, and evaluate in memory. Evaluation then costs no network call and adds well under a millisecond. If the flag service is unreachable, the SDK serves the last cached value, or the flag default if it has never fetched. For a kill switch I want fail closed to the default, for a checkout experiment I might want fail to the control variant. That choice is per flag, stored in the flag itself, not hardcoded in callers.

Data model and multi-team isolation

Teams get a project or namespace. Flags, environments, and permissions live inside it, so one team cannot read or flip another team's checkout flag. Environments (dev, staging, prod) are separate flag values for the same key, which prevents a staging test from leaking into prod. Every mutation writes an immutable audit record: who changed what, old value, new value, timestamp, and a required reason for prod changes. That is what makes a bad rollout reversible and reviewable.

TypeScript
// Checked against TypeScript 5.x, Node 20
type Variant = string;
type Flag = {
  key: string;
  type: 'boolean' | 'multivariate';
  defaultVariant: Variant;
  rules: Array<{ when: Record<string, string>; variant: Variant }>;
  rollout?: { percentage: number; salt: string }; // 0-100
};

function hashBucket(salt: string, userId: string): number {
  let h = 2166136261;
  for (const ch of salt + ':' + userId) {
    h ^= ch.charCodeAt(0);
    h = Math.imul(h, 16777619);
  }
  return (h >>> 0) % 100;
}

function evaluate(flag: Flag, ctx: Record<string, string>): Variant {
  for (const rule of flag.rules) {
    if (Object.entries(rule.when).every(([k, v]) => ctx[k] === v)) return rule.variant;
  }
  if (flag.rollout) {
    const id = ctx.userId ?? ctx.deviceId;
    if (id && hashBucket(flag.rollout.salt, id) < flag.rollout.percentage) return 'on';
  }
  return flag.defaultVariant;
}

The salt matters. If a team changes the rollout from 10% to 50%, the same salt keeps the original 10% inside the new 50%. Changing the salt rebuckets everyone, which breaks stickiness and invalidates an experiment already running.

Evaluation path

App code calls SDK SDK checks local cache Evaluate rules and rollout in memory Return variant, log exposure if experiment Control plane: admin API Flag store with audit log Poll or stream updates to SDKs
ConcernChoiceWhy
---------
---------
---------
Update deliveryStream with poll fallback, 30 s pollStream gives sub-second kill switch, poll covers dropped connections
CacheFull flag set per environment, in memoryEvaluation stays local, no per-call latency
Stale cache on outageServe last value, then defaultApp keeps running, flag changes pause rather than crash
Exposure loggingLog assignment separately from exposureAssignment without exposure inflates the denominator in analysis
Flag dependenciesAllow prerequisites, reject cycles at write timeA cycle would make evaluation order undefined

Failure modes I would test for

Inconsistent evaluation across services is the common one. The web tier and the API tier each cache flags, and a user gets on in the browser and off on the server for the same request. The fix is shared context (the same user id passed through), the same bucketing function, and a short cache TTL during active rollouts. I would add a debug endpoint that returns the evaluated variant and the rule that matched, so support can answer "why did this user see the new flow" without guessing.

Second, flag sprawl. Teams create a flag per experiment and never delete it. I would set an owner and a review date on every flag, surface flags older than 90 days in the UI, and block new flags in a namespace that has too many stale ones. Cleanup is part of the service, not a quarterly chore.

Third, targeting on sensitive attributes. Rules that match on email or other PII put that data in logs and in the flag store. I would restrict targeting attributes to a declared allowlist, hash identifiers used for bucketing, and keep raw PII out of exposure events.

Finally, a flag service outage during a launch. Because SDKs evaluate locally, the blast radius is stale flags, not a down app. I would rehearse that path by killing the service in staging and confirming checkout still completes with cached values, and I would alert on SDKs that have not fetched an update in more than five minutes.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-76How would you design notifications for an order-shipped feature across in-app, email, and push, and how would you stop duplicate sends when a worker retries?

The 90-second answer

I would not send email or push from the order request. The request writes the order change and a notification row in the same database transaction, then a background worker picks up that row and delivers it. If the request sent directly and the mail provider timed out, the order would be saved but the user would never know, and the client retry could send the message twice.

The notification row is the unit of work. It stores the user, the category, the channel, a status, and a dedup key built from the event and the channel. The worker claims a pending row, checks the user's preferences for that category, renders the message, and calls the channel provider. Only after the provider accepts it does the worker mark the row sent.

SQL
CREATE TABLE notifications (
  id          UUID PRIMARY KEY,
  dedup_key   TEXT NOT NULL UNIQUE, -- order_id:user_id:channel
  user_id     UUID NOT NULL,
  category    TEXT NOT NULL,        -- 'order_shipped'
  channel     TEXT NOT NULL,        -- 'in_app' | 'email' | 'push'
  status      TEXT NOT NULL,        -- 'pending' | 'sent' | 'suppressed' | 'failed'
  payload     JSONB NOT NULL,       -- order id and tracking id, not a copy of the order
  attempts    INT NOT NULL DEFAULT 0,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ON notifications (status, created_at);

Why the dedup key stops duplicates

Suppose the worker sends the email, the provider accepts it, and the worker crashes before it writes sent. The row is still pending, so the worker runs it again. The second attempt uses the same dedup_key. Before calling the provider, the worker checks whether a row with that key is already sent, and if the provider supports an idempotency key it passes the same value. Either check returns the first result instead of sending a second email. Without that key, a retry after a timeout is indistinguishable from a new event.

The same row also handles suppression. If the user turned off email for order updates, the worker marks the row suppressed with a reason instead of deleting it. That gives us a count of how many notifications were intentionally not sent, which we need to tell a preference change apart from a delivery failure in the metrics.

Choosing channels for this event

ChannelStrength for order shippedWeaknessMy use
In-appAlways available, no provider costUser must open the appPrimary record, with a read marker
EmailGood for tracking links and detailBounces, spam filters, slowerSend with tracking link
PushFastest interruptionNeeds a valid device token, easy to annoySend only if a token exists

I would send all three for a shipped order because the user needs to act on it, but I would not send all three for every category. A weekly summary, for example, would be in-app and email only. The category table in the code, not the worker, decides which channels get a row, so adding a category does not mean editing delivery logic.

Failure handling

Retries use backoff, for example after 1 minute, then 5 minutes, then 30 minutes, then mark failed. A push token that the provider reports as invalid gets deleted at once, so we stop wasting attempts on it. An email bounce webhook marks the address as bad. In-app delivery rarely fails because it is just the row, so it acts as the fallback record when email and push both fail.

I would render the message at send time from the order id in the payload, not from fields copied at event time. If the order is cancelled while the notification sits in the queue, the send-time check sees the cancelled status and suppresses the shipped message. That one check prevents the most embarrassing failure here, telling a user a cancelled order is on its way.

What I would watch

Sent rate per channel, suppressed rate by reason, failed rate after retries, and time from order event to sent at p95. If failed rate rises for push only, the token table is stale. If suppressed rate rises after a launch, the event is firing for orders that should not notify, and the fix belongs in the event, not in a higher retry count.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-77How would you design search autocomplete for a large catalog, from indexing and ranking to the API and how you would measure whether it works?

The 90-second answer

I would treat autocomplete as a separate, latency-critical read path, not as the main search endpoint with a smaller limit. The catalog is indexed offline into a prefix structure keyed by normalized tokens, ranked by a blend of popularity, relevance and business signals, and served from a small in-memory or Redis cache in front of the index. The client debounces, cancels in-flight requests, and renders the top 6 to 8 suggestions. Success is measured on search success rate and p95 latency, not on how many keystrokes we save.

Assume a catalog of 2 million products, 3,000 autocomplete requests per minute at peak (50 QPS), and a p95 budget of 80 ms end to end. That budget drives the design. A full-text search over product descriptions will not fit it reliably, so the index stores only what autocomplete needs: product id, display title, brand, category, and a precomputed rank score.

Index and ranking

Offline, I tokenize titles and brand names, lowercase and strip diacritics, and build an inverted index from token prefixes to product ids. For a query like wirele, the lookup is prefix wirele against tokens such as wireless. A trie works for this, but in practice an inverted index with prefix expansion, or a library such as Lucene or Elasticsearch with an edge-ngram field, is easier to operate and to update incrementally.

Ranking happens at index time for the static part and at query time for the small dynamic part. Static score combines click-through rate from historical search logs, purchase rate, and a freshness decay so a discontinued bestseller does not dominate forever. Query-time scoring adds exact prefix match over fuzzy match, brand match over title match, and in-stock filtering. Personalization, such as boosting a category the user has bought from, is a later experiment, not a launch requirement, because it complicates caching per user.

Catalog writes Change stream Tokenizer and normalizer Prefix index builder Rank score precompute Index replicas Autocomplete API Client suggestions

API contract

FieldValue
------
------
------
------
GET /search/autocompleteq, limit=8, locale, optional category
Responsesuggestions: [{id, title, brand, category, type}], query, took_ms
CacheCache-Control: private, max-age=30 on the CDN or edge, plus server-side cache keyed by normalized query
Errors400 for empty or overlong q (over 100 chars), 200 with empty list for no matches

The response carries only display fields. Price and stock are excluded on purpose. They change by the minute, and including them would force cache invalidation on every price tick and invite stale prices in the dropdown. The product page fetches price and stock after selection, which is the same trade-off we make for product cards.

Worked trace for q=wirele:

StepWhat happensTime
NormalizeLowercase, trim, collapse spaces<1 ms
Cache lookupMiss for wirele, hit for wire from previous keystroke2 ms
Index lookupPrefix expansion returns 340 candidate ids12 ms
Rank and filterExact prefix first, in-stock only, top 88 ms
Serialize8 suggestions, about 2 KB JSON3 ms
Total serverp95 targetunder 80 ms

Arithmetic check: at 50 QPS with a 30 second server cache, the cache key space is bounded by distinct prefixes. If 20% of queries are single letters or two letters, those keys are hot and cheap to serve, but they return generic results. I set a minimum query length of 2 characters and cap limit at 8, which keeps the response small and avoids rendering a long list that users do not scan.

Failure modes I would watch

Stale index after a title or stock change. The change stream rebuilds affected prefix entries within a minute, and I would alert on index lag above 5 minutes. A popular prefix such as iphone returning the same 8 items for everyone is handled by the precomputed score, but I would also log zero-result rate by query length. A spike in zero results after a tokenizer change usually means normalization drift between index time and query time, for example diacritics stripped in one place and not the other.

Cache stampede on a trending query. When a product goes viral, thousands of requests for the same prefix arrive together. The server cache uses a short lock or request coalescing so only one request rebuilds the entry while others serve the previous value for up to 30 seconds.

Measurement and experiment

I would log every autocomplete request with the query, the suggestions shown, their positions, latency, and whether a suggestion was clicked, plus the eventual search or purchase in the session. Primary metric: search success rate, defined as a session where an autocomplete click leads to a product view or a submitted search with results. Guardrails: p95 latency, zero-result rate, and downstream conversion so a faster but less relevant ranking does not ship.

For a ranking change, I would run an A/B test with sticky bucketing by user id, 50/50 split, and a precomputed sample size based on baseline success rate. If success rate rises but p95 latency crosses 120 ms, I would not ship, because the dropdown that feels slow gets abandoned even when its results are better.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-78How do stateless services and load balancers let you scale a product API by adding more instances?

The 90-second answer

A stateless service keeps no per-user state in process memory. Session data, carts, drafts and counters live in a shared store such as Postgres or Redis, and each request carries what the instance needs to act, usually an auth token. Any instance can therefore handle any request. A load balancer sits in front of the pool and spreads incoming requests across healthy instances, so capacity grows by adding instances behind it instead of making one instance bigger.

That is the whole mechanism. If an instance dies or a new one joins, the balancer reroutes traffic and nothing about a user's in-flight work is lost, because that work was never stored on the instance.

Client Load balancer Instance A Instance B Instance C Postgres / Redis Health checks

Why statelessness is the precondition

With in-memory sessions, the balancer must send a given user to the same instance every time. That is sticky sessions, and it caps scaling: the pool cannot rebalance load evenly, a deploy that drains one instance logs its users out, and a failed instance takes its sessions with it. Moving state out removes that coupling. The balancer can use a simple round-robin or least-connections policy and treat instances as interchangeable.

For a product API this shows up in concrete places. A checkout service that stores the cart in memory cannot scale past the instance holding the cart. The same service reading the cart from Redis by cart_id can run on 2 instances or 20 with no code change. The same applies to uploaded file metadata, feature flag evaluation results cached per request rather than per user, and rate limit counters kept in Redis rather than in a local map.

What the load balancer actually does

It terminates or forwards connections, runs health checks against each instance, for example GET /healthz every 5 seconds, removes failing instances from the pool, and distributes new requests. It also gives you a single DNS name and port to deploy against, so clients never learn instance addresses.

EventStateless pool, no balancerStateless pool with balancer
Instance B crashes mid-requestClient retry hits a dead addressHealth check fails, B leaves pool, retry lands on A or C
Deploy adds instance DClients must be told about DD passes health checks and starts receiving traffic
Traffic doublesOne instance saturates, p99 climbsAdd instances, balancer spreads the extra load
User logs in on A, next request goes to CWorks, state is in RedisWorks, state is in Redis

Worked capacity example, hypothetical figures

Suppose one instance handles 200 requests per second at a p95 under 300 ms before CPU saturates. At 1,000 requests per second you need at least 5 instances for throughput, and 6 or 7 in practice so one failure or deploy does not push the rest over the knee. The balancer makes that arithmetic usable because load is spread roughly evenly. Without it, a single instance would need to handle all 1,000, and its p95 would blow out long before that point.

Failure modes and limits

Stateless does not mean stateless everywhere. Long-lived WebSocket connections are stateful by nature, so a balancer needs connection draining and clients need to reconnect to another instance, with subscription state rebuilt from the shared store. In-memory caches inside an instance are fine as a performance layer, but they must be disposable, meaning a cold instance returns correct data from the database, just slower. Shared stores become the new bottleneck, so Redis or Postgres connection pools, not instance count, often set the real ceiling. Finally, health checks can lie: an instance can return 200 on /healthz while its database pool is exhausted, so check a dependency or use separate readiness and liveness probes.

When I design a feature endpoint, I check one thing first: can I kill any instance between two requests from the same user and still serve the second correctly? If yes, the balancer can scale the feature. If no, I have hidden state to move out before adding instances helps at all.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-79Your catalog must stay readable in both regions during a partition, checkout must never oversell the last unit, and a cart edited offline in both regions must merge without losing either edit. How do you assign CP or AP per data type and handle the conflicts?

The 90-second answer

I would not pick CP or AP for the catalog. I would split product data by cost of a wrong answer, because the three constraints you named pull in different directions. Catalog reads stay available in both regions during a partition, so they are AP with eventual consistency. Checkout stock is CP with a single primary per SKU, so the minority region must refuse the sale instead of overselling. A cart edited offline in both regions cannot be CP without locking the user out, and cannot be naive AP without losing edits, so it needs AP storage with a merge rule that preserves both sides.

That split is the whole design. One global setting either takes the storefront down during a partition or lets two partitions sell the same last unit.

Why CAP forces the split

CAP applies only during a partition. If the network splits, a CP system rejects writes on the minority side so all nodes agree on one value. An AP system accepts writes on both sides and reconciles after healing, so the same key can hold two values for a while. Outside a partition both can be strongly consistent, which is why PACELC matters in normal operation: synchronous cross-region replication buys agreement and costs latency, roughly 80 to 150 ms added to a write in my last setup, while asynchronous replication returns in about 10 ms and can lose updates if the primary fails before the replica catches up.

For product data I classify before I choose a database.

DataChoicePartition behaviourMerge rule
Title, description, images, search indexAP, eventualBoth regions serve reads, writes accepted locallyImmutable media versions, last writer wins per text field with a server timestamp
Price and stock used at checkoutCP, single primary per SKUMinority region returns 503 for checkout, catalog page still renders with an as-of timeNone, minority writes never commit
Cart, saved views, wishlistAP with per-session read-your-writesBoth regions accept edits offlineVersion vector per cart, union of line items, quantity conflicts surface to the user
Experiment assignmentCP write once, then AP readsUser keeps the assigned variant in either regionAssignment stored before exposure is logged, never recomputed
Analytics eventsAP, append onlyEvents buffer and flush after healingDedupe on event ID, late events backfilled by event time
No Yes Stock, price, assignment Catalog copy, cart, events Write Partition? Replicate, sync only where latency budget allows Data type CP: primary commits, minority rejects AP: accept locally, merge on heal

Checkout: never oversell the last unit

Stock needs a primary per SKU, not per region. The primary region owns decrement, the other region forwards the request or fails fast. The frontend must not treat a cached product page as proof of stock. It renders stock_as_of for display, then checkout revalidates against the primary with a version check.

TypeScript
// TypeScript, Node 20 fetch
async function checkout(sku: string, qty: number, etag: string) {
  const res = await fetch(`https://api.example.com/inventory/${sku}/decrement`, {
    method: 'POST',
    headers: { 'If-Match': etag, 'Idempotency-Key': crypto.randomUUID() },
    body: JSON.stringify({ qty }),
  });
  if (res.status === 412) return { ok: false, reason: 'stock_changed' };
  if (res.status === 503) return { ok: false, reason: 'primary_unavailable' };
  return { ok: true, order: await res.json() };
}

The 503 branch is the subtle failure mode. If checkout falls back to a stale replica to stay available, CP quietly becomes AP for the one field where that choice creates a refund. I would rather show "we could not confirm stock" than confirm an order I cannot fulfil.

Worked trace, one unit left, partition between region A (primary for that SKU) and region B:

TimeRegion A shopperRegion B shopperOutcome
t+0 msDecrement with If-Match: v41 reaches primaryDecrement forwarded, primary unreachableA commits, stock becomes 0
t+40 msOrder confirmed503, no local decrementB cart keeps the item, marked unconfirmed
t+5 sReplication resumesB syncs stock 0, cart shows out of stockOne sale, no oversell, no merge

Cart: merge without losing either edit

A cart cannot use last writer wins on the whole cart. If a user adds shoes offline in B and changes quantity in A, whole-cart LWW discards one edit. I store line items keyed by SKU with a version vector per cart, and merge by union. Quantity for the same SKU edited in both places is the one case I do not auto-merge, because adding 1 and setting to 2 are different intents. The UI shows both values and asks, which is cheaper than silently picking one and charging for the wrong quantity.

Clock based LWW also fails here. Device clocks skew by minutes, so a later edit can carry an earlier timestamp and lose. A server assigned sequence per cart, plus the version vector, avoids that. Read-your-writes is handled at the session layer: the client keeps its own pending operations and applies them over the last server snapshot until the server acknowledges them.

Failure modes I would name unprompted

First, eventual consistency on experiment assignment flips users between variants mid-session and corrupts the metric, so assignment is a CP write before the exposure event. Second, a single CP setting for the whole catalog turns a regional partition into a storefront outage for descriptions that could have stayed readable. Third, showing a live stock count on the product page without an as-of timestamp trains users to trust a number checkout will contradict, so the page either shows the timestamp or drops the count in favour of "in stock" from the last sync.

My rule in the room: money and promises go CP, copy and personalization go AP, carts go AP with an explicit merge, and every surface that renders replicated data shows how old it is.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-80When would you use a message queue for async work like sending email instead of doing it inline in the request?

The 90-second answer

Use a queue when the work is slow, can fail independently of the request, and the user does not need its result to see a correct response. Sending email fits all three. The API writes the user, enqueues a job, and returns. A separate worker sends the email, retries on provider errors, and scales without adding web servers.

Inline sending couples two failure domains. If the mail provider takes 600 ms, every signup pays that cost. If the provider is down, signups fail even though account creation would have succeeded. A queue turns that into a delayed email and a visible backlog you can alert on.

TypeScript
// POST /signup, checked against Node 20 and Postgres 15
app.post('/signup', async (req, res) => {
  const user = await db.users.create({ email: req.body.email });
  // Same transaction as the user row. No email is sent here.
  await db.outbox.create({
    type: 'email.send',
    payload: { userId: user.id, template: 'welcome' },
    idempotencyKey: `welcome:${user.id}`,
  });
  res.status(202).json({ userId: user.id, emailStatus: 'queued' });
});

// Worker, run as its own deployment
async function handle(job) {
  await mailer.sendTemplate(job.payload.template, job.payload.userId);
  await db.outbox.markSent(job.id);
}

The outbox matters. If you insert the user, commit, then publish to the queue, a crash between the two loses the email. If you publish first, a crash can send mail for a user who was never saved. Writing the job row in the same transaction as the user, then having a relay publish it, closes that gap. The relay can publish twice, so the worker still needs idempotency.

ApproachRequest latencyProvider outageRetryScaling
Inline in requestAdds provider latency, often 200 to 800 ms for SMTP or an API callSignup fails or times outClient retries the whole signupWeb tier scales to cover mail latency
Queue plus workerReturns in normal API time, say 60 to 120 ms in a worked exampleBacklog grows, signups still succeedWorker retries with backoffAdd workers, web tier unchanged
Cron batch every 10 minSame as queue for the requestEmails delayed up to 10 minNext cron run retriesSimple, but latency is fixed and failures are harder to trace per job
POST /signup Write user + outbox row Return 202 Relay publishes job Worker sends via provider Mark sent Retry with backoff Dead letter queue after 5 attempts

What the queue buys you, concretely

Decoupling, retries, and independent scaling. Suppose a launch sends 20,000 welcome emails in an hour. Inline, you need enough web capacity to absorb provider latency for all of them. With workers, you run 10 workers at 2 emails per second each and drain the queue in about 17 minutes, while the web tier stays sized for signups. If the provider returns 429 or 503, the worker backs off, for example 30 seconds, 2 minutes, 10 minutes, and the user never sees an error. You also get an observable number: queue depth and oldest job age. Alert when the oldest job passes 5 minutes for welcome mail, because that is a user-facing delay even though the API looks healthy.

Failure modes to name before the interviewer asks

Delivery is at least once in most systems, including SQS and RabbitMQ with acknowledgements. The worker can send the email, then crash before marking the job done, and the job is redelivered. Guard with an idempotency key per job, stored before sending, and check it on redelivery. A poison message, such as a template that always throws on a malformed address, will loop forever without a cap. Send it to a dead letter queue after a fixed number of attempts, keep the payload and error, and page on dead letter growth. Ordering is not guaranteed across workers. That is fine for independent welcome emails. It is not fine if you must send a password reset before a verification email and the second must not arrive first. Use one worker for that stream, a single partition key, or put both in one job.

When I would not use a queue

If the caller needs the result in the response, such as checking an email address before telling the user it is valid, do the check inline or return a pending state explicitly. If volume is a few dozen a day and the provider is reliable, a queue adds a broker, a worker deployment, and a dead letter process to operate for little gain. A background thread in the same process is not a middle ground I trust in production, because a deploy or crash kills in-flight jobs and you get no durable retry. If you need strict ordering and exactly once delivery across services, a queue alone does not give you that. You need idempotent consumers and often a transactional outbox, as above.

For a product engineer, I would also instrument the outcome, not just the enqueue. Log email_queued, email_sent, and email_failed with template and provider message ID, so you can measure delivery rate per signup cohort and spot a template that fails for one locale while the queue looks fine.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-81You have a vendor's OpenAPI spec for a shipping rates API and need it in our React app next week. How would you decide between generating a client from the spec and writing calls by hand, and where would you put the vendor-specific code?

The 90-second answer

I would generate the client from the spec for the request and response types, and hand-write a small adapter around it for auth, errors, and timeouts. Generation keeps us in sync when the vendor renames a field. The adapter keeps vendor shapes out of the React components, so a spec change touches one file instead of every screen that shows a rate.

The choice comes down to who owns drift. With hand-written calls I own every field name, and a vendor change breaks us silently at runtime. With a generated client the compiler breaks us at build time when I regenerate, which is easier to find and fix. The cost of generation is that generated code can be verbose and awkward to call, so I do not let components call it directly.

ApproachStrengthCostWhen I pick it
Hand-written fetch callsSmall, readable, easy to customiseI must track every spec change by handA tiny API with two endpoints and no published spec
Generated client from OpenAPITypes match the spec, regeneration surfaces breaking changesGenerated surface is larger than I needA published OpenAPI 3.x spec with more than a handful of endpoints
Generated client plus adapterTypes plus a stable internal modelOne extra layer to maintainThis case, where the UI needs rates for the next year

I pin the spec file in the repo and regenerate in CI to check for drift. If the vendor publishes a new version, I diff it first and update the adapter in the same pull request.

TypeScript
// Checked against TypeScript 5.4 and Node 20
// vendor/ratesAdapter.ts: the only file that imports the generated client
import { createClient, ApiError } from './generated/shippingClient';

const client = createClient({
  baseUrl: process.env.SHIPPING_BASE_URL,
  apiKey: process.env.SHIPPING_API_KEY, // server only, never bundled for the browser
});

export type Rate = { carrier: string; priceCents: number; etaDays: number };

export async function getRates(weightKg: number, signal: AbortSignal): Promise<Rate[]> {
  try {
    const res = await client.rates.list(
      { weight_kg: weightKg },
      { signal, timeoutMs: 2500 },
    );
    return res.data.map((r) => ({
      carrier: r.carrier_code,
      priceCents: r.price_cents,
      etaDays: r.eta_days,
    }));
  } catch (e) {
    if (e instanceof ApiError && e.status === 429) {
      throw new Error('rates_unavailable');
    }
    if (e instanceof ApiError && e.status >= 500) {
      throw new Error('rates_unavailable');
    }
    throw e;
  }
}

The React side then depends only on Rate. It never sees carrier_code, vendor error bodies, or the API key. I call the adapter from a server route or server component, because the key is a secret and the browser should not hold it. The component receives plain rates and renders loading, empty, and error states from that shape.

A worked trace for the error path shows why the mapping matters:

Vendor responseAdapter resultUI state
200 with 3 ratesRate[] with 3 itemsList of carriers
200 with 0 rates[]Empty state: no carrier serves this weight
429 with Retry-After: 2throws rates_unavailableError state with retry after 2 seconds
503 timeout after 2,500 msthrows rates_unavailableError state, checkout can continue without rates

I test the adapter against recorded sandbox responses for those four cases. If the sandbox starts returning a field the spec does not describe, the recorded test fails and I update the pinned spec or the mapping before users see a broken price. That is the main failure mode generation alone does not fix: the spec and the live API can disagree, so the fixture test is the check that catches it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-82Why is cursor pagination preferred over offset pagination for a feed that gains new items while you scroll?

The 90-second answer

Cursor pagination is preferred for a feed that gains new items while you scroll because offset pagination counts rows from the start, so inserts before the current position shift everything after it. Cursor pagination remembers the last row you saw and asks for rows after that row, so new items at the top do not move the rows you have not seen yet.

Offset asks for a position. Cursor asks for a continuation. That is the whole rule.

The shift, in one trace

Page size is 3, newest first. The feed starts as 10, 9, 8, 7, 6, 5. You load page 1 and see 10, 9, 8. Then row 11 is inserted at the top.

RequestOffset queryWhat you getCursor queryWhat you get
Page 1LIMIT 3 OFFSET 010, 9, 8First 3 rows, cursor set to 810, 9, 8
Page 2 after insert of 11LIMIT 3 OFFSET 38, 7, 6Rows after 87, 6, 5

Offset repeats 8 because 11 pushed every older row one place down. The client renders 8 twice. If a row is deleted instead, offset skips a row in the same way. Cursor does not count places. It resumes after the last id it returned, so the insert behind it has no effect on the next page.

What the cursor stores

The cursor is the sort key of the last row on the page. For a feed sorted by creation time, that is usually the timestamp plus the row id, since two rows can share a timestamp.

SQL
-- Next page after the row with created_at = '2026-05-01T10:00:00Z' and id = 918273
SELECT id, created_at, title
FROM activity
WHERE (created_at, id) < ('2026-05-01T10:00:00Z', 918273)
ORDER BY created_at DESC, id DESC
LIMIT 50;

The server encodes that pair as an opaque string, for example base64 of JSON, and returns it as next_cursor. The client sends it back unchanged on the next request. It never builds one itself.

JSON
{
  "items": [{"id": 918273, "title": "Order shipped"}],
  "next_cursor": "eyJjcmVhdGVkX2F0IjoiMjAyNi0wNS0wMVQxMDowMDowMFoiLCJpZCI6OTE4MjczfQ"
}

With an index on (created_at DESC, id DESC) the database seeks to that row and reads the next 50. Offset, by contrast, has to count and discard every row before the offset on each request, so deep pages get slower as the list grows. For a scrolling feed that cost and the duplicate or skipped rows are both reasons to pick cursor.

Offset still has a place. If the interface shows page numbers and a user must jump to page 12, offset maps directly to that control and cursor does not. For a feed, a search result list, or any infinite scroll list that changes while it is open, the one step test is: does the list change under the user? If yes, use cursor.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-83Two users edit the same product record at once and your API uses a version field. How do you detect the conflict, stop a silent overwrite, and decide what the client should do next?

The 90-second answer

I put an integer version on the row, return it with the resource, and require the client to send it back on every write. The write only succeeds if the version still matches. If it does not, I return the current resource and version and let the client decide whether to reload, merge, or reapply its change. I never retry blindly on the server, because a retry that succeeds can still overwrite the other person's intent.

SQL
-- PostgreSQL, checked against 15
UPDATE products
SET title = $1, price_cents = $2, version = version + 1
WHERE id = $3 AND version = $4
RETURNING version;

Zero rows returned means either the row is gone or the version moved. I fetch the row to tell those apart, then return 409 with code: version_conflict and the current version and fields. updated_at alone does not do this job. Two writes in the same timestamp tick, clock skew across app servers, and a backfill that touches updated_at all break it. A monotonic integer incremented inside the same UPDATE does not.

Worked trace

TimeUser AUser BRow
t0GET returns version: 7GET returns version: 7v7
t1PATCH with If-Match: 7 succeedsv8, B's title
t2PATCH with If-Match: 7rejected, 409
t3Client reloads v8, shows B's title next to its own price editv8
t4Client reapplies price edit with If-Match: 8v9, both edits kept

The HTTP form is the same idea. GET /products/{id} returns ETag: "7". The client sends If-Match: "7" on PATCH. A strong ETag derived from the version is fine here. A weak ETag or a hash of the body is not, because I need to compare the version I read, not guess whether two representations are equivalent.

What the client does next depends on the edit

yes no no yes Client sends write with base version Version matches? Commit and return new version Return 409 with current resource Fields overlap? Reapply onto new version Show diff and ask user

If A changed the price and B changed the title, the fields do not overlap. The client can reapply the price change on top of v8 without asking anyone. If both changed the price, reapplying silently picks a winner. That needs a diff view, or a deliberate rule such as last writer wins for a low stakes field, stated in the product spec rather than invented in the retry loop.

Field level merging only works if the API supports partial updates and the version check covers the whole row. A PATCH that touches one field still increments the version, so a concurrent edit to another field still conflicts at the row level and then merges cleanly in the client. That is cheaper than locking the row during editing, which would block the second user for as long as the first keeps the form open.

Failure modes I watch for

Read-modify-write in application code. Fetching the row, changing it in memory, then saving without the WHERE version = ? clause loses the check entirely. The check has to live in the same statement as the write.

Silent retry on 409. A mobile client that retries three times with the same stale version will fail three times. A client that refetches and reapplies without showing the other change will succeed and hide it. I log conflicts with the resource id, base version, and current version, and alert if the conflict rate jumps, since that usually means a client started sending a stale version after a deploy.

Version increments on no-op writes. An autosave that fires every 30 seconds and bumps the version even when nothing changed creates conflicts for real edits. I skip the write when the submitted fields equal the current values.

For state transitions, such as moving an order from pending to shipped, version alone is not enough. I check the allowed transition in the same update, so a stale client cannot ship an order that was already cancelled. The version stops the lost update. The state check stops the invalid one.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-84How do you validate data quality in an analytics pipeline before a dashboard or experiment decision depends on it?

The 90-second answer

I validate at three points, because a check that only runs in the dashboard finds the problem after someone has already acted on it. At ingestion I check the raw event is well formed. In staging I check it is complete, unique and internally consistent. Before a mart or KPI table is published I check it reconciles to its source and is fresh enough to use.

For a product engineer the checks that matter most are the ones tied to a decision. If an experiment or a launch review reads checkout_completed, I need to know that events are not being dropped, duplicated or double counted by a backfill. A dashboard that looks plausible is not evidence.

What I check, and what happens on failure

CheckExample rule for an events tableFailure action
CompletenessRow count within 20% of the 7 day median for the same hour, and no missing partitionBlock publish, alert owner
FreshnessLatest event_time is within 15 minutes of pipeline run timeBlock publish, page on call if it repeats
UniquenessDuplicate event_id rate below 0.1%Quarantine duplicates, do not aggregate
Validityuser_id not null, event_time not in the future, amount_cents >= 0Route rows to a quarantine table with the reason
ConsistencySum of checkout_completed in the mart matches the raw count after dedupe, within 0.5%Block publish, investigate the transform
Referential integrityEvery order_id in events exists in orders, or is flagged as late arrivingFlag, do not silently drop

Thresholds like these are starting points for a typical daily product pipeline, not universal constants. I tune them from the observed variance of the table so a normal Monday spike does not page anyone.

SQL
-- Staging check for an events table, run before the mart is built
-- Postgres / DuckDB syntax, checked against a deduped staging table
WITH deduped AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY ingested_at) AS rn
  FROM staging.events
  WHERE event_date = CURRENT_DATE
)
SELECT
  COUNT(*) AS rows_in,
  COUNT(*) FILTER (WHERE rn = 1) AS rows_deduped,
  COUNT(*) FILTER (WHERE user_id IS NULL) AS null_user,
  COUNT(*) FILTER (WHERE event_time > NOW() + INTERVAL '5 minutes') AS future_events,
  COUNT(*) FILTER (WHERE amount_cents < 0) AS negative_amounts
FROM deduped;

A run that returns null_user > 0 or future_events > 0 fails the build. The rows go to quarantine.events with a reason column, so I can count them and fix the producer instead of guessing how many were lost.

pass fail pass fail pass fail Raw events land Schema and validity checks Dedupe and staging checks Quarantine with reason Reconcile to source Publish mart and KPI tables Dashboard and experiment reads

Trade-offs and failure modes I watch for

Strict checks at ingestion catch a broken producer early, but they can block the whole pipeline for a small bad batch. That is why I quarantine rows instead of failing the partition, and only block publish when a check affects the KPI being read. A 0.2% duplicate rate in a clickstream is noise. The same rate in payment_succeeded changes revenue.

The failures that reach dashboards are usually quiet. A producer renames a field and the transform writes nulls, which pass a row count check but break the funnel. A backfill replays three days of events and inflates a cohort unless dedupe on event_id runs before aggregation. Late arriving mobile events make yesterday look complete at 09:00 and then change by 5% at noon, which invalidates an experiment read taken too early. Timezone handling does the same thing in miniature when one client sends UTC and another sends local time.

I detect those by reconciling at two levels. Row counts catch drops. Aggregate reconciliation catches double counting, for example SUM(amount_cents) in the mart against the deduped raw total. For experiments I also check that assignment and exposure counts move together. If exposures rise 30% while assignments are flat, the logging changed, not user behaviour.

When a check fails I want three things in the alert: the table, the check name and the observed value against the threshold. "Pipeline failed" sends an engineer to read logs. "staging.events: duplicate event_id rate 4.1%, threshold 0.1%, 18,204 rows quarantined" sends them straight to the producer.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-85How would you design a product metrics dashboard that people actually use, from the metrics and API behind it to the layout on screen?

The 90-second answer

I start with the decision the dashboard has to support, not the charts. For a product team that is usually: is the feature working, where is it leaking, and what do we do next. Every card must answer one of those in under ten seconds, or it does not ship.

I would put one north star and two or three input metrics at the top, each with a definition, a target, and a freshness timestamp. Below that, one funnel for the flow being watched. Everything else is drill-down. A dashboard with 18 equal cards gets opened once and then ignored, because nobody knows which number matters when they disagree.

Behind it, I need the metric definition to live in one place. If the frontend computes conversion one way and the SQL in the warehouse computes it another, the team argues about the dashboard instead of the product.

SQL
-- metric: checkout_conversion, version 3, checked against Postgres 15
-- denominator: distinct visitors who reached checkout_started in the window
-- numerator: distinct visitors with a paid order within 24h of that start
SELECT
  date_trunc('day', started_at) AS day,
  COUNT(DISTINCT visitor_id) FILTER (WHERE paid_at IS NOT NULL) * 1.0
    / NULLIF(COUNT(DISTINCT visitor_id), 0) AS conversion
FROM checkout_events
WHERE started_at >= now() - interval '28 days'
GROUP BY 1;

The API serves that definition, not raw events. GET /metrics/checkout_conversion?from=...&to=...&segment=... returns the value, the prior period, the sample size, the definition version, and computed_at. The frontend never re-derives it from event rows.

LayerChoiceWhy it holds up
---------
---------
---------
---------
Metric storePre-aggregated table, refreshed every 5 minA 28-day scan over 50M event rows takes 8-20 s in our warehouse. The aggregate answers in 40 ms.
APIOne endpoint per metric, cached at the edge for 60 s30 viewers opening the page at 9 am would otherwise fire 30 identical heavy queries.
FrontendServer-rendered first paint, charts lazy-loadedThe headline number is readable before the chart library finishes downloading.
Freshnesscomputed_at shown on every cardA stale number labelled as live destroys trust faster than a missing chart.

Layout and interaction

Is it working? Where is it leaking? What changed? Open dashboard What decision? North star vs target Funnel step with largest drop Segment and cohort split Drill to segment Link to experiment or issue

Each card follows the same contract: title in plain language, current value, change against the previous comparable period, sparkline for trend, and a link that filters the underlying data. No card shows a percentage without its denominator. "Conversion up 12%" on 40 visitors is noise. "Conversion 31.2% (312 of 1,000), up from 28.1%" is a claim someone can check.

I would also separate the dashboard for the team that acts on it from the one shown to leadership. The working view gets segments, experiment overlays, and raw counts. The leadership view gets three numbers and a sentence of interpretation. Mixing both audiences into one page is how you end up with a page nobody uses.

Failure modes I design for

First, vanity metrics. Page views and total signups rise with marketing spend even when the product gets worse. I pair every volume metric with a rate or a retention metric, and I drop any metric nobody has acted on in four weeks. Usage data tells me which cards get opened. In one dashboard I worked on, 14 of 19 cards had under 5% of the opens of the top card. We deleted them and the remaining page got used daily.

Second, silent staleness. The aggregation job fails at 2 am and the dashboard keeps showing yesterday's numbers with no warning. I add a freshness check in the API: if computed_at is older than twice the refresh interval, the response carries stale: true and the UI banners it. That turns a quiet data outage into a visible one.

Third, definition drift after a rename or an experiment. When an event name changes, old and new events get mapped in the ingestion layer, not in each chart query, and the metric version bumps. An A/B test overlay reads assignment and exposure from the experiment service, so a dashboard spike during a test is read against the variant, not mistaken for organic growth.

I would measure whether the dashboard works the same way I measure the feature: weekly active viewers from the team, cards clicked through to a drill-down, and whether a decision was recorded in the experiment or roadmap doc that references it. A dashboard nobody opens after week two is a failed feature, however accurate its numbers are.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-86When stakeholders disagree on a feature plan, who gets the final say on scope, and how do you record the decision so it sticks?

The 90-second answer

One named owner gets the final say per decision, and the decision goes in a written log in the plan. For scope and priority, that owner is product, because product owns the metric the feature is meant to move. For the technical contract, it is the engineering owner. For interaction and copy, it is design. Nobody gets a veto over another owner's call, and a decision only reopens when new evidence arrives, such as a failed prototype test or a guardrail metric breaching its threshold.

Without that rule, alignment means everyone agrees in the meeting and then relitigates in Slack. With it, disagreement has a place to end. The log makes the end visible to people who were not in the room.

MARKDOWN
## Decision log
| Date | Decision | Owner | Evidence | Reopen if |
| --- | --- | --- | --- | --- |
| 12 May | Cut scheduled email of saved views | @pm | 20 eng-days available, plan needs 28 | Reuse target missed after launch |
| 12 May | Share by link only, no permissions UI | @design | 3 of 18 reps asked for permissions | Support tickets cite wrong sharing |
| 13 May | Store filter state server side | @eng | List p95 is 900 ms, client state would resend it | p95 stays above 400 ms at 5% rollout |

I set the owners before the review, not during it. The plan names them at the top, next to the metric. If a stakeholder wants a different owner, we change the name in the doc before we debate the content. That one move stops the common pattern where the loudest voice in the room becomes the de facto owner.

Decision areaFinal sayThey can be overruled by
---------
Problem, scope, ship or cutProduct ownerNew user or metric evidence
Flow, layout, copy, empty and error statesDesign ownerUsability test result
API contract, data model, migration, rollout mechanicsEngineering ownerLoad test or incident data
Launch date and commsProduct owner, with support inputSupport readiness check

The log entry needs four fields. What was decided, who decided it, what evidence it rested on, and what would reopen it. "We decided to cut email" is not enough. "@pm cut scheduled email on 12 May because the plan needed 28 engineer-days against 20 available, reopen if weekly reuse misses the +15% target" is enough. Anyone reading it later can see whether the reopen condition has happened.

No Yes Disagreement raised Identify decision area Named owner decides Write entry in decision log Plan freezes at v1 New evidence? Decision stands Owner revisits and updates log

In the review I run the rule out loud. When two people push opposite scopes, I ask which metric each scope moves and by how much, then the product owner picks. When engineering and design clash on where state lives, I ask for the latency or correctness figure behind each option, then the engineering owner picks the contract and design picks how it renders. The figures matter because they turn a preference into evidence the log can cite.

A worked trace from a recent plan: design wanted a permissions picker on shared views, product wanted the date held, engineering estimated the picker at 6 engineer-days including audit logging. The owner for scope was product, so the picker was cut and link sharing shipped. The log recorded the reopen condition as support tickets about wrong sharing. Two weeks after launch, support logged zero such tickets, so the decision stood and the picker went into the next quarter's backlog with its estimate attached. Nobody reopened it in standup, because the condition for reopening had not occurred.

That is the whole mechanism. Name the owner, let them decide, write down the evidence and the reopen condition, and freeze the plan. Alignment is not consensus. It is a shared record of who decided what, and why.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-87Walk me through how you would turn a vague request for real-time collaborative saved views, offline on old mobile builds, into concrete architecture decisions you can defend in review?

The 90-second answer

I rewrite each requirement as a constraint I can test, then let the constraint pick the architecture. A requirement like "collaborative saved views, real time, works offline" contains four separate decisions: who can write, what happens when two people write at once, what the client does with no network, and what the server does when it cannot tell which write came first. I write those down before I draw a box, and every box in the diagram has to trace back to one of them.

Take a concrete case I have shipped: saved dashboard views, two editors, offline edits on mobile builds that cannot send version headers, and no silent overwrite. The constraints force a server-authoritative model with explicit conflict handling, not a peer-to-peer merge and not last-write-wins.

Requirement as statedConstraint I extractDecisionCost I accept
Two editors see changes livePresence and edits must arrive in one order per viewOne WebSocket channel per view, server assigns a monotonic seq per viewServer holds connection state; a reconnect replays from last seq
Edit offline, sync laterClient cannot invent ordering the server will trustClient queues ops with a client-generated op_id; server orders them on arrivalOffline edits may land after a newer online edit, so the user sees a conflict
Old mobile builds, no version headerOptimistic concurrency via If-Match is unavailable on that pathServer rejects a stale base with 409 and returns the current view plus the conflicting opClient must implement a merge UI instead of a blind retry
Never lose either person's changesA write must not overwrite a field the writer never sawField-level ops (set_filter, rename) instead of whole-view replacementMore op types to validate, and a field the user did not touch stays untouched

That last row is the decision most teams miss. If the client sends the whole view JSON, an offline edit based on yesterday's filters will erase a colleague's rename made this morning. Field-level ops make the conflict visible and small.

no yes Editor A, online API: apply op Editor B, offline queue API: apply op on reconnect View store: seq per view Broadcast op + seq to view subscribers Base seq matches? 409 + current view + conflicting op

The server is the only sequencer. Client timestamps never order ops, because two phones can disagree by minutes and a laptop clock can be set wrong. seq is per view, not global, so a busy view does not block an unrelated one. Arithmetic I check in review: at 2,000 concurrent editors sending 1 op per 5 seconds, that is 400 ops per second to sequence and broadcast. Each broadcast to a view with 3 subscribers is 1,200 messages per second, which a single Node or Go process handles, but the reconnect replay has to be capped. I cap replay at the last 200 ops and send a snapshot beyond that, or a client returning after a week would download a week of history.

I record the decision where the next engineer will find it, in the repo, not in a slide:

YAML
# docs/adr/014-saved-views-collaboration.md
status: accepted
decision: Server assigns per-view seq; clients send field-level ops with op_id
rejected: Last-write-wins on whole-view JSON
  reason: Offline whole-view writes erase unseen fields
rejected: Client timestamp ordering
  reason: Clock skew across devices makes order unrecoverable
consequence: Every client needs a conflict UI for 409 responses

Failure modes I name in the same review: a client that retries an op after a timeout must reuse the same op_id, or the server will apply it twice, so the store keeps op_id per view for 7 days and returns the original seq. A client that queues ops for a view it no longer has access to gets 403 on reconnect and must drop the queue, not keep retrying. And if the WebSocket tier drops, clients fall back to polling every 15 seconds for seq greater than their last seen value, which keeps the feature usable at the cost of up to 15 seconds of staleness. If I cannot state the cost in that form, the requirement is still vague and I go back to product with the specific choice, not a diagram.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-88How do you use a proof of concept to validate technical risk before committing to a full build?

The 90-second answer

I start by writing the risk as a falsifiable sentence, not a topic. "Can the vendor shipping API return rates in under 300 ms at p95 for 50 requests per second, using the auth model we actually have?" That sentence decides what the proof of concept must touch. If the POC does not exercise the riskiest path, it proves nothing.

Then I agree the pass or fail threshold before writing code, timebox the work to days rather than weeks, and build the thinnest slice that hits that path with realistic data and load. The POC is throwaway code. Its job is a decision: build, buy, redesign, or drop the feature. I write that decision down with the numbers that forced it.

How I run it

  1. Name the risk and the cost of being wrong. A slow third party API, a rendering approach that drops frames at 5,000 rows, a sync model that loses edits offline. Each has a different test.
  2. Set the threshold from the product constraint. If checkout has a 500 ms budget and the new call sits on the critical path, the POC threshold might be p95 under 250 ms at peak traffic, leaving room for the rest of the request. A threshold invented after seeing results is not a threshold.
  3. Build only the risky seam. For an API risk, that is one endpoint, real credentials, real payload sizes, no UI polish. For a rendering risk, that is the list component fed with production-shaped data, no backend.
  4. Measure under conditions close to production. Synthetic tiny data hides the failure. I use a production data sample, the same payload shape, and a load profile based on expected peak, not average traffic.
  5. Record the result and stop. If it passes, the POC code is deleted and the real implementation starts clean. If it fails, I check whether a different approach clears the same threshold before abandoning the feature.
Yes No Risk stated as a measurable claim Pass threshold agreed Thinnest slice on the risky path Measure with realistic data and load Threshold met? Build for real, delete POC Try one alternative or drop feature

Worked example: vendor rates API

Hypothesis: the vendor can serve our checkout at peak. Peak is 200 requests per second for 10 minutes during a promotion, and our budget for this call is p95 under 250 ms with an error rate under 0.5%.

CheckPOC setupPass thresholdIf it fails
Latency200 rps for 10 min, real payloads, 50th to 99th percentile recordedp95 under 250 msCache rates, move off critical path, or pick another vendor
Rate limitSustained load plus a burst of 3x for 60 secondsNo 429s at peak, burst handled or queuedNegotiate a higher tier or add a queue with a timeout
Auth and failure modeExpired token, vendor timeout, malformed responseClient fails closed with a clear error, no retry stormAdd circuit breaker and a fallback rate table

A small load script is enough to collect the evidence. This Node script, checked against Node 20, fires concurrent requests and reports percentiles:

TypeScript
// poc-rates.ts — run with: npx tsx poc-rates.ts
const URL = process.env.VENDOR_URL!;
const CONCURRENCY = 50;
const DURATION_MS = 60_000;
const latencies: number[] = [];
let errors = 0;
let done = false;

async function worker() {
  while (!done) {
    const start = performance.now();
    try {
      const res = await fetch(URL, { method: "POST", body: JSON.stringify({ weightKg: 2, to: "DE" }) });
      if (!res.ok) errors++;
      latencies.push(performance.now() - start);
    } catch { errors++; }
  }
}

setTimeout(() => { done = true; }, DURATION_MS);
await Promise.all(Array.from({ length: CONCURRENCY }, worker));
latencies.sort((a, b) => a - b);
const p = (q: number) => latencies[Math.floor(q * latencies.length)];
console.log({ count: latencies.length, errors, p50: p(0.5)?.toFixed(0), p95: p(0.95)?.toFixed(0), p99: p(0.99)?.toFixed(0) });

Suppose the run returns p95 of 410 ms and 2% errors at 200 rps. That fails the threshold I set, so the decision is not "ship and hope." Options become concrete: cache the 20 most common routes, which in our traffic cover about 80% of calls, and call the vendor only on a cache miss off the critical path, or evaluate the second vendor against the same script. The arithmetic matters here. If 80% of calls hit cache at 5 ms and 20% take 410 ms, the blended p95 lands near the cache miss path, so I would need the miss rate and the miss latency separately before claiming the budget is met.

Failure modes I watch for

A POC that uses a sandbox with faster responses, a mocked dependency, or 10 rows of test data passes for the wrong reason. A POC that grows into the real feature burns the time it was meant to save and creates pressure to ship untested code. A POC with no agreed threshold ends with a debate about whether the numbers are "good enough." I guard against all three by fixing the threshold in writing, using production-shaped data, and putting a hard stop on the calendar. The output is a short note: the claim, the measured numbers, and the decision. That note is what product and engineering can act on.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-89You need in-app announcements and onboarding checklists in eight weeks, a vendor quotes $40k a year and owns the data model, and building would take two engineers six weeks. How do you evaluate buying versus building?

The 90-second answer

I would not start with features. I would start with whether this capability differentiates the product, how fast it will change, and what it costs to leave. For in-app announcements and onboarding checklists, that is usually commodity work. The vendor quote is $40k a year. Building it properly is not six weeks of UI. It is targeting, scheduling, frequency caps, delivery receipts, preference centre, accessibility, and an admin tool product and support will use daily. I would timebox a one-week spike against the vendor API, price the build over three years including maintenance, and only build if the vendor fails a hard requirement or the three-year cost and exit risk clearly beat the subscription.

How I score it

I put numbers on the same criteria for both options before anyone argues from a feature checklist. Weights come from the product risk, not from engineering preference.

CriterionWeightVendorBuild in-house
Fit for current workflow25%4/5, covers targeting and scheduling5/5 if we scope it exactly
Time to first value20%2 weeks integration6 weeks to MVP, longer to parity
Three-year total cost20%$40k/yr plus integrationsee arithmetic below
Data ownership and exit15%Depends on export and API limitsFull control
Change rate over next year10%Vendor roadmap may not matchWe control priority
Operational burden10%Vendor runs delivery and uptimeWe own on-call, deliverability, abuse

A vendor that scores 3 or below on fit for a must-have workflow is out, however cheap. A vendor that passes fit but blocks data export is also out if the data feeds experiments or billing. Everything else is a trade-off I can price.

Worked arithmetic, labelled as hypothetical

Assume a loaded engineer cost of $180k per year, or about $3,460 per week. Two engineers for six weeks is $41,500 in salary cost. That ignores the product manager, designer, QA, and the opportunity cost of delaying the feature they would have built instead. Maintenance for targeting, rendering, and admin tooling is rarely under 20% of build cost per year, so add roughly $8k to $15k a year once shipped, plus infrastructure and on-call time.

Year 1Year 2Year 3
Vendor$40k licence + 2 weeks integration ($7k) = $47k$40k, plus 5% uplift = $42k$44k
Build$42k build + $10k run cost = $52k$12k run cost$12k run cost

On those figures the build looks cheaper by year two. That is exactly why I would not decide on licence price alone. The build number excludes the second engineer we pull off the roadmap for six weeks, the admin tool v2 requests in month four, and the cost of matching vendor features we did not plan, such as multi-language rendering or quiet hours. If the vendor charges per monthly active user, I would model the price at 2x and 5x current volume, because a per-seat or per-message price that looks fine at 10,000 users can dominate at 100,000.

The spike that decides it

In one week I would connect the real app to the vendor sandbox and prove five things: create and target a segment from our user data, schedule and cap frequency, render it in our React shell without layout shift, receive delivery and click events back into our analytics pipeline, and export every announcement, audience, and event we created through the API or bulk export. I would also test the failure path. What does the UI show when the vendor API times out, and can we degrade to no announcement rather than a blank onboarding step?

If the spike passes, I buy and I negotiate the exit at signing: data export format, retention after cancellation, API rate limits, uptime SLA, and price caps on renewal. If it fails on targeting or export, I build, but I build only the wedge the vendor cannot do and I keep the interface behind our own announcement service so a later vendor can slot in.

Failure modes I check before signing

Vendor lock-in usually shows up as a proprietary editor or targeting model with no export, so I ask for a sample export in the spike. Pricing surprises show up as overages for messages, seats, or API calls, so I ask for the overage rate in writing. Operational risk shows up when the vendor is a single point of failure for a blocking UI step, so I keep announcements non-blocking and cache the last known state client-side. The build failure mode is the opposite: we ship a thin v1, then spend a year rebuilding commodity features while the roadmap slips. That is why the decision gets revisited after six months of real usage data, not after the demo.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-90What does total cost of ownership for feature infrastructure include beyond the build cost?

The 90-second answer

Total cost of ownership is everything the feature costs from first commit to final deletion, not just the build. I write it as:

TCO = Build + Run + Operate + Change + Retire

Build covers the engineering to ship it. Run covers the metered infrastructure bill. Operate covers the human time to keep it running. Change covers later modifications. Retire covers export, deletion, and contract exit. If an estimate only has build and a monthly infrastructure price, it is missing most of the cost.

Python
# Python 3.12, figures are hypothetical
build = 24_000          # 6 engineer-weeks at a loaded $4,000 per week
run = 1_200 * 12        # $1,200 per month for compute, storage, and egress
operate = 800 * 12      # $800 per month for on-call and maintenance time
change = 8_000          # two small changes and one migration in year one
retire = 3_000          # data export, deletion, and account closure

tco_12m = build + run + operate + change + retire
print(tco_12m)  # 59000

That hypothetical feature costs $59,000 in its first 12 months. Build is $24,000 of it. The remaining $35,000 is the part a build-only estimate drops.

BucketWhat belongs in itA concrete example
BuildFeature code, tests, migration, launch work6 engineer-weeks to ship and migrate existing data
RunInstances, database, storage, egress, per-event fees$1,200 per month at forecast traffic
OperateOn-call pages, debugging, upgrades, vendor tickets$800 per month of loaded engineering time
ChangeNew fields, traffic growth, cleanup of flags and schemas$8,000 across the year for expected changes
RetireExport, deletion, contract termination$3,000 to export data and close the vendor account

Why the extra buckets matter in practice

Run is the only bucket a vendor calculator prices for you. It also grows with traffic and stored data, so I price it at month 12 volume rather than launch volume. Logs and event tables keep growing even when request volume stays flat.

Operate is where internal features get underpriced. The engineer already on the team still has a loaded cost, and the hours spent on pages and upgrades come directly out of the next feature. I use loaded cost and state the rate in the estimate so finance can replace it with their own figure.

Change and Retire are the buckets people skip because they happen after launch. A flag left at 100%, a table nobody deletes, and a vendor contract with a minimum term all keep costing money. I check the contract for minimum term and export fees before I put a Retire number in the doc.

How I present the number

I show a 12-month total and a 36-month total. Build dominates year one. Run and Operate dominate year three. I also state the traffic volume the Run line assumes, because a per-event price that looks cheap at launch volume can overtake the cost of running the feature internally at higher volume. That volume assumption is what makes the estimate checkable instead of a single number nobody can defend.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-91Your checkout component tests pass, yet users fail to pay when the payment API is slow and the session expires mid-flow. How do you split component and end-to-end tests to catch that without a flaky suite?

The 90-second answer

I test the checkout at three layers, and I assign each failure to the cheapest layer that can catch it reliably. Component tests with React Testing Library cover rendering and interaction logic in isolation: disabled states, validation, optimistic updates, error branches. End-to-end tests with Playwright cover only what components cannot prove: the real browser, real routing, real network timing, and the contract with the payment API. API contract tests sit between them and pin the request and response shapes so a backend change fails fast instead of in a browser.

The scenario you described, slow payment API plus session expiring mid-flow, is exactly where teams over-invest in E2E and under-invest in component tests. A component test can simulate a 5 second payment response and an expired session deterministically in 200 ms. An E2E test that waits on a real slow API will be flaky, slow, and still may not hit the expiry window. So I push the timing logic down and keep E2E to a thin happy path plus one or two critical failure paths with mocked network at the browser boundary.

What each layer owns

FailureComponent testContract testE2E test
Pay button stays enabled during submit, double click creates two ordersYes, assert disabled and single callNoNo, too slow to be the primary guard
Card validation rejects a valid expiry formatYesNoNo
Frontend sends card_token but API now expects payment_method_idNo, mock hides itYes, schema and example payloadsYes, as a smoke check
Session expires after 30 s, user loses cart and sees a generic errorYes, with fake timers and a mocked 401NoYes, one test with a short-lived test session
Payment takes 8 s, spinner times out at 3 s and user retriesYes, fake timers advance past timeoutNoYes, with Playwright route delay
Full purchase completes in a real browserNoNoYes, one golden path

The rule I use in review: if a bug can be reproduced by rendering the component with a mocked hook, it does not belong in E2E. E2E is for integration risk, not logic risk.

Component test: make timing deterministic

TSX
// CheckoutForm.test.tsx, React Testing Library + Vitest, fake timers
import { render, screen, fireEvent, act } from '@testing-library/react';
import { vi } from 'vitest';
import { CheckoutForm } from './CheckoutForm';

const pay = vi.fn();

it('keeps the form recoverable when payment is slow and the session expires', async () => {
  vi.useFakeTimers();
  pay.mockImplementation(() => new Promise((resolve) =>
    setTimeout(() => resolve({ status: 401, code: 'session_expired' }), 5000)));

  render(<CheckoutForm pay={pay} cart={[{ id: 'sku_1', qty: 1 }]} />);
  fireEvent.click(screen.getByRole('button', { name: /pay/i }));

  expect(screen.getByRole('button', { name: /pay/i })).toBeDisabled();
  await act(async () => { vi.advanceTimersByTime(5000); });

  expect(screen.getByRole('alert')).toHaveTextContent(/session expired/i);
  expect(screen.getByRole('button', { name: /pay/i })).not.toBeDisabled();
  expect(pay).toHaveBeenCalledTimes(1);
  vi.useRealTimers();
});

That test runs in under a second, never touches a network, and pins three behaviours that matter in production: no double submit, a timeout that does not strand the user, and a re-enabled button after a 401 so the user can re-authenticate without losing the cart. I would add a sibling case where the payment resolves at 8 s and assert the spinner shows a "still processing, do not refresh" state instead of timing out at 3 s. The timeout value itself is a product decision, and the test makes a change to it visible in review.

E2E test: thin, mocked at the edge, run on every merge

TypeScript
// checkout.spec.ts, Playwright
import { test, expect } from '@playwright/test';

test('completes purchase and recovers from an expired session', async ({ page }) => {
  await page.route('**/api/payments', async (route) => {
    await new Promise((r) => setTimeout(r, 1500));
    await route.fulfill({ status: 200, json: { order_id: 'ord_42' } });
  });
  await page.goto('/checkout');
  await page.getByLabel(/card number/i).fill('4242 4242 4242 4242');
  await page.getByRole('button', { name: /pay/i }).click();
  await expect(page.getByText(/order confirmed/i)).toBeVisible();
});

I mock the payment API with page.route rather than calling a sandbox, because a sandbox adds latency variance and occasional 500s that teach the team to ignore red builds. The one test I keep unmocked is a nightly run against staging with a test card, which catches deploy and CORS and cookie issues that mocks hide. That nightly run is allowed to be slower and is not a merge gate.

How I keep the suite fast and trustworthy

Component tests: roughly 120 cases for checkout, target under 20 s in CI. Contract tests: generated from the OpenAPI schema, run against a stub server, under 10 s. E2E: 5 to 8 tests covering the golden path, the expired session path, and the slow payment path, target under 3 minutes. If an E2E test flakes twice in a week, I move its assertion down a layer or delete it. A flaky E2E test that everyone retries is worse than no test, because it trains the team to merge through failures.

The failure mode I watch for is mock drift. Component tests mock usePay, so a renamed field in the real API passes every component test and fails only in E2E. Contract tests close that gap by validating the actual request body against the schema on every PR. When the backend changes a field, the contract test fails in seconds with a diff, and I update the mock and the E2E stub together.

Developer changes checkout Component tests: logic and timing Contract tests: API shape E2E: browser plus mocked payment Nightly: real staging payment Merge gate is B plus C plus D

That split is why the slow API and expiry case gets caught. The component layer proves the UI behaves correctly under those conditions, the contract layer proves the UI talks to the API correctly, and the E2E layer proves the assembled app works in a browser. Each layer is fast enough to run on every pull request, so a regression is found before merge instead of in a nightly report nobody reads.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-92How do you keep TypeScript types in sync across frontend and backend contracts when a field change can break the other side?

The 90-second answer

Put the contract in one place both sides import, and make the build fail when it drifts. In a TypeScript monorepo that is usually a packages/contracts package holding Zod schemas. The backend validates incoming requests with the schema and serialises responses through it. The frontend imports the same schema, infers its types with z.infer, and parses every response before rendering. A rename or type change then breaks compilation on one side or the other, instead of surfacing as undefined in production.

Types alone do not do this. TypeScript types are erased at runtime, so a backend that returns { totalCents: "1200" } while the frontend expects a number compiles cleanly and fails in the browser. The schema has to run on the wire, not just in the editor.

TypeScript
// packages/contracts/order.ts  (checked against Zod 3.23, TypeScript 5.5)
import { z } from "zod";

export const OrderSchema = z.object({
  id: z.string(),
  status: z.enum(["open", "paid", "shipped"]),
  totalCents: z.number().int().nonnegative(),
});
export type Order = z.infer<typeof OrderSchema>;

// backend (Express / Fastify handler)
const order: Order = { id: "o_42", status: "paid", totalCents: 1200 };
res.json(OrderSchema.parse(order));

// frontend
const res = await fetch("/api/orders/o_42");
const order = OrderSchema.parse(await res.json()); // throws on drift, typed as Order

Choosing the mechanism

ApproachSource of truthRuntime checkMain cost
Shared Zod schemaspackages/contractsYes, both sides parseCouples frontend and backend releases
OpenAPI + generated clientopenapi.yamlOnly if you also validate server-sideCodegen tooling, generated diffs in review
Shared TS types only.d.ts or types.tsNoSilent drift, the failure above
tRPCProcedure definitionsYes, via the routerLocks you to TypeScript on both ends, no REST for other clients

I default to shared Zod when both ends are ours and ship together. If a public API or a partner consumes the same endpoints, OpenAPI wins because non-TypeScript clients need a language-neutral spec. tRPC is fine for an internal-only app, but it does not help a mobile client or a webhook sender.

drift: field renamed or retyped drift packages/contracts: Zod schemas Backend validates request and response Frontend infers types and parses response CI: typecheck plus contract tests fail

Where it breaks

Version skew is the usual one. The web frontend deploys daily, the backend weekly, and an old mobile build may call the API for months. A shared package that forces lockstep releases will block that. The fix is to version the contract, not the package: keep OrderV1Schema and OrderV2Schema side by side, have the backend accept both request shapes during a transition, and add a contract test that runs the old fixture through the new parser. A breaking change (renaming totalCents, changing status from string to enum) gets a new version. An additive change (a new optional field) does not.

Second failure: the backend bypasses the schema for speed or convenience, for example building JSON by hand in a SQL query. Then the schema only describes what the frontend hopes for. I catch that with a snapshot test that hits the real endpoint in CI and parses the body with the contract schema. One failing fixture, say totalCents arriving as a string from a SUM() that Postgres returns as numeric text, is worth more than a hundred type assertions.

Third: validation errors leak internals. When parse throws on the frontend, show a generic "unexpected response" state and log the payload with the trace ID. Do not render the raw Zod issue list to users, and do not retry blindly, because a schema mismatch will fail identically on every retry.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-93A dashboard scrolls fine until live price ticks update 500 rows, then it janks. How do you diagnose CSS layout thrashing and reflow, and prove a fix worked?

The 90-second answer

I would first separate slow style calculation from forced synchronous layout. A normal style recalc can be batched by the browser. Thrashing happens when JavaScript writes a style, then reads a layout property, then writes again, in a loop. The read forces the browser to flush pending style and layout work immediately, so the next write invalidates it again.

In DevTools I record a Performance profile while reproducing the jank, then look for long Layout and Style Recalculation entries and the yellow forced reflow warnings in the console. I check the bottom-up call stack for the read that triggered it, usually offsetWidth, offsetHeight, getBoundingClientRect(), getComputedStyle(), or scrollTop. If those reads sit inside a per-row loop after a write, that is the suspect.

The fix is to batch all reads first, cache the values, then do all writes, ideally inside requestAnimationFrame. Where animation is involved I move width, top, or margin changes to transform and opacity, which can stay on the compositor. I then re-record the same interaction and compare frame time and layout count, rather than trusting that the code looks cleaner.

What the trace looks like

Hypothetical trace for 500 dashboard rows updated on a price tick:

StepCodeBrowser work
1row.style.height = h + 'px'Marks style dirty
2row.offsetHeightForces sync layout for that row
3Next row writeMarks dirty again
4Next row readForces sync layout again

That pattern can turn one tick into hundreds of layouts. In a profile I have seen a 16 ms frame budget become 140 ms of layout for a few hundred rows, which drops the page to roughly 7 fps during the update. The exact number depends on DOM size and depth, so I measure on the real page instead of quoting it.

Bad pattern:

JavaScript
// Checked against Chrome 126, JavaScript
for (const row of rows) {
  row.style.width = row.dataset.w + 'px';
  const h = row.offsetHeight; // forced reflow here
  row.style.height = h + 'px';
}

Fixed pattern:

JavaScript
const heights = rows.map(row => row.offsetHeight); // all reads first
requestAnimationFrame(() => {
  rows.forEach((row, i) => {
    row.style.height = heights[i] + 'px'; // all writes after
  });
});

How I confirm it in production and in the lab

In the lab I use the Performance panel with CPU throttling at 4x, because a fast desktop can hide a problem that hurts a mid-range phone. I also enable paint flashing and layout shift regions to see what actually repainted. A PerformanceObserver for layout-shift tells me about visual instability, but it does not prove thrashing. Long layout entries in the profile do.

JavaScript
const observer = new PerformanceObserver(list => {
  for (const entry of list.getEntries()) {
    if (entry.value > 0.1) console.warn('layout shift', entry);
  }
});
observer.observe({ type: 'layout-shift', buffered: true });

For field data I would add a user timing mark around the tick handler and check whether p75 interaction latency rose after the feature shipped. That ties the lab finding to the metric product cares about, usually INP on the dashboard.

No Yes Yes No Record Performance profile Long Layout entries? Check style recalc and paint cost Inspect stack for layout reads Read after write in loop? Batch reads, then writes in rAF Reduce DOM size or use contain Re-record same interaction

Alternatives and when they are the wrong fix

transform helps for movement and scaling, but it does not fix a layout read that still forces work. content-visibility: auto and contain: layout help offscreen or isolated sections, yet they do nothing for a loop that reads getBoundingClientRect() on every visible row. Virtualizing a long list reduces the number of rows in the DOM, which is often the real fix for a 5,000-row grid, but it adds scroll and keyboard complexity I would only accept if batching alone still leaves layout above the frame budget.

I would also check for libraries that read layout on scroll or resize, such as some chart and tooltip code. A resize handler that reads clientWidth after setting a container width on every event can thrash even when my own code is clean. Debouncing the handler and caching the measurement removes that path without touching the component that renders the rows.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-94Which of localStorage, IndexedDB, and cookies is sent automatically with every request to the server?

The 90-second answer

Cookies. A cookie that matches the request URL is attached by the browser to every HTTP request to that domain, without any JavaScript running. localStorage and IndexedDB are never sent automatically. Code has to read them and put the value in a header, a body, or a query parameter itself.

That single difference decides most uses. Put data in a cookie when the server must see it on each request, such as a session identifier. Keep data in localStorage or IndexedDB when only the page needs it, such as a theme preference or cached product data.

StorageSent automaticallyRead by JavaScriptTypical use
CookieYes, if path, domain, and expiry matchOnly if HttpOnly is absentSession ID the server checks
localStorageNoYes, synchronouslySmall client-only settings
IndexedDBNoYes, asynchronouslyLarger structured offline data

How it shows up in code

JavaScript
// The browser attaches this cookie to the next request to example.com.
document.cookie = "session=abc123; Path=/; Max-Age=3600; Secure; SameSite=Lax";

// Nothing is sent until code reads it and adds it explicitly.
const theme = localStorage.getItem("theme");
fetch("/api/preferences", {
  headers: { "X-Theme": theme }
});

With an HttpOnly cookie, JavaScript cannot read the value at all. The browser still sends it, and the server reads it from the Cookie header. That is why session cookies are usually HttpOnly. A token in localStorage is readable by any script running on the origin, so a cross-site scripting flaw can copy it.

Limits that follow from the rule

Cookies are kept small because they travel on every matching request. Browsers limit a cookie to about 4 KB, and a large cookie slows every call, including calls that do not need it. Setting Path=/ makes it travel to more URLs than a narrower path would.

localStorage holds roughly 5 to 10 MB per origin and stores strings only. IndexedDB holds far more, often hundreds of MB within the browser quota, and stores objects with indexes. Neither is sent unless code sends it, so neither adds bytes to a request by default.

For a feature, I would store the session in a cookie, a small preference in localStorage, and searchable offline data in IndexedDB. The check is simple: does the server need this value without the client code asking? If yes, cookie. If no, keep it on the client.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-95Your product API sits behind a shared CDN, is polled every 30 seconds by 20,000 clients, returns per-user discounted prices, and checkout updates the same resource with If-Match, while a stale price becomes a refund. How do you set Cache-Control and ETags to cut traffic without leaking prices or losing updates?

The 90-second answer

I would split the resource before touching headers. The public catalogue fields go in one cacheable representation. The per-user discounted price goes in a separate private representation. A shared CDN can then cache the public part aggressively while the private part never enters a shared cache. Polling clients revalidate both, get a 304 when nothing changed, and checkout uses a strong validator for optimistic concurrency.

That split is forced by the constraints. Cache-Control: public on a URL means any shared cache may store that response and serve it to the next requester for the same URL. If the body contains user A's discounted price, user B can receive it. Adding Vary: Authorization does not fix this on most CDNs, because the cache key still needs to include the credential and many edge configurations ignore or strip it. private stops shared storage, but then the CDN gives you no traffic reduction at all. Splitting the endpoint is the only design that keeps both properties.

HTTP
GET /api/products/42/catalog
Cache-Control: public, max-age=60, must-revalidate
ETag: "cat-42-9f3c"

GET /api/products/42/price
Cache-Control: private, max-age=0, must-revalidate
ETag: "price-42-a1b2-u881"

The catalogue response can use max-age=60 because a 60 second stale catalogue entry is a product decision, not a correctness bug. The price response uses max-age=0 because a stale price at checkout becomes a refund. Both use must-revalidate, so a cache must ask the origin before reusing a stored copy after expiry. Without it, a cache may serve stale content when the origin is unreachable.

Exact revalidation working

The origin generates a strong ETag from a version that changes only when a field in that representation changes. For the catalogue, that is a catalog_version column bumped by the catalogue write path. For the price, it is a hash of the base price, discount rule version, and user segment, or a version row updated when either changes. I would not hash the serialised JSON body per request. At 667 polls per second, hashing a 48 KB body costs more CPU than the bandwidth it saves.

TypeScript
// Node 20, Express-style handler
app.get('/api/products/:id/price', async (req, res) => {
  const user = await authenticate(req);
  const row = await db.prices.findForUser(req.params.id, user.id);
  if (!row) return res.status(404).json({ code: 'product_not_found' });
  const etag = `"price-${row.version.toString(36)}-${user.id}"`;
  res.set('ETag', etag);
  res.set('Cache-Control', 'private, max-age=0, must-revalidate');
  if (req.headers['if-none-match'] === etag) return res.status(304).end();
  res.json({ productId: row.productId, priceCents: row.priceCents, currency: 'USD' });
});

On a poll, the client or its cache sends If-None-Match with the stored validator. A match returns 304 Not Modified with no body. The cache then reuses the stored body and updates its stored headers from the 304 response, including a fresh Age and Cache-Control. A mismatch returns 200 with a new body and a new ETag. The browser fetch layer normally handles 304 transparently, but a custom React data layer that treats any non-200 as an error will surface it as a failure, so I check that wrapper explicitly.

Worked trace

PollClient sendsOrigin seesOrigin returnsResult
1no validatorfirst request200, 48 KB catalogue, ETag: "cat-42-9f3c"CDN stores it
2, 30 s laterIf-None-Match: "cat-42-9f3c"version unchanged304, about 0.4 KBCDN serves stored body
3, after title editIf-None-Match: "cat-42-9f3c"version now a1b2200, 48 KB, new ETagCDN replaces stored body
4, price pollIf-None-Match: "price-42-a1b2-u881"discount rule changed200, 0.3 KB, new ETagonly that user refetches
No Yes Yes No No Yes Poll every 30s Representation cached? Origin 200 + strong ETag Send If-None-Match Validator matches? Origin 304, reuse body Checkout PATCH uses If-Match Strong ETag matches? 412, client refetches Apply update, bump version

Traffic arithmetic, hypothetical figures labelled as such

20,000 clients polling every 30 seconds is 667 requests per second. If the catalogue body is 48 KB and 95% of polls are unchanged, the origin sends a full body for about 33 requests per second and a 304 for the other 634. Egress drops from roughly 32 MB/s to about 1.8 MB/s. The origin still pays a version lookup per poll, so I would index the version column and alert on the 304 rate at the origin and at the edge separately. A falling edge 304 rate with a steady origin rate usually means the CDN is not forwarding If-None-Match or is collapsing requests incorrectly.

Where this breaks in practice

Weak validators (W/"...") are acceptable for If-None-Match on a GET, because the client only needs to know whether the meaning changed. They are not acceptable for If-Match on the checkout PATCH. A weak validator can match while the underlying bytes differ, for example after a representation change that preserves semantics, and that permits a lost update. Checkout needs a strong ETag, and a mismatch must return 412 Precondition Failed so the client refetches and retries against the current version instead of overwriting it.

The second failure is validator churn. If the catalogue ETag is derived from a row that also holds last_viewed_at or view_count, every view bumps the version and every poll becomes a 200. The 304 rate collapses to near zero and the CDN stores a fresh copy constantly. I keep volatile fields out of the versioned representation or out of the version calculation.

The third failure is Last-Modified used as the only validator. It has one second granularity, so two price changes inside the same second produce the same validator, and it depends on server clocks across instances. ETag avoids both problems. I would still send Last-Modified for debugging, but I would not branch on If-Modified-Since alone.

stale-while-revalidate would cut latency further by serving the old price while refreshing in the background. For the catalogue view that trade is defensible. For the price that feeds checkout, it deliberately serves a price the origin already knows is stale, so I would leave it off that endpoint and accept the extra round trip.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-96How would you use SQL window functions to build a leaderboard that shows the top 100 players, handles ties, and also shows the current user's rank outside the top 100?

The 90-second answer

Aggregate scores to one row per player first, then rank that result with a window function, then filter. Window functions run after WHERE and GROUP BY, so you cannot put rank <= 100 in the same query that computes the rank. Wrap it in a CTE or subquery and filter outside.

Assume PostgreSQL 15 and a scores(user_id, season_id, points, earned_at) table. A player may have many score rows in a season, so the leaderboard needs their total, not their best single row.

SQL
-- PostgreSQL 15
WITH totals AS (
  SELECT user_id, SUM(points) AS score
  FROM scores
  WHERE season_id = $1
    AND earned_at >= $2
  GROUP BY user_id
),
ranked AS (
  SELECT
    user_id,
    score,
    RANK() OVER (ORDER BY score DESC) AS rank,
    ROW_NUMBER() OVER (ORDER BY score DESC, user_id) AS row_num
  FROM totals
)
SELECT user_id, score, rank, row_num,
       user_id = $3 AS is_current_user
FROM ranked
WHERE row_num <= 100 OR user_id = $3
ORDER BY row_num;

That one query returns the top 100 plus the current user when they sit at row 101 or lower. The API can then render the list and highlight the current user without a second round trip. If the client only needs the current user rank on a profile page, run the same CTE and filter to user_id = $3 alone.

Ties decide which function you pick

FunctionScores 100, 100, 90, 90, 80Use it when
ROW_NUMBER()1, 2, 3, 4, 5You need a stable, unique position for pagination
RANK()1, 1, 3, 3, 5Displayed rank should skip after a tie, as in most games
DENSE_RANK()1, 1, 2, 2, 3Displayed rank should not skip, for example league tiers

I return both rank and row_num. The UI shows rank as the badge and uses row_num for ordering and pagination. Picking only RANK() for the cutoff creates a boundary problem: if rows 100 and 101 both have rank 100, a rank <= 100 filter returns 101 rows and the page size changes from request to request. Filtering on row_num keeps exactly 100 rows. If product wants everyone tied at the cutoff included, filter on rank instead and tell the client the list can exceed 100 rows.

The tiebreak inside ROW_NUMBER(), here user_id, matters for stability. Without it, Postgres can return tied rows in either order, so a player can move between page 1 and page 2 on refresh even though no score changed. A deterministic tiebreak, such as earliest achievement time or user_id, fixes the order. It does not change the displayed rank, which still comes from RANK().

Where this breaks at scale

The query sorts every player in the season on each request. With 50,000 players that sort is cheap, often under 20 ms with an index on (season_id, points DESC). With 2 million players and a leaderboard on the home screen, it stops being cheap. Two fixes, in order of effort:

  1. Cache the ranked result for 30 to 60 seconds and serve the cached rows. Leaderboards tolerate a minute of staleness far better than a checkout price does, and the cache turns a sort per request into a sort per minute.
  2. Maintain a materialized leaderboard table. On each score write, update that player's total and recompute ranks in a background job, or store totals in a table indexed on (season_id, score DESC) so the window query reads in index order. This trades write complexity for read speed and is worth it only when the cached query still misses the latency budget.

A common bug is filtering before ranking. WHERE score >= 1000 before the window function removes players who would have pushed someone else down, so ranks come out wrong. Another is ranking raw score rows instead of grouped totals, which puts the same player at ranks 1, 2 and 3. Both disappear once the CTE order is totals, then rank, then filter.

For the API contract, I would return rank, row_num, score, user_id, is_current_user, and a cutoff_score so the client can show "12 points behind 100th place" for a user outside the top 100. That last field is why the current user row matters beyond a highlight: it turns a dead end at row 101 into a concrete target for the next session.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-97How would you use aggregations and GROUP BY to build a funnel query that shows step conversion by variant without double-counting users?

The 90-second answer

I would aggregate at the user level first, then count users per step. A funnel is a count of distinct users who reached each step, grouped by the dimension I am comparing, usually variant or day. COUNT(*) on raw events double-counts a user who viewed a page five times, so the query needs COUNT(DISTINCT user_id) per step, with the first step as the denominator for conversion.

Assume an events table with user_id, event_name, variant, and occurred_at, and a three-step flow: viewed, started, completed. Conditional aggregation does this in one pass:

SQL
-- PostgreSQL 15
SELECT
  variant,
  COUNT(DISTINCT user_id) FILTER (WHERE event_name = 'viewed') AS viewed_users,
  COUNT(DISTINCT user_id) FILTER (WHERE event_name = 'started') AS started_users,
  COUNT(DISTINCT user_id) FILTER (WHERE event_name = 'completed') AS completed_users
FROM events
WHERE event_name IN ('viewed', 'started', 'completed')
  AND occurred_at >= now() - interval '7 days'
GROUP BY variant
ORDER BY variant;

Conversion is then derived in the dashboard or a wrapping query: started_users * 1.0 / NULLIF(viewed_users, 0). NULLIF stops a division by zero when a variant has no viewers yet, which happens in the first hour of a test.

Worked trace, hypothetical figures

variantviewed_usersstarted_userscompleted_usersview to startstart to complete
A1,00042018042.0%42.9%
B98047023548.0%50.0%

Reading the table, B wins on both transitions. If I had used COUNT(*) and A had a retry bug firing viewed twice per page load, A would show roughly 2,000 views and the view-to-start rate would halve, even though the same 1,000 users arrived.

Where the simple version breaks

Presence alone ignores order. A user who fired completed from a stale tab before started would count in both steps. For a strict funnel I first reduce to one row per user and step with MIN(occurred_at), then keep only users where each later step timestamp is after the previous one. That subquery is slower, so I use it when the flow has a real sequence constraint, such as payment after cart creation, and keep the conditional aggregation for unordered checklists.

ApproachStrengthCost
Conditional aggregation with FILTEROne scan, easy to add steps, easy to group by variant or dayCannot enforce step order
Per-user MIN() then timestamp comparisonEnforces order and a conversion window, for example complete within 24 hours of startExtra aggregation pass, harder to maintain as steps grow

Two more checks before I trust the numbers. First, the window: events outside the 7-day filter, or a user who viewed on day 1 and completed on day 9, will inflate the last step unless the window is applied consistently. Second, identity: logged-out and logged-in rows for the same person split into two user_id values, which understates conversion. I would flag that in the dashboard footnote and check what share of traffic is anonymous before comparing variants.

In an interview I would close by naming the index that makes this fast at scale: a composite index on (event_name, occurred_at, variant, user_id) for the filter and grouping, and I would pre-aggregate daily if the raw table passes a few hundred million rows.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-98What threshold does the Bonferroni correction set for 20 comparisons when you want a 5% family-wise error rate?

The 90-second answer

Use the Bonferroni correction. Divide your target significance level by the number of comparisons, and only call a result significant if its p-value falls below that smaller threshold.

For 20 comparisons at a 5% family-wise error rate, the threshold is 0.05 divided by 20, which is 0.0025. A result at p = 0.01 would look significant in a single test, but it does not clear the corrected bar for a family of 20.

The reason is simple arithmetic. Each test at alpha = 0.05 has a 5% chance of a false positive when there is no real effect. Run many tests and those chances stack. Bonferroni keeps the chance of any false positive across the whole family at or below 5%.

The worked numbers

Comparisons (m)Uncorrected thresholdBonferroni threshold (0.05 / m)Chance of at least one false positive if uncorrected
10.050.05005.0%
50.050.010022.6%
200.050.002564.2%
500.050.001092.3%

The last column is 1 minus (1 - 0.05) raised to the power m. With 20 independent tests, you are more likely than not to see at least one p-value below 0.05 even when nothing works. That is the false positive problem Bonferroni is guarding against.

Python
# Python 3
m = 20
alpha = 0.05
threshold = alpha / m
fwer_uncorrected = 1 - (1 - alpha) ** m
print(threshold)            # 0.0025
print(round(fwer_uncorrected, 3))  # 0.642

How I apply it in an experiment

I write the number of comparisons into the experiment plan before launch. That count includes the primary metric plus every secondary metric or segment comparison the team intends to act on. If the plan names 20, the decision threshold is 0.0025 for all of them.

The trade-off is power. A stricter threshold means a real but small effect needs more traffic or a larger lift to cross it. That cost is the point. It stops a team from shipping whichever of 20 slices happened to cross p < 0.05 by chance, and it forces a choice to test fewer, better hypotheses when the traffic cannot support 20 corrected comparisons.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-99Your A/B test shows a 3% lift at p = 0.04 after you peeked at the dashboard daily for two weeks. How do you apply probability fundamentals before you ship it?

The 90-second answer

I would pause the ship decision and treat p = 0.04 after daily peeking as weak evidence, not a 96% chance the lift is real. A p-value is the probability of data at least this extreme if the null were true. It says nothing directly about the probability the feature works. Daily peeking also breaks the nominal 5% false positive rate, because I gave the test many chances to cross the line by luck. Before shipping I would check the pre-registered primary metric, the confidence interval for the effect, the prior plausibility of a 3% lift, and whether the result survives a correction for the looks I actually took.

Why the naive reading fails

Three pieces of probability do the real work here: base rate, power, and sequential testing.

Base rate first. Most checkout tweaks do nothing. Suppose, as a labelled hypothetical, only 10% of similar changes produce a true lift, the test has 80% power, and alpha is 5%. Bayes gives the chance a significant result is real:

P(real | significant) = 0.80 x 0.10 / (0.80 x 0.10 + 0.05 x 0.90) = 0.08 / 0.125 = 64%

If the prior is 1%, which fits a cosmetic copy change, the same calculation gives 0.008 / 0.0575 = 14%. Same p-value, very different decision. That is why I ask what else we believed before the data arrived, and whether the observed lift matches the mechanism. A 3% lift from moving a button is plausible. A 3% lift from changing a footer link is a reason to suspect noise or a logging bug.

Power and interval width come next. A significant result with a wide interval can still include effects too small to pay for maintenance. I want the interval, not just the point estimate.

Hypothetical result, 10% baseline conversionValue
Users per arm5,000
Observed lift3% relative, 0.3 points absolute
Standard error of differenceabout 0.60 points
95% interval for absolute lift-0.88 to +1.48 points
InterpretationData are compatible with harm, nothing, and a useful gain

With numbers like those, p = 0.04 would not even arise. When it does arise at larger n, I still read the interval against the minimum effect worth shipping, for example 0.5 points, and against guardrails such as refund rate and page latency.

Peeking is the failure mode I see most often. Checking a fixed-horizon test daily and stopping when it looks good inflates false positives well above 5%. This simulation shows the mechanism for a null effect:

Python
import random, math
random.seed(7)

def one_run(looks=14, n_per_look=1000):
    # null true: both arms 10% conversion, accumulate data
    a_conv = b_conv = 0
    a_n = b_n = 0
    for _ in range(looks):
        a_n += n_per_look; b_n += n_per_look
        a_conv += sum(random.random() < 0.10 for _ in range(n_per_look))
        b_conv += sum(random.random() < 0.10 for _ in range(n_per_look))
        pa, pb = a_conv / a_n, b_conv / b_n
        se = math.sqrt(pa*(1-pa)/a_n + pb*(1-pb)/b_n)
        if se and abs(pb - pa) / se > 1.96:
            return True  # would have stopped and claimed a win
    return False

wins = sum(one_run() for _ in range(2000))
print(wins / 2000)  # typically 0.15 to 0.20, not 0.05

The exact figure depends on the look schedule and correlation between looks. The direction does not. More looks, more chances to declare a win on noise.

What I do instead

I pre-register the primary metric, sample size from a power calculation, and the analysis date before launch. If the business needs interim reads, I use a sequential method with an alpha-spending boundary, or I treat interim dashboards as diagnostics and keep the decision at the planned end. I also check for the usual confounders that probability alone cannot fix: assignment versus exposure mismatch, novelty effects in week one, day-of-week imbalance, and a segment driving the whole result.

If the corrected result still clears the bar, I ship with the interval attached to the decision record: expected lift, plausible range, and the guardrail that would trigger a rollback. If it does not, I iterate on the hypothesis or kill it. Shipping on a peeked p-value spends user trust and engineering time on a coin flip dressed up as certainty.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-100Walk me through how you would own a feature from discovery through production iteration next quarter, including what you would ship, measure, and change?

The 90-second answer

I would own the loop, not just the build. Discovery produces a falsifiable hypothesis and a decision rule before code. Delivery ships behind a flag to a small slice with instrumentation already in place. Production iteration is scheduled before launch, with a date to keep, kill, or iterate based on the primary metric and guardrails. If any of those three pieces is missing, I do not call the feature done.

Assume a concrete example: a saved-views feature for a B2B dashboard, 12 weeks next quarter, one frontend engineer, one backend engineer, and a designer half time. The plan below is how I would run it.

PhaseWeeksArtefact that gates the next phaseExit decision
Discovery1 to 28 user interviews, support ticket sample, baseline funnel from existing eventsProblem confirmed or killed
Prototype and contract3 to 4Clickable prototype tested with 5 users, API schema, event taxonomyScope frozen for v1
Build behind flag5 to 9Flagged code at 0% production, dashboards, alertsInternal dogfood passes
Experiment10 to 1250/50 sticky assignment, pre-registered analysis dateShip, iterate, or roll back
IterationFollowing quarterDecision memo with metric read and next hypothesisKeep, extend, or remove flag

Discovery: make the bet explicit

I start with the current funnel, not opinions. If saved views are meant to increase weekly reuse, I pull the last 28 days: how many users create a view manually, how often they return to the same filter set, and where they drop off. I interview users who already export CSVs or screenshot filters, because that workaround is the strongest signal of unmet need.

The hypothesis goes in writing: "If users can save and reload a filter set in one click, weekly active users who create a view will reuse it at least twice in 14 days, and dashboard sessions per user will rise by 10% without increasing p95 load time above 800 ms." That sentence names the primary metric, the guardrail, and the population. It also prevents a later argument where a 40% rise in views created is declared a win while reuse stays flat.

Prototype and contract: cut scope by risk

In weeks 3 to 4 I test the riskiest assumption first. For saved views that is not the database, it is whether users understand what a saved view contains and trust that it will not change under them. A prototype with fake data answers that in a week. The API contract is drafted at the same time: POST /saved-views, GET /saved-views?owner=me, DELETE /saved-views/{id}, with an ETag on update so two tabs do not silently overwrite each other.

Instrumentation is part of the contract, not a follow-up ticket:

TypeScript
// Checked against TypeScript 5.4, shared by web and server emitters
type SavedViewEvent =
  | { name: 'saved_view_created'; user_id: string; view_id: string; filter_count: number }
  | { name: 'saved_view_applied'; user_id: string; view_id: string; source: 'list' | 'link' | 'default' }
  | { name: 'saved_view_deleted'; user_id: string; view_id: string };

Events carry stable IDs, never email addresses or raw filter values that could contain customer names. Assignment and exposure are logged separately. Assignment happens at flag evaluation, exposure happens when the user actually sees the saved-views entry point. Without that split, users who never saw the feature dilute the treatment group and the read is biased toward zero.

Build and experiment: size the test before launch

Code ships behind a flag at 0%. I dogfood internally in week 9, then enable for 5% of eligible users. The experiment is pre-registered: primary metric is 14-day reuse rate among creators, guardrails are dashboard p95 latency, error rate on GET /saved-views, and support contacts tagged saved-view.

Sample size is worked out before anyone looks at results. Hypothetical figures: baseline reuse is 8%, I want to detect a 10% relative lift to 8.8% with 80% power at alpha 0.05. Using the normal approximation, that needs roughly 18,400 users per variant. At 3,000 eligible users per week, that is about 12 weeks of exposure, which does not fit the quarter. So I either widen eligibility, pick a larger minimum detectable effect, or accept a directional read at week 12 with a decision to extend. Pretending a 2-week test can detect that lift is how teams ship noise.

Ship Iterate Kill Discovery hypothesis Prototype and contract Build behind flag Dogfood and instrument Experiment at 50 percent Read at pre-set date Roll out and clean flag Remove code and flag

Production iteration: decide on the date, not on enthusiasm

At the pre-set date I read the primary metric first, then guardrails, then segment by new versus existing users. Three failure modes I watch for: novelty effect, where week 1 spikes and week 3 fades; selection bias, where power users self-select into creating views; and instrumentation drift, where a rename breaks the dashboard and the team argues from a partial count. I check event volume against flag evaluation volume as a sanity check before trusting any lift.

If reuse rises and guardrails hold, I roll out to 100% over two weeks, then remove the flag and the dead code path within one sprint. A flag left at 100% for a quarter becomes a second codebase. If the read is flat, I do not add more features to the same hypothesis. I go back to discovery with the segment data and write the next hypothesis, or I kill it and record why, so the next team does not rebuild it.

Ownership, in practice, means I am the person who can answer three questions at any point in the quarter: what would make us stop, what are we measuring this week, and what happens to the code if the answer is no. If I cannot answer all three, the feature is not ready to ship.

Curated: · Written: · Reviewed: —

Difficulty: Medium