Favorites System Design: Idempotent Writes and Cache Consistency

    A practical guide to designing a favorites service with a database-backed source of truth, request-level idempotency, cache invalidation and recovery, cursor pagination, and transactional events for recommendation systems. Includes SQL, pseudocode, failure scenarios, and validation checklists for handling retries, concurrent updates, and asynchronous content synchronization.

    Introduction: Why Favorites Need System Design

    A favorites feature can start as a table linking users to content, with two endpoints: add and remove. At scale, several problems emerge. How do repeated clicks avoid duplicate effects? How do deep favorites pages remain responsive? How do reads return the correct state after cache invalidation? And how can favorite activity safely become a recommendation signal?

    This guide covers five parts of the design, using SQL and pseudocode alongside failure scenarios, recovery measures, and validation checklists.

    1. Data Modeling and Indexes: The Main Table Is the Source of Truth

    Store each favorite relationship once, in user_favorite. Each user–content pair has a single row. Removing a favorite sets status to 0; adding it again sets status back to 1. The database enforces uniqueness through uk_user_content, so application code does not need a separate uniqueness check.

    1. CREATE TABLE user_favorite (
    2. id BIGINT NOT NULL AUTO_INCREMENT,
    3. user_id BIGINT NOT NULL,
    4. content_id BIGINT NOT NULL,
    5. status TINYINT NOT NULL DEFAULT 0 COMMENT '1 active, 0 removed',
    6. ver BIGINT NOT NULL DEFAULT 0 COMMENT 'Incremented by the server on each state change',
    7. fav_time DATETIME(3) NOT NULL COMMENT 'Time of the latest transition from removed to active',
    8. PRIMARY KEY (id),
    9. UNIQUE KEY uk_user_content (user_id, content_id),
    10. KEY idx_user_status_time (user_id, status, fav_time, content_id)
    11. ) ENGINE=InnoDB;

    Removing a favorite is a soft delete: the row stays in the table. Adding it again updates the same row rather than creating another relationship. The server increments ver on every state change for concurrency control and event ordering.

    The main table does not store client timestamps. An earlier approach used a client-side op_ts to determine which operation was newer. However, two devices belonging to the same user may have clocks that differ by several minutes. A later operation can therefore carry an earlier timestamp, allowing an outdated state to overwrite a newer one. This design instead uses server-side commit order as the sole ordering rule.

    Store idempotency records in a separate log table:

    1. CREATE TABLE favorite_op_log (
    2. req_id VARCHAR(64) NOT NULL COMMENT 'UUID generated for each client click and reused on retries',
    3. user_id BIGINT NOT NULL,
    4. content_id BIGINT NOT NULL,
    5. action TINYINT NOT NULL COMMENT '1 add favorite, 0 remove favorite',
    6. created_at DATETIME(3) NOT NULL,
    7. PRIMARY KEY (req_id),
    8. KEY idx_created (created_at)
    9. ) ENGINE=InnoDB;

    Titles, cover images, author names, and other list-display fields belong in content_brief, not the main relationship table. The content service owns this data and sends change events to the favorites service. The favorites service maintains a local read model, allowing list queries to use a local join instead of making cross-service calls on every request.

    1. CREATE TABLE content_brief (
    2. content_id BIGINT NOT NULL,
    3. content_type TINYINT NOT NULL,
    4. title VARCHAR(255) NOT NULL,
    5. cover_url VARCHAR(512),
    6. author_name VARCHAR(64),
    7. is_online TINYINT NOT NULL DEFAULT 1 COMMENT '0 unavailable or deleted',
    8. content_version BIGINT NOT NULL COMMENT 'Version published by the content service',
    9. PRIMARY KEY (content_id)
    10. ) ENGINE=InnoDB;

    content_brief stores the latest content metadata. If the product needs the title as it appeared when the user added the favorite, add a field to the main table and populate it at that time. Current metadata and historical snapshots are different semantics and should not share the same representation.

    Content change events carry content_version. Apply an update only when the incoming version is greater than the stored version:

    1. UPDATE content_brief
    2. SET title = ?, cover_url = ?, author_name = ?, is_online = ?, content_version = ?
    3. WHERE content_id = ? AND content_version < ?;

    The application handles the result using the affected-row count. One affected row means the update succeeded. If zero rows are affected, first check whether the record exists:

    • The record exists: The event version is no newer than the stored version. Treat it as an out-of-order or duplicate event and acknowledge it.
    • The record does not exist: Execute an INSERT. If it returns DuplicateKey(1062), another consumer inserted the record concurrently. Run the conditional UPDATE again. If it still affects zero rows, acknowledge the event as not newer. Retry only once; if processing still fails, send the event to a dead-letter queue for manual investigation.

    To validate this behavior, send events for the same content item in version order 3, 1, 2, 2, then send the sequence again. The final title must match version 3.

    Synchronization latency depends on message-queue backlog. Monitor both:

    • Consumer backlog: the number of unconsumed messages in each partition.
    • P99 latency from event publication by the content service to application in the local read model.

    Measure latency through monitoring rather than assuming a value based on experience.

    If a content item has no row in content_brief, display a placeholder card and asynchronously request the missing metadata from the content service. Protect this backfill path in three ways:

    1. Allow only one request for the same content_id within a defined interval.
    2. Apply a global rate limit to requests sent to the content service.
    3. Apply backfill results through the same version-conditional update, making repeated backfills safe.

    Failure Scenarios

    • A content publication event is lost: Version numbers alone cannot detect the missing update. Run daily sampled comparisons between local content_version values and the latest versions in the content service.
    • An event is delayed: Users may temporarily see content that is no longer available. When the local record marks it unavailable, show an “Unavailable” label rather than silently hiding the item or returning an error.

    Checklist

    • Verify that user_favorite has the unique index, and test duplicate inserts before deployment.
    • Use version-conditional updates for content_brief; handle zero affected rows as described and test the DuplicateKey branch.
    • Pass the out-of-order and duplicate-event test using versions 3, 1, 2, 2.
    • Display placeholders for missing content_brief rows, with deduplicated and rate-limited backfill requests.
    • Monitor consumer backlog and P99 synchronization latency, with alerts configured.

    2. Idempotent Writes: Applying a Repeated Request Only Once

    Repeated requests fall into two categories:

    1. A user clicks several times in quick succession, creating separate operations.
    2. A client retries the same operation after a timeout on an unreliable network.

    Use req_id to distinguish them. The client generates a UUID for each click and reuses that UUID for retries. The primary key on favorite_op_log ensures that each request ID is processed only once.

    The add-favorite flow is:

    1. favorite(req_id, user_id, content_id):
    2. BEGIN
    3. try:
    4. INSERT INTO favorite_op_log (req_id, user_id, content_id, action)
    5. VALUES (?, ?, ?, 1)
    6. except DuplicateKey(1062): # Already processed or being processed concurrently
    7. ROLLBACK
    8. return OK
    9. INSERT INTO user_favorite (user_id, content_id, status, ver, fav_time)
    10. VALUES (?, ?, 0, 0, NOW(3))
    11. ON DUPLICATE KEY UPDATE user_id = user_id # Ensure the row exists without changing it
    12. affected = UPDATE user_favorite
    13. SET status = 1, ver = ver + 1, fav_time = NOW(3)
    14. WHERE user_id = ? AND content_id = ? AND status = 0
    15. if affected == 1:
    16. INSERT INTO favorite_event (...) # Same transaction; see Section 5
    17. UPDATE content_stat SET fav_cnt = fav_cnt + 1 WHERE content_id = ?
    18. COMMIT
    19. return OK

    The meaning of “affected rows” must be explicit. MySQL can report either matched rows or rows actually changed. Connector/J returns matched rows by default; enabling useAffectedRows=true returns changed rows.

    The counts are equal only when every matched row is modified. Here, the UPDATE condition includes status = 0, and every matching row changes to 1. Both counting modes therefore produce the same result, independent of the driver setting. Document this in a code comment and test both configurations.

    Removing a favorite follows the same pattern:

    1. cancel(req_id, user_id, content_id):
    2. BEGIN
    3. INSERT INTO favorite_op_log ... # action = 0; on a duplicate, return OK
    4. affected = UPDATE user_favorite
    5. SET status = 0, ver = ver + 1
    6. WHERE user_id = ? AND content_id = ? AND status = 1
    7. if affected == 1:
    8. INSERT INTO favorite_event (...)
    9. UPDATE content_stat SET fav_cnt = fav_cnt - 1 WHERE content_id = ?
    10. COMMIT
    11. return OK

    For removal, zero affected rows can mean either:

    • The record does not exist because the user has never added this content to favorites.
    • The record exists but status is already 0, because the request repeats a removal or overlaps with a removal from another device.

    Both cases return success without emitting an event or changing the count.

    Only a real transition from 1 to 0 emits an event and decrements the count. This ensures that each actual state change generates exactly one event. A discrepancy between the main table and the counter should therefore indicate a code defect or database failure and can be detected through reconciliation.

    Cross-Device Ordering

    The server determines operation order across devices. Operations on the same relationship are serialized by the database row lock, and the later committed operation determines the final state. Document this rule in the product specification and verify it with tests. Client clocks do not participate in ordering.

    If the product must reject stale operations from an offline device, the client can include the last base_ver it observed. The server then uses a conditional update:

    1. UPDATE user_favorite
    2. SET status = 0, ver = ver + 1
    3. WHERE user_id = ? AND content_id = ? AND status = 1 AND ver = ?;

    If no row is affected and the stored version has changed, return a conflict. The client should fetch the current state before deciding whether to replay the operation.

    Transaction Boundary

    The main-table update, event insert, and counter update belong in the same transaction. A failure at any step rolls back the entire transaction, preventing partial commits across state, events, and counts.

    Failure Scenarios and Recovery

    • Concurrent duplicate requests: Two requests with the same req_id arrive together. The second waits on the unique index. Once the first commits, the second receives error 1062 and returns success.
    • Transaction rollback: The operation log and main-table changes roll back together. Retrying with the same req_id can then apply the operation normally.
    • Event insertion failure: The entire transaction rolls back and the state remains unchanged. The client can retry after receiving an error. The state cannot commit without its event.
    • Counter inconsistency: Recalculate fav_cnt daily from rows in user_favorite where status = 1. Alert on discrepancies and repair them with a script.
    • Operation-log expiration: Retain logs longer than the maximum client retry window—for example, seven days. Reject requests whose created_at is older than the retention window so that an expired retry cannot reapply an old operation.

    Checklist

    • Submit the same req_id concurrently and verify that it produces only one effective state change.
    • Run the UPDATE tests with both useAffectedRows=false and useAffectedRows=true; results must match.
    • Test all removal branches: missing row, already inactive, and transition from 1 to 0. Verify responses, events, and counts.
    • Test device clock skew: device A is ten minutes ahead and commits an add first; device B is ten minutes behind and commits a removal afterward. The final state must be inactive.
    • Inject a failure midway through the transaction and verify that state, events, and counts roll back together.
    • Deploy daily counter reconciliation.

    3. Cache Invalidation Order and Recovery

    Favorite-state reads greatly outnumber writes, making caching useful. Cache three kinds of data:

    • Individual favorite state.
    • A user’s total number of favorites.
    • The first page of a user’s favorites list.

    The following examples use individual favorite state; the same invalidation rules apply to the other two.

    The core rule is to commit the database transaction before deleting the cache entry. Do not delete cache entries inside the transaction, and do not replace invalidation with direct cache updates.

    Deleting an entry before a transaction that later rolls back may merely cause another database read. More importantly, deleting before commit can allow a concurrent reader to repopulate the cache with the old state.

    1. favorite(...):
    2. result = complete the write transaction and COMMIT
    3. if result indicates an actual state change:
    4. cache.delete(key(user_id, content_id)) # Delete only after commit
    5. cache.delete(key(user_id, "count"))

    Even this order leaves a race. A reader can retrieve the old database value before the write commits, then place that old value in the cache after invalidation. The stale entry may survive until its TTL expires.

    The design addresses this in two layers.

    Layer 1: Delayed Double Deletion

    Delete once after the write, then delete again after a delay of approximately 500 milliseconds. This covers most read/write interleavings. The delay should exceed the time needed for a database read and subsequent cache population.

    Layer 2: Event-Driven Invalidation

    A more reliable approach is to drive invalidation from favorite_event rather than relying solely on a delete call in request-handling code. The consumer deletes cache entries when it receives a change event, using the same deduplication guarantees as the event-consumption path described in Section 5.

    With this approach, business logic is responsible for committing the database transaction, while an independent consumer handles cache consistency.

    Recovering from Failed Deletes

    cache.delete can fail or time out. When that happens, write an invalidation task to cache_retry. A background worker retries with exponential backoff until the deletion succeeds.

    TTL provides a fallback for all recovery mechanisms. Add random jitter—for example, ±10% of the base TTL—to prevent large numbers of keys from expiring simultaneously and creating a surge of database reads.

    1. invalidate(key):
    2. for attempt in 1..5:
    3. if cache.delete(key) succeeds: return
    4. sleep(backoff(attempt)) # 100ms, 200ms, 400ms ...
    5. cache_retry.insert(task: delete key) # Continue retrying in a background worker

    On a cache miss, use singleflight to coalesce concurrent database reads for the same key. Otherwise, invalidating a hot favorite-state entry can send many simultaneous requests to the database.

    Failure Scenarios

    • Cache deletion fails: Retry tasks handle recovery, with TTL as a fallback.
    • A read/write race repopulates stale data: Delayed double deletion or event-driven invalidation addresses the race.
    • The cache cluster fails: All favorite reads fall back to the database. Assess database fallback capacity in advance and configure circuit breaking.

    Checklist

    • Confirm in code review that cache deletion occurs after commit, never inside the transaction.
    • Inject deletion failures and verify that recovery tasks eventually delete the key.
    • Simulate a reader retrieving old data before commit and delaying its cache write. Verify that the delayed or event-driven deletion removes the stale entry.
    • Add TTL jitter and use singleflight for hot-key cache misses.
    • During cache-failure drills, keep fallback database traffic within capacity.

    4. SQL for Cursor Pagination

    Display favorites in descending order of the time they were added. With OFFSET pagination, deep pages require the database to scan and discard large numbers of rows. New favorites added during browsing can also shift page boundaries and cause repeated items.

    Cursor pagination avoids offset-based scanning and page shifts.

    The index idx_user_status_time (user_id, status, fav_time, content_id) supports the query’s filtering and ordering. Use:

    1. fav_time DESC, content_id DESC

    content_id provides a stable secondary order when multiple rows share the same fav_time.

    First Page

    1. SELECT f.content_id, f.fav_time,
    2. b.title, b.cover_url, b.author_name, b.is_online
    3. FROM user_favorite f
    4. LEFT JOIN content_brief b ON b.content_id = f.content_id
    5. WHERE f.user_id = ? AND f.status = 1
    6. ORDER BY f.fav_time DESC, f.content_id DESC
    7. LIMIT 21;

    Fetch 21 rows for a page size of 20. The extra row determines whether another page exists and is discarded before returning the response.

    Subsequent Pages

    Use the last returned item’s cursor, (last_fav_time, last_content_id):

    1. SELECT f.content_id, f.fav_time,
    2. b.title, b.cover_url, b.author_name, b.is_online
    3. FROM user_favorite f
    4. LEFT JOIN content_brief b ON b.content_id = f.content_id
    5. WHERE f.user_id = ? AND f.status = 1
    6. AND (f.fav_time < ? OR (f.fav_time = ? AND f.content_id < ?))
    7. ORDER BY f.fav_time DESC, f.content_id DESC
    8. LIMIT 21;

    Cursor Boundary Details

    • Preserve time precision. fav_time is DATETIME(3). Return the cursor time at millisecond precision, and have the client send it back unchanged without floating-point conversion.
    • Preserve large IDs. Content IDs may exceed 2^53, beyond JavaScript Number’s exact integer range. Return content_id as a JSON string.
    • Encode or sign cursors. Return a parameter error if parsing fails rather than silently returning an empty page.
    • New favorites appear at the front. Their newer fav_time values place them before the cursor, rather than inserting them into pages already traversed.
    • Removed favorites disappear. An item removed during pagination no longer appears in the results; this is expected behavior.

    Use EXPLAIN to inspect both the first-page and subsequent-page queries. Check that Extra does not contain Using filesort, that the favorites-table access type is ref or range, and that the index supports the query as intended. The right side of the LEFT JOIN uses a primary-key lookup and does not multiply rows.

    If content_brief is missing and b is null, return placeholder metadata rather than failing the entire page. If is_online = 0, retain the item and show “Unavailable” so the user can still remove it from favorites.

    Failure Scenarios

    • A cursor is tampered with: Reject it with a parameter error when signature verification fails.
    • An item is removed between pages: It disappears from subsequent results without shifting offset-based page boundaries.
    • The final page is reached: If fewer than 21 rows are returned, set has_more=false and omit the next cursor.

    Checklist

    • Test pagination across multiple records with identical fav_time values; there must be no duplicates or omissions.
    • Verify that neither first-page nor subsequent-page queries use filesort.
    • Round-trip millisecond-precision cursor timestamps without changes.
    • Verify correct client parsing of content IDs greater than 2^53.
    • Confirm that a missing content_brief row does not prevent the page from being returned.

    5. Safely Feeding Favorite Events into Recommendations

    Favorite activity is an important recommendation signal. Calling the recommendation service directly from request-handling code creates two problems:

    • If the recommendation service is temporarily unavailable, the favorite operation may fail or its signal may be lost.
    • Retrying may cause the recommendation system to count the same favorite more than once.

    Events must therefore remain consistent with state changes and be delivered reliably.

    Write events to an outbox table in the same transaction as the main-table update. The event table definition begins as follows:

    1. CREATE TABLE favorite_event (
    2. event_id BIGINT NOT NULL AUTO_INCREMENT,
    3. user_id BIGINT NOT NULL,
    4. content_id BIGINT NOT NULL,
    5. action TINYINT NOT NULL COMMENT '1 add favorite, 0 remove favorite',
    6. ver BIGINT NOT NULL COMMENT 'Version in the main table',
    7. occurred_at DATETIME(3) NOT NULL,
    8. published TINYINT NOT NULL DEFAULT 0,
    9. PRIMARY KEY (event_id),