Building a Reliable Favorites or Bookmarks Service for Content Platforms

    This article explains how to design a reliable favorites (bookmarks) service for a content platform, treating it as a high-frequency write, strongly consistent, and auditable domain capability rather than a boolean flag on the content table. It covers domain modeling and data structures, idempotent writes, read-after-write consistency, content visibility filtering, separating counters from relations to avoid hot rows, cursor-based pagination, hot/warm/cold storage tiering, caching and concurrency control, API contracts and error semantics, and observability, capacity, and governance. Readers will get concrete schema, SQL, and event-flow examples plus the core conclusions for delivering a consistent, reliable, and scalable favorites feature without heavy dependencies.

    1. Why Favorites Deserve Their Own Design

    In content community products, favorites are often treated as an insignificant button. From an engineering perspective, however, they are a typical interaction capability that is “write-heavy, strongly consistent, and auditable.” The original material only presents the “favorite” interaction entry point; this article abstracts it into a general technical problem: how to build a reliable user-content favorites service for a content platform.

    Favorites differ from likes and shares in three key ways:

    1. Favorites are a user’s private view. The detailed counts are usually not exposed publicly, but for the user themselves they must be strongly consistent: after favoriting, the item must appear immediately when the user returns to their list.
    2. Favorites are time-sensitive and context-driven. Users typically use them in “read later” or “save for reference” scenarios, so the list needs to support reverse-chronological ordering, categorization, and search.
    3. Favorites are a long-lived, revocable relationship. Data accumulates continuously, naturally forming large tables and hot users, so sharding and archiving must be considered from the start.

    For these reasons, favorites should be designed as an independent domain capability, not as a boolean flag added to the content table.

    2. Domain Modeling and Data Structures

    2.1 Core Entities

    A favorite relationship is essentially a many-to-many relationship between users and content. It is recommended to abstract at least three types of entities:

    • Favorite relation table: records who, what, when, and status.
    • Content summary table: denormalizes title, author, cover, and visibility for fast list rendering.
    • User favorite count table: records each user’s effective favorite count to avoid real-time COUNT.

    A schematic relation table structure is shown below (pseudocode, expressing field semantics only):

    1. CREATE TABLE favorite_relation (
    2. user_id BIGINT NOT NULL,
    3. content_id BIGINT NOT NULL,
    4. status TINYINT NOT NULL DEFAULT 1, -- 1 active, 0 canceled
    5. created_at TIMESTAMP NOT NULL,
    6. updated_at TIMESTAMP NOT NULL,
    7. PRIMARY KEY (user_id, content_id)
    8. ) SHARD BY user_id;

    Key design points:

    • Using (user_id, content_id) as the composite primary key naturally guarantees that the same user has only one record for the same content, eliminating duplicate favorites at the storage layer.
    • Sharding by user_id keeps read requests like “my favorites list” on a single shard, avoiding cross-shard aggregation.
    • Using status instead of physical deletion enables recycle-bin-style recovery, behavior analysis, and auditing, while avoiding write amplification from primary key churn.

    2.2 Index and Query Pattern Alignment

    Read requests for favorites are highly concentrated in one pattern: a user’s favorites list paginated in reverse-chronological order. The index order should therefore be (user_id, created_at DESC). If the business needs to count favorites by content dimension, it should not run real-time aggregation on this table but instead use an independent counting or analytics pipeline, which is covered in Section 4.

    3. Write Path: Idempotency, Transactions, and Consistency

    3.1 Idempotency Is the First Principle

    Mobile and weak-network environments cause duplicate submissions. The implementation relies on the composite primary key for “insert-as-idempotent”:

    1. INSERT INTO favorite_relation(user_id, content_id, status, created_at, updated_at)
    2. VALUES (?, ?, 1, NOW(), NOW())
    3. ON DUPLICATE KEY UPDATE status = 1, updated_at = NOW();

    This single statement covers both “first-time favorite” and “re-favorite after canceling,” and is naturally idempotent. Canceling a favorite only updates the status bit and keeps the historical row.

    3.2 Handling Read-After-Write Consistency

    After a user successfully favorites an item and immediately opens their personal list, a read routed to a read-only replica may briefly not show it. There are three common approaches:

    1. Session stickiness: route reads within the same session to the primary database. Simple to implement, suitable for small to medium scale.
    2. Read-after-write compensation: after a successful write, place the user_id in a short-lived cache marker; when the read path hits the marker, force a read from the primary.
    3. Logically accept eventual consistency, but do optimistic insertion on the frontend, pinning the just-favorited item locally, with the server reconciling asynchronously.

    For small to medium scale, approach one or two is recommended; once scale grows, introduce log-based incremental sync.

    3.3 Consistency with Content Visibility

    Favoriting happens while content is visible, but the content may later be deleted by the author or set to private. List rendering must apply visibility filtering. The principle is “keep the relation, filter the display”: do not delete the favorite row, only join the content status at query time and filter, avoiding users mistakenly thinking data was lost.

    4. Counting and Aggregation: Avoiding Hot Rows

    If you use COUNT(*) on the content table to count favorites, top content forms a single-row hotspot with obvious write queuing and lock waits. The common industry practice is to separate counting from relations:

    • User-dimension count: incremented in the same transaction as the favorite write or via a reliable message immediately after; read directly on demand to avoid counting a large table.
    • Content-dimension count: asynchronously accumulated into an independent counter store via a message queue, tolerating second-level delay.
    • Periodic calibration: reconcile offline against the relation table as the source of truth to correct drift.

    Schematic reliable event delivery (pseudocode):

    1. def on_favorite(user_id, content_id):
    2. db.upsert_favorite(user_id, content_id) # idempotent write
    3. mq.publish("favorite.changed", { # async aggregation
    4. "user_id": user_id,
    5. "content_id": content_id,
    6. "action": "add"
    7. })

    The consumer partitions by content_id to guarantee accumulation order for the same content, avoiding count errors caused by out-of-order “decrement then increment” events.

    5. Read Path: Lists, Pagination, and Hot/Cold Separation

    5.1 Cursor Pagination Over Offset Pagination

    With deep pagination, LIMIT offset, size scans and discards many rows. Favorites lists should use a cursor:

    1. SELECT content_id, created_at
    2. FROM favorite_relation
    3. WHERE user_id = ? AND status = 1
    4. AND (created_at, content_id) < (?, ?)
    5. ORDER BY created_at DESC, content_id DESC
    6. LIMIT 20;

    The composite cursor (created_at, content_id) solves duplicate or missing items across pages caused by batch favoriting within the same second.

    5.2 Hot/Cold Separation and Archiving

    Heavy users may have tens of thousands of favorites or more. The strategy is:

    • Hot data: the most recent items kept resident in cache or an in-memory table to support the first screen.
    • Warm data: the main body of the relation table, served via indexed queries.
    • Cold data: expired or over-limit portions archived to object storage or columnar storage, loaded on demand when the user actively searches.

    This tiering balances cost and latency and prevents a single table from growing infinitely.

    6. Caching, Deduplication, and Concurrency Control

    Cache only “list page results + counts,” not the write path of individual relations, to prevent cache-primary inconsistency from double writes. The recommended update strategy is “write the database first, then invalidate the cache,” with a short TTL on the cache as a fallback.

    At the concurrency level, three types of contention need attention:

    1. A user repeatedly tapping favorite: resolved by composite-primary-key idempotency.
    2. High-concurrency favoriting of the same content: resolved by async counting and partitioned consumption.
    3. Bulk favorite import: requires rate limiting and a batch interface; each batch should be kept small and undergo deduplication checks.

    7. API Contracts and Error Semantics

    A clear API contract significantly reduces collaboration cost:

    • Add favorite: inputs user_id, content_id, and an idempotency key; returns the current status.
    • Cancel favorite: same inputs; returns the current status.
    • List query: inputs a cursor, page size, and optional category; returns items and the next cursor.
    • Batch status query: used to render “already favorited” on detail pages; should support batching to save round trips.

    For error semantics, duplicate favoriting is not an error but a success; nonexistent or invisible content should return a clear business code; count delay should not block the main flow.

    8. Observability, Capacity, and Governance

    Before launch, four categories of metrics should be defined: write success rate and latency, list query P99, count drift rate, and cache hit rate. Capacity estimation uses “daily active users × average favorite actions per user × peak factor” to estimate write QPS, and “list read amplification factor” to estimate read QPS, based on which shard count and replica count are set.

    For governance, it is recommended to: apply rate limiting and risk-control flagging to abnormal favorite-spam behavior; build a batch status sync task for content takedowns; and provide an on-demand retrieval channel for archived data. If the whole system runs in the cloud, you can combine a container platform to host stateless services, a message queue for async aggregation, object storage for cold data, and logging and monitoring/alerting services to close the observability loop. These are all general capability categories and can be trimmed according to your own scale.

    9. Summary

    Favorites may look simple, but they span data modeling, idempotent writes, consistency trade-offs, count aggregation, pagination, and tiered storage. The core conclusions are: use a composite primary key for natural idempotency and deduplication; use a status bit instead of physical deletion to preserve auditability; use read/write separation and async aggregation to defuse hotspots; and use cursor pagination and hot/cold tiering to support long-term growth. Following this path delivers a consistent, reliable, and scalable favorites capability without introducing complex dependencies.