Short-Video Recommendation Home Feed: Data Modeling, Ranking, and Display in Practice
The home feed of a short-video app is more than a simple list API. This article covers the end-to-end engineering design behind a recommended feed: deriving card fields from the UI, building a unified data model for video, live, ad, and banner cards, formatting counts, durations, and relative times, ranking and interleaving cards with diversity constraints, cursor pagination, caching, observability, and testing. It also explains why raw values should be stored separately from formatted display values and how to avoid duplicates and gaps during continuous refresh.
Problem Background
The home feed is one of the most common UI surfaces in content platforms. A single screen can contain video cards, live streams, ad slots, and topic/banner entries. Each card typically shows a cover, title, duration, play count, danmaku count, like count, and publish time.
From an engineering perspective, this type of page has three main difficulties.
- Diverse data sources: Videos, live streams, ads, and other content are produced by different services, and their field structures are not the same.
- Complex display rules: Similar numbers must be formatted with one consistent rule; timestamps must be rendered as relative or absolute time; durations must be converted into a readable format.
- High refresh and performance requirements: Users continuously pull down to load more content. The list must show new items promptly, while avoiding duplicates or missing items.
The following sections walk through the design from the data flow perspective.
Deriving the Field Model from the Page
Start by breaking down every piece of information on the page and mapping it to a field. For a video card, the common fields are:
| Page Element | Field | Type | Notes |
|---|---|---|---|
| Cover | cover_url |
string | Image URL; support size fallback |
| Title | title |
string | Truncate for display |
| Lower-right duration | duration_sec |
int | Stored in seconds; converted for display |
| Play count | play_count |
int | Raw value stored; formatted for display |
| Danmaku count | danmaku_count |
int | Same as play count |
| Like count | like_count |
int | Same as play count |
| Publish time | published_at |
timestamp | Stored as UTC |
| Category tag | category |
string | Used for filtering and diversity control |
The storage layer keeps raw values, while the display layer handles formatting. Separating these two concerns makes ranking, statistics, and internationalization easier.
Unified Data Model
Different content types should share a common outer structure and be distinguished by a type field. The following Python example uses a dataclass to express this idea.
from dataclasses import dataclass, fieldfrom datetime import datetimefrom enum import Enumfrom typing import Optionalclass CardType(str, Enum):VIDEO = "video"LIVE = "live"AD = "ad"BANNER = "banner"@dataclassclass FeedCard:card_id: strcard_type: CardTypetitle: strcover_url: strpublished_at: datetime # stored as UTCduration_sec: Optional[int] = Noneplay_count: int = 0danmaku_count: int = 0like_count: int = 0category: str = ""extra: dict = field(default_factory=dict)
Two design points matter here.
- Ad and live cards should not pollute video statistics. An ad card has no play count, and a live card uses “duration” differently from a video card. Putting those differences into
extraor a dedicated subclass avoids dirtying the metric definitions. - Store time in UTC. Convert to the user’s timezone only at display time. This prevents “future time” bugs and timezone confusion.
Formatting Numbers and Durations
Display formatting functions should be pure functions: raw value in, formatted string out. That makes them easy to unit test.
def format_count(n: int) -> str:"""Convert a count to a compact form, e.g. 9999, 1.2万, 3.5亿."""if n < 10_000:return str(n)if n < 100_000_000:return f"{n / 10_000:.1f}万".replace(".0万", "万")return f"{n / 100_000_000:.1f}亿".replace(".0亿", "亿")def format_duration(seconds: int) -> str:"""Convert seconds to mm:ss or h:mm:ss."""hours, rest = divmod(seconds, 3600)minutes, secs = divmod(rest, 60)if hours:return f"{hours}:{minutes:02d}:{secs:02d}"return f"{minutes:02d}:{secs:02d}"
A few notes:
- The rounding rule should be consistent. The sample removes
".0万"and".0亿"so values like10.0万become10万. - Boundary values should be tested:
9999,10000,99999999, and100000000. - Duration edge cases should include
0seconds and durations longer than one day.
The compact-unit labels in the example are locale-specific. In an English UI, the unit strings can be replaced while preserving the same rounding behavior.
Relative Time Display
Publish time is usually shown as relative time, then switches to an absolute date after a threshold.
from datetime import datetime, timezonedef format_relative_time(published_at: datetime, now: datetime) -> str:"""Both datetimes must carry timezone information."""if published_at.tzinfo is None or now.tzinfo is None:raise ValueError("timezone-naive datetimes are not supported")seconds = int((now - published_at).total_seconds())if seconds < 0:seconds = 0 # clock skew: treat tiny negative values as "just now"if seconds < 60:return "just now"if seconds < 3600:return f"{seconds // 60} min ago"if seconds < 86400:return f"{seconds // 3600} hr ago"if seconds < 7 * 86400:return f"{seconds // 86400} days ago"return published_at.astimezone().strftime("%m-%d")if __name__ == "__main__":now = datetime.now(timezone.utc)print(format_relative_time(now, now)) # just now
Clock skew is a real issue. Server clocks are not perfectly synchronized, so a publish time can be slightly later than the current time. The negative-value fallback handles that gracefully.
Ranking and Interleaving Strategy
Feed ranking should not depend on a single metric. A common and easy-to-explain approach combines interaction signals with time decay:
score = (w_play * log(1 + play_count)+ w_like * log(1 + like_count)+ w_danmaku * log(1 + danmaku_count)) / ((1 + age_hours / T) ** g)
Where:
- Using
log(1 + count)prevents a few viral items from completely suppressing all other content. - The time-decay term gives newer content a chance to appear.
w_*are weights, whileTandgcontrol decay speed. They should be tuned with offline evaluation.
This is a general ranking idea, not a fixed formula. The actual parameters should come from your own business data.
For interleaving, at least two constraints are needed:
- Type quotas: for example, at most one ad card per screen, and no more than two consecutive live cards.
- Category diversity: too many consecutive cards from the same category makes the feed feel repetitive.
These constraints can be applied as a post-processing step. The following example scans the ranked sequence and enforces the quotas:
def interleave(cards: list[FeedCard], max_ad_per_page: int = 1) -> list[FeedCard]:result, ad_count, last_category = [], 0, Nonefor card in cards:if card.card_type == CardType.AD:if ad_count >= max_ad_per_page:continuead_count += 1if card.category and card.category == last_category:# Defer this card and re-insert it at a later position.continueresult.append(card)last_category = card.category or last_categoryreturn result
This example omits the back-fill logic. In a real system, skipped cards should go into a pending queue and be inserted again at appropriate positions, so the list does not lose content.
Cursor Pagination
Feeds should use cursor pagination, not OFFSET. While the user keeps scrolling, new content is inserted at the top of the list, so an offset becomes invalid and can cause duplicates or missing items.
A cursor is usually composed of the sort keys. With publish time and card ID as a composite sort key, the SQL looks like this:
SELECT card_id, title, cover_url, duration_sec, play_count,danmaku_count, like_count, published_at, categoryFROM feed_cardsWHERE (published_at, card_id) < (%s, %s)ORDER BY published_at DESC, card_id DESCLIMIT %s;
Use placeholders for parameters instead of string concatenation to avoid SQL injection.
The server encodes the last row’s (published_at, card_id) tuple and returns it to the client as an opaque string. The client should not depend on the internal structure of the cursor, so the sort key can be adjusted later without breaking clients.
Also create a composite index on (published_at, card_id); otherwise paging can degrade into a full table scan.
Caching and Refresh
The home feed is read-heavy, so caching is a natural fit. A common approach is to cache pages with a short TTL.
- First-screen cache: TTL can be tens of seconds to a few minutes, balancing freshness and load.
- Stale-while-revalidate: return old cached data first, then refresh asynchronously, to reduce user waiting time.
- Interaction numbers can be delayed: play, like, and danmaku counts can tolerate minute-level delay, but whether a card still exists or has been removed should take effect quickly.
- Cache keys should include visible filter conditions and the pagination cursor, otherwise different users or different filters may read stale or incorrect data.
Observability and Quality Monitoring
Feed quality cannot be checked item by item manually. A metrics system should be in place. At minimum, monitor the following:
| Metric | Meaning | Action |
|---|---|---|
| API P95 latency | First-screen and paging response time | Alert when threshold is exceeded |
| Empty page rate | Percentage of requests returning empty results | Check ranking and filter conditions when it rises |
| Duplicate card rate | Percentage of repeated cards in the same session | Check cursor encoding and cache keys |
| Formatting exception count | Exceptions thrown by formatting functions | Usually indicates missing or wrong-type upstream fields |
| Ad quota violation count | Interleaving results that violate type quotas | Check whether all branches of the interleaving logic are covered |
These metrics should be baselined before launch by replaying real requests, not only by observing production after deployment.
Testing Recommendations
- Write parameterized unit tests for
format_count,format_duration, andformat_relative_time, covering boundary values and abnormal inputs. - Test cursor pagination consistency: insert new data during paging and confirm the results have no duplicates or gaps.
- Use property-based tests for the interleaving function: generate random card sequences and verify that quota constraints always hold.
- Run stress tests in a staging environment with a copy of production traffic, watching cache hit rate and database index usage.
Summary
A home feed looks like a simple list, but it actually involves data modeling, display formatting, ranking, interleaving, pagination, caching, and monitoring. The key principles can be summarized as:
- Keep raw values in storage and centralize formatting in the display layer.
- Model content types separately and enforce constraints during interleaving.
- Use cursor pagination, and design caching to balance freshness and load.
Following these principles makes the service easier to extend with new content types and easier to debug when issues appear.
