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.

    1. Diverse data sources: Videos, live streams, ads, and other content are produced by different services, and their field structures are not the same.
    2. 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.
    3. 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.

    1. from dataclasses import dataclass, field
    2. from datetime import datetime
    3. from enum import Enum
    4. from typing import Optional
    5. class CardType(str, Enum):
    6. VIDEO = "video"
    7. LIVE = "live"
    8. AD = "ad"
    9. BANNER = "banner"
    10. @dataclass
    11. class FeedCard:
    12. card_id: str
    13. card_type: CardType
    14. title: str
    15. cover_url: str
    16. published_at: datetime # stored as UTC
    17. duration_sec: Optional[int] = None
    18. play_count: int = 0
    19. danmaku_count: int = 0
    20. like_count: int = 0
    21. category: str = ""
    22. 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 extra or 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.

    1. def format_count(n: int) -> str:
    2. """Convert a count to a compact form, e.g. 9999, 1.2万, 3.5亿."""
    3. if n < 10_000:
    4. return str(n)
    5. if n < 100_000_000:
    6. return f"{n / 10_000:.1f}万".replace(".0万", "万")
    7. return f"{n / 100_000_000:.1f}亿".replace(".0亿", "亿")
    8. def format_duration(seconds: int) -> str:
    9. """Convert seconds to mm:ss or h:mm:ss."""
    10. hours, rest = divmod(seconds, 3600)
    11. minutes, secs = divmod(rest, 60)
    12. if hours:
    13. return f"{hours}:{minutes:02d}:{secs:02d}"
    14. return f"{minutes:02d}:{secs:02d}"

    A few notes:

    • The rounding rule should be consistent. The sample removes ".0万" and ".0亿" so values like 10.0万 become 10万.
    • Boundary values should be tested: 9999, 10000, 99999999, and 100000000.
    • Duration edge cases should include 0 seconds 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.

    1. from datetime import datetime, timezone
    2. def format_relative_time(published_at: datetime, now: datetime) -> str:
    3. """Both datetimes must carry timezone information."""
    4. if published_at.tzinfo is None or now.tzinfo is None:
    5. raise ValueError("timezone-naive datetimes are not supported")
    6. seconds = int((now - published_at).total_seconds())
    7. if seconds < 0:
    8. seconds = 0 # clock skew: treat tiny negative values as "just now"
    9. if seconds < 60:
    10. return "just now"
    11. if seconds < 3600:
    12. return f"{seconds // 60} min ago"
    13. if seconds < 86400:
    14. return f"{seconds // 3600} hr ago"
    15. if seconds < 7 * 86400:
    16. return f"{seconds // 86400} days ago"
    17. return published_at.astimezone().strftime("%m-%d")
    18. if __name__ == "__main__":
    19. now = datetime.now(timezone.utc)
    20. 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:

    1. score = (
    2. w_play * log(1 + play_count)
    3. + w_like * log(1 + like_count)
    4. + w_danmaku * log(1 + danmaku_count)
    5. ) / ((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, while T and g control 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:

    1. Type quotas: for example, at most one ad card per screen, and no more than two consecutive live cards.
    2. 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:

    1. def interleave(cards: list[FeedCard], max_ad_per_page: int = 1) -> list[FeedCard]:
    2. result, ad_count, last_category = [], 0, None
    3. for card in cards:
    4. if card.card_type == CardType.AD:
    5. if ad_count >= max_ad_per_page:
    6. continue
    7. ad_count += 1
    8. if card.category and card.category == last_category:
    9. # Defer this card and re-insert it at a later position.
    10. continue
    11. result.append(card)
    12. last_category = card.category or last_category
    13. return 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:

    1. SELECT card_id, title, cover_url, duration_sec, play_count,
    2. danmaku_count, like_count, published_at, category
    3. FROM feed_cards
    4. WHERE (published_at, card_id) < (%s, %s)
    5. ORDER BY published_at DESC, card_id DESC
    6. LIMIT %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, and format_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.