Designing Favorites and Activity Feeds: Data Models, Idempotency, and Push-Pull Delivery
This article explains how to engineer favorites and activity feeds by defining scope boundaries, designing storage schemas, handling idempotent favorite writes, decoupling activity generation through messages, and assembling feeds with hybrid push-pull delivery. It also covers visibility filtering, cursor pagination, caching, capacity estimation, and monitoring, with a focus on the tradeoffs between strong consistency for favorites and acceptable latency for derived activity data.
1. Requirements Breakdown and Scope
Favorites and activity feeds may look simple, but they differ significantly in data volume, read/write ratio, and consistency requirements. A favorite is a user’s personal mark on a piece of content. The core requirements are fast writes, fast checks for whether an item has already been favorited, and paginated queries in reverse chronological order. An activity feed aggregates user actions. Its core requirement is to let followers see other users’ new actions in a timely manner, and it is read far more frequently than it is written.
Before designing the system, define three boundaries:
- Data retention: Favorites are usually stored long term. Activities can be trimmed by time window, for example, keeping only the last 30 days of detail.
- Visibility rules: Some users may set favorites to private. The activity feed must filter out invisible entries during assembly.
- Real-time requirements: Activities can tolerate some delay, and second-level latency is usually acceptable. The “already favorited” status must be visible immediately after a write.
Only after these boundaries are clear can you determine which parts need strong consistency and which parts can accept eventual consistency.
2. Data Model Design
2.1 Favorites Table
There are two core access patterns for favorites: checking whether a user has favorited an item, and listing a user’s favorites. Therefore, a unique constraint is needed to prevent duplicate favorites, along with a descending index keyed by user.
CREATE TABLE favorite (user_id BIGINT NOT NULL,item_id BIGINT NOT NULL,created_at TIMESTAMP NOT NULL,is_deleted TINYINT NOT NULL DEFAULT 0,PRIMARY KEY (user_id, item_id),KEY idx_user_time (user_id, created_at));
Using (user_id, item_id) as the primary key naturally guarantees idempotency. Unfavoriting uses logical deletion, which supports reconciliation and asynchronous cleanup.
2.2 Activity Table
Activities are recorded as events. Each event contains the actor, action type, target object, and occurrence time.
CREATE TABLE activity (activity_id BIGINT NOT NULL PRIMARY KEY,actor_id BIGINT NOT NULL,action_type VARCHAR(32) NOT NULL,target_id BIGINT NOT NULL,created_at TIMESTAMP NOT NULL,KEY idx_actor_time (actor_id, created_at));
For activity_id, a time-ordered globally unique ID is recommended so that pagination cursors can advance directly based on the ID, avoiding the performance problems caused by deep pagination.
3. Idempotency and Consistency for Favorite Writes
Favorite actions may be clicked repeatedly on the frontend, and network retries can also cause duplicate requests. The server should ensure that executing the same operation multiple times produces the same result as executing it once.
The following practices can be used:
- During writes, use
INSERT ... ON DUPLICATE KEY UPDATEor an equivalent statement, relying on the primary key for idempotency. - After a favorite succeeds, synchronously update the user’s favorite count cache. On failure, the database remains authoritative, and the cache is corrected from the source on the next read.
- Decouple favorites from activity generation. After a favorite write succeeds, asynchronously deliver a “favorite event” through a message channel. The activity service consumes it and creates an activity record. This way, even if the activity service is temporarily unavailable, the main favorite flow is unaffected.
The key judgment here is that favorites themselves are strongly consistent data, while activities are derived data. Derived data may be delayed but must not be lost. Therefore, message delivery needs at-least-once semantics, and the consumer must handle idempotency.
4. Activity Feed Generation Strategies
There are three common approaches to activity feeds, each with its own tradeoffs.
4.1 Push Model (Write Fanout)
When an action occurs, the activity is written into the inboxes of all followers. Reads then query only the user’s own inbox, providing very high read performance. The cost is significant write amplification: every action by an account with many followers produces many writes.
4.2 Pull Model (Read Fanout)
At read time, first query the follow list, then fetch the latest records from each followee’s activity table, and finally merge and sort the results. Writes are simple, but read cost grows linearly with the number of followees, and users who follow many accounts experience noticeable latency.
4.3 Hybrid Push-Pull
A common compromise in practice is to use the push model for normal accounts and pull activities in real time for large accounts whose follower count exceeds a threshold, then merge them with inbox results. The threshold can be set based on follower count and write pressure, for example 10,000, and adjusted dynamically through configuration.
The following example shows the core merge logic for hybrid push-pull, with the storage layer abstracted behind interfaces:
from heapq import mergefrom itertools import isliceHOT_FOLLOWEE_THRESHOLD = 10000 # follower count threshold, configurabledef build_feed(user_id, page_size, cursor, inbox_store, activity_store, graph_store):"""Assemble a user's activity feed by merging inbox (push) and high-profile followee (pull) activities.All stores are abstract interfaces injected by the caller and do not depend on a specific implementation."""# 1. Read pushed activities from the inbox in reverse chronological orderinbox_items = inbox_store.fetch(user_id, before=cursor, limit=page_size)# 2. Find high-profile followees and pull their latest activities in real timehot_followees = graph_store.hot_followees(user_id, HOT_FOLLOWEE_THRESHOLD)pulled_streams = [activity_store.fetch_by_actor(actor_id, before=cursor, limit=page_size)for actor_id in hot_followees]# 3. Merge multiple ordered streams, deduplicate, and take one pagemerged = merge(inbox_items, *pulled_streams, key=lambda a: a.activity_id, reverse=True)seen, page = set(), []for item in merged:if item.activity_id in seen:continueseen.add(item.activity_id)page.append(item)if len(page) >= page_size:breaknext_cursor = page[-1].activity_id if page else Nonereturn page, next_cursor
This example demonstrates three key points: each stream is already ordered by time, so merging can replace full sorting; deduplication by activity_id handles overlap between pushed and pulled data; and pagination uses a cursor rather than a page number, avoiding page shifts when new data is inserted.
5. Visibility Filtering and Read Optimization
After the activity feed is assembled, it still needs to be filtered according to visibility rules. Private favorites, banned accounts, and removed content can all cause entries to be hidden. It is recommended to query visibility status in batches during assembly rather than querying item by item.
Read optimization can focus on the following areas:
- Tiered caching: The most recent pages of an inbox can be cached in an in-memory database with a short expiration time.
- Batch queries: Favorite status checks should be combined into a batch interface, for example, checking whether the contents of one page have been favorited by the current user in a single request.
- Degradation strategy: When pulling from high-profile accounts times out, return only inbox content and mark the response as partial so the frontend can decide whether to retry.
6. Capacity Estimation and Monitoring
Before launch, perform a basic capacity estimate to avoid a design that is disconnected from the actual load. Consider an example with 1 million daily active users, an average of 3 activity actions per user per day, and an average of 200 followers:
- Daily activity writes are about 3 million. With a pure push model, fanout writes are about 600 million, far beyond the capacity of an ordinary relational database.
- After setting a threshold, most normal accounts still use the push model, and write pressure can be kept within an acceptable range.
Specific numbers should be based on load test results. The numbers above are only intended to illustrate the estimation method.
For monitoring, track the following metrics: favorite write success rate and latency, message consumption lag, P99 latency of activity feed assembly, cache hit rate, and the timeout ratio for high-profile account pulls. A sustained increase in message consumption lag is usually an early signal of delayed derived data and should trigger an alert.
7. Conclusion
Although favorites and activity feeds are both common features, their design priorities differ. Favorites require strong consistency and idempotency, while activity feeds require high throughput and acceptable latency. With a clear data model, message-based decoupling of the two, a hybrid push-pull feed strategy, cursor pagination, batch filtering, and tiered caching, you can build an implementation that is both stable and easy to extend for medium-scale workloads. Before launch, validate capacity against real traffic and continuously observe the monitoring metrics above, adjusting thresholds and caching strategies based on the data.
