Designing and Implementing a Favorites Feature: From Data Modeling to High-Concurrency Systems

    A favorites feature may look like a simple interaction, but it plays an important role in content products. This article explains how to design its data model, build idempotent APIs, optimize counters and list queries, handle traffic spikes, and maintain consistency through asynchronous processing and monitoring. The same principles also apply to likes, follows, votes, and other lightweight user-content relationships.

    Designing and Implementing a Favorites Feature: From Data Modeling to High-Concurrency Systems

    1. Why the Favorites Feature Deserves Careful Design

    A favorites action may look like a lightweight, one-click interaction, but it serves several important purposes in a content product:

    1. User value: It helps users save content they care about, build a personal knowledge base, and increase return visits and time spent.
    2. Data value: A favorite is a strong intent signal. Compared with browsing or liking, it often reflects user interest more directly and can be used as a feature in recommendation systems.
    3. System value: When highly popular content—such as a trending video or viral article—is published, favorite requests can create sudden traffic spikes. This makes the feature a useful test of a system’s elasticity.

    A well-designed favorites system should do more than support saving content. It should be idempotent, responsive, scalable, and measurable.

    2. Data Model Design

    2.1 Core Tables

    The core of a favorites system is a many-to-many relationship between users and content. In most cases, two tables are sufficient.

    Favorites relationship table

    1. CREATE TABLE user_favorite (
    2. id BIGINT PRIMARY KEY AUTO_INCREMENT,
    3. user_id BIGINT NOT NULL,
    4. content_id BIGINT NOT NULL,
    5. folder_id BIGINT DEFAULT 0, -- Favorites folder
    6. status TINYINT DEFAULT 1, -- 1: active, 0: canceled
    7. create_time DATETIME NOT NULL,
    8. update_time DATETIME NOT NULL,
    9. UNIQUE KEY uk_user_content (user_id, content_id),
    10. KEY idx_user_folder (user_id, folder_id, update_time)
    11. );

    Content-level counter table

    1. CREATE TABLE content_favorite_count (
    2. content_id BIGINT PRIMARY KEY,
    3. fav_count BIGINT NOT NULL DEFAULT 0,
    4. update_time DATETIME NOT NULL
    5. );

    2.2 Key Design Considerations

    • Use a unique index as the final safeguard: The unique key on (user_id, content_id) prevents duplicate favorites. Even if a user clicks repeatedly or a message is delivered more than once, duplicate relationship records cannot be created.
    • Use a status field instead of physical deletion: This makes auditing and anti-abuse analysis easier and preserves continuity when a user cancels and later restores a favorite.
    • Store counters separately: Updating the main content table at high frequency can create row-lock contention. A dedicated counter table also makes it easier to migrate the counter to a cache or a specialized counting service later.

    3. API Design and Idempotency

    3.1 Core APIs

    1. POST /favorites Add a favorite
    2. DELETE /favorites/{contentId} Cancel a favorite
    3. GET /favorites?userId=&folderId=&cursor= List favorites with cursor pagination
    4. GET /favorites/count?contentId= Query the favorite count
    5. GET /favorites/status?contentId= Check whether the content is favorited

    3.2 Implementing Idempotency

    Both adding and canceling a favorite must be idempotent. A recommended approach is to combine an atomic write with a unique-key safeguard:

    1. def add_favorite(user_id, content_id):
    2. try:
    3. db.execute(
    4. "INSERT INTO user_favorite(user_id, content_id, status, create_time, update_time) "
    5. "VALUES (%s, %s, 1, NOW(), NOW()) "
    6. "ON DUPLICATE KEY UPDATE status = 1, update_time = NOW()",
    7. (user_id, content_id)
    8. )
    9. # Update the counter asynchronously
    10. mq.send("fav_count_incr", {"content_id": content_id})
    11. return {"ok": True}
    12. except DBError:
    13. return {"ok": False, "msg": "please retry"}

    The key points are:

    1. Use ON DUPLICATE KEY UPDATE, or an equivalent upsert operation, to combine the existence check and write into one atomic operation. This avoids a check-then-write race under concurrent requests.
    2. Send a counter message only when the relationship status actually changes. The affected-row count or equivalent write result can be used to prevent duplicate increments.

    4. Optimization Strategies for High-Concurrency Scenarios

    4.1 Cache Counters and Persist Them Asynchronously

    Popular content can generate extremely high QPS for favorite-count queries. Reading the database directly is not a viable approach at that scale. A typical architecture is:

    • Read counters from Redis first, using atomic operations such as INCR and DECR.
    • Use scheduled jobs or a message queue to batch-write counter updates to the database.
    • Allow temporary inconsistency between the cache and database in exchange for higher availability, with eventual consistency as the target.
    1. User request → Write to DB (upsert) → Publish to MQ → Consumer updates Redis counter → Periodically persist to DB

    4.2 Smooth Writes for Hot Content

    When a piece of content becomes highly popular, favorite requests can reach tens of thousands per second. Common strategies include:

    1. Use a message queue for traffic smoothing: Keep the write path limited to necessary persistence operations and process counter updates asynchronously.
    2. Aggregate locally: On the counter consumer side, aggregate increments for each content item in memory over a short interval, then update Redis in batches. This reduces network traffic and computation overhead.
    3. Apply rate limiting and graceful degradation: Rate-limit the favorites API by user. Under extreme conditions, temporarily delay counter display rather than disrupting the primary favorite operation.

    4.3 Optimize Favorites List Queries

    • Use cursor-based pagination instead of deep pagination with OFFSET. For example:

      1. WHERE update_time < last_time
      2. ORDER BY update_time DESC
      3. LIMIT 20

      This avoids scanning large numbers of skipped rows.

    • Retrieve titles, cover images, and other content metadata through a batch request to the content service, and add a short-TTL cache where appropriate.
    • If a user has a very large number of favorites—thousands or more—consider partitioning storage by favorites folder or introducing a search or document-oriented store to support multi-condition filtering.

    5. Consistency and Monitoring

    5.1 Consistency Guarantees

    • Allow weak consistency for counters: The display layer can tolerate a small error in the favorite count. Availability should take priority.
    • Reconcile data periodically: Use scheduled jobs to sample and compare database and Redis counters. If a discrepancy is detected, trigger a correction.
    • Ensure message reliability: Failed message processing should enter a retry queue. Consumers must be idempotent, using a unique key or equivalent mechanism to prevent duplicate counter increments.

    5.2 Key Monitoring Metrics

    Metric Description
    Favorite success rate A core availability metric. A sudden decline usually indicates a storage or dependency failure.
    P99 write latency Reflects write performance under hot-content traffic.
    Counter discrepancy rate The difference ratio found when reconciling Redis and database counters.
    MQ consumer backlog A direct signal of whether the traffic-smoothing capacity is sufficient.

    6. Summary

    A favorites feature is a typical example of a small product requirement that can become a substantial engineering project. Four principles are especially important:

    1. For the data model, use a unique key to guarantee correctness, a status field instead of physical deletion, and a separate counter store.
    2. For API design, use upsert operations to achieve idempotency and cursor-based pagination to support large favorite lists.
    3. For performance architecture, separate reads and writes, place caching in front of high-frequency access, and use asynchronous processing to smooth traffic spikes.
    4. For operations and reliability, reconcile data to correct discrepancies and monitor the entire request and processing path.

    The same approach applies to likes, follows, votes, and other lightweight relationships between users and content. Once these patterns are understood, they can be reused across a wide range of interactive systems.