Pluggable Filter and Scoring Pipeline for Ticket Listings
Data Structure DesignModel answerLast updated
Design an extensible object-oriented engine that drops ineligible events with pluggable rules, then orders the rest by a weighted blend of scoring strategies.
Ticket Listings: Pluggable Filtering and Scoring
A ticket marketplace wants to suggest events to users based on their preferences. Eligibility rules and ordering rules will keep growing over time, so the design must make it easy to add new ones without editing existing code.
Each event is described by this class:
class Event:
def __init__(self, id, category, price, popularity_score, start_time):
self.id = id
self.category = category
self.price = price
self.popularity_score = popularity_score
self.start_time = start_time
What to build
- An abstraction for filters, which decide whether an event is eligible. Provide concrete examples such as a category filter and a price-range filter.
- An abstraction for rankers, which assign an event a score used for ordering. Provide concrete examples such as a popularity ranker and a price ranker.
- A
RecommendationEnginethat accepts a list of events, removes any event rejected by a filter, and orders the survivors by a weighted combination of all active rankers.
Example
Filter: category is 'Sports'. Ranker: popularity.
| id | category | price | popularity_score |
|---|---|---|---|
| 1 | Sports | 50 | 0.8 |
| 2 | Music | 30 | 0.9 |
| 3 | Sports | 100 | 0.7 |
Expected result: events 1 and 3, in that order (event 2 is dropped by the filter; the remaining two are ordered by popularity).
Requirements
- The code should be clean and extensible and follow the Open/Closed Principle: adding a new filter or ranker must not require changing the engine.
- If no events pass the filters, the engine must return an empty result without error.
- Several rankers must be usable at once, for example a weighted blend of popularity and price.
What to discuss
Explain your class structure, how filters are combined, how scores from rankers with different scales are blended, the complexity of the pipeline, and the edge cases you handle.
Hints
Hint 1
Treat the work as two stages: first a boolean eligibility check per event (all filters must agree), then a numeric ordering of whatever survived.
Hint 2
Give every ranker the same contract, 'a higher score is better', so a cheaper-is-better ranker can simply return the negated price and the engine never needs to know directions.
Hint 3
Price might range up to hundreds while popularity sits between 0 and 1. Rescale each ranker's scores across the surviving candidates before applying weights, and decide what to do when every candidate has the same raw score.
Hint 4
Think about the boundaries: an empty candidate list, no rankers configured, one single candidate, negative weights, and an invalid price range.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is an object-oriented design problem. The natural fit is the Strategy pattern inside a two-stage pipeline:
- Filter stage. Each filter exposes
matches(event) -> bool. An event is kept only if every filter accepts it (logical AND). - Ranking stage. Each ranker exposes
score(event) -> float, where higher means better. The engine rescales each ranker's scores across the surviving candidates, multiplies by the weight, sums, and sorts descending.
The engine depends only on the two abstract interfaces. A new rule (a date-window filter, a distance ranker) is one new class, and the engine is untouched. That is the Open/Closed Principle in practice.
Key design decisions
- Uniform direction. Every ranker returns "higher is better". A price ranker returns
-price. The engine therefore never special-cases a ranker. - The engine owns normalization. Price may span 0 to 500 while popularity spans 0 to 1. Without rescaling, the larger-scale ranker would dominate no matter what weights the caller picks. Min-max scaling over the candidate set makes the weights mean what the caller intends.
- Composable filters.
AndFilter,OrFilterandNotFilterwrap other filters, so callers can express "Sports OR Music, and NOT too expensive" without touching the engine. Operator overloads (&,|,~) make this readable. - Validation at construction. Reject negative weights and an inverted price range early, so misconfiguration fails loudly rather than producing odd orderings.
Code
from abc import ABC, abstractmethod
from typing import Iterable, List, Optional, Sequence, Tuple
class Event:
def __init__(self, id, category, price, popularity_score, start_time):
self.id = id
self.category = category
self.price = price
self.popularity_score = popularity_score
self.start_time = start_time
def __repr__(self):
return f"Event({self.id})"
class Filter(ABC):
@abstractmethod
def matches(self, event: Event) -> bool: ...
def __and__(self, o): return AndFilter(self, o)
def __or__(self, o): return OrFilter(self, o)
def __invert__(self): return NotFilter(self)
class CategoryFilter(Filter):
def __init__(self, *categories: str):
if not categories:
raise ValueError("need at least one category")
self.categories = frozenset(categories)
def matches(self, event):
return event.category in self.categories
class PriceRangeFilter(Filter):
def __init__(self, min_price: Optional[float] = None,
max_price: Optional[float] = None):
if (min_price is not None and max_price is not None
and min_price > max_price):
raise ValueError("min_price must not exceed max_price")
self.min_price, self.max_price = min_price, max_price
def matches(self, event):
if self.min_price is not None and event.price < self.min_price:
return False
if self.max_price is not None and event.price > self.max_price:
return False
return True
class AndFilter(Filter):
def __init__(self, *fs): self.fs = fs
def matches(self, e): return all(f.matches(e) for f in self.fs)
class OrFilter(Filter):
def __init__(self, *fs): self.fs = fs
def matches(self, e): return any(f.matches(e) for f in self.fs)
class NotFilter(Filter):
def __init__(self, inner): self.inner = inner
def matches(self, e): return not self.inner.matches(e)
class Ranker(ABC):
@abstractmethod
def score(self, event: Event) -> float:
"""Raw score, higher is better."""
class PopularityRanker(Ranker):
def score(self, event): return float(event.popularity_score)
class PriceRanker(Ranker):
def score(self, event): return -float(event.price)
class RecommendationEngine:
def __init__(self, filters: Optional[Iterable[Filter]] = None,
rankers: Optional[Iterable[Tuple[Ranker, float]]] = None):
self.filters: List[Filter] = list(filters or [])
self.rankers: List[Tuple[Ranker, float]] = []
for r, w in rankers or []:
self.add_ranker(r, w)
def add_filter(self, f):
self.filters.append(f)
return self
def add_ranker(self, r, weight=1.0):
if weight < 0:
raise ValueError("weight must be non-negative")
self.rankers.append((r, weight))
return self
def recommend(self, events: Sequence[Event],
top_k: Optional[int] = None) -> List[Event]:
cands = [e for e in events if all(f.matches(e) for f in self.filters)]
if not cands or not self.rankers:
return cands[:top_k] if top_k is not None else cands
totals = [0.0] * len(cands)
for ranker, weight in self.rankers:
raw = [ranker.score(e) for e in cands]
lo, hi = min(raw), max(raw)
if hi == lo:
continue # no information, contributes nothing
span = hi - lo
for i, s in enumerate(raw):
totals[i] += weight * (s - lo) / span
order = sorted(range(len(cands)), key=lambda i: -totals[i])
result = [cands[i] for i in order]
return result[:top_k] if top_k is not None else result
Sorting indices by -total relies on Python's stable sort, so tied events keep their input order and the output is deterministic.
Walkthrough of the example
The category filter keeps events 1 and 3. Popularity values 0.8 and 0.7 normalize to 1.0 and 0.0, so the result is [Event(1), Event(3)].
Complexity
Let N = events, F = filters, M = survivors, R = rankers.
- Filtering: O(N·F), short-circuiting on the first rejection.
- Scoring and normalization: O(M·R).
- Sorting: O(M log M). With a
top_k,heapq.nlargestreduces this to O(M log k). - Extra space: O(M).
Edge cases
- No matches: return
[]before anymin/maxcall. - No rankers: return the filtered events in original order.
- All scores equal, or a single candidate: the range is zero, so skip that ranker instead of dividing by zero.
- Negative weight: raise
ValueError; express the opposite preference with an inverse ranker. - Inverted price range: raise
ValueError. Open-ended ranges (only a min or only a max) are allowed. top_klarger than M: slicing handles it.
Trade-offs and common mistakes
- Mixing raw scores of different scales without normalization, so one ranker silently dominates.
- Putting
if isinstance(...)branches in the engine, which breaks Open/Closed. - Letting each ranker decide its own direction, which pushes inconsistency into the engine.
- Normalizing over the whole catalog rather than the filtered set, which makes results depend on events the user can never see. Normalizing over the candidates is cheaper and more relevant, but scores are then not comparable across different requests; if stable scores matter, use fixed known bounds per ranker instead.
- Forgetting empty-input and zero-range cases.
Possible follow-ups
Add a DateWindowFilter using start_time, a DistanceRanker that takes the user location, caching of expensive scores, or per-user weight profiles loaded from configuration.