Ranking a Design Gallery and Turning Prompts into Safe UI Snippets
Machine LearningModel answerLast updated
Design an ML system that ranks a creative community's feed and also converts natural-language requests into validated, safe HTML/CSS components, including evaluation and feedback loops.
Design: A Personalized Gallery Feed Plus a Prompt-to-UI Generator
You are building two features for an online creative platform where members publish designs and browse a feed of work from the community. Members can also type a request into a prompt box and get back a ready-to-embed HTML/CSS component.
Part 1: Personalized gallery feed
Design the system that decides which designs each member sees and in what order. Cover:
- Candidate generation: how to narrow a corpus of tens of millions of designs to a manageable shortlist.
- Ranking: the model stages, inputs and training objectives you would use.
- Cold start: how brand-new members and brand-new creators get a fair experience despite having no history.
- Evaluation: offline metrics (for example NDCG, MRR, recall) and online metrics (for example CTR, dwell time, long-term retention).
Part 2: Prompt-to-component generation
Design a service that accepts a request such as "make a frosted-glass login button" and returns a working HTML/CSS snippet.
- Modeling approach: for example a fine-tuned code LLM, retrieval-augmented generation over a component library, a multimodal model, or a combination.
- Safety and quality constraints: how you prevent malicious output and slow or broken layouts.
- Evaluation: how you measure visual quality and functional correctness.
What to deliver
- A text-based architecture diagram showing the main components, including the feature store, model serving, and the event-logging pipeline.
- A discussion of the latency versus model-complexity trade-off for both the ranker and the generator.
- A description of the feedback loops: how likes, edits, and re-prompts flow back to improve both models.
State your scale assumptions up front and be explicit about trade-offs.
Hints
Hint 1
Begin by quantifying scale (users, feed loads, corpus size, prompts per day) and latency budgets; these numbers drive the funnel shape: many cheap retrievers, then a light ranker, then a heavy ranker, then re-ranking.
Hint 2
For cold start, lean on content-derived item features (image/text embeddings) and reserved exploration slots, and for new members seed from onboarding choices and context. For the generator, treat safety as layered: constrained output format, sanitization, then sandboxed rendering and checks, not just a prompt instruction.
Hint 3
Close the loop with implicit signals: feed saves, remixes, and hides into the ranker; accepted, edited, or re-prompted snippets into preference data for the generator. Remember to warn about position bias, clickbait optimization, and leakage from random train/test splits.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model answer
1. Scope and numbers
Assumptions (state them, then adjust if the interviewer pushes back):
| Item | Assumption | Implication |
|---|---|---|
| Daily active members | ~20M | |
| Feed loads per member/day | ~10 | ~2.3k QPS average, ~10k peak |
| Corpus | ~50M designs, +200k/day | Needs ANN retrieval, not brute force |
| Prompts/day | ~1M | ~12 QPS average, ~50 peak |
Latency targets: feed p99 under ~200 ms; generator first preview within ~3 s and a fully validated snippet within ~6 s.
Goals differ by part. The feed should optimize long-term value (saves, remixes, follows), not raw clicks. The generator must produce output that is safe, renders correctly, and is accessible.
2. Architecture (text diagram)
Client (feed UI / prompt UI)
| |
Feed Service Generation Service
| \ | \
Retrieval Ranking Pattern index Code LLM (GPU)
(ANN + (light -> (component |
rules) heavy) library RAG) Sandbox validator
| | (sanitize, render, a11y, perf)
+--- Feature Store (online + offline) ---+
| |
+------- Event log (Kafka) <-------------+
-> stream jobs -> data lake -> training
-> ranker / towers / LLM SFT+preference tuning -> model registry
Key APIs: GET /feed, POST /generate, POST /events (impression, click, dwell, save, remix, edit, reprompt, reject).
3. Part 1: Feed ranking
Candidate generation (50M to ~2k). Run several retrievers in parallel and merge:
- Two-tower model. The user tower encodes history, the current session and profile; the item tower encodes a visual embedding of the thumbnail, text, tags and creator. Train with in-batch sampled softmax on strong positives (saves, remixes) and apply logQ correction so popular items are not over-favored. Item vectors are precomputed into an ANN index (HNSW or ScaNN) for roughly 10 ms lookups.
- Follow graph: recent work from followed creators.
- Trending and fresh pools: short-window popularity plus new uploads.
- Item-to-item co-engagement: members who remixed X also saved Y.
Ranking.
- Light ranker (~2k to ~300): GBDT or small MLP on cheap features, under ~20 ms.
- Heavy ranker (~300 to ~50): a DCN-v2 or transformer over user-item cross features and the recent action sequence, with multi-task heads for click, dwell, save, remix, follow and hide. Combine into one score, e.g.
w1*pClick + w2*log(dwell) + w3*pSave + w4*pRemix - w5*pHide. The weights encode product intent and are tuned through online experiments. - Re-ranking: diversity (MMR or per-creator caps), an exploration slot for fresh items, and policy filters (blocked creators, unsafe content).
Cold start.
- New members: seed the embedding from onboarding topic picks and context (locale, device, referral), fall back to segment-level popularity, and explore more aggressively in early sessions.
- New creators/items: the item tower uses content features, so a new design is retrievable immediately. Reserve roughly 5-10% of slots for exploration (Thompson sampling or similar), and stop boosting once an item has enough impressions to be scored on evidence.
Evaluation.
- Offline: recall@k for retrieval; NDCG@k and MRR for ranking; per-head log loss and calibration. Always use a time-based split, since random splits leak future behavior.
- Online: A/B tests with CTR, dwell, and saves/remixes per session as primary metrics; hide rate and creator coverage (e.g. Gini of exposure) as guardrails; D7/D30 retention and creator retention as north stars. A CTR win paired with a retention loss signals clickbait.
4. Part 2: Prompt-to-component generation
Approach: retrieval plus a specialized code model.
- Intent parsing: extract component type, style, and constraints (theme, the member's design tokens).
- Retrieval: fetch top-k vetted snippets from a curated library and the member's design system to ground the output.
- Generation: a mid-size code LLM (roughly 7-34B) fine-tuned on prompt to vetted HTML/CSS pairs, using constrained decoding (tag/attribute allowlist grammar, approved CSS properties, no script).
- Validate and repair: run deterministic checks; on failure, give the errors back to the model for a single repair pass.
- Multimodal input: use a vision-language model only when a screenshot or reference is supplied, because it adds latency.
Safety, layered.
- Output format limited to HTML and CSS, no JavaScript.
- Allowlist sanitizer (DOMPurify-style) removing event handlers,
javascript:URLs, external resources outside an approved CDN, CSS@importand legacyexpression(). - Render in a headless browser in a locked-down sandbox: no network, CSP
default-src 'none', CPU/time limits, separate origin. - Performance checks: DOM node count, nesting depth, costly properties (stacked
backdrop-filter, huge shadows), layout shift, render time. - Accessibility checks: contrast, labels, focus states, semantic elements.
Evaluation.
- Automatic: validity rate, sanitizer pass rate, render success, a11y and perf scores, and visual similarity (embedding or SSIM) to references when they exist.
- Model-based: a vision-language judge scoring prompt adherence on rendered screenshots, calibrated against human ratings.
- Human review on a rotating sample.
- Online: acceptance rate, edit distance after insertion, re-prompt rate, and time to an accepted result.
5. Latency versus complexity
- Ranker: the funnel is the trade-off. Cheap models see many items; expensive models see few. Precompute embeddings, cache user features, and use distillation or quantization if the heavy ranker threatens the 200 ms budget.
- Generator: smaller models, speculative decoding, prefix caching of the retrieved context, and streaming a preview keep perceived latency low. Cache results for frequent prompts. Reserve the larger model or additional repair passes for failures or premium use.
6. Feedback loops
- Feed: impressions and actions are logged with position and model version. Stream jobs update real-time features; batch jobs retrain daily or weekly. Correct for position bias (position as a training feature that is neutralized at serving, or inverse propensity weighting), and keep a small randomized slice for unbiased evaluation.
- Generator: an accepted snippet is a positive; a heavily edited one provides a (generated, edited) pair; a quick re-prompt is a weak negative; an explicit reject is a strong negative. Use these for supervised fine-tuning on accepted outputs and preference tuning (DPO) on pairs, after passing the same validators and a human audit so the model cannot learn from unsafe data. Promising snippets can be added to the retrieval library after review.
7. Common mistakes
- Optimizing for clicks alone.
- Random train/test splits that leak the future.
- Ignoring cold start and creator fairness.
- Relying on prompt instructions for safety instead of enforced validation.
- Evaluating generated code only by text similarity rather than rendering it.
- Feeding unfiltered user feedback straight back into training.