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

    A production-ready favorites feature requires more than a simple add or remove operation. This article covers requirement boundaries, relationship modeling, idempotent writes, counter maintenance, cursor pagination, cache consistency, fault handling, and monitoring strategies for building a reliable favorites system under concurrent traffic.

    1. Requirements and Feature Boundaries

    Favorites are one of the most common interactions on content platforms. When users find a valuable article, video, or product, they expect to retrieve it quickly later. Although the feature appears simple, it involves writes, removals, counter updates, list rendering, and status checks. If any part is implemented incorrectly, the system may create duplicate records, produce inaccurate counts, or return inconsistent lists.

    Before designing the system, define the feature boundaries clearly:

    • Favorite targets: Should the system support multiple content types through a unified model? A unified model improves reuse, but it must retain extensible fields for different types.
    • Favorite folders: Should users be able to organize favorites into multiple folders? If so, each relationship must include a folder identifier, and query conditions will become more complex.
    • Visibility: Can other users view a user’s favorites? This determines the authorization requirements for list APIs.
    • Removal semantics: Should canceled favorites remain in the database? Most use cases only need the current state, but behavioral analytics may require historical records.

    Once these boundaries are established, the data model and APIs can be designed with less risk of major rework later.

    2. Data Model Design

    A favorite is essentially a relationship between a user and a content item. The most direct approach is to create a relationship table:

    1. CREATE TABLE favorite (
    2. id BIGINT NOT NULL PRIMARY KEY,
    3. user_id BIGINT NOT NULL,
    4. item_type SMALLINT NOT NULL, -- Content type, such as article, video, or product
    5. item_id BIGINT NOT NULL,
    6. status SMALLINT NOT NULL DEFAULT 1, -- 1 means active, 0 means canceled
    7. created_at TIMESTAMP NOT NULL,
    8. updated_at TIMESTAMP NOT NULL,
    9. UNIQUE (user_id, item_type, item_id)
    10. );
    11. CREATE INDEX idx_user_status_time ON favorite (user_id, status, created_at);

    Several design decisions are important here:

    1. The unique constraint is the final safeguard against duplicates. Even if a race condition exists in the application layer, the database will not store two identical relationships. Business code should not rely only on a “check, then insert” sequence.

    2. Use a status field instead of physical deletion. When a user removes a favorite, set status to 0. When the user favorites the item again, update the same row. This avoids frequent deletes and inserts, reduces index fragmentation, and preserves data that may be useful for behavioral analysis.

    3. Build indexes around high-frequency queries. The primary list query typically retrieves a user’s active favorites and sorts them by time. The composite index (user_id, status, created_at) allows the database to filter and order efficiently, reducing table lookups and sorting overhead.

    4. Use globally unique primary keys. As the dataset grows, database sharding may become necessary. Adopting globally unique IDs from the beginning reduces the cost of future migrations.

    3. Write Path: Preventing Duplicates and Ensuring Idempotency

    Users may double-click a button, retry automatically after a network timeout, or perform the same action simultaneously from multiple devices. These situations can produce concurrent writes. The first priority should be idempotency, followed by performance optimization.

    An operation is idempotent when executing the same request once or multiple times produces the same result.

    The following pseudocode illustrates an idempotent add operation:

    1. function addFavorite(userId, itemType, itemId):
    2. begin transaction
    3. row = findFavorite(userId, itemType, itemId)
    4. if row exists:
    5. if row.status == 1:
    6. commit
    7. return OK // Already favorited; return success
    8. updateStatus(row.id, from=0, to=1) // Restore a previously canceled favorite
    9. incrementCounter(itemType, itemId, +1)
    10. commit
    11. return OK
    12. try:
    13. insertFavorite(userId, itemType, itemId, status = 1)
    14. incrementCounter(itemType, itemId, +1)
    15. commit
    16. catch uniqueConflict:
    17. rollback
    18. return OK // Another concurrent request succeeded
    19. return OK

    The key points are:

    • Repeated requests should return the same result. The client does not need to know whether a previous request has already taken effect. Retrying remains safe.
    • State and counter changes should be handled in the same transaction. If they are executed independently, a failure between the two operations may leave the favorite state updated while the counter remains unchanged.
    • A unique-key conflict can be treated as success. If two requests attempt to insert the same relationship concurrently, one will fail because of the unique constraint. Since the other request has already completed the write, returning success is appropriate.

    Removing a favorite should use a conditional update:

    1. function removeFavorite(userId, itemType, itemId):
    2. affected = updateStatusIf(userId, itemType, itemId, from=1, to=0)
    3. if affected == 1:
    4. decrementCounter(itemType, itemId, -1)
    5. return OK

    The conditional update ensures that the counter is decremented only when the status actually changes from 1 to 0. If the user clicks the remove button repeatedly, the second update affects zero rows, so the counter is not decremented again.

    4. Maintaining Favorite Counters

    Content detail pages commonly display the number of favorites. Running COUNT against the favorites table for every request can put sustained pressure on the database, especially for popular content. The count should therefore be maintained separately.

    There are three common approaches:

    • Synchronous counter updates: Update the counter at the same time as the favorite relationship. This provides strong consistency but makes the write path longer.
    • Asynchronous event processing: Publish favorite events to a message queue and let consumers update the counter. This improves write latency, but the displayed count may be temporarily delayed.
    • Periodic reconciliation: Use an offline task to compare the relationship table with the counter value and correct discrepancies. This acts as a fallback for the first two approaches.

    In practice, these approaches are often combined. Transactional scenarios may use synchronous updates, while display-oriented scenarios may use asynchronous updates together with periodic reconciliation.

    Popular content creates another challenge: many concurrent requests may update the same counter row, producing a write hotspot. A general mitigation strategy is counter sharding:

    1. shardKey = itemType + ":" + itemId + ":" + (userId % SHARD_COUNT)
    2. increment(shardKey, delta)
    3. // Aggregate all shards when reading the total
    4. total = sum(get(itemType + ":" + itemId + ":" + i) for i in 0..SHARD_COUNT-1)

    Sharding distributes writes across multiple rows. The trade-off is that reads must aggregate the shards. The total should therefore be cached in a storage layer optimized for read-heavy workloads, with a reasonable expiration time.

    5. List Queries and Pagination

    Favorite lists are usually displayed in reverse chronological order. With OFFSET pagination, the database must scan and discard all preceding records before returning the requested page. The deeper the page, the more expensive the query becomes.

    Cursor-based pagination avoids this problem by using the sorting values from the last item on the previous page as the starting point:

    1. SELECT id, item_id, created_at
    2. FROM favorite
    3. WHERE user_id = ?
    4. AND status = 1
    5. AND (created_at < ? OR (created_at = ? AND id < ?))
    6. ORDER BY created_at DESC, id DESC
    7. LIMIT 20;

    Two details are especially important:

    1. The ordering fields must uniquely identify a position. Multiple records may have the same timestamp, so id is added as a secondary sort field. This makes the cursor stable and unambiguous.

    2. The list API should return relationship data only. After obtaining the content IDs, retrieve content details in batches. If some items have been deleted or unpublished, filter them at the presentation layer and use an asynchronous task to clean up invalid favorite relationships.

    6. Caching and Consistency

    The question “Has the current user favorited this item?” is frequently asked on content detail pages and is a good candidate for caching. Cache keys can be organized by user, with the value containing the set of items favorited by that user.

    A practical update strategy is to update the database first and then delete the cache:

    1. function updateFavoriteWithCache(userId, itemType, itemId, action):
    2. write database (add or remove favorite)
    3. deleteCache(user:favorite-set:userId)

    This approach is simple and usually avoids long-lived stale data. If cache deletion fails, retries or message-based compensation can ensure eventual deletion. The cache should also have a finite expiration time as a final safeguard.

    Cache consistency must be balanced against performance. For display-only states such as whether an item has been favorited, brief inconsistency is often acceptable. For counters and transactional decisions, the database should be treated as the source of truth, or the primary database should be read directly on critical paths.

    7. Failure Handling and Resilience

    In production, the cache, message queue, and database can all experience failures. The system should define handling strategies in advance:

    • Cache unavailability: Fall back to direct database access, while applying rate limits to protect the database from a cascading failure.
    • Counter drift: Scan the relationship table in batches by primary-key range. Keep each batch small to avoid holding locks for too long. Record discrepancies in logs and trigger alerts.
    • Repeated requests: Include a client-generated request ID or business idempotency key in write requests so the server can identify and reject duplicates.
    • Invalid content: Favorites for deleted content should not continue to appear. Presentation-layer filtering and asynchronous cleanup should be used together.

    Monitoring is essential for detecting problems. At a minimum, track the following metrics:

    • Write success rate
    • Percentage of duplicate requests
    • Counter discrepancy volume
    • List API latency percentiles, such as P99
    • Cache hit rate

    Each metric should have clearly defined alert thresholds and be connected to the release process.

    8. Pre-Launch Checklist

    Before releasing the feature, verify the following items:

    1. Unique constraints and query indexes have been created, and query plans confirm that the indexes are being used.
    2. Add and remove APIs are idempotent, with consistent results for repeated requests.
    3. State changes and counter updates occur in the same transaction, or a reliable asynchronous mechanism guarantees eventual consistency.
    4. List APIs use cursor-based pagination, and the ordering fields provide a unique and stable position.
    5. Counter reconciliation tasks have been prepared.