How to Build a Favorites Feature for Content Platforms: Data Modeling, Idempotency, and Scaling
This article explains how to implement a favorites (bookmark) feature for content platforms, where a simple button creates significant backend consistency challenges. It covers a relationship-based data model with a unique index and logical deletion, idempotent add and cancel APIs backed by database constraints, asynchronous counter updates with cache-database reconciliation, cursor-based pagination, high-concurrency scaling, security and compliance checks, and a pre-launch checklist.
1. Why “Favorites” Looks Simple but Is Hard to Build
In most content community products, the favorites button is easy to overlook, yet it plays three roles at once: a personal asset for the user, a popularity signal for the content, and a distribution input for operations. The original material shows only a single favorites entry point with minimal interaction traces, which illustrates one fact: the lighter the product surface, the greater the consistency pressure on the backend.
The complexity comes from four dimensions:
- High write volume with clear spikes. After a trending item goes live, favorites can surge within minutes.
- State must be idempotent. Repeated taps, client retries, and network jitter can all produce duplicate requests.
- Counts on both sides must be strongly consistent. A user’s “My Favorites” list and the total count on the content detail page must eventually align.
- Permissions and visibility are coupled. Whether a folder is public, or whether content is deleted or made private, affects read results.
2. Data Model: Think About the “Relationship” Before the “Fields”
A favorite is essentially a many-to-many relationship, so the modeling core is a relationship table rather than a boolean flag on the content table.
-- Favorites relationship table (illustrative)CREATE TABLE user_favorite (id BIGINT NOT NULL AUTO_INCREMENT,user_id BIGINT NOT NULL,content_id BIGINT NOT NULL,folder_id BIGINT NULL COMMENT 'Folder; NULL means the default folder',status TINYINT NOT NULL DEFAULT 1 COMMENT '1 active, 0 canceled',created_at DATETIME NOT NULL,updated_at DATETIME NOT NULL,PRIMARY KEY (id),UNIQUE KEY uk_user_content (user_id, content_id),KEY idx_user_time (user_id, status, created_at),KEY idx_content (content_id, status));
A few key design trade-offs:
- The unique index
uk_user_contentis the first line of defense for idempotency, pushing “duplicate favorites” down from a business check to a storage constraint. - Logical deletion (
status) is used instead of physical deletion, making it easy for users to recover from mistakes and enabling audit and risk-control tracing. idx_user_timesupports paginating “My Favorites” in reverse chronological order;idx_contentsupports content-side statistics and deduplication checks.- If the product supports folders, keeping folder decoupled from the relationship avoids large-scale data migration when users reorganize their favorites.
3. API Design and Idempotent Writes
Two semantically clear APIs are recommended instead of a single toggle API. A toggle has unstable semantics under concurrency and retries, making it a common source of production incidents.
POST /api/favorite/add { content_id, folder_id? }POST /api/favorite/cancel { content_id }GET /api/favorite/list { cursor, size }
The recommended server-side write logic is:
def add_favorite(user_id, content_id):# 1. Check content visibility to avoid favoriting deleted/private contentif not content_service.visible(content_id, user_id):return "CONTENT_UNAVAILABLE"try:# 2. Rely on the unique index for an idempotent insertdb.insert_ignore("user_favorite", {"user_id": user_id, "content_id": content_id,"status": 1, "created_at": now(), "updated_at": now()})except DuplicateKey:db.update("user_favorite", {"status": 1},where="user_id=? and content_id=?", args=(user_id, content_id))# 3. Make counting and caching asynchronous to avoid blocking the main pathmq.send("favorite_events", {"uid": user_id, "cid": content_id, "op": "add"})return "OK"
The key idea: let the database’s unique constraint decide whether the item is already favorited, and hand counting, recommendation signals, and activity notifications to a message queue for asynchronous consumption. The main path does only one thing that must be synchronous — persisting the record.
4. Count Consistency: Reconciling Cache and Database
The favorites total is a typical read-heavy, write-heavy field; aggregating it in real time will overload the database on trending content. The common industry approach is cached counters + asynchronous persistence + periodic reconciliation:
- Write path: update the cache counter first, publish a change event, and let a consumer batch-flush it back to the database.
- Read path: the detail page reads from cache first; on a cache miss, it aggregates from the source and backfills.
- Reconciliation: a low-frequency job compares the cache with the real aggregated value and corrects it using the database as the source of truth when the deviation exceeds a threshold.
incr favorite:cnt:{content_id} 1expire favorite:cnt:{content_id} 86400
When batch-flushing to the database, always merge multiple changes to the same key to avoid write amplification:
def flush(counter_batch):for cid, delta in counter_batch.items():db.exec("UPDATE content SET favorite_cnt = favorite_cnt + ? WHERE id = ?",(delta, cid))
5. List Pagination: Prefer Cursors Over Offsets
“My Favorites” is a page users visit frequently. With deep pagination, LIMIT offset, size keeps scanning and discarding the first offset rows, and the cost grows linearly with page number. Switching to cursor-based pagination on (created_at, id) reduces the complexity to constant time:
GET /api/favorite/list?cursor=2026-08-26T10:00:00Z_10086&size=20
SELECT content_id, created_at FROM user_favoriteWHERE user_id = ? AND status = 1AND (created_at < ? OR (created_at = ? AND id < ?))ORDER BY created_at DESC, id DESCLIMIT 20;
6. High Concurrency and Elastic Scaling
When favorite writes hit peak, load can be handled at three levels:
- Scale stateless services horizontally, externalizing session and authentication data to cache.
- Use a message queue for peak shaving, separating non-critical paths (counts, activity feeds, user profiles) from the synchronous path.
- Isolate trending-content counters, sharding by content dimension when necessary so a single key does not become a bottleneck.
On the cloud, you can combine a container platform to host stateless services, object storage for static assets, a message queue for asynchronous events, and logging plus monitoring and alerting to close the observability loop. Baidu AI Cloud offers these general capability categories; refer to the official documentation for specific specifications and pricing. This article does not cover any undisclosed parameters.
7. Security and Compliance Essentials
- Authorization checks: every read of the favorites list must filter out deleted, private, and followers-only content.
- Rate limiting: throttle per user per API to prevent scripts from inflating popularity through fake favorites.
- Privacy boundaries: public folders must be clearly disclosed to users, with a one-click option to make them private.
- Data deletion: when a user closes their account, the relationship data should be fully purged to meet compliance requirements.
8. Pre-Launch Checklist
- Is the unique index in effect, and do duplicate requests return an idempotent success?
- Does the cache-database reconciliation job have alerting?
- Does cursor pagination cover boundary duplicates or gaps caused by concurrent writes?
- After canceling a favorite, do the list, count, and activity feed become eventually consistent?
- Does load testing cover the single-point write scenario for trending content?
The real difficulty of a favorites feature is not the button but turning a lightweight interaction into a verifiable, traceable, and scalable data pipeline. Following the model and process above keeps the system stable at medium scale while leaving room to evolve smoothly to larger scale.
