Design and Implementation of a Content Platform Favorite Feature
This article explores the technical design and implementation of a favorite/bookmark feature for content platforms, covering requirement boundaries, data modeling, idempotent write operations, consistency strategies, stable pagination, caching, permission handling, and migration practices. It provides practical guidance for building a scalable and reliable favorite system.
Design and Implementation of a Content Platform Favorite Feature
A favorite feature may seem simple: a user clicks a button, and content appears in their favorites list. However, in a real-world content platform, favoriting often intersects with user relationships, content state, counters, notifications, review visibility, pagination, and high-concurrency writes. If implemented merely as a “user–content” relation table, the system is prone to duplicate records, inaccurate counters, unstable list pagination, and interface timeouts under data growth, hot content, and abnormal retry scenarios. From a general technical perspective, this article discusses the requirement boundaries, data model, API design, consistency strategy, and operational practices of a favorite feature.
1. Requirement Boundaries and Design Goals
The first step is to clarify what is being favorited. Typically, favorite targets are content entities such as articles, videos, or posts. The favorite result belongs to a user and may support a default folder or custom folders. Core requirements include: adding a favorite, removing a favorite, checking whether an item is favorited, paginated retrieval of the user’s favorite list, maintaining content favorite counts, and defining display behavior for deleted or removed content.
The design should cover at least four goals:
- Idempotent writes – repeated clicks or client retries must not create duplicate favorites.
- Stable queries – list pagination must not cause large-scale duplication or omission when new data is inserted.
- Explainable counters – content favorite counts may be eventually consistent but must have a calibration mechanism.
- Clear permission and privacy – private favorites, content under review, and deleted content must have explicit visibility rules.
2. Data Model and Storage Choices
It is recommended to model favorite relations and favorite counters separately. The relation table stores the core user–content relationship, while the counter table or field stores the aggregated result. The relation table should have a unique constraint on user_id + content_id to avoid duplicates, and include a status field to distinguish between valid, canceled, and hidden states for auditing and recovery.
A sample DDL for a generic relational model is shown below:
CREATE TABLE user_favorite (user_id BIGINT NOT NULL,content_id BIGINT NOT NULL,folder_id BIGINT NOT NULL DEFAULT 0,status SMALLINT NOT NULL, -- 1 valid, 0 canceledclient_req_id VARCHAR(64) NOT NULL,created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL,PRIMARY KEY (user_id, content_id),UNIQUE (user_id, client_req_id));CREATE TABLE content_favorite_counter (content_id BIGINT NOT NULL PRIMARY KEY,favorite_count BIGINT NOT NULL DEFAULT 0,updated_at TIMESTAMP NOT NULL);
The relation table is suitable for strongly consistent checks of “has this been favorited” and “my favorite list.” The counter table supports high-frequency reads of total favorite counts. For favorite lists, you can shard or partition by user dimension; for content counters, shard by content ID. If the folder hierarchy is complex, add a separate folder table, but avoid stacking too many mutable attributes in the relation table.
3. API Design and Idempotency Control
Write APIs for favorites should carry a client request ID for idempotent deduplication. The API semantic should be “set as favorited” rather than “insert a favorite,” which makes repeated calls inherently safer. Example request:
POST /api/v1/favorites{"contentId": "c_10086","folderId": "default","clientRequestId": "req-7f3a-2024"}
The response should return the current final state instead of simply returning “added successfully”:
{"contentId": "c_10086","favorited": true,"favoriteCount": 1280}
Server-side processing pseudocode:
function setFavorite(userId, contentId, folderId, requestId):begin transactionrecord = queryIdempotency(userId, requestId)if record exists:commitreturn record.resultrow = queryFavorite(userId, contentId)if row exists and row.status == 1:saveIdempotency(userId, requestId, success)commitreturn successupsertFavorite(userId, contentId, folderId, status=1)saveIdempotency(userId, requestId, success)if row not exists or row.status == 0:incrementCounter(contentId, +1)commitpublishFavoriteEvent(userId, contentId)return success
In concurrent scenarios, the unique constraint is the last line of defense. If two requests insert simultaneously, catch the unique key conflict, re-read the final state, and return success—avoid exposing the conflict to the user. Removing a favorite follows the same principle with status flipping and idempotency logging.
4. Consistency Strategy and Counter Calibration
Favorite relations and favorite counters have a natural consistency challenge. A strong consistency approach updates both the relation and the counter in the same database transaction, which is simple but may cause row-lock contention on hot content. An eventually consistent approach writes the relation and emits an event first, then an asynchronous consumer updates the counter. This offers higher throughput but may cause temporary lag in counters.
In practice, a hybrid strategy works well: for normal content, update the counter within the transaction; for hot content, use asynchronous aggregation with a short-period calibration job. The calibration job uses the relation table as the source of truth, compares it with the counter table, and repairs deviations. For user-facing “favorited” status, always rely on the relation table. Total favorite counts may be eventually consistent, but the API should return a version or timestamp to help the frontend handle stale data.
5. Query, Pagination, and Caching
The “my favorites” list should use cursor-based pagination rather than large-offset pagination. The cursor can be based on updated_at + content_id, and the query uses the sorting key of the last item from the previous page. This prevents newly added favorites at the top from causing large-scale duplication on subsequent pages.
For caching, user favorite lists are suitable for short-TTL caches, invalidated per user after write operations. Content favorite counters are suitable for hot-item caches, but they must have expiration and failback strategies. Cache keys should include a visibility dimension to avoid exposing private favorites or content under review. For deleted or removed content, the list query can return placeholder information or filter it out, depending on product rules.
6. Permissions, Privacy, and Content State
Favorite APIs must validate user identity, content visibility, and operation permissions. Private favorites should not appear in public aggregations. Content under review restrictions should not receive new favorites; existing favorites may be hidden or marked according to rules. It is important to distinguish between “remove favorite” (changes relation status) and “delete folder” (requires migrating or batch-processing relations inside it).
For security, apply rate limiting, anti-abuse measures, parameter validation, and audit logging. Watch for abnormally high-frequency favoriting, enumeration of abnormal content IDs, etc. Audit records should include at least user, content, operation type, request ID, and result for troubleshooting.
7. Observability and Capacity Management
Instrument the favorite pipeline with metrics: write QPS, success rate, idempotency hit rate, unique conflict rate, counter deviation, list query latency, cache hit rate, and message queue backlog. Logs should include request IDs to trace across API, database, and asynchronous tasks. Watch for hot content writes, deep pagination of user lists, counter row contention, and message queue backlog.
8. Migration and Gradual Rollout
If migrating from an old favorite logic, consider a four-step approach: dual-write, backfill, comparison, and read switchover. First dual-write to the new and old models and log differences; then offload historical relations; then compare counters and statuses per user or content dimension; finally, roll out the read path with a rollback switch. All write APIs must remain idempotent during migration to avoid conflicts between backfill and real-time writes.
Summary
The engineering difficulty of a favorite feature lies not in the button but in relation modeling, idempotent writes, counter consistency, stable pagination, and permission boundaries. By enforcing relation correctness with unique constraints, implementing idempotency with request IDs, balancing consistency and performance with transactions and asynchronous calibration, improving query stability with cursor pagination and layered caching, and adding auditing, rate limiting, and observability, you can build a favorite capability that evolves over the long term.
