E-Commerce Landing-Page Module Ranking System

Medium · ML System Design · Applied Scientist · Onsite

Prompt

A large online home-and-lifestyle marketplace assembles its main landing page from stacked horizontal carousels ("modules") rather than one flat SKU feed — for example, blocks like "Autumn Kitchen Event", "Fast-Rising Decor", "Resume Browsing: Modular Sofas", and vendor-sponsored showcases.

Architect the end-to-end machine-learning and real-time serving platform that chooses which modules appear and orders them vertically for each visit. Anchor your design in marketplace economics and product trade-offs first, then walk through training signals, model architecture, page construction, and production serving.

Because vertical slot counts, eligibility rules, and mathematical objectives are intentionally open, declare concrete working assumptions up front and keep page-level module ordering distinct from intra-module SKU ranking. Make sure your assumptions address which shopper behaviors and financial metrics govern success, how pinned banners or vendor-guaranteed impression commitments share the screen with algorithmic picks, what recency SLAs and calendar cutoffs govern fast-moving trend shelves versus fixed-date promotional events, and how the page avoids repeating identical items across multiple blocks.

Scope & Expectations

  • Business objective & system boundary: Define a north-star financial objective with guardrail metrics, explain why naive engagement targets distort merchandising mix, and cleanly separate module selection from within-module product ranking.
  • Eligibility, freshness, and merchandising rules: Specify how campaign start/end windows, near-real-time trend refresh, contractual vendor pacing, and cross-carousel SKU deduplication work together.
  • Predictive modeling, cold start, and slate assembly: Detail label construction, viewport and position-bias correction, multi-task value estimation, diversity-aware greedy slate building, and exploration for cold visitors or newly launched seasonal events.
  • Low-latency serving & causal measurement: Present the online serving latency budget, fallback behavior during dependency outages, unbiased offline replay, and site-wide A/B experimentation.

Step-by-step walkthrough

  1. Clarify the goal, scope, and business rules

    Think of an e-commerce homepage as the front display window of a large home-goods store. Most shoppers only see the first two or three horizontal shelves before deciding whether to scroll, search, or leave. Because attention drops sharply down the page, the order of homepage modules steers traffic and profit between product categories, between full-price goods and clearance sales, and between the retailer's own margins and promised vendor placements.

    Separate the two ranking problems

    • Module ranking (this system): choosing which content blocks appear on the landing page and in which vertical slot (for example, Slot 1: "Autumn Kitchen Event", Slot 2: "Resume Browsing: Modular Sofas", Slot 3: "Fast-Rising Decor").
    • Item ranking inside a module: choosing which 8–20 individual products fill a single module. We assume an item ranker already exists. Rather than merging both into one giant model, the module ranker queries each eligible module's top items for the current visitor and summarizes their quality as input features — because "Autumn Kitchen Event" is only valuable to this visitor if the specific sale items inside it match their taste and budget.

    Explicit working assumptions

    • Target business & shopper metrics: Our primary north-star metric is contribution margin per visitor over 7 days — the money the marketplace actually keeps from orders after subtracting wholesale product cost, shipping subsidies, payment processing fees, and expected return costs. Secondary metrics are orders per visitor, add-to-cart rate, and wishlist saves. Guardrail metrics (metrics that must not degrade) are bounce rate, order return rate, page latency, and 28-day repeat visits. Raw clicks are a fast learning signal, not the business goal.
    • Pinned & vendor-contracted placements: Yes, three types coexist with ranked slots: (1) site-wide event banners pinned to Slot 1 during flagship campaigns, (2) vendor-funded showcases contracted for a target number of viewed impressions per day within Slots 2–5, and (3) urgent legal or fulfillment notices. All remaining slots are algorithmically ranked.
    • Recency windows & campaign cutoffs: "Fast-Rising" trend activity is aggregated over a rolling 2-hour decay window and refreshed every 5 minutes. Dated seasonal and promotional modules enforce exact start and end timestamps in the shopper's or campaign's local time zone. Item prices and in-stock status are verified at render time so a shopper never clicks an expired discount or sold-out sofa.
    • Cross-carousel SKU overlap: A discounted ceramic Dutch oven can legitimately qualify for both "Fast-Rising Decor" and "Autumn Kitchen Event". We handle overlap at two levels: penalizing candidate modules whose top items heavily overlap during page assembly, and stripping duplicate items top-down before rendering.
    • Page geometry & candidate scale: 8 module slots on mobile (~1.5 visible above the fold without scrolling) and 10 on desktop (~3 visible). A central registry holds ~200 curated module definitions, of which 30–50 pass hard eligibility filters on a typical request.

    Non-functional requirements

    • Latency & throughput: Module ranking p99 latency <= 80 ms within the overall homepage render budget, provisioned for 1,500 requests/second (~2x daily peak).
    • Reliability: Graceful fallback to a precomputed segment layout if feature stores or scoring services time out — the homepage must never fail to load.
  2. Back-of-the-envelope capacity and sparsity math

    Before choosing models, check compute load, data volume, and how fast a brand-new module accumulates statistical evidence.

    Traffic & impressions (assumed for a large home-goods retailer)
      Homepage views:                 20M / day  -> ~230 req/s avg, ~700 req/s peak (size for 1,500 req/s)
      Module registry:                ~200 definitions -> 30 to 50 eligible after rules per request
      Avg modules viewed per visit:   ~4 slots (due to scroll drop-off) -> 80M viewed impressions / day
    
    Funnel conversion rates (per viewed module impression)
      Click-through rate (CTR):       3.0%       -> 2.4M module clicks / day
      7-day purchase given click:     2.0%       -> ~48,000 attributed orders / day
      7-day purchase given seen:      3% x 2% = 0.06% (purchases are 50x sparser than clicks!)
    
    Serving compute
      50 candidates x 1,500 req/s   = 75,000 module evaluations / second at 2x peak
      Tree model at ~20 microseconds = 1.5 CPU cores total across the fleet
      -> Scoring arithmetic is cheap; latency is dominated by parallel network fetches for features.
    
    Logging & training storage
      ~2 KB per page (slots, items, scores, exploration weights) x 20M/day = ~40 GB / day
      28-day training window: 80M/day x 28 = 2.24B viewed rows (keep 100% of clicks, sample 10% of non-clicks)
    

    Why sample-size math shapes the cold-start design

    To estimate a conversion probability p within a ±10% relative margin of error (e = 0.10 × p) at 95% confidence, standard binomial sample-size math requires n ≈ 1.96² × p × (1 − p) / e² viewed impressions:

    • For a 3% click rate (p = 0.03, e = 0.003): n ≈ 3.8416 × 0.03 × 0.97 / 0.000009 ≈ 12,400 viewed impressions.
    • For a 0.06% purchase rate (p = 0.0006, e = 0.00006): n ≈ 3.8416 × 0.0006 × 0.9994 / 0.0000000036 ≈ 640,000 viewed impressions.

    If a new holiday module is viewed on 1% of daily homepage visits (200,000 viewed impressions/day, or ~8,300/hour), learning its click rate takes ~1.5 hours, whereas learning its purchase rate directly takes ~3.2 days — almost an entire 4-day holiday weekend! That 50x sparsity gap is why we decompose the prediction into separate click and conversion stages and rely on early proxies like add-to-cart for new modules.

  3. Frame the ML objective, labels, and position bias

    Decomposed business value per viewed impression

    For each candidate module m and visitor context x, the scorer predicts the expected dollar value generated if the visitor actually views that module:

    v(x, m) = P(click | seen, x, m) x [ a + P(purchase in 7d | click, x, m) x E(margin | purchase, x, m) ]
    
    • P(click | seen, x, m): probability the visitor clicks into the module (either a product card or "See all"), given it was visible on screen.
    • P(purchase in 7d | click, x, m): probability that a click leads to an order within 7 days (home-goods shoppers often measure rooms and compare options for days before buying).
    • E(margin | purchase, x, m): expected dollar contribution margin of that order, net of shipping and category-specific return costs.
    • a: a small, experiment-tuned dollar reward per click (for example, $0.05–$0.15) representing discovery value such as saving items for later visits.

    Compare two modules for a shopper who has been browsing modular sofas:

    Module A ("Clearance Throw Pillows: 70% Off", low stock):
      P(click | seen) = 0.06,  P(purchase | click) = 0.005,  E(margin) = $15,  a = $0.08
      v(A) = 0.06 x [ $0.08 + 0.005 x $15 ] = 0.06 x $0.155 = $0.0093 per seen view
    
    Module B ("Resume Browsing: Modular Sofas", matched to visitor):
      P(click | seen) = 0.025, P(purchase | click) = 0.025,  E(margin) = $90,  a = $0.08
      v(B) = 0.025 x [ $0.08 + 0.025 x $90 ] = 0.025 x $2.33  = $0.0583 per seen view
    

    A click-only ranker puts Module A on top (6.0% > 2.5%); our value formula ranks Module B more than 6x higher because its clicks actually convert into high-margin orders.

    Clean training labels and viewability

    • Viewability filter (seen): Using client viewport events, a module impression only enters training if at least 50% of its height stayed on screen for at least 1 second. Modules in Slot 7 that a shopper never scrolled down to were never evaluated by the shopper — treating them as negative examples would unfairly punish lower-ranked modules.
    • Attribution & immature margin: If a shopper clicks two modules before buying an item within 7 days, split purchase credit equally (0.5 each). Until the 30-day return window closes, estimate margin as item_price - wholesale_cost - shipping - category_return_rate × avg_return_cost.

    Correcting position bias

    Even among seen modules, Slot 1 gets higher click rates than Slot 5 because shoppers have fresher attention at the top of the page. This effect is called position bias (items ranked higher receive extra engagement purely from their screen position rather than their true appeal). Left uncorrected, a model creates a rich-get-richer feedback loop favoring past winners. We apply two complementary fixes:

    1. Position as a training feature, neutralized at serving: Include slot_index (and device) as an input feature during training so the model absorbs the slot boost, then set slot_index = 1 for every candidate at serving time so all 50 modules are compared on equal footing.
    2. Measured examination curve e(k): Measure e(k) — the probability that a visitor views Slot k — from client viewability logs and our randomized exploration slice, then use e(k) when assembling the full slate.
  4. API and data model

    Serving and event APIs

    POST /v1/homepage/layout
      Request:  { visitor_id, user_id (nullable), device, locale, region, timestamp,
                  referrer_campaign, session_item_ids: [...] }
      Response: { layout_id,
                  modules: [ { slot, module_id, title, item_ids: [...],
                               reason: "ranked" | "pinned" | "contract" | "explore" } ] }
    
    POST /v1/homepage/events
      Request:  { layout_id, module_id, slot, event_type: "seen" | "click" | "add_to_cart",
                  item_id (nullable), timestamp }
    

    Core storage schemas

    module_definition (module_id PK, module_type, title, item_query_rule, start_at, end_at,
                       time_zone, allowed_regions, min_items, pinned_slot, contract_id, enabled)
    
    vendor_contract   (contract_id PK, module_id, target_viewed_per_day, contract_slots,
                       current_boost_beta, start_date, end_date)
    
    layout_log        (layout_id PK, visitor_id, ts, context_json, is_explore_slice,
                       rendered_slots: [ { slot, module_id, item_ids, predicted_value } ],
                       explore_candidates: [ { module_id, sampling_weight } ])
    
    module_event      (layout_id, module_id, slot, event_type, item_id, ts)
    
    module_stats_5m   (module_id, slot, bucket_5m, seen_count, click_count, cart_count)
    

    Why log explore_candidates with their sampling_weight on the 5% exploration traffic? Offline evaluation needs the propensity — the probability that the logging policy placed module m in slot k. Logging the 30–50 candidate weights (~200 bytes per exploration page, ~200 MB/day) lets offline batch jobs compute exact or Monte Carlo slot propensities without adding latency to live requests or trying to reconstruct historical feature states later.

  5. High-level architecture

                                     Homepage Request
                                            |
                                            v
     +------------------+     +---------------------------+     +-----------------------------+
     | Module Registry  |---->| 1. Eligibility Filter     |---->| 2. Parallel Item Summaries  |
     | (~200 defs,      |     | time window + time zone,  |     | top items & scores per mod  |
     | in-memory cache) |     | region, kill switches     |     | (cached 5m per mod+segment) |
     +------------------+     +---------------------------+     +--------------+--------------+
                                                                               | (30-50 eligible)
     +------------------+                                                      v
     | Feature Store    |---------------------------------------------> +--------------+
     | visitor (batch + |                                               | 3. Multi-Task|
     | session stream); |                                               | Module Scorer|
     | module (5m stats)|                                               +------+-------+
     +--------^---------+                                                      | v(x, m)
              |                                                                v
     +--------+-------------+                                    +----------------------------+
     | Streaming Jobs       |                                    | 4. Rule-Aware Assembler    |
     | - 5m trending items  |                                    | pins, contract boosts,     |---> Layout
     | - 5m module CTR/cart |                                    | diversity, item dedup,     |     + Async
     | - live session views |                                    | 5% softmax explore         |     Log
     +--------^-------------+                                    +----------------------------+
              |
       Client Events + Orders (Kafka) ---> Daily Offline Pipeline: 7-day label join -> GBDT / Multi-Task
                                           train -> isotonic calibration -> IPS eval -> canary -> A/B
    

    End-to-end request flow (< 80 ms p99)

    1. Eligibility filter (~2 ms): Drop inactive, out-of-region, or out-of-window holiday modules from ~200 definitions down to 30–50 candidates.
    2. Parallel feature + item-summary fetch (~30 ms): Fetch visitor batch/session features while querying cached segment top-50 item lists for each candidate module, lightweight-reranking them for the visitor to compute top-4 item quality summaries and verify live stock/prices.
    3. Multi-task scoring (~5 ms): Predict calibrated P(click | seen), P(purchase | click), and E(margin), combining them into v(x, m).
    4. Page assembly (~3 ms): Place pins, apply contract boosts, greedily select diverse modules, deduplicate repeated products top-down, and emit async layout_log events.
  6. Features, multi-task scoring, and probability calibration

    Feature engineering across four groups

    Visitor features          is_new_visitor, logged_in, days_since_last_visit, 30d/365d category
                              affinities, historical price tier, open_cart_categories, in-session views
    Module features           module_type (trending, holiday_sale, personalized, editorial), age_hours,
                              hours_until_expiry, avg_discount_pct, stock_ratio, smoothed CTR & CVR
    Visitor x Module cross    cosine similarity between visitor & module category vectors; visitor's
                              past CTR on this module_type; Item-Ranker Summary: mean P(purchase) and
                              mean expected margin of the top 4 items this visitor would see inside m
    Context features          device, region (climate/season), hour, days_to_holiday, referrer_campaign,
                              slot_index (real slot during training; fixed to 1 at serving)
    

    The Visitor × Module item-ranker summary is the bridge between the two ranking layers: if a shopper only browses cast-iron cookware and "Autumn Kitchen Event" has strong Dutch ovens in stock at high margin, its top-4 summary immediately signals high value even if the module launched 10 minutes ago.

    Model progression

    • Phase 1 — Gradient-Boosted Decision Trees (GBDTs): Train separate GBDT models — ensembles of shallow decision trees built sequentially so each tree corrects the residual errors of earlier trees — for P(click | seen), P(add_to_cart | click), P(purchase_7d | click), and E(margin | purchase). GBDTs handle missing values (crucial for new visitors), mixed numeric/categorical features, and CPU serving in ~5 ms with zero GPU infrastructure.
    • Phase 2 — Multi-task neural network: Once learned embeddings of browsing sequences and product catalogs show offline lift, move to a shared-bottom multi-tower network predicting all heads jointly so the sparse purchase head shares representations learned from the 50x denser click head.

    Why strict probability calibration is mandatory

    In single-objective ranking, only relative score order matters (0.40 > 0.20 behaves the same as 0.04 > 0.02). Here, we multiply P(click) by P(purchase | click) and add dollar click value a plus contract boosts β. If P(click) is 2x too high on clearance modules, it distorts every downstream dollar trade-off. This requirement is calibration — ensuring that among impressions given a 3.0% predicted probability, close to 3.0% actually click.

    1. Undo negative downsampling first: Because training keeps 100% of clicks and samples w = 0.10 of non-clicks, raw model probabilities p_raw overstate true rates. Convert back analytically: p_unbiased = p_raw / (p_raw + (1 - p_raw) / w).
    2. Fit isotonic regression: On a held-out day after the training window, fit isotonic regression — a lightweight non-parametric monotonic step function that maps p_unbiased to empirical rates — separately per head, and verify calibration per module_type.
  7. Deep dive 1: Rule-aware greedy page assembly and contract pricing

    Suppose our mobile homepage has 8 slots with the following measured examination curve e(k) (probability the visitor scrolls far enough to view slot k):

    Slot k (1-indexed):   1      2      3      4      5      6      7      8
    Examination e(k):   1.00   0.70   0.52   0.40   0.31   0.25   0.20   0.16
    

    If modules were completely independent, total expected page value would be sum_k e(k) × v(m_k), and sorting modules from highest v to lowest v would be mathematically optimal (pairing the largest values with the largest weights). Four real-world constraints break independence:

    1. Pinned modules: Site-wide event banners lock into their required slot (pinned_slot = 0 for Slot 1) before anything else is ranked.
    2. Vendor contracts as paced boosts (plus true opportunity cost): Suppose a lighting brand pays for 300,000 viewed impressions/day across Slots 2–5 (0-indexed 1..4). Hard-pinning it to Slot 2 wastes top real estate once it hits 300k. Instead, add a dollar boost β ≥ 0 to its value only when evaluated for Slots 2–5, adjusting β every 15 minutes (up if cumulative viewed impressions trail the daily target curve, down if ahead). To tell the business what the contract truly cost in lost organic margin, run assemble_page twice per request — once with use_contract_boosts=True and once with False — and evaluate both resulting slates using unboosted e(k) × v(m_k). Simply comparing v(displaced) − v(contract) gets the math wrong because inserting a contract module at Slot 2 pushes every module below it down to a lower-visibility slot! Running the second greedy pass takes < 1 ms.
    3. Diversity via Jaccard penalty and merchandising caps: Two patio-sale modules on the same screen cannibalize each other. At each open slot from top to bottom, penalize candidate m by λ × max_similarity(m, already_placed), where similarity is the Jaccard similarity of their top-20 items — the number of shared items divided by the total unique items across both sets (|A ∩ B| / |A ∪ B|). Also enforce hard layout rules: no two adjacent modules of the same module_type, and at most 2 "sale" modules in the top 4 slots.
    4. Top-down item deduplication: Once the module order is chosen, populate each module's displayed items from Slot 1 downward, skipping any item_id already shown in a higher module and backfilling from that module's ranked list. Drop and shift up if backfill leaves fewer than min_items (say, 4 items).
    def assemble_page(candidates, num_slots, pinned, diversity_weight, max_sales_in_top4, use_boosts=True):
        """Build an ordered homepage layout of length num_slots.
    
        candidates: dict mapping module_id -> {
            "value": float,               # intrinsic expected $ per seen view
            "type": str,                  # e.g. "sale", "trending", "personalized"
            "top_items": set[str],        # top 20 item_ids for Jaccard overlap check
            "allowed_slots": set[int] | None,   # optional hard slot restriction
            "contract_slots": set[int],   # slots where vendor impression contract applies
            "contract_boost": float,      # paced boost beta ($ per seen view)
        }
        pinned: dict mapping 0-based slot_index -> module_id.
        """
        # Phase 1: lock mandatory pinned modules into their designated slots first.
        page = [None] * num_slots
        used_modules = set()
        for slot_idx, module_id in pinned.items():
            page[slot_idx] = module_id
            used_modules.add(module_id)
    
        # Phase 2: fill remaining open slots greedily from top (highest attention) to bottom.
        for slot_idx in range(num_slots):
            if page[slot_idx] is not None:
                continue
    
            best_module_id = None
            best_adjusted_score = float("-inf")
    
            for module_id, module in candidates.items():
                if module_id in used_modules:
                    continue
                if not is_allowed_in_slot(page, slot_idx, module, candidates, max_sales_in_top4):
                    continue
    
                # Apply vendor pacing boost only if this slot counts toward the contract.
                effective_value = module["value"]
                if use_boosts and slot_idx in module.get("contract_slots", set()):
                    effective_value += module.get("contract_boost", 0.0)
    
                # Subtract penalty proportional to worst item overlap with already-placed modules.
                overlap_penalty = diversity_weight * max_jaccard_overlap(module, page, candidates)
                adjusted_score = effective_value - overlap_penalty
    
                if adjusted_score > best_adjusted_score:
                    best_adjusted_score = adjusted_score
                    best_module_id = module_id
    
            # Use 'continue' (not 'break') so an unfillable constrained slot near a pin
            # does not leave lower unconstrained slots empty.
            if best_module_id is None:
                continue
    
            page[slot_idx] = best_module_id
            used_modules.add(best_module_id)
    
        return page
    
    
    def max_jaccard_overlap(module, page, candidates):
        """Return maximum item-set Jaccard similarity |A & B| / |A | B| against placed modules."""
        worst_overlap = 0.0
        items_a = module["top_items"]
        for placed_id in page:
            if placed_id is None:
                continue
            items_b = candidates[placed_id]["top_items"]
            union_size = len(items_a | items_b)
            if union_size > 0:
                jaccard = len(items_a & items_b) / union_size
                worst_overlap = max(worst_overlap, jaccard)
        return worst_overlap
    
    
    def is_allowed_in_slot(page, slot_idx, module, candidates, max_sales_in_top4):
        """Check hard merchandising rules: slot restrictions, adjacent types, and top-4 sale cap."""
        allowed_slots = module.get("allowed_slots")
        if allowed_slots is not None and slot_idx not in allowed_slots:
            return False
    
        # Check both neighbors because slot_idx + 1 may already hold a pre-placed pinned module.
        for neighbor_idx in (slot_idx - 1, slot_idx + 1):
            if 0 <= neighbor_idx < len(page) and page[neighbor_idx] is not None:
                neighbor_type = candidates[page[neighbor_idx]]["type"]
                if neighbor_type == module["type"]:
                    return False
    
        # Prevent promo fatigue: cap total "sale" modules in the top 4 slots (indexes 0..3).
        if module["type"] == "sale" and slot_idx < 4:
            sales_in_top4 = sum(
                1 for placed_id in page[:4]
                if placed_id is not None and candidates[placed_id]["type"] == "sale"
            )
            if sales_in_top4 >= max_sales_in_top4:
                return False
    
        return True
    

    Why not train an end-to-end slate model that scores entire 8-module permutations directly? Choosing 8 ordered modules out of 40 candidates yields 40 × 39 × … × 33 ≈ 3.1 × 10¹² possible pages, so historical logs cover practically zero exact combinations and merchandising rules change weekly. Greedy marginal-relevance assembly runs in microseconds, respects hard business rules immediately, and captures almost all of the theoretical optimum.

  8. Deep dive 2: Cold-start seasonal modules, new visitors, and exploration

    Evaluating and launching a brand-new 4-day seasonal event

    An "Autumn Kitchen Event" runs for 96 hours and generates peak demand on Day 1. We cannot wait 3 days for purchase labels.

    1. Zero-history content features + smoothed priors: On minute zero, the module already has strong non-historical features: module_type, discount depth, category mix, days to campaign end, and the item-ranker summary of the specific discounted products each visitor would see inside it. Historical rate features use empirical Bayes smoothing — blending observed clicks with a prior rate r_prior from last year's equivalent seasonal module: smoothed_ctr = (clicks + k × r_prior) / (seen + k) with k = 5,000, smoothly shifting weight from the prior to real data as impressions arrive.
    2. 5% softmax exploration slice: On 5% of returning-visitor traffic, fill non-pinned Slots 1–4 by sampling without replacement proportional to exp(adjusted_score / τ) (softmax sampling, which favors strong modules while giving plausible runners-up real exposure), enforcing a minimum probability floor for modules under 72 hours old.
    3. Thompson sampling on the main 95% traffic: For modules younger than 72 hours, replace the deterministic smoothed_ctr feature with a random draw per request from a Beta distribution — a probability curve on [0, 1] shaped by pseudo-clicks and pseudo-non-clicks: Beta(k0 × r_prior + clicks, k0 × (1 − r_prior) + seen − clicks) updated every 5 minutes. Crucially, use a much weaker prior weight k0 = 200 here than k = 5,000: at r_prior = 3%, k0 = 5,000 has standard deviation sqrt(0.03 × 0.97 / 5001) ≈ 0.24 percentage points (too narrow to explore), whereas k0 = 200 gives ≈ 1.20 percentage points (±40% relative spread), letting a promising new seasonal module occasionally leap into Slots 1–2, gather its 12,400 views within a couple of hours, and quickly converge to its true performance.
    4. In-session purchase proxies: Because 7-day purchase conversion takes days to accumulate and mature, blend add_to_cart and wishlist-save rates (observed within minutes) into a short-term multiplier calibrated on past seasonal events.

    Ranking for a brand-new visitor (~33% of landing-page traffic)

    • Exploit request context, especially acquisition intent: A first-time visitor still carries device, region (climate/season: patio heaters vs snow blowers), local timestamp, and referrer_campaign. Someone arriving from a search ad or social campaign for "modular linen sofas" immediately gets living-room and modular-sofa modules boosted.
    • Train natively with missing-history flags: Include is_new_visitor = 1 and null-history indicators directly in GBDT training rather than maintaining a brittle hand-curated static page.
    • Intra-session adaptation & conservative exploration: As soon as the visitor clicks 1–2 products, stream those categories into session features so modules lazy-loaded further down the scroll (or on a return to the homepage seconds later) personalize immediately. Exclude first-time visitors from aggressive exploration because a poor first impression risks permanent bounce.

    Seasonal eligibility is a hard rule, never a soft model score: Showing "Christmas Shipping Guaranteed" on December 26 destroys user trust regardless of its historical CTR. Enforce start_at ≤ now < end_at in the module's configured time zone on every request, and cap any segment-level layout cache TTL at the next upcoming module boundary.

  9. Deep dive 3: Unbiased offline evaluation and online A/B testing

    Offline evaluation without logging bias

    First evaluate individual heads on a post-training week: calibration curves per module_type and within-page AUC (whether the model orders candidate modules for the same visitor accurately, avoiding global AUC inflation caused by easy differences between heavy clickers and bouncers).

    To compare two full page-assembly policies offline (for example, tuning diversity weight λ), naively re-scoring historical pages favors whatever the old ranker showed in Slot 1. Instead, evaluate on the 5% exploration slice using inverse propensity scoring (IPS) — dividing each observed reward by the probability p_i(k) that the logging policy placed that module in Slot k, so rarely shown candidates count proportionally when matched:

    IPS_value(slot k) = (1 / N) x sum over exploration pages i of:
                          reward_{i, k} x I(new_policy_slot_k(i) == logged_slot_k(i)) / p_i(k)
    
    Estimated 4-slot page value = sum_{k=1..4} IPS_value(slot k)
    

    Notice two critical subtleties:

    1. Do not multiply IPS_value(slot k) by e(k): The logged reward_{i, k} (0 whenever the visitor never scrolled to Slot k) already incorporates real-world viewability at Slot k.
    2. Compute marginal slot propensities p_i(k) offline, never on the live request path: For Slots 2–4, p_i(k) is the marginal probability that module m landed in Slot k across all possible prefixes in Slots 1..k-1. Enumerating 50 × 49 × 48 = 117,600 prefixes during live serving would blow our 80 ms latency budget! Because we logged the 30–50 explore_candidates weights (~200 bytes), our offline evaluation job runs 10,000 fast Monte Carlo Plackett-Luce draws per exploration page in batch, getting accurate marginal propensities (clipped at e.g. p_i(k) ≥ 0.01 to cap variance) at zero serving cost.

    Online A/B experiment design

    • Randomization unit: Visitor (account_id if logged in, stitched to visitor_id cookie), never page view — a shopper visits multiple times before checking out.
    • Measure site-wide margin, not homepage-attributed margin: A flashier homepage might merely cannibalize orders that the shopper would otherwise have placed via the search bar 10 seconds later. Only total site-wide contribution margin per visitor proves true incremental lift.
    • Sample size & variance reduction: Detecting a 1% relative lift on a 3% baseline visitor conversion rate (δ = 0.0003, 80% power, 5% two-sided test) requires n ≈ 16 × 0.03 × 0.97 / 0.0003² ≈ 5.2M visitors per arm. Dollar margin per visitor is roughly twice as noisy (~10.5M visitors per arm) because order margins vary widely on top of the 97% zero-purchase rate. Apply CUPED (Controlled-experiment Using Pre-Experiment Data — subtracting each returning visitor's pre-experiment baseline margin scaled by a regression weight to cancel persistent big-spender noise) and winsorize (cap) extreme commercial B2B bulk orders to cut required runtime to 2–3 full weeks. Maintain a permanent 1–2% holdout on the baseline policy to track seasonal drift across holiday vs non-holiday months.
  10. Serving latency, monitoring, failure fallbacks, and trade-off summary

    End-to-end p99 latency budget (80 ms ceiling)

    Component                                         p99 Budget   Notes
    ------------------------------------------------  ----------   -----------------------------------------
    Fetch visitor features (batch + session stream)       10 ms    Low-latency key-value store (Redis/Aerospike)
    Module eligibility check (~200 defs)                   2 ms    In-memory registry refreshed every 60 s
    Parallel item-ranker summaries + stock check          30 ms    Top-50 cached 5m per mod+segment; live stock
    Multi-task scoring (up to 50 candidates)               5 ms    Vectorized CPU batch per request
    Greedy page assembly + counterfactual + dedup          3 ms    Two greedy passes (< 1 ms each) + item dedup
    Network overhead & safety slack                       30 ms    absorbs GC pauses and tail jitter
    Total                                                 80 ms
    

    Anonymous first-time visitors arriving without a specific ad campaign share a short-lived (2-minute) layout cache keyed by (device, region), logged with propensities and capped at the next holiday boundary — shedding up to 25% of peak traffic during flash-sale surges.

    Production monitoring and graceful degradation

    • Monitors & alerts: Calibration ratio (predicted / observed CTR and CVR per module type and slot), vendor contract delivery vs 15-minute plan, fallback page rate, feature-stream lag, and a zero-tolerance alert if even a single expired holiday module renders past end_at.
    • Failure modes:
      • Feature store or scorer timeout (> 45 ms): Serve a precomputed segment layout (device × region × is_new_visitor, rebuilt every 10 minutes), still filtering eligibility and applying pins live.
      • Trending stream lag (> 30 minutes): Automatically suppress "Trending Now" rather than calling stale products trending.
      • Bad creative or pricing bug in a module: Per-module kill switch in the registry takes effect across all servers within 60 seconds.

    Summary of core architectural trade-offs

    • Two decoupled rankers bridged by top-4 item summaries reuses the existing item ranker and keeps candidate count at 30–50 instead of millions, trading away minor cross-layer interactions.
    • Expected 7-day margin + calibrated click bonus aligns ranking with true retail profitability despite 50x purchase sparsity and delayed returns.
    • Greedy diversity-penalized assembly + paced contract boosts gives merchandisers hard guardrails and exact dollar contract cost accounting without intractable 3.1 × 10¹² slate combinatorics.
    • 5% softmax exploration + weak-prior (k0 = 200) Thompson sampling learns new holiday sales in hours and enables unbiased offline IPS evaluation while protecting 95% of traffic.

Intuition & how it works

Imagine arranging the themed display tables right inside the front entrance of a large home-and-lifestyle store. Department specialists already know which specific skillets, lamps, or sofa sectionals belong on each themed table (item ranking), while your job as store manager is deciding which tables go closest to the front door for each shopper walking in (module ranking — ordering horizontal content blocks like "Autumn Kitchen Event", "Fast-Rising Decor", or "Resume Browsing: Modular Sofas").

The naive approach is to rank modules by their raw historical click-through rate. That fails for three reasons: flashy clearance banners attract curiosity clicks that rarely turn into profitable orders, whatever sits in Slot 1 stays on top simply because shoppers look at the top of the screen first, and brand-new 4-day seasonal events start with zero clicks and starve before getting discovered. Worse, scoring each module in isolation can fill the top of the screen with three nearly identical kitchen deals showing the exact same cookware.

Instead, we score each eligible module by the contribution margin (order revenue minus wholesale cost, shipping, payment fees, and expected returns) it is expected to generate if viewed, adjusted for item overlap and business commitments. Walk through a mobile visit with 3 slots for a shopper arriving from a cookware ad:

Candidates scored on level footing (slot feature fixed to 1):
  1. "Autumn Kitchen Event"    intrinsic value v = $0.080  top items: {pan_1, kettle_2, knife_3, bowl_4}
  2. "Chef's Cookware Deal"    intrinsic value v = $0.072  top items: {pan_1, kettle_2, knife_3, mixer_9}
  3. "Sponsored Espresso Bar"  intrinsic value v = $0.045  + $0.030 contract boost in Slots 2-5 -> $0.075
  4. "Fast-Rising Decor"       intrinsic value v = $0.055  top items: {bowl_4, vase_7, lamp_8, tray_5}

Greedy top-down assembly (diversity penalty weight lambda = 0.05):
  - Slot 1: "Autumn Kitchen Event" wins ($0.080; Sponsored Espresso Bar's boost only applies in Slots 2-5).
  - Slot 2: "Chef's Cookware Deal" shares 3 of 5 unique items with Slot 1 (overlap = 3/5 = 0.60),
            dropping its score to $0.072 - 0.05 x 0.60 = $0.042. "Sponsored Espresso Bar" ($0.075) wins Slot 2!
  - Slot 3: "Fast-Rising Decor" ($0.055 - 0.05 x (1/7) = $0.048) beats "Chef's Cookware Deal" ($0.042),
            and item dedup swaps out repeated bowl_4 for the next ranked accent piece in its list.

Key trade-offs

  • Expected contribution margin vs raw clicks as the objective. Clicks are immediate and 50x more plentiful than orders, making models easy to train, but optimizing clicks promotes low-stock or low-margin clickbait. Optimizing 7-day contribution margin matches true business profit at the cost of sparse, delayed labels; multiplying P(click | seen) by P(purchase | click) × E(margin) plus a small experiment-tuned click value bridges both timescales.
  • Two-stage ranking bridged by item summaries vs one joint item-and-module model. Keeping item ranking separate reuses existing infrastructure and shrinks homepage scoring to 30–50 module candidates (~5 ms on CPU). Summarizing the top 4 visitor-personalized items per module recovers most cross-layer personalization without joint combinatorial complexity.
  • Rule-aware greedy assembly vs end-to-end learned slate ranking. An end-to-end slate model can theoretically learn subtle cannibalization across slots, but ordering 8 slots from 40 candidates creates 3.1 × 10¹² combinations with near-zero log coverage and opaque behavior when merchandising rules change. Greedy assembly with Jaccard similarity penalties (shared items divided by total unique items across two modules) and hard type caps is transparent, microsecond-fast, and directly tunable.
  • Exploration traffic vs immediate page yield. Reserving a 5% softmax exploration slice (sampling candidates with probabilities weighted smoothly by score) and running Thompson sampling (drawing uncertain rates from a Beta distribution, a probability curve over [0, 1] updated as views and clicks arrive) sacrifices a tiny fraction of short-term margin. In exchange, new holiday sales gather reliable click estimates within ~1.5 hours and log the propensities (selection probabilities) required for unbiased offline evaluation.
  • Paced contract boosts vs hard-pinned vendor slots. Hard-pinning a vendor module to Slot 2 guarantees delivery easily but wastes prime real estate once daily impressions are met. Applying a dynamic boost β every 15 minutes inside Slots 2–5 hits the target efficiently and lets a second unboosted assembly pass measure the exact dollar margin given up across all shifted slots, at the cost of running a feedback loop.
  • Strict probability calibration vs rank-order-only training. Because our value equation multiplies probabilities by dollars and adds boosts, miscalibrated heads skew trade-offs across module types. Undoing negative downsampling and fitting isotonic regression (a monotonic step-function mapping predicted scores to empirical rates on post-training data) adds a calibration step to the daily pipeline but keeps dollar units truthful.

Common mistakes

  • Optimizing module click-through rate alone, which fills top slots with deep-discount clickbait whose clicks bounce or lose money after shipping and returns.
  • Ignoring position bias and viewport visibility, either counting unseen below-the-fold slots as negative labels or training without neutralizing slot position, creating a self-reinforcing loop where Slot 1 winners never get displaced.
  • Ranking modules as static titles without item-ranker summaries, forgetting that "Spring Sale" means completely different products — and different conversion odds — to a patio shopper versus a nursery shopper.
  • Treating holiday start/end windows as soft ML features rather than hard request-time filters, or caching anonymous layouts past midnight so expired holiday promotions still render.
  • Allowing duplicate modules and duplicate items on the same page, such as stacking two nearly identical sale carousels featuring the exact same hero sofa.
  • Measuring only homepage-attributed orders in A/B tests, which mistakes traffic cannibalized from search or category navigation for genuine site-wide incremental margin.
  • Computing multi-slot marginal propensities synchronously at serving time (or forgetting to log exploration candidate weights altogether), either blowing the 80 ms p99 latency budget or leaving offline inverse propensity scoring (IPS) (reweighting logged rewards by 1 / selection_probability) impossible.

Follow-up questions

  • How does your system personalize module order for an anonymous first-time shopper with zero prior site activity? Exploit the context signals already present on the opening request: device, region (local climate and season), time of day, and especially referrer_campaign (a shopper arriving from a "modular linen sofas" ad should immediately see living-room and modular-sofa carousels near the top). Train the main GBDT scorer with an explicit is_new_visitor flag and native missing-history splits so it learns high-converting cold-start defaults rather than serving a brittle static layout. Stream session interactions in real time as soon as the shopper clicks 1–2 items so lazy-loaded lower slots and subsequent landing-page views adapt within seconds, while holding random exploration minimal to avoid bouncing first-time visitors.
  • How can you score and measure a newly launched seasonal campaign block before it accumulates click or order history? At minute zero, score the block using non-historical features (discount depth, category distribution, time remaining in the campaign, and the visitor-personalized item-ranker summary of its top 4 SKUs) paired with empirical Bayes smoothing seeded from last year's comparable seasonal event. On launch, grant it a probability floor in the 5% exploration slice and draw its rate feature via Thompson sampling with a deliberately wide prior (k0 ≈ 200 impressions) so it gathers ~12,400 seen views within ~1.5 hours to pin down CTR within ±10%. Because 7-day order conversion needs ~640,000 views (~3.2 days), blend in-session add_to_cart and save rates as calibrated early proxies, and evaluate net page impact using exploration-slice IPS margin per page or a site-wide A/B split rather than standalone module CTR.
  • What mechanisms stop the page assembler from stacking redundant modules or repeating the same products across carousels? Layer soft overlap penalties, hard structural merchandising rules, and top-down SKU deduplication inside greedy slate assembly. First, subtract λ × max_jaccard_overlap from each candidate's score based on the fraction of top-20 items it shares with modules already placed higher on the page. Second, enforce structural layout rules: disallow two adjacent modules of the same module_type and cap "sale" modules at 2 within Slots 1–4. Finally, deduplicate individual product IDs from Slot 1 downward, backfilling from each module's ranked SKU list and dropping any carousel whose remaining in-stock items fall below min_items.
  • Suppose an online test lifts module click-through rates while order volume or repeat-visit health drops — how do you diagnose and fix it? Hold or roll back the treatment immediately, prioritizing site-wide contribution margin per visitor and retention guardrails over raw click gains. Break results down by module_type, slot, and visitor segment to pinpoint clickbait blocks (for example, steep clearance shelves with depleted sizes or misleading hero thumbnails), verify whether landing-page clicks cannibalized higher-intent search sessions, and inspect post-click quick-back rates, return rates, and 28-day repeat visits. Then correct the scoring formula directly by reducing the per-click reward a, penalizing rapid post-click bounces or low-stock SKUs, and tracking a 1–2% long-term holdout to catch delayed trust erosion.

Follow-up questions

Similar questions

More Wayfair interview questions

All 11 Wayfair questions →