AI System DesignAI System Design Case StudiesProduction ML Diagnosis and Pricing Reliability
How to Diagnose and Fix E-Commerce Pricing Algorithm Underpricing
Question 8 of 47 · Updated
On this page
- 1. Establish what underpricing means
- 2. Contain the production incident
- 3. Diagnostic architecture: trace the actual price
- 4. Measure scope and prioritize investigations
- 5. Root-cause decision tree
- 6. Reproduce the incident with point-in-time replay
- 7. Investigate source-data and feature defects
- Data leakage
- Feature drift versus training-serving skew
- 8. Diagnose systematic prediction bias
- 9. Audit the objective, labels and loss functions
- 10. Enforce margin protection independently
- 11. Practical implementation: exact minor-unit floor and signed-bias checks
- 12. Repair the decision, publication and checkout layers
- 13. Regression tests and invariants
- 14. Offline evaluation and controlled experimentation
- Offline
- Shadow and canary
- Controlled business experiment
- 15. Monitoring that detects recurrence
- 16. Rollback and incident recovery lifecycle
- 17. Scalability and reliability considerations
- 18. Worked incident scenario
- 19. Interview follow-ups and common mistakes
- 20. Concise interview-ready answer
- References and research transparency
I would treat systematic underpricing as a production incident, not immediately retrain the pricing model. First contain unsafe price publication, establish what constitutes an incorrectly low price, and trace the complete pricing decision from inputs through the model, optimization, discounts, publication and checkout. Then isolate the failing layer with reproducible historical replay, correct it, validate hard margin constraints, and deploy the fix gradually with independent outcome monitoring and a rollback plan.
The original interview question is: How would you fix an algorithm that underprices products on an e-commerce site?
This lesson addresses diagnosis and remediation of an existing production system. The earlier Airbnb dynamic pricing case explains how to build a pricing system from first principles, including demand estimation and constrained optimization. Here the emphasis is on finding which component broke, proving the root cause, containing financial and customer impact, and ensuring that the deployed repair actually works.
All monetary examples, incident timelines, workloads and metrics are illustrative, not measured results from a particular retailer.
1. Establish what underpricing means#
Underpricing has several distinct meanings, and each requires a different fix.
| Meaning | Evidence needed | Example |
|---|---|---|
| Contractual or policy violation | Applicable approved price constraint | A price falls below an authorized minimum |
| Negative or insufficient contribution | Effective proceeds, marginal costs and approved objective | A discount leaves less contribution than required |
| Systematic prediction underestimation | Valid observed target and point-in-time prediction | Predictions are consistently below a defined cost or price target |
| Poor economic decision | Credible evidence about outcomes at alternative prices | A higher feasible price may improve contribution |
| Display or checkout inconsistency | Versioned publication and transaction records | Checkout receives an obsolete lower amount |
A low price relative to a competitor is not sufficient evidence of an error. It may reflect different product quality, inventory strategy, fulfillment terms, customer discounts or commercial objectives. An intentional approved clearance campaign can also rationally accept a low margin. Conversely, a product can appear profitable at its advertised list price while stacked discounts make its effective contribution negative.
Clarify the pricing objective, whose margin matters, which costs are included, and whether there are authorized exceptions. For a marketplace, distinguish seller proceeds from marketplace revenue and the total paid by the buyer.
Specify the diagnostic unit: SKU or variant, seller or retailer, market, currency, channel, pricing timestamp and applicable promotion. Avoid averaging raw price differences across currencies and incomparable products.
A reference price must have defensible semantics. A model predicting historical transaction prices can be evaluated against those prices, but historical transaction prices are not necessarily the economically optimal prices. If the incident concerns opportunity cost, estimate it separately under documented causal assumptions.
2. Contain the production incident#
If prices violate approved constraints or a material financial exposure is suspected, do not wait for the next model training cycle.
- Assign an incident owner and coordinate pricing, engineering, finance, operations and customer support.
- Pause or restrict automated price publication for affected inventory using the approved feature flag or control plane.
- Preserve model artifacts, feature snapshots, cost records, promotion versions, decision logs, and deployment history.
- Use a verified last-known-good price or authorized manual policy only when it is still valid against current costs, inventory, promotions and other constraints.
- Reconcile published prices and accepted orders. Identify affected transactions and obtain authorized decisions about remediation.
- Communicate the customer impact accurately; do not silently change accepted order amounts or invent commercial policies to recover losses.
The appropriate incident severity depends on breadth, financial exposure, customer impact and contractual requirements. A single erroneous price in a high-volume product may be more urgent than a small bias across low-volume products.
A rollback of a model artifact is not a rollback of the prices already stored in the catalog. Price projections, caches, search results and checkout quotes may all retain earlier values. Recovery requires reconciliation of the complete publication lifecycle.
3. Diagnostic architecture: trace the actual price#
The key debugging practice is to inspect intermediate values rather than treating final prices as a black-box output of a model. The exact ordering of promotions and validation depends on business rules, but the final amount that affects proceeds must be validated after all applicable adjustments.
Each trace should identify the SKU and channel, currency, decision timestamp, feature versions and availability times, model artifact, raw prediction, optimization result, applied adjustments, approved constraints, effective amount and policy version. Track a decision ID through catalog publication and checkout. Restrict access to commercially sensitive data and avoid logging unnecessary customer information.
4. Measure scope and prioritize investigations#
Start with an incident dashboard that compares the current pricing pipeline with an appropriate unaffected period or approved reference. Slice by release version, product category, seller, channel, currency, fulfillment method, promotion state, cost-data freshness and inventory state.
Useful incident measures include:
- Count and fraction of eligible SKU decisions that violate approved constraints.
- Count of affected SKUs and accepted orders, separated from merely generated recommendations.
- Realized negative contribution and estimated exposure, using finance-approved accounting definitions.
- Signed error, absolute error and underestimation frequency for genuinely observed model targets.
- Price discrepancies between authoritative state, customer display and checkout.
- Feature age, missingness, fallback usage, model version and publication delay.
Distinguish a change in product mix from a change in within-product pricing behavior. For instance, an influx of inexpensive products can lower average prices without any SKU becoming underpriced. Compare matched SKU cohorts where possible, and separately report newly added or discontinued products.
Use volume-weighted and SKU-weighted measures together. A small number of frequently purchased products can dominate financial impact while the median SKU appears unaffected. Do not report a hypothetical counterfactual revenue difference as confirmed lost revenue.
5. Root-cause decision tree#
This tree is a guide to organizing hypotheses, not proof that each branch is mutually exclusive. Multiple failures can coexist. For example, an incorrect cost feed and a missing margin check can both contribute to the incident. Identify the initiating fault and the failed containment control.
Choose an affected product and a matched unaffected control. Reconstruct their exact decision traces. Then identify the earliest layer at which the affected value becomes inconsistent with the intended specification.
6. Reproduce the incident with point-in-time replay#
Replay the pricing decision using the same input snapshot, model version, preprocessing, objective, optimization configuration and promotion rules that were active when the erroneous price was generated. Avoid substituting today's corrected cost or inventory into a historical replay and calling it the original incident.
Create a minimal fixture containing the source inputs, expected intermediate values and actual output. Run controlled replacements one component at a time:
| Replay configuration | Diagnostic purpose |
|---|---|
| Original inputs and original bundle | Reproduce the observed failure |
| Corrected data and original bundle | Isolate a suspected data defect |
| Original data and known-good compatible bundle | Test regression associated with the release |
| Corrected data and repaired bundle | Verify the complete candidate fix |
| Repaired bundle on unaffected and edge-case fixtures | Check for unintended regressions |
The original bundle must include compatible feature schemas, model weights, preprocessing, optimization and policy configuration. Rolling back just the model weights can leave a new incompatible scaler or feature encoder in place.
Replay may require immutable feature snapshots or reconstructable point-in-time features. If the historical information is incomplete, document the gap rather than claiming deterministic reproduction. A repair inferred from incomplete logs still needs appropriate validation.
7. Investigate source-data and feature defects#
Many apparent model failures originate before inference. Begin with the strongest concrete invariants.
| Suspected defect | How to investigate | Corrective action |
|---|---|---|
| Cost-feed delay | Compare event time, ingestion time and effective cost version | Repair ingestion, enforce freshness and reconcile |
| Missing costs represented as zero | Compare null flags, defaults and source completeness | Reject unsupported decisions or use an approved fallback |
| Currency or minor-unit mismatch | Compare explicit units at every service boundary | Use typed amounts and tested currency conversions |
| Incorrect product join | Validate SKU, variant, seller and effective-date keys | Repair the join and enforce identity constraints |
| Incorrect product quantity | Compare unit, bundle and pack-size definitions | Normalize quantities consistently |
| Stale or incorrect inventory | Compare versioned authoritative inventory with derived features | Refresh and reject incompatible snapshots |
| Promotion duplication | Trace adjustment identities and eligibility | Make adjustments idempotent and validate final amounts |
| Changes to fulfillment costs | Compare source accounting definitions and applicable cost components | Update the authorized cost contract and replay |
A currency bug can create orders-of-magnitude errors, while stale fees may create a smaller but widespread systematic margin loss. Check both.
Data leakage#
Leakage occurs when training uses information unavailable at the real decision time. Examples include future realized sales, later promotion outcomes, updated costs, or the final price that a downstream pricing service generated after the model ran.
Such a model may look accurate in a notebook because it has indirect access to the answer, but fail once those features are absent or replaced with defaults online. Leakage can cause underpricing, overpricing or other errors; it does not necessarily produce one direction of bias.
Rebuild features using availability timestamps and temporal joins, compare offline and online feature definitions, and evaluate using chronological holdouts. Fit imputation, encoding and normalization only on the appropriate training partition. Use the same versioned transformations in serving.
Feature drift versus training-serving skew#
Training-serving skew means feature computation or semantics differ across environments. Drift means the distribution of observations or the relationship between inputs and target changes over time.
A category encoder that maps new product types to the wrong index is a serving defect. A genuine increase in input costs may be a distribution shift. An upstream cost-data schema change may cause both.
Use exact paired feature comparisons for skew. For drift, compare distributions, missingness and relevant conditional metrics over time; PSI, KS tests or distribution-distance measures can help prioritize investigation. They are not proof of degraded business outcomes. Interpret them alongside representative target quality, cohort size and seasonality.
8. Diagnose systematic prediction bias#
Only evaluate residuals against a target that actually has observed, valid labels. Let p be a prediction and y the corresponding reference target.
signed error = p - y
mean signed error = mean(p - y)
MAE = mean(abs(p - y))
underestimation rate = count(p < y) / nNegative mean signed error indicates average underprediction under this sign convention. MAE measures error magnitude without direction. A near-zero average residual can hide severe errors that cancel.
Consider a fabricated example:
| Product | Reference target | Prediction | Signed error |
|---|---|---|---|
| A | $100 | $90 | -$10 |
| B | $120 | $110 | -$10 |
| C | $50 | $60 | +$10 |
Mean signed error is approximately -$3.33 and MAE is $10. The first two products are underestimated, while the third is overestimated. Report residuals by segment and price range instead of applying a single universal correction.
Check whether bias began after a release, occurs only on unseen categories, grows with cost or price, or tracks feature age. Compare a recent holdout with historical holdouts under consistent labels. Quantify uncertainty and account for correlations across repeated observations of the same SKU.
If the model predicts demand or conversion, its residuals are in demand or probability units, not dollars. A price that is too low may result from overestimated demand sensitivity, inaccurate conversion probabilities, or optimization errors even when the price prediction itself is not a modeled target.
9. Audit the objective, labels and loss functions#
A common design flaw is training a regressor to reproduce past realized transaction prices and then assuming those predictions maximize profit. This can reproduce past discounts and historical mistakes. Sold-product data also exclude opportunities that did not convert at the offered price.
Verify that the supervised target and pricing objective are aligned:
- Cost forecasts should predict the relevant future cost under a specified accounting definition.
- Demand or conversion models should estimate outcomes conditional on an offered price and context.
- A direct price predictor trained on an approved reference price learns to reproduce that reference, not necessarily to optimize economic value.
- The decision layer should optimize an explicitly authorized objective under appropriate constraints.
For regression, squared error emphasizes large misses and targets the conditional mean under ideal conditions. Absolute error targets a conditional median. Huber loss balances squared and linear penalties. Log-space transformations can change the implied target; exponentiating a log-space prediction does not in general yield an unbiased conditional mean in the original units.
An asymmetric loss can penalize underestimation more when the target and costs justify it. For example, quantile regression uses pinball loss, where underprediction of the reference receives weight tau and overprediction receives weight 1 - tau. A tau greater than 0.5 targets a higher conditional quantile.
However, using a higher quantile of historical prices is not automatically an economically optimal correction. It can overprice products, lower conversion or amplify existing inequities. Use asymmetric loss only when the prediction target and business harm support that choice, and validate it against the complete decision objective. A hard margin constraint should be enforced independently of the model's training loss.
If demand response is the underlying cause, distinguish predictive correlation from causal elasticity. Historically higher prices may coincide with strong demand because managers raised prices in anticipation of demand. Use appropriate observational assumptions or approved controlled experiments to assess the effect of changing prices. The Airbnb case covers first-principles price-response modeling in greater depth; the incident here requires establishing whether the existing estimate actually caused the faulty decision.
10. Enforce margin protection independently#
Suppose an approved pricing policy requires an effective selling price P, variable cost C, proportional fee rate f and minimum contribution margin rate m. Define contribution as P - C - fP and margin as contribution divided by P.
For positive P:
(P - C - fP) / P >= m
P * (1 - f - m) >= C
minimum effective price = C / (1 - f - m)The denominator must be positive. If a ceiling is below this minimum, no feasible price exists under the stated rules. Do not silently ignore the constraint.
For a synthetic example, cost is $80, the proportional fee is 5% of effective revenue and the required margin is 15%. The minimum effective price is $80 / 0.80 = $100. At $90, the fee is $4.50, contribution is $5.50 and the margin is approximately 6.11%, below the required 15%.
If an otherwise valid $100 price receives a 10% retailer-funded discount, the effective proceeds before fees may become $90. A validator that only checked the original list price would miss the violation. The actual treatment depends on discount funding, taxes, shipping charges, payment fees, returns and other approved cost definitions.
This example uses simplified costs and assumes fees are charged on the effective price. Actual accounting may include fixed fees, tiered charges, rebates, different tax treatment and multiple parties. Finance and policy owners must define the formula. Authorized clearance, promotional subsidies or strategic below-margin decisions should use explicit, auditable exceptions rather than bypassing validation.
Round the minimum up to the valid currency increment, not down. If fee rounding is mandated at transaction level, validate against the exact fee calculation after rounding. Protect the final customer-facing amount and corresponding merchant proceeds, not merely an intermediate recommendation.
11. Practical implementation: exact minor-unit floor and signed-bias checks#
The following Python example uses integer minor units and integer basis points to calculate a simplified minimum effective price. One basis point is 0.01 percentage points; 10,000 basis points equals 100%. It also provides a small residual diagnostic.
PYTHONfrom math import isfinite def minimum_price(cost, fee_bps, margin_bps): if any(type(v) is not int or v < 0 for v in (cost, fee_bps, margin_bps)): raise ValueError("nonnegative integers required") denominator = 10000 - fee_bps - margin_bps if denominator <= 0: raise ValueError("infeasible fee and margin") return (cost * 10000 + denominator - 1) // denominator def validate_price(candidate, cost, fee_bps, margin_bps, ceiling): if any(type(v) is not int or v < 0 for v in (candidate, ceiling)): raise ValueError("invalid price") floor = minimum_price(cost, fee_bps, margin_bps) if floor > ceiling: return None return min(ceiling, max(floor, candidate)) def signed_bias(pairs): if not pairs: raise ValueError("empty observations") if any(not isfinite(pred) or not isfinite(ref) for pred, ref in pairs): raise ValueError("nonfinite observation") return sum(pred - ref for pred, ref in pairs) / len(pairs) assert minimum_price(8000, 500, 1500) == 10000 assert minimum_price(8001, 500, 1500) == 10002 assert minimum_price(0, 0, 0) == 0 assert validate_price(9000, 8000, 500, 1500, 12000) == 10000 assert validate_price(11000, 8000, 500, 1500, 12000) == 11000 assert validate_price(13000, 8000, 500, 1500, 12000) == 12000 assert validate_price(9000, 8000, 500, 1500, 9999) is None assert signed_bias([(90,100),(110,120)]) == -10 assert signed_bias([(90,100),(110,100)]) == 0 for fn in [lambda: minimum_price(100, 9000, 1000), lambda: validate_price(-1,8000,500,1500,12000), lambda: signed_bias([]), lambda: signed_bias([(float('nan'),100)])]: try: fn() except ValueError: pass else: raise AssertionError("invalid input accepted") print("13 checks passed")
Observed local execution output:
13 checks passedThe checks cover rounding, exact bounds, infeasible prices, signed residuals, empty observations, nonfinite observations and invalid constraints. The example treats the candidate as the final effective price and uses a simplified proportional fee without separate fee rounding. It is not an accounting engine, an automatic publication authority, or an empirical demand model.
Clamping a proposed price to the feasible interval is useful for a teaching example, but may change demand or customer-facing terms. In a real system, a clamped proposal may require re-optimization and approval. A zero-price promotion is an exceptional policy case; although the algebraic helper permits zero when cost is zero, a percentage margin at zero revenue is undefined and requires explicit handling in production.
The floor and interval functions take constant time in the number of inputs, ignoring arbitrary-precision arithmetic. The signed-bias function expects a nonempty reusable sequence of numeric prediction/reference pairs and takes O(n) time and O(1) additional memory. Its inputs must use consistent units. For monetary accounting, prefer integer minor units or a documented decimal arithmetic contract; statistical residual averages may be fractional.
12. Repair the decision, publication and checkout layers#
Even a correct model and cost calculation can produce a wrong effective price if the publication system accepts stale or incompatible writes.
A price decision should carry a unique decision ID, product/variant ID, currency, market, channel, intended effective time, input snapshot versions, model version, policy version and authorization context. Before committing it:
- Verify the product and currency match the authoritative catalog.
- Revalidate current costs, approved price bounds and all applicable discounts.
- Reject missing or unsupported information rather than silently replacing it with zero.
- Respect the effective-time schedule, overrides and current policy.
- Use a conditional version check so an older worker cannot overwrite a newer authorized price.
Store the effective-price update and its publication event transactionally where possible. Consumers should process the event idempotently, reject outdated versions and reconcile derived projections.
A checkout quote references the applicable price version and terms. A stale search projection is not the final authority for a new quote. If a price changes before an order is accepted, apply the documented quote policy and clearly communicate any required change. After acceptance, do not unilaterally alter the transaction merely because an algorithm generated an erroneous earlier price; follow authorized customer remediation and applicable obligations.
For promotions, maintain adjustment identities and funding sources. Check whether the same promotion is applied more than once, incompatible discounts combine, or a seller-funded and retailer-funded adjustment are accounted for incorrectly. Recalculate the effective contribution after the complete composition, including any applicable rounding.
13. Regression tests and invariants#
A good fix proves that the exact defect no longer occurs and protects adjacent failure cases.
| Test layer | Representative cases |
|---|---|
| Data contracts | Missing costs, wrong currency, duplicate SKU mappings, stale effective dates |
| Model parity | Identical inputs produce compatible offline and online transformations |
| Objective | Expected contribution and feasibility match an independently computed example |
| Price composition | Multiple valid and invalid promotion combinations, rounding, funding distinctions |
| Concurrency | Delayed jobs, duplicate events, conflicting overrides and version mismatch |
| Integration | Catalog, search, cart, quote and checkout remain consistent |
| Recovery | Kill switch, fallback, artifact rollback and projection reconciliation |
| Business impact | Authorized exceptions, conversion, contribution and customer outcomes |
Use property-based tests for invariants such as nonnegative valid amounts, no unauthorized below-floor price, correct currency, monotonic version application and deterministic replay under fixed artifacts. A valid exception must be represented explicitly rather than hidden by weakening the assertion.
Test time boundaries: midnight in market-local time, daylight-saving changes where relevant, promotion start/end, cost-feed updates and scheduled model release. Verify the implementation under realistic traffic and retry conditions.
14. Offline evaluation and controlled experimentation#
Fix deterministic correctness defects first. A missing cost, wrong currency conversion or unauthorized margin violation should not be left active merely to collect experimental evidence. Compare the repaired system against a compliant baseline.
Offline#
Use an untouched temporal holdout to evaluate observed model targets. Report signed bias, MAE, relevant quantile loss, calibration for demand probabilities and performance by affected versus unaffected cohorts. Include uncertainty and label maturity. Evaluate price-decision feasibility separately.
Replay actual historical decisions using preserved input snapshots. Compare previous and candidate outputs on the same products and dates. Count corrected violations, unresolved cases, changed promotion outcomes and prices requiring review.
Historical replay cannot observe what customers would have purchased at unoffered prices. Treat expected contribution computed from a demand model as an estimate, not realized improvement. Use sensitivity analysis over plausible demand response and costs.
Shadow and canary#
Run the repaired bundle without changing effective prices. Inspect its divergence from the approved baseline and verify the independent validator. Once the incident owner approves, enable a controlled canary for a small, representative, eligible product cohort with active guardrails. Increase exposure only when the predefined release criteria pass.
Controlled business experiment#
If uncertainty remains about the economic objective or demand model after correctness has been restored, use an approved randomized experiment. Select a randomization unit that avoids inconsistent prices and accounts for substitution across products; SKU or cluster assignment may be appropriate depending on interference. Define the primary metric, minimum detectable effect, experiment duration and analysis plan in advance.
Monitor contribution per eligible visitor or product opportunity, realized net contribution, conversion, cancellations, return rates, stock availability, customer complaints and relevant fairness outcomes. Analyze the full assigned population rather than only completed sales. An increase in margin per order can coexist with a decline in total contribution because fewer customers convert.
Never test a variant that knowingly violates hard price constraints or customer commitments. Do not coordinate prices with competitors, exploit sensitive personal characteristics or apply unjustified individualized price discrimination. Current pricing, competition, consumer-protection and tax obligations require appropriate jurisdiction-specific review.
15. Monitoring that detects recurrence#
Create monitors for separate failure layers rather than relying on a single average-price dashboard.
| Signal | What it detects | Response |
|---|---|---|
| Below-policy effective price count | Hard constraint breach | Stop affected automated publication and investigate |
| Missing or stale cost share | Broken feature contract | Degrade affected decisions safely |
| Prediction signed bias by cohort | Systematic model error | Investigate labels, drift and loss |
| Distribution and missingness changes | Data shift or upstream failure | Compare with business outcomes and source versions |
| Promotion composition discrepancies | Price adjustment defect | Quarantine affected configuration |
| Catalog versus quote version mismatch | Publication inconsistency | Reconcile and investigate stale consumers |
| Fallback frequency | Dependency degradation | Investigate operational availability |
| Realized contribution and conversion | Business outcome changes | Analyze cohort effects and causal evidence |
Use hard invariant alerts for unauthorized invalid prices and statistically justified monitoring windows for noisy model/business metrics. Tune alerts against representative historical variance and known seasonality; do not invent one universal alarm threshold.
Record metrics by version, currency, channel and relevant cohort. Trace incidents to an accountable owner. Avoid putting sensitive supplier prices, customer identifiers or commercial strategy details into broadly accessible logs.
16. Rollback and incident recovery lifecycle#
The rollback runbook should identify which artifacts are compatible, which decisions were committed, what the active policy permits and which derived projections require correction. If no compatible safe fallback exists, hold automated repricing and escalate to the authorized pricing owner.
Do not restore an outdated price automatically if the product's costs, promotions or policy have changed. Re-evaluate the fallback against current authoritative constraints. Reconcile accepted orders and customer impacts separately from future effective prices.
A post-incident review should establish a timeline from evidence, quantify known impact, identify the initiating failure and missing safeguards, and assign corrective actions with owners. Avoid declaring the cause to be model drift without proof. Track completion of fixes such as typed currency contracts, data-quality gates, independent margin validation, better trace retention and safe release controls.
17. Scalability and reliability considerations#
A large catalog can generate millions of pricing decisions, but it is unnecessary to recompute every SKU after every event. Group changed inputs by relevant catalog key, coalesce duplicate jobs and prioritize affected eligible items. Keep bulk replay workloads separate from live price lookup.
For example, a hypothetical 2 million SKU catalog with four scheduled decisions per day produces 8 million candidate decisions per day, about 93 per second on average before event-driven refreshes. At a fivefold illustrative peak, this is about 463 per second. A 500-byte trace per decision would create about 4 GB per day before storage overhead. Benchmark actual volumes, promotion fan-out and incident-replay demand.
Partition decision workloads by compatible product and market keys. Preserve the authority and version semantics of cost feeds, price constraints and promotions. Use bounded retries, idempotency, transactional outbox or equivalent reliable publication, and monitored dead-letter handling.
| Failure mode | Safe behavior |
|---|---|
| Cost data unavailable | Abstain or use an explicitly approved compatible price |
| Inference fails | Retain a currently valid authorized baseline |
| No feasible interval | Return an explicit conflict for review |
| Stale decision arrives | Reject the write and recompute from current inputs |
| Validator unavailable | Suspend affected automated price publication |
| Derived cache fails to refresh | Reconcile from authoritative effective price and quote policy |
| Financial reporting delayed | Preserve traceability and distinguish estimated from realized impact |
Cost optimization should not remove validation or audit evidence needed for safe prices. Use lightweight deterministic checks on every applicable final decision; reserve expensive model replay and broad business evaluation for asynchronous workloads.
18. Worked incident scenario#
Assume a fictional retailer observes a sudden rise in below-margin decisions following a new cost-feed integration. Several products are affected, while their model version and raw prediction logic remain unchanged.
For one synthetic product, the old cost was $60 and the current authorized cost is $80. The candidate price is $90. With the simplified fee and required margin in section 10, the old minimum was $75, while the correct minimum is $100. The candidate appears valid when evaluated using the obsolete cost but violates the current policy.
The incident team reproduces the erroneous decision from its historical trace and confirms that the feature store served a stale cost version. Correcting the cost snapshot causes the independent validator to reject or revise the $90 proposal under the approved policy. Restoring older model weights alone does not resolve the bug.
The repair is to fix ingestion and freshness, require compatible cost versions at publication, add regression cases for cost changes, reconcile affected catalog entries and validate the recovered prices against current constraints. Only after this technical correction should a business experiment examine whether a different feasible price improves contribution.
This scenario illustrates a verified-by-construction hypothetical root cause, not an investigation of a real retailer. In a genuine incident, alternative hypotheses would remain open until the evidence establishes the cause.
19. Interview follow-ups and common mistakes#
Should I immediately increase all prices by 10%? No. First establish which prices violate policy or are economically suboptimal. Blanket adjustments can overprice healthy products and leave the true defect intact.
Should I retrain using higher historical prices? Not without determining whether the target, data and objective are correct. Reproducing historical prices is not the same as optimizing contribution.
How can I prove the model is responsible? Compare exact decision traces, reproduce the defect, substitute corrected components under controlled replay and validate on unaffected products. If the raw model prediction is reasonable but checkout differs, investigate downstream layers.
What if the model has negative signed bias but no margin violations? Investigate target semantics and cohort-level residuals; a systematic forecast error is relevant, but it does not establish that every final price should be higher.
Why separate hard constraints from training loss? Statistical predictions can be wrong or unsupported. The final validator provides deterministic enforcement of approved feasibility conditions even when the model fails.
What if higher prices reduce sales? Evaluate total contribution and customer outcomes, not just price or margin per unit. Estimate demand response with appropriate causal evidence.
What if rollback does not fix the live site? Reconcile the effective price store, derived catalog projections, caches and quotes. A model rollback changes future inference, not every previously published state.
20. Concise interview-ready answer#
I would start by identifying whether underpricing means a margin violation, a model prediction bias, a poor economic decision or a publication defect. I would contain any unsafe automated pricing, preserve affected decision traces and quantify realized impact separately from estimated opportunity cost.
Next I would replay representative decisions with their original cost, inventory, promotion, model and policy versions. I would compare intermediate outputs to find the first incorrect layer, checking stale or missing costs, currency units, feature drift, training-serving skew, leakage, biased labels, optimization objectives and downstream price composition. I would correct the demonstrated root cause rather than blindly increasing all prices.
I would enforce an independent final effective-price validator, with exact monetary arithmetic, approved margin and price constraints, version-aware publication and an explicit no-feasible-price result. I would add regression and integration tests, evaluate on temporal holdouts, shadow the corrected bundle, deploy through a guarded canary and use controlled experimentation only for unresolved economic questions within approved constraints.
Finally I would reconcile published prices and affected transactions, monitor both invariants and realized contribution, and maintain a tested rollback and fallback runbook. The distinguishing principle is that fixing production underpricing requires evidence across the full decision lifecycle, not merely a better regression model.
References and research transparency#
The authorized offline research exception was applied. The references below support established ML engineering, forecasting, causal evaluation, incident management and transaction-consistency practices. Their current contents and availability could not be live-verified; the current Supabase changelog was also unavailable. The three Mermaid diagrams are supplied in standard fenced Mermaid syntax and reviewed structurally, but parser execution and live website rendering were not verified. The Python example was executed locally with all 13 checks passing. Numerical examples are synthetic, and no empirical improvement or retailer-specific implementation is claimed.
- Google — Rules of Machine Learning: Best Practices for ML Engineering
- Google SRE Workbook — Incident Response
- Google SRE Workbook — Canarying Releases
- Sculley et al. — Hidden Technical Debt in Machine Learning Systems
- Breck et al. — The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction
- Hyndman and Athanasopoulos — Forecasting: Principles and Practice
- scikit-learn — Common Pitfalls and Recommended Practices
- scikit-learn — Model Evaluation
- Kohavi, Tang and Xu — Trustworthy Online Controlled Experiments
- Hernán and Robins — Causal Inference: What If
- PostgreSQL — Transaction Isolation
References
- 1.Google — Rules of Machine Learning: Best Practices for ML Engineeringdevelopers.google.com
- 2.Google SRE Workbook — Incident Responsesre.google
- 3.Google SRE Workbook — Canarying Releasessre.google
- 4.
- 5.
- 6.
- 7.scikit-learn — Common Pitfalls and Recommended Practicesscikit-learn.org
- 8.scikit-learn — Model Evaluationscikit-learn.org
- 9.
- 10.Hernán and Robins — Causal Inference: What Ifhsph.harvard.edu
- 11.PostgreSQL — Transaction Isolationpostgresql.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython