Pluggable Scoring Pipeline for Ranking Concert and Show Listings
Data Structure DesignModel answerLast updated
Design an object-oriented ranking engine where scoring and filtering rules can be chained, weighted, reordered and isolated from failures, with a backfill tier when too few results come back.
Build a Pluggable Ranking Pipeline for Live Events
You are building the recommendation component of a ticket-selling site. Given a user and a list of candidate events, it must return the best count events, ranked by a combined relevance score.
The ranking logic has to be modular. Individual rules must be easy to switch on or off, swap out, or reorder without touching the engine. Each request may carry different constraints, such as a location, a spending limit or a preferred category. Many requests will also return too few events from the main rules, so the engine needs a second tier of rules that tops up the list.
What to build
- A
RecommendationRuleabstraction exposingapply(user_id, event_list), which returns a mapping from event to score. - A
RecommendationEnginethat stores rules, decides the order they run in, combines their scores, and handles the backfill tier. - At least two concrete rules:
PopularityRule: higher score for events with more total ticket sales.ProximityRule: higher score for events closer to the user's current position.
Skeleton
class Event:
def __init__(self, id, category, price, popularity, lat, lon):
self.id = id
# ... remaining attributes
class RecommendationEngine:
def __init__(self):
# set up rule storage and fallback handling
pass
def add_rule(self, rule, priority):
pass
def get_recommendations(self, user_id, events, count):
# return the top `count` events using the prioritized rules
pass
You may extend add_rule with optional parameters (for example a weight and a flag marking a rule as fallback), as long as the two-argument call still works.
Example
Ten events are supplied, the user is at (40.7, -74.0), and count = 3. The engine runs ProximityRule with weight 0.7 and PopularityRule with weight 0.3. It returns three Event objects ordered by the weighted combination of the two scores.
Constraints
- A single request may contain thousands of events.
- Rules must be independent of each other and interchangeable.
- If one rule fails (for example, a dependent service times out), the engine must carry on with the remaining rules instead of failing the request.
What to cover in your answer
Describe the class design, how scores from different rules become comparable, how priority and weights work, how the fallback tier is triggered, and how failures are contained. Give complexity and code, and mention edge cases.
Hints
Hint 1
Rules measure very different things (ticket counts, kilometers). Think about how to map every rule's output into the same range before mixing them with weights.
Hint 2
Let a rule express filtering simply by leaving an event out of its returned mapping. Then budget, category and radius limits are just more rules, and priority becomes the run order.
Hint 3
Wrap each rule call in a try/except. If a rule fails, skip it and exclude its weight from the denominator so scores from different requests stay comparable. Run the fallback tier only on events not already selected.
Hint 4
For top-k selection over thousands of events, a heap avoids a full sort. Break ties by input position so results are deterministic.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is mostly an object-oriented design task with a small ranking algorithm inside. The pieces:
- Strategy pattern for rules. Every rule implements
apply(user_id, events) -> {event_id: score}. Scores are normalized to[0, 1]so a rule measuring ticket counts and a rule measuring kilometers can be blended. - Weighted average in the engine. For an event, the final score is
sum(w_i * s_i) / sum(w_i), taken over the rules that actually ran successfully. - Filtering by omission. If a rule leaves an event out of its output, the event becomes ineligible. A
BudgetFilterRulereturns entries only for affordable events. Request constraints therefore need no special machinery; they are rules like any other. - Priority is execution order. Lower numbers run first. Running filters early means costly scorers see a smaller candidate list.
- Two tiers. Primary rules produce the main ranking. If they yield fewer than
countevents, fallback rules score the events not yet chosen and fill the remaining slots. - Failure isolation. Each
applycall sits in atry/except. A failing rule is logged and skipped, and its weight is dropped from the normalization. If an entire tier fails, it contributes nothing and the next tier takes over.
add_rule(rule, priority) gains optional weight=1.0 and fallback=False arguments, so the original call still works while the 0.7 / 0.3 example becomes expressible.
Why this is correct
- Any event that survives to the end of a tier received a score from every rule that succeeded in that tier, because eligibility is intersected after each rule. No event is compared on a partial sum.
- Dividing by the weight of successful rules keeps scores comparable when a rule drops out. Without it, a proximity timeout would silently lower every score by up to 0.7 and make the tiers inconsistent.
- The fallback tier only sees events not already selected, so there are no duplicates and primary results always outrank backfill.
- Ties resolve by input order, giving deterministic output, which helps caching and experiment analysis.
Complexity
With R rules, N events, k = count:
- Time: O(R·N) for scoring plus O(N log k) for heap-based top-k.
- Space: O(N) for score maps and the candidate list.
Thousands of events per request is trivial at this cost.
Edge cases
count <= 0or an empty list: return[].- Duplicate event IDs: keep the first occurrence.
- All popularity values are 0: return 0.0 for everything to avoid dividing by zero.
- A rule raises or returns something that is not a dict: skip it.
- No primary rules, or all fail: the fallback tier fills the whole result.
- Filters eliminate everything: the fallback tier runs on the full set.
- Fewer events than
count: return what exists.
Trade-offs and common mistakes
- Forgetting to renormalize after a rule failure, which skews scores.
- Letting a rule mutate shared event objects, which breaks independence.
- Mixing raw units (km, counts) without normalization, so one rule dominates.
- Running expensive scorers before cheap filters.
- Sorting the full list instead of using a heap; harmless at this scale but worth noting.
- Hard-coding rules in the engine, which defeats interchangeability.
Possible follow-ups: per-rule timeouts and circuit breakers, caching rule outputs per user, and making weights configurable per request or experiment.
Python code
import heapq
import logging
import math
from abc import ABC, abstractmethod
log = logging.getLogger(__name__)
class Event:
def __init__(self, id, category, price, popularity, lat, lon):
self.id = id
self.category = category
self.price = price
self.popularity = popularity
self.lat = lat
self.lon = lon
def __repr__(self):
return f"Event({self.id!r})"
class RecommendationRule(ABC):
name = "rule"
@abstractmethod
def apply(self, user_id, events):
"""Return {event_id: score in [0, 1]}; omitted events are filtered out."""
class PopularityRule(RecommendationRule):
name = "popularity"
def apply(self, user_id, events):
top = max((e.popularity for e in events), default=0)
if top <= 0:
return {e.id: 0.0 for e in events}
return {e.id: max(e.popularity, 0) / top for e in events}
def haversine_km(lat1, lon1, lat2, lon2):
r = 6371.0
p1, p2 = math.radians(lat1), math.radians(lat2)
dp, dl = p2 - p1, math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * r * math.asin(math.sqrt(a))
class ProximityRule(RecommendationRule):
name = "proximity"
def __init__(self, location_provider, scale_km=25.0):
self.location_provider = location_provider # user_id -> (lat, lon); may raise
self.scale_km = scale_km
def apply(self, user_id, events):
lat, lon = self.location_provider(user_id)
return {
e.id: 1.0 / (1.0 + haversine_km(lat, lon, e.lat, e.lon) / self.scale_km)
for e in events
}
class BudgetFilterRule(RecommendationRule):
name = "budget"
def __init__(self, budget_provider):
self.budget_provider = budget_provider # user_id -> max price
def apply(self, user_id, events):
budget = self.budget_provider(user_id)
return {e.id: 1.0 for e in events if e.price <= budget}
class RecommendationEngine:
def __init__(self):
self._primary = [] # (priority, seq, rule, weight)
self._fallback = []
self._seq = 0
def add_rule(self, rule, priority, weight=1.0, fallback=False):
if weight < 0:
raise ValueError("weight must be non-negative")
tier = self._fallback if fallback else self._primary
tier.append((priority, self._seq, rule, weight))
tier.sort(key=lambda t: (t[0], t[1]))
self._seq += 1
def remove_rule(self, rule):
self._primary = [t for t in self._primary if t[2] is not rule]
self._fallback = [t for t in self._fallback if t[2] is not rule]
def _score_tier(self, user_id, events, entries):
candidates = list(events)
totals = {e.id: 0.0 for e in candidates}
weight_used = 0.0
for _, _, rule, weight in entries:
if not candidates:
break
try:
scores = rule.apply(user_id, candidates)
if not isinstance(scores, dict):
raise TypeError("rule must return a dict")
except Exception:
log.exception("rule %s failed; skipping", getattr(rule, "name", rule))
continue
candidates = [e for e in candidates if e.id in scores]
for e in candidates:
totals[e.id] += weight * float(scores[e.id])
weight_used += weight
if weight_used == 0:
return {}
return {e.id: totals[e.id] / weight_used for e in candidates}
def get_recommendations(self, user_id, events, count):
if count <= 0 or not events:
return []
by_id = {}
for e in events:
by_id.setdefault(e.id, e)
unique = list(by_id.values())
order = {e.id: i for i, e in enumerate(unique)}
def top(scores, k):
# highest score first; ties go to earlier input position
best = heapq.nsmallest(
k, scores.items(), key=lambda kv: (-kv[1], order[kv[0]])
)
return [by_id[eid] for eid, _ in best]
result = top(self._score_tier(user_id, unique, self._primary), count)
if len(result) < count and self._fallback:
chosen = {e.id for e in result}
remaining = [e for e in unique if e.id not in chosen]
fb = self._score_tier(user_id, remaining, self._fallback)
result += top(fb, count - len(result))
return result
Usage for the example: register ProximityRule with weight=0.7 and PopularityRule with weight=0.3, then call get_recommendations(user_id, events, 3).