Content Platform Architecture: Engineering Practice for the Favorites Feature
Favorites look like a one-click button, but behind that single tap sits a multi-to-many relationship that is write-heavy, read-concentrated, continuously growing, and demanding in terms of consistency and traceability. This article walks through the engineering of a favorites (bookmarks) system for a content platform: modeling the user–content relationship as a first-class entity with history, designing idempotent APIs with cursor pagination and batch status lookup, keeping favorite counters accurate through asynchronous, reconciled processing, adding full-text search and auto-tagging so saved items stay retrievable, and covering storage tiering, security and compliance, deployment, capacity estimation, and a practical launch checklist.
1. What a Single “Favorite” Click Reveals About a Content Platform
Almost every article page on a content community has a “favorite” entry at the bottom. One click adds the article to the current user’s favorites list, usually organized under a “default folder.” The interaction is a single tap; the engineering behind it is far more than “write a row”:
- For the user, a favorite is a private bookmark that syncs across devices, a “read later” list, and an accumulation of personal knowledge.
- For the platform, favorites are a long-term signal of content value. Read alongside views, likes, shares, and comments, they feed ranking and recommendation.
- For engineering, a favorite is a many-to-many relationship between users and content. These records are written frequently, read heavily per user, and grow steadily — while expectations for consistency and traceability stay high.
Most platforms end up with a favorites feature that “works but is hard to use,” and the root causes cluster in five areas:
- Saved but unfindable — no search, tags, or folders, so the list becomes “save and forget.”
- State out of sync — after cross-device actions, the icon no longer matches the stored data.
- Inaccurate counters — repeated clicks or duplicate message consumption skew the favorite count.
- No recovery path — a deleted favorite cannot be restored.
- Authorization gaps — endpoints that don’t verify ownership, creating data-exposure risk.
The rest of this article works through those problems layer by layer, from domain modeling to implementation.
2. Information Architecture: The Two-Layer Structure of Columns and Favorites
On a content platform, a column (series) is an aggregation container maintained by an author or editor, holding thematically related content such as technical tutorials, industry analysis, or serialized pieces. A favorite is a reader’s personal annotation of content. Both are ways to group content together, but their roles differ sharply:
| Dimension | Content column | Personal favorites |
|---|---|---|
| Ownership | Platform/author, publicly visible | Private to the user |
| Organization | Curated by the author, order and theme matter | Collected ad hoc, mostly reverse-chronological |
| Primary goal | Systematic, continuous reading | Fast retrieval, re-consumption |
| Change frequency | Low | High-volume add/remove |
| Data volume | Relatively limited | Grows linearly with active users |
These differences drive different engineering trade-offs. A column can be maintained as an ordered content list in a relational database, with a cache layer that comfortably handles reads. Favorites have to be designed around high-concurrency writes plus massive reads along the user dimension.
From an information-architecture perspective, a complete favorites system usually has three layers:
- Storage layer — folders (categories) and tags (descriptors), providing tree-shaped organization and network-shaped association respectively.
- Operation layer — add, remove, move, rename, bulk organize.
- Consumption layer — timeline browsing, full-text search, tag filtering, share/export, and integration with the recommendation system.
Once these three layers are clear, the boundaries for API and data-structure design follow naturally.
3. Domain Modeling: Entities, Relationships, and Constraints
3.1 Core entities and relationships
- User — the actor; the owner of favorite data.
- Item (content) — the favoriteable object, such as an article or column, distinguished by an item-type field so video, Q&A, and future types can be added later.
- Favorite relationship — the entity connecting user and item, recording favorite time, owning folder, source channel, and more.
- Folder — a user-defined container. A “single level plus default folder” structure covers most scenarios.
The important point: a favorite should be modeled as a first-class entity, not just a boolean flag. Only by recording time, source, and change history can you support timeline browsing, interest-preference analysis, and rollback/restore.
3.2 Table design
-- User favorites relationship tableCREATE TABLE user_favorite (id BIGINT NOT NULL COMMENT 'Primary key',user_id BIGINT NOT NULL COMMENT 'User ID',item_id BIGINT NOT NULL COMMENT 'Content ID',item_type TINYINT NOT NULL DEFAULT 1 COMMENT 'Content type',folder_id BIGINT NULL COMMENT 'Folder ID; NULL means the default folder',source VARCHAR(32) NULL COMMENT 'Source channel, e.g. page favorite, share favorite',status TINYINT NOT NULL DEFAULT 1 COMMENT '1-active, 0-canceled',created_at DATETIME NOT NULL COMMENT 'First favorite time',updated_at DATETIME NOT NULL COMMENT 'Last change time',PRIMARY KEY (id),UNIQUE KEY uk_user_item (user_id, item_type, item_id),KEY idx_user_created (user_id, created_at, id)) COMMENT 'User favorites relationship table';
Key design decisions:
- Unique key — the unique index on
(user_id, item_type, item_id)rules out duplicate favorites at the database level and is the foundation for idempotent writes. - User-dimension index —
idx_user_createdsupports reverse-chronological pagination for the “My favorites” list. - Logical delete — canceling a favorite updates status instead of deleting the row. This preserves behavior history and leaves room for a recycle bin.
- Composite primary key and cursor — prefer an append-friendly key that embeds time information over a random key, avoiding page splits.
- Sharding — once a table passes ~10 million rows, shard by
user_idmodulo. Since nearly all queries are scoped to the current user, this sharding scheme routes cleanly and keeps cross-shard queries rare.
3.3 Two easily overlooked details
Cancel and re-favorite. With the unique index on a logical table, a given “user–item” pair has exactly one row forever. Canceling updates the status; favoriting again restores it and refreshes updated_at. History stays fully traceable.
Handling dead content. When the original is deleted, made private, or taken down, how the list renders is a joint product and engineering decision. The recommended approach is a placeholder with an optional hide: keep the entry in the list, label it “content unavailable,” and offer a one-click bulk cleanup.
4. API Design: Semantics, Idempotency, and Batch Handling
The goals are clear semantics, safe retries, and batch support. The paths below are illustrative and can be adapted to your own conventions.
| Method | Path (illustrative) | Description | Idempotent? |
|---|---|---|---|
| POST | /api/favorites | Add favorite | Repeated calls produce the same result |
| DELETE | /api/favorites/{itemId} | Remove favorite | Repeated calls do not error |
| GET | /api/favorites | List favorites, cursor-paginated | Read-only |
| GET | /api/favorites/status | Batch-query favorite state for items | Read-only |
| POST | /api/folders | Create folder | Idempotency key recommended |
| PATCH | /api/folders/{id} | Rename, reorder | Yes |
| POST | /api/favorites/{id}/move | Move to another folder | Yes |
4.1 Idempotent writes
On mobile networks, timeout-and-retry is unavoidable. If “add favorite” isn’t idempotent, a retry can create duplicate rows or count multiple times. Relying on the unique index, adding a favorite looks like this:
def add_favorite(user_id, item_id, item_type, folder_id=None, source=None):# 1. Validate that the item exists and is favoriteableitem = content_service.get_item(item_id, item_type)if item is None or not item.collectable:raise BizError("ITEM_NOT_COLLECTABLE")# 2. Insert against the unique index; a duplicate favorite counts as successrow = db.insert_ignore(table="user_favorite",values={"id": id_generator.next_id(),"user_id": user_id,"item_id": item_id,"item_type": item_type,"folder_id": folder_id,"source": source,"status": 1,"created_at": now(),"updated_at": now(),},)# 3. Restore if previously canceled; only a restore needs a change eventchanged = row.inserted == 0 and db.restore_if_canceled(user_id, item_id, item_type)if row.inserted or changed:event_bus.publish(Event(type="favorite.add",user_id=user_id,item_id=item_id,item_type=item_type,occur_at=now(),))return {"collected": True}
The critical part: a state-change event is published only on a first-time favorite or a restore from canceled state. Repeated clicks create no new data and trigger no redundant counter updates.
Canceling must be idempotent too:
def cancel_favorite(user_id, item_id, item_type):updated = db.update("user_favorite",where={"user_id": user_id, "item_id": item_id, "item_type": item_type,"status": 1},set={"status": 0, "updated_at": now()},)if updated > 0:event_bus.publish(Event(type="favorite.cancel", user_id=user_id,item_id=item_id, item_type=item_type,occur_at=now()))return {"collected": False} # Also succeeds when nothing was favorited
4.2 Batch favorite-state lookup
Feeds, search results, and column detail pages often render dozens of items at once, each needing a “favorited” icon. Calling the favorites service once per item produces a textbook N+1 query problem. The right move is a batch endpoint that takes a list of item IDs and returns the favorited set:
def batch_collected(user_id, item_ids, item_type):rows = db.query("SELECT item_id FROM user_favorite ""WHERE user_id = ? AND item_type = ? AND item_id IN ? AND status = 1",[user_id, item_type, item_ids],)return list({row.item_id for row in rows})
Callers then use a simple set membership check to render icons in bulk — one request instead of N.
4.3 Cursor pagination
The favorites list is primarily reverse-chronological. At deep offsets, “page number + offset” causes two problems: the larger the offset, the more rows the database scans; and if new favorites arrive between page loads, items appear twice or go missing. Cursor pagination is the better fit:
GET /api/favorites?limit=20&cursor=eyJ0IjoxNzEsImlkIjo5OX0# The cursor decodes to {"t": 171..., "id": 99} — the time and primary key# of the last item on the previous page
SELECT id, item_id, folder_id, created_atFROM user_favoriteWHERE user_id = ? AND status = 1AND (created_at < ? OR (created_at = ? AND id < ?))ORDER BY created_at DESC, id DESCLIMIT ?;
The cursor is opaque to callers, so its internal encoding can change at any time. Combining time and ID in the predicate resolves ordering ambiguity when multiple favorites happen within the same second.
5. Consistency: Counters, Out-of-Order Events, and State Sync
The favorite count is the most direct signal of content popularity. On hot content it can face hundreds or thousands of concurrent writes per second. If every favorite synchronously updated a counter column on the content row, you’d create a single-row hotspot and let lock contention drag down the main flow. A common industry approach has three layers:
- Decouple the write from the counter — once the favorite row is written, publish an event to a message queue and let a dedicated counter service consume it asynchronously.
- Accumulate first, persist later — increment in a distributed cache and flush to the database in batches on a fixed interval.
- Reconciliation as a safety net — periodically recount from the detail rows and correct drift.
def on_favorite_event(event):key = f"cnt:fav:{event.item_type}:{event.item_id}"delta = 1 if event.type == "favorite.add" else -1# Atomic increment to avoid read-then-write racescache.incr(key, delta)# Push the occurrence time into the pending-flush queue for async persistencepending_queue.push(key=key, occur_at=event.occur_at)# Background job: periodically flush accumulated values to the databasedef flush_counter():while batch := pending_queue.poll(max_size=500):for key, value in aggregate_by_key(batch).items():db.upsert_counter(key, value)
Two more details matter:
- Out-of-order messages — favorites and cancels can happen within the same second while arriving in a different order. Carrying the occurrence time on every event and having the consumer converge on “keep the latest event per item” absorbs most of the reordering impact.
- Floor on decrements — guard both the cached value and the per-period decrement against going below zero. When the cache misses or data looks anomalous, rebuild the count from the database rather than emitting a negative number.
Read-cache strategy. The favorite count on a content detail page is read-heavy and write-light, which suits Cache-Aside: read the cache first, fall back to the database on a miss and backfill; invalidate on counter changes and let the next read rebuild. If many requests concurrently miss on the same hot item within a single second, single-flight can coalesce them and prevent a cache stampede.
Finally, there is an unavoidable instant when a hot count sits between a cache miss and its rebuild, so the number may briefly “jitter.” Displaying an approximate value plus periodic calibration weakens the visual impact — no need to pay an outsized engineering price for extreme consistency.
6. Search, Organization, and Personalization: Making Favorites Findable Again
6.1 Full-text search
Once favorites pass a hundred items, a timeline alone is hard to navigate. Build a dedicated index per user with fields for title, summary, body excerpt, tags, folder name, and favorite time. At very large user scale, shard the index by user and resolve the shard from a routing table before searching.
Ranking shouldn’t rely on text relevance alone. Favorite behavior itself carries preference signal: frequently favorited tags, topics, and authors can contribute weighting. Giving a modest boost to technical topics the user favorites often makes results feel closer to individual needs.
// Illustrative search request{"query": {"bool": {"must": [{ "term": { "user_id": 10086 } },{ "multi_match": {"query": "distributed consistency","fields": ["title^3", "summary", "content^1", "tags^2"]}}],"filter": [{ "term": { "status": 1 } },{ "range": { "favorited_at": { "gte": "2025-01-01" } } }]}},"sort": [{ "_score": "desc" },{ "favorited_at": "desc" }]}
6.2 Automatic categorization and tagging
Generating a semantic vector as new content lands unlocks three capabilities:
- Auto-tagging — suggest tags from content semantics, cutting manual curation effort.
- Related suggestions — on a favorite’s detail page, surface “other content you may have saved.”
- Cluster-based tidying — group long-untouched favorites by topic and propose “to organize” groups.
6.3 Recycle bin and interest profiles
Accidental deletion is a high-frequency scenario, so offer a recycle bin with a configurable retention window (for example, 30 days) followed by a single cleanup pass. With consent, favorite behavior can also feed an interest profile that improves recommendation and search ranking, upgrading favorites from a static list into a personal interest asset.
7. Storage Tiering and Performance
7.1 Hot and cold tiering
Recent behavior data is read frequently; historical behavior is rarely touched. Tiering fits:
- Hot — recent favorite relationships in a relational database, accelerated by a distributed cache.
- Warm — the full stream of favorite events delivered to a message queue via change data capture, then landed in a data warehouse or object storage for offline analytics and user profiling.
- Cold — long-term history for low-activity users, archived to infrequent-access or archive storage classes in object storage for cheap long-term retention.
7.2 Static assets and content delivery
Large files such as images inside article bodies belong in object storage, delivered through a CDN for low-latency access. You can also store only the original URL and let the presentation layer generate thumbnails at the required sizes on demand, reducing storage and bandwidth cost.
7.3 Cache layers
| Layer | Cached content | Purpose |
|---|---|---|
| Client cache | Favorited state, first page of the list | Fewer repeat requests, usable on weak networks |
| Local cache | Favorite counts for hot content, content metadata | Fewer network round trips |
| Distributed cache | Favorite counts, user favorite lists, status sets | Support high-concurrency reads |
| Database | Full source-of-truth data | Consistency baseline |
One caveat: client-side state can be stale, so reconcile it against the server’s batch status endpoint before rendering. Otherwise you end up with the familiar “the icon shows favorited, but it actually isn’t.”
7.4 Capacity estimation
Let D be daily active users and K the average number of favorite operations per user per day. New favorite relationships run about D × K rows per day, and at roughly 100 bytes per row the annual growth is about D × K × 365 × 100 bytes.
With D = 1,000,000 and K = 2, that’s about 2 million rows per day, roughly 700 million rows and about 70 GB per year — before indexes, replicas, and historical canceled records are added. From there you can derive shard timing, archival policy, and storage budget instead of leaving capacity planning to guesswork.
8. Security and Compliance
- Ownership checks — every read and write involving favorites must be scoped to the authenticated user from the session. Never trust a
user_idsupplied by the client; this is how unauthorized access to other users’ favorites happens. - Sharing and export — publicly shared content should link to the original content, not expose a user’s private data. Rate-limit export and cap the number of items per export to prevent bulk scraping.
- User input safety — folder names and similar input need length limits, content moderation, and output encoding to guard against injection risks.
- Audit and compliance — log key operations, offer a “download my data” capability, and follow applicable personal-data-protection regulations by stating the collection scope, retention period, and deletion method for favorite data.
- Network transport — issue login credentials with a sensible lifetime plus a refresh mechanism, and apply rate limiting to sensitive endpoints to blunt automated abuse.
9. Deployment and Operations
Service layering. Split the favorites service by responsibility:
- The gateway layer handles authentication and rate limiting.
- The favorites service handles CRUD.
- The counter service consumes messages and maintains counts.
- Offline jobs handle reconciliation, archival, and profile computation.
Keep services stateless so they scale horizontally on managed container platforms.
Infrastructure. A practical combination of general-purpose cloud services:
- A relational database for favorite detail records.
- A distributed cache to accelerate hot reads.
- Object storage for static assets such as article images, plus archived data.
- A message queue for traffic smoothing and module decoupling.
- A logging service to centralize access and error logs.
- A monitoring and alerting service to track API latency, error rate, and message backlog.
Elastic scaling. Evening content-consumption peaks can be several times the trough. Configure autoscaling on metrics such as CPU utilization and request rate: pre-warm capacity ahead of the peak and scale down automatically afterward.
Gradual rollout. Favorite data is a user asset, so schema changes should follow “compatible first, switch second, clean up last” — complete dual writes and backfill, verify, then switch the read path.
10. Launch Checklist
- Does the unique index cover duplicate favorites, repeated clicks, and retries?
- Can a canceled favorite be restored, and is behavior history traceable?
- Does the batch status endpoint avoid N+1 queries?
- Does list pagination use cursors to avoid deep pagination and data drift?
- Are counter updates asynchronous, with reconciliation as a fallback?
- When the original content is gone, does the list show a clear signal and handling path?
- Does every endpoint verify user ownership against the server-side session?
- Are hot/cold tiering and archival in place, with capacity quantitatively estimated?
- Can favorite data be exported and fully deleted on request?
- Are key metrics (favorite rate, cancel rate, search click-through) wired into monitoring?
11. Conclusion
Favorites look like a small feature, yet they cut across data modeling, API design, consistency, search and recommendation, security and compliance, and capacity planning. Doing it well comes down to three points:
- Treat the favorite relationship as a first-class entity, preserving time and history.
- Use idempotent writes and asynchronous counting to get both correctness and performance.
- Layer on search, tags, recommendation, and a recycle bin so favorites are genuinely findable and reusable.
As those capabilities accumulate, favorites stop being a button and become an important bridge between a platform’s content ecosystem and a user’s personal knowledge management.
