Eliminate Duplicates in a Personalized Content Feed
System DesignModel answerLast updated
Design a system that ensures each piece of content appears only once in the initial screen of a personalized homepage with multiple thematic rows.
You're building a personalized content homepage for a streaming service. The page consists of multiple horizontal rows, each with its own theme (e.g., "Action Movies," "Because You Watched X," "Trending Now," "Continue Watching"). Each row displays several content items as tiles.
Your task is to design a system that ensures no content item appears more than once in the portion of the page visible when it first loads (the "initial viewport"). This constraint applies across all rows and within each row.
Additional considerations:
- Each row has semantic meaning and eligibility rules. An item shown in "Because You Watched Breaking Bad" must legitimately belong there based on the recommendation logic.
- Some items have editorial requirements (e.g., a newly launched show must appear in position 1 of a specific row).
- Content has age ratings and regional availability that must be respected.
- The goal is to maximize overall relevance to the user while satisfying the uniqueness constraint.
- Users scroll both vertically (more rows) and horizontally (more items in a row), so you need to handle pagination efficiently.
- The viewport size varies by device: large screens might show 4 rows × 6 items, while mobile shows 3 rows × 2-3 items.
Design the complete system including:
- Data models for rows and content candidates
- APIs for serving the homepage and handling pagination
- The algorithm for selecting and placing items to maximize relevance while enforcing deduplication
- Strategies for handling edge cases (insufficient candidates, conflicting requirements)
- Caching approach and performance targets
- How you'd measure success
State your assumptions about scale, clarify ambiguities, and discuss trade-offs in your design choices.
Hints
Hint 1
Think about whether deduplication should be strict only in the viewport or applied more broadly
Hint 2
Consider processing editorial requirements and hard constraints before running the main selection algorithm
Hint 3
A greedy approach can work well if you process items in the right order—what metric determines priority?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Personalized Feed with Content Deduplication
1. Clarifying Requirements and Scale Assumptions
Functional Requirements
- Uniqueness constraint: Every content item visible in the initial viewport must be distinct. Deduplication is by canonical content ID (different seasons or dubbed versions of the same show count as one item).
- Row integrity: Items must satisfy their row's eligibility criteria. You can't place a romance film in "Action Thrillers" just to fill a slot.
- Hard constraints:
- Age rating restrictions based on the profile
- Geographic licensing boundaries
- Editorial placements (certain content must appear in specific positions)
- Optimization goal: Maximize the sum of relevance scores, weighted by visibility (top-left positions matter more than bottom-right).
- Graceful degradation: A partially filled page is better than a failure.
Scale and Performance Assumptions
- Traffic: ~100 million active users, peak load around 75,000 requests/second
- Viewport sizes: 10-25 constrained cells depending on device
- Target latency: 250ms p99 end-to-end, with the deduplication logic consuming under 5ms
- Candidate pool: Each row has 50-200 pre-ranked candidates
Clarifications to Establish
- Does the hero/billboard banner count toward the viewport? (Assume yes)
- How strict is deduplication below the fold? (Apply as a soft penalty, not a hard constraint)
- Can "Continue Watching" show duplicates? (Yes, but mark them as used for other rows)
2. Data Models
Row Schema
{
rowId: string,
displayTitle: string,
rowType: enum (genre, similarity, trending, editorial, continue_watching),
eligibilityFilter: function,
minItemsToRender: int, // Row won't display if it can't reach this
allowDuplicates: boolean, // Special handling for Continue Watching
baseScore: float // How important this row is overall
}
Candidate Schema
{
rowId: string,
contentId: string, // Canonical identifier
entityId: string, // Specific version (S2 vs S1, different dub)
score: float, // P(engagement | row, user)
ageRating: string,
availableRegions: set,
artworkUrl: string,
reasonTag: string // "Because you watched X"
}
Editorial Pin Schema
{
rowId: string,
contentId: string,
position: int,
priority: int, // Higher priority wins conflicts
mustShow: boolean, // Hard vs soft pin
activeWindow: [startTime, endTime]
}
Profile Context
{
profileId: string,
maxAgeRating: string,
region: string,
device: enum,
recentViews: [contentId], // For freshness filtering
experimentGroup: string
}
3. API Design
GET /api/homepage
Query params: profileId, device, viewportRows, viewportCols
Response: {
sessionId: string,
viewport: {
rows: [{
rowId: string,
title: string,
items: [{contentId, entityId, artwork, position}],
hasMore: boolean
}]
},
overflowCandidates: { // For client-side viewport adjustments
rowId: [contentId]
},
scrollToken: string
}
GET /api/homepage/more-rows
Query params: sessionId, scrollToken
Response: { rows: [...], scrollToken: string }
GET /api/homepage/row/{rowId}/items
Query params: sessionId, offset
Response: { items: [...], hasMore: boolean }
The overflowCandidates list allows the client to re-run deduplication locally when the viewport changes (device rotation) without a server round-trip.
4. System Architecture
Offline/Nearline Pipeline
- Personalization engine generates candidate items for each row type per profile
- Items are ranked by predicted engagement: P(play | row, user, content)
- Results cached in a distributed cache (e.g., Redis, Memcached) keyed by
profileId:region:maturityLevel - Cache refreshes triggered by: new content releases, user viewing activity, daily batch updates
Online Service Flow
- Fetch Phase (parallel): Retrieve pre-ranked candidates for each row from cache with 50ms timeout
- Filter Phase: Apply hard constraints (age rating, regional availability, recent impressions within 7 days)
- Assembly Phase: Run viewport deduplication algorithm
- Hydration Phase: Fetch artwork and metadata for selected items
- Response: Return assembled page with overflow candidates
Latency Budget
- Cache fetch: 50ms
- Filtering: 10ms
- Deduplication assembly: 5ms
- Metadata hydration: 80ms
- Serialization + network: 105ms
- Total: ~250ms p99
5. Deduplication Algorithm
Core Approach: Priority-Based Greedy with Conflict Resolution
function assembleViewport(rows, viewportShape, pins):
usedContent = new Set()
result = []
// Phase 1: Lock in editorial pins
activePins = filterActivePins(pins).sortBy(priority, desc)
for pin in activePins:
if pin.contentId not in usedContent:
placeInPosition(result, pin.rowId, pin.position, pin.contentId)
usedContent.add(pin.contentId)
else if pin.mustShow:
logConflict(pin) // Alert editorial team
// Phase 2: Build conflict set
conflicts = findContentInMultipleRows(rows, viewportShape)
// Phase 3: Resolve conflicts using opportunity cost
for contentId in conflicts.sortBy(totalScore, desc):
eligibleRows = getEligibleRows(contentId, rows, viewportShape)
// Calculate "regret" for each row: how much worse is the next-best option?
regrets = []
for row in eligibleRows:
nextBestScore = getNextUnusedScore(row, usedContent)
currentScore = getScoreFor(row, contentId)
regret = currentScore - nextBestScore
regrets.append({row, regret, weightedScore: currentScore * positionWeight})
// Assign to the row where loss would be greatest
bestChoice = regrets.maxBy(regret * weightedScore)
assignToRow(result, bestChoice.row, contentId)
usedContent.add(contentId)
// Phase 4: Fill remaining cells greedily
for row in rows:
for position in viewportPositions(row):
if position not filled:
candidate = getNextUnused(row.candidates, usedContent)
if candidate and meetsConstraints(candidate):
placeInPosition(result, row.rowId, position, candidate)
usedContent.add(candidate.contentId)
// Phase 5: Backfill sparse rows
for row in result:
if row.itemCount < row.minItemsToRender:
if tryBackfill(row, usedContent) fails:
demoteRow(row) // Move below fold, promote next row
return result, usedContent
Key Insights
- Regret calculation prevents suboptimal assignments. If a content item is strong in Row A but Row A has many good alternatives, while Row B has few, assign it to Row B.
- Position weighting comes from eye-tracking data. First position in the top row might be 1.0, while bottom-right is 0.3.
- Deterministic tie-breaking using
hash(contentId + sessionId)ensures the server and client get identical results.
Complexity: O(C log C) where C is the total number of candidates (~1000-2000), dominated by sorting conflicts.
6. Handling Edge Cases
Insufficient Candidates
When a row runs out of unique candidates:
- Try fetching deeper from the candidate pool (beyond the cached top-100)
- Fall back to a "similar themes" pool (e.g., general "Drama" when "Crime Drama" is exhausted)
- If still below
minItemsToRender, hide the row and shift lower rows up - Never compromise row integrity by placing ineligible content
Conflicting Editorial Pins
Two pins claim the same content for different rows:
- The pin with higher priority wins
- Log the conflict for editorial team review
- If the losing pin is
mustShow: true, trigger an alert
Deduplication Below the Fold
Apply a discount factor rather than strict exclusion:
scoreAdjusted = score * (alreadyShown ? 0.5 : 1.0)
This discourages repetition but allows it when alternatives are weak.
Continue Watching Special Case
User expectations: seeing the same show in "Continue Watching" and "Trending Drama" is acceptable. Mark Continue Watching items as used for other rows, but allow the row itself to show them.
7. Caching Strategy
Multi-Layer Cache
- L1 (CDN edge): Cache full homepage responses for 30-60 seconds with profile-blind bucketing for cold starts
- L2 (Application cache): Per-profile candidate lists, TTL 5-15 minutes, invalidated on user activity
- L3 (Database): Ranked candidates with daily refresh
Cache Keys
homepage:v2:{profileId}:{region}:{maturity}:{device}:{experimentVariant}
row:{rowType}:{profileId}:{depth}
Invalidation Triggers
- User completes watching something → invalidate Continue Watching
- New content launch → selective invalidation of affected row types
- Midnight UTC → batch refresh of trending/editorial rows
8. Pagination and Scrolling
Vertical Scroll (More Rows)
Return a continuation token encoding:
{sessionId, lastRowIndex, usedContentBloomFilter}
The Bloom filter (~2KB) lets the server maintain deduplication context across requests without keeping session state. False positives are acceptable (overly conservative deduplication).
Horizontal Scroll (More Items in Row)
Each row's overflow candidates are already ranked and deduplicated relative to the viewport. Simply return the next N items, applying only within-row deduplication.
9. Measurement and Validation
Key Metrics
- Viewport fill rate: % of viewport cells successfully populated (target: >98%)
- Deduplication correctness: % of sessions with zero duplicates in viewport (target: 100%)
- Relevance preservation: Mean score of placed items vs theoretical maximum (target: >90%)
- Row integrity: % of items that pass eligibility checks (target: 100%)
A/B Test Design
- Control: Existing system or simpler deduplication (first-come-first-served)
- Treatment: Priority-based algorithm with conflict resolution
- Metrics: Engagement rate (plays per visit), time-to-first-play, scroll depth
Common Failure Modes to Monitor
- Pin conflicts causing editorial items to not show
- Rows collapsing due to insufficient backfill candidates
- Latency spikes when conflict resolution touches many rows
- Cache stampede on new content launches
10. Trade-offs and Alternatives
Server-Side vs Client-Side Assembly
Chosen: Server-side
- Pro: Single source of truth, easier testing, works on all devices
- Con: Higher server load, can't react to viewport resize instantly
- Mitigation: Provide overflow candidates for client-side adjustment
Exact Optimization vs Greedy
Chosen: Greedy with regret heuristic
- Exact (Hungarian algorithm): O(n³), overkill for 25 cells
- Greedy: O(n log n), 5ms budget, achieves ~85-90% of optimal in practice
- When to reconsider: If engagement gains from exact optimization justify 50ms+ latency
Global Dedup vs Viewport-Only
Chosen: Strict in viewport, soft below fold
- User doesn't see duplicates in the initial experience (most critical)
- Allows flexibility for deep scrollers
- Reduces chance of running out of candidates
This design balances user experience, engineering complexity, and system performance while maintaining flexibility for future enhancements like real-time event-based updates or multi-profile households.