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.
CREATE TABLE user_favorite (id BIGINT NOT NULL AUTO_INCREMENT,user_id BIGINT NOT NULL,content_id BIGINT NOT NULL,status TINYINT NOT NULL DEFAULT 0 COMMENT '1 active, 0 removed',ver BIGINT NOT NULL DEFAULT 0 COMMENT 'Incremented by the server on each state change',fav_time DATETIME(3) NOT NULL COMMENT 'Time of the latest transition from removed to active',PRIMARY KEY (id),UNIQUE KEY uk_user_content (user_id, content_id),KEY idx_user_status_time (user_id, status, fav_time, content_id)) 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:
CREATE TABLE favorite_op_log (req_id VARCHAR(64) NOT NULL COMMENT 'UUID generated for each client click and reused on retries',user_id BIGINT NOT NULL,content_id BIGINT NOT NULL,action TINYINT NOT NULL COMMENT '1 add favorite, 0 remove favorite',created_at DATETIME(3) NOT NULL,PRIMARY KEY (req_id),KEY idx_created (created_at)) 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.
CREATE TABLE content_brief (content_id BIGINT NOT NULL,content_type TINYINT NOT NULL,title VARCHAR(255) NOT NULL,cover_url VARCHAR(512),author_name VARCHAR(64),is_online TINYINT NOT NULL DEFAULT 1 COMMENT '0 unavailable or deleted',content_version BIGINT NOT NULL COMMENT 'Version published by the content service',PRIMARY KEY (content_id)) 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:
UPDATE content_briefSET title = ?, cover_url = ?, author_name = ?, is_online = ?, content_version = ?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 returnsDuplicateKey(1062), another consumer inserted the record concurrently. Run the conditionalUPDATEagain. 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:
- Allow only one request for the same
content_idwithin a defined interval. - Apply a global rate limit to requests sent to the content service.
- 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_versionvalues 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_favoritehas the unique index, and test duplicate inserts before deployment. - Use version-conditional updates for
content_brief; handle zero affected rows as described and test theDuplicateKeybranch. - Pass the out-of-order and duplicate-event test using versions
3, 1, 2, 2. - Display placeholders for missing
content_briefrows, 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:
- A user clicks several times in quick succession, creating separate operations.
- 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:
favorite(req_id, user_id, content_id):BEGINtry:INSERT INTO favorite_op_log (req_id, user_id, content_id, action)VALUES (?, ?, ?, 1)except DuplicateKey(1062): # Already processed or being processed concurrentlyROLLBACKreturn OKINSERT INTO user_favorite (user_id, content_id, status, ver, fav_time)VALUES (?, ?, 0, 0, NOW(3))ON DUPLICATE KEY UPDATE user_id = user_id # Ensure the row exists without changing itaffected = UPDATE user_favoriteSET status = 1, ver = ver + 1, fav_time = NOW(3)WHERE user_id = ? AND content_id = ? AND status = 0if affected == 1:INSERT INTO favorite_event (...) # Same transaction; see Section 5UPDATE content_stat SET fav_cnt = fav_cnt + 1 WHERE content_id = ?COMMITreturn 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:
cancel(req_id, user_id, content_id):BEGININSERT INTO favorite_op_log ... # action = 0; on a duplicate, return OKaffected = UPDATE user_favoriteSET status = 0, ver = ver + 1WHERE user_id = ? AND content_id = ? AND status = 1if affected == 1:INSERT INTO favorite_event (...)UPDATE content_stat SET fav_cnt = fav_cnt - 1 WHERE content_id = ?COMMITreturn 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
statusis already0, 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:
UPDATE user_favoriteSET status = 0, ver = ver + 1WHERE 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_idarrive together. The second waits on the unique index. Once the first commits, the second receives error1062and returns success. - Transaction rollback: The operation log and main-table changes roll back together. Retrying with the same
req_idcan 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_cntdaily from rows inuser_favoritewherestatus = 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_atis older than the retention window so that an expired retry cannot reapply an old operation.
Checklist
- Submit the same
req_idconcurrently and verify that it produces only one effective state change. - Run the
UPDATEtests with bothuseAffectedRows=falseanduseAffectedRows=true; results must match. - Test all removal branches: missing row, already inactive, and transition from
1to0. 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.
favorite(...):result = complete the write transaction and COMMITif result indicates an actual state change:cache.delete(key(user_id, content_id)) # Delete only after commitcache.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.
invalidate(key):for attempt in 1..5:if cache.delete(key) succeeds: returnsleep(backoff(attempt)) # 100ms, 200ms, 400ms ...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:
fav_time DESC, content_id DESC
content_id provides a stable secondary order when multiple rows share the same fav_time.
First Page
SELECT f.content_id, f.fav_time,b.title, b.cover_url, b.author_name, b.is_onlineFROM user_favorite fLEFT JOIN content_brief b ON b.content_id = f.content_idWHERE f.user_id = ? AND f.status = 1ORDER BY f.fav_time DESC, f.content_id DESCLIMIT 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):
SELECT f.content_id, f.fav_time,b.title, b.cover_url, b.author_name, b.is_onlineFROM user_favorite fLEFT JOIN content_brief b ON b.content_id = f.content_idWHERE f.user_id = ? AND f.status = 1AND (f.fav_time < ? OR (f.fav_time = ? AND f.content_id < ?))ORDER BY f.fav_time DESC, f.content_id DESCLIMIT 21;
Cursor Boundary Details
- Preserve time precision.
fav_timeisDATETIME(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 JavaScriptNumber’s exact integer range. Returncontent_idas 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_timevalues 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=falseand omit the next cursor.
Checklist
- Test pagination across multiple records with identical
fav_timevalues; 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_briefrow 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:
CREATE TABLE favorite_event (event_id BIGINT NOT NULL AUTO_INCREMENT,user_id BIGINT NOT NULL,content_id BIGINT NOT NULL,action TINYINT NOT NULL COMMENT '1 add favorite, 0 remove favorite',ver BIGINT NOT NULL COMMENT 'Version in the main table',occurred_at DATETIME(3) NOT NULL,published TINYINT NOT NULL DEFAULT 0,PRIMARY KEY (event_id),
