The Technical Implementation Guide for the Favorites Feature on Content Platforms

    This article explains why the favorites feature is a harder engineering problem than it appears, sitting at the intersection of write hotspots, read hotspots, and data consistency. It compares three data modeling approaches, then walks through idempotent writes, layered counting and caching, cursor-based pagination, cache-storage consistency on unfavorite, capacity governance with hot-cold tiering, and the observability and load-testing checks worth covering before launch.

    1. Why “Favorites” Is an Underrated Technical Problem

    In content community products, favorites are often treated as the simplest feature there is: the user taps once, and you record a relationship. In real production environments, though, favorites sit at the intersection of write hotspots, read hotspots, and data consistency. A single top-performing piece of content can be favorited by millions of users within an hour, creating a classic single-key write hotspot. Meanwhile, the “My Favorites” page has to return results paginated in reverse chronological order, which puts heavy demands on query performance. Treating favorites as “insert a row” usually exposes problems at peak traffic.

    It is worth being clear that favorites, likes, and follows are highly similar in data shape — all are many-to-many “user-to-object” relationships — but they differ in business semantics in two ways. First, favoriting usually carries an intent to “read later,” so users have a stronger expectation of returning to the content, which makes list ordering and retrieval more important. Second, favorites are often organized into groups or folders, adding an extra dimension of ownership. These two points mean a flat association table is not enough.

    2. Data Model: Trade-offs Among Three Mainstream Shapes

    The first is relational modeling: one association table recording (user ID, content ID, creation time, group ID). Its strengths are clear semantics, natural idempotency (deduplication via a unique index), and easy multi-dimensional aggregation. Its weakness is that as the table grows, write and index maintenance costs rise.

    The second is document/wide-table modeling, which aggregates one user’s favorites into a single record and stores content IDs in an array. Reading one user’s favorites takes a single query, but the record size grows with the number of favorites, and updates require rewriting the whole row, which is unsuitable for very large collections.

    The third is scattered-set modeling, which maintains an ordered set structure per user, with content IDs as members and the favorite timestamp as the score. It naturally supports reverse-chronological pagination and range trimming, fits the “favorites folder” read pattern very well, and is the most commonly used shape in practice.

    The more robust engineering approach is to combine them: use relational storage as the single source of truth to guarantee traceability and auditability, and use in-memory data structures to serve hot reads and ordering, with the two aligned through an asynchronous sync pipeline.

    1. -- Source of truth: the unique index guarantees idempotency
    2. CREATE TABLE user_favorite (
    3. user_id BIGINT NOT NULL,
    4. content_id BIGINT NOT NULL,
    5. group_id BIGINT NOT NULL DEFAULT 0,
    6. created_at TIMESTAMP NOT NULL,
    7. UNIQUE KEY uk_user_content (user_id, content_id),
    8. KEY idx_user_time (user_id, created_at)
    9. );

    3. Write Path: Idempotency, Deduplication, and Ordering

    The favorite write path has to answer three questions: what happens on duplicate submissions, what happens on concurrent taps, and what happens on retries after failure. The answer to all three is “idempotency.” The most reliable way to achieve idempotency is not read-then-insert, but relying on the database unique constraint so that a duplicate insert fails outright and is handled as a success.

    1. def add_favorite(user_id, content_id, group_id=0):
    2. try:
    3. db.insert_ignore("user_favorite", {
    4. "user_id": user_id, "content_id": content_id,
    5. "group_id": group_id, "created_at": now()
    6. })
    7. except DuplicateKeyError:
    8. pass # Already favorited; return success idempotently
    9. cache.zadd(f"fav:{user_id}", {content_id: ts})
    10. return {"ok": True}

    On the client side, the button state should be updated optimistically with request debouncing to avoid duplicate requests triggered by network jitter. On the server side, merging requests for the same user and same object within a short window at the gateway layer can significantly reduce invalid writes.

    4. Counting and Caching: Handling Hot Keys Correctly

    The content detail page needs to display the total favorite count — a counter that is read-heavy and write-heavy at the same time. If every favorite directly updates an aggregate value in the database, hot content becomes the bottleneck. The common solution is layering: maintain count increments in memory and flush them to the database in batches on a fixed time window; on reads, take the cached value first and fall back to aggregation only on a cache miss.

    Three points matter in cache design. First, cache null and default values to prevent unfavorited content from repeatedly penetrating to the database. Second, randomize expiration times to avoid a cluster of keys expiring at once and causing an avalanche. Third, use local caching with a short TTL for hot keys, keeping the pressure inside the process. If you use the relevant foundational capabilities from Baidu AI Cloud, general categories such as caching and object storage can carry hot data and static assets, so there is no need to build the underlying operations yourself.

    5. Reads and Pagination: Cursors Over Offsets

    If the “My Favorites” list uses page-number offset pagination, deep paging forces the database to scan and discard all preceding records, and the cost grows linearly with the page number. A better approach is cursor-based pagination, using the timestamp and ID of the last item on the previous page as the starting point for the next page.

    1. def list_favorites(user_id, cursor_ts=None, cursor_id=None, size=20):
    2. if cursor_ts is None:
    3. items = cache.zrevrange(f"fav:{user_id}", 0, size - 1, withscores=True)
    4. else:
    5. items = cache.zrevrangebyscore(
    6. f"fav:{user_id}", (cursor_ts, cursor_id), "-inf",
    7. start=0, num=size, withscores=True)
    8. return {"items": items, "next": build_cursor(items)}

    Watch out for identical timestamps: multiple favorites within the same millisecond make the cursor ambiguous, so the sort key should be a (timestamp, content ID) tuple to guarantee a unique total order.

    6. Unfavoriting and Data Consistency

    Unfavoriting is semantically an idempotent delete, and a repeated delete should return success. The genuinely hard part is short-term inconsistency between cache and storage: after a successful delete, the cache still returns stale data, and the user sees “unfavorite failed.” The practical trade-off is to accept second-level eventual consistency and broadcast change events asynchronously to each cache node through a message queue. For scenarios with stronger consistency requirements, you can use the order “delete the cache first, then write the database, and backfill on failure,” backed by a retry queue.

    Making things event-driven has an additional benefit: favorites, unfavorites, and group changes can all be abstracted into a unified domain event that downstream modules such as recommendations, statistics, and notifications subscribe to and consume, so the main path does not need to be aware of them.

    7. Capacity Governance and Hot-Cold Tiering

    Once a single user reaches tens of thousands of favorites, loading everything is no longer viable. Governance measures include capping capacity per user per group with a clear message, sharding oversized collections, and migrating long-unaccessed favorites to low-cost object storage or an archive tier, loading them on demand only when the user actively views them. Also set up data inspection jobs to clean up dangling associations pointing to deleted content, so the list does not show blank items.

    8. Observability and Load-Testing Priorities

    Before launch, cover at least three kinds of validation: idempotency validation, where concurrent duplicate submissions produce a single result; hotspot validation, simulating high-concurrency favorites on a single item and observing count lag and cache hit rate; and deep-paging validation, comparing the response differences between cursor and offset approaches at high page numbers. For monitoring, watch write success rate, cache hit rate, sync lag, and the percentile latency of the list endpoint rather than averages alone.

    9. Summary

    The engineering complexity of the favorites feature concentrates in three places: write idempotency, hot counting, and deep-paging reads. Using relational storage as the source of truth, an ordered set to carry hot reads, and event-driven alignment of state across tiers is a robust combination that balances correctness and performance. Get these three solid, and favorites grow from “a button” into a stable foundational capability that can support billions of relationships.