Design a B2B Product Engagement & Liking System
System DesignModel answerLast updated
Design a scalable backend architecture for product likes on a wholesale platform, handling dual-access querying, search result enrichment, counter aggregation, and brand metrics.
Design the backend system for product likes (engagement reactions) on a wholesale B2B marketplace.
On this platform, brands list products and retailers browse, search, and express interest in them.
Your design must support four core functional capabilities:
- Toggle Reaction: A retailer can like or dislike (remove like / set neutral) a product.
- Retailer Liked Products: A retailer can retrieve a paginated view of all products they have liked, ordered by most recent.
- Search Result Enrichment: When a retailer executes a search or browses a catalog page, each returned product must show its total aggregate like count and an indicator of whether the current retailer has liked it.
- Brand Analytics: A brand can view engagement stats and buyer interaction histories across all products in their brand catalog.
Specific Scope & Constraints to Address
- Define latency vs. consistency trade-offs (e.g., immediate visibility for the active buyer vs. eventual consistency for public counts).
- Present data models and storage choices for handling both access directions efficiently (retailer-centric and product/brand-centric).
- Detail the read path strategy for search enrichment to prevent $N+1$ query bottlenecks.
- Explain counter maintenance, idempotency, data reconciliation, and lifecycle policies (soft deletes of products or retailer accounts).
Hints
Hint 1
Clarify whether 'dislike' represents an explicit negative signal or simply removing a previously applied like. Choose a clean status model.
Hint 2
Address the two main query paths: querying by retailer_id to show a user's library versus querying by product_id/brand_id for search and vendor analytics.
Hint 3
Separate the strict read-your-own-writes consistency path for the acting buyer from the highly performant, eventually consistent aggregation path for public search counters.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirement & System Boundaries
Functional Requirements
- Toggle Engagement: A retailer can like or remove a like (unlike/set neutral) on a product. Writes must be idempotent. (For this design, "dislike" is defined as undoing a like / reverting to a neutral state; explicit negative downvoting can use the same state column if extended later).
- Buyer Library: A retailer can retrieve a paginated list of products they currently like, sorted by the timestamp of when the like was added.
- Search Result Enrichment: Given a batch of $N$ product IDs (e.g., 20–50 search results):
- Retrieve total like count per product.
- Retrieve whether the requesting retailer currently likes each product.
- Brand Insights: A brand can retrieve aggregate like counts across their catalog, with drill-down access to recent buyer engagement records.
Non-Functional Requirements & Scale Assumptions
- Scale:
- 10M registered retailers, 100k active brands, 50M active products.
- ~300M total active like records.
- Traffic:
- Read QPS: 10,000 peak QPS (Search/Browse enrichment).
- Write QPS: 500 peak QPS (Toggle like).
- Latency Targets:
- Like/Unlike mutation: $< 50\text{ ms}$ (p99).
- Search enrichment overhead: $< 15\text{ ms}$ (p99) added to search responses.
- Consistency Models:
- Read-your-own-writes for the acting retailer (their UI must immediately reflect their action).
- Eventual consistency (lag of 1–3 seconds) for public counter totals in search results and brand dashboards.
2. Data Storage & Schema Design
To efficiently serve dual access paths (retailer-centric reads vs. brand/product-centric aggregations), we separate the transactional source of truth, caching layer, and aggregated counts.
+-----------------------+
| Client App / Web |
+-----------+-----------+
|
v
+-----------------------+
| API Gateway |
+-----------+-----------+
|
v
+-----------------------+
| Likes Service |
+----+-------------+----+
| |
Write / Read | | Read Path (Fast Path)
Source of Truth v v
+--------------+ +---------------+
| PostgreSQL | | Redis Cache |
+--------------+ +---------------+
|
v (Event Async)
+--------------+
| Kafka Engine | ---> Counter Aggregation & Search Index
+--------------+
Relational Schema (Transactional Source of Truth: PostgreSQL)
Table: product_likes
Stores individual retailer-to-product interactions.
CREATE TABLE product_likes (
retailer_id UUID NOT NULL,
product_id UUID NOT NULL,
brand_id UUID NOT NULL,
status SMALLINT NOT NULL DEFAULT 1, -- 1: Liked, 0: Neutral/Unliked
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (retailer_id, product_id)
);
-- Index for retrieving a retailer's liked products sorted by date
CREATE INDEX idx_retailer_timeline
ON product_likes (retailer_id, status, updated_at DESC);
-- Index for brand analytics and product level queries
CREATE INDEX idx_brand_products
ON product_likes (brand_id, product_id, status);
Table: product_like_counters
Durable fallback store for aggregate product counts.
CREATE TABLE product_like_counters (
product_id UUID PRIMARY KEY,
like_count BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
3. Core API Specifications
1. POST /v1/products/{product_id}/likes
Headers: Authorization: Bearer <retailer_token>
Body: { "action": "LIKE" } -- Values: "LIKE", "UNLIKE"
Response: 200 OK { "product_id": "p123", "liked": true, "like_count": 142 }
2. GET /v1/retailers/me/likes
Headers: Authorization: Bearer <retailer_token>
Params: limit=20, cursor="eyJjcmVhdGVkX2F0IjoiMjAyMy0xMC0yNFQxM..."
Response: 200 OK {
"items": [
{ "product_id": "p123", "liked_at": "2023-10-24T12:30:00Z" }
],
"next_cursor": "ey..."
}
3. POST /v1/products/batch-engagement
Headers: Authorization: Bearer <user_token>
Body: { "product_ids": ["p101", "p102", "p103"] }
Response: 200 OK {
"engagements": {
"p101": { "like_count": 142, "user_liked": true },
"p102": { "like_count": 12, "user_liked": false }
}
}
4. Operational Workflows & Execution Paths
Write Path: Toggling a Like
- DB Upsert: Execute an idempotent
UPSERTon PostgreSQL:INSERT INTO product_likes (retailer_id, product_id, brand_id, status, updated_at) VALUES ($1, $2, $3, $status, NOW()) ON CONFLICT (retailer_id, product_id) DO UPDATE SET status = EXCLUDED.status, updated_at = EXCLUDED.updated_at; - User Cache Invalidation/Update: Write user state to Redis Hash for instant cache hits:
HSET retailer_likes:{retailer_id} {product_id} {status}
- Event Emission: Publish
LikeToggledEventto Kafka:- Payload:
{ retailer_id, product_id, brand_id, action: "LIKE", timestamp }.
- Payload:
Retailer --> Likes Service --> PostgreSQL (Upsert)
|
+--> Redis (Update user cache key)
|
+--> Kafka (Publish event for async counter updates)
Read Path 1: Buyer Library (Retailer's Liked Items)
Queries execution uses cursor pagination directly from index idx_retailer_timeline:
SELECT product_id, updated_at
FROM product_likes
WHERE retailer_id = $1 AND status = 1 AND updated_at < $cursor_timestamp
ORDER BY updated_at DESC
LIMIT $limit;
For fast access, active users can also store their set of liked product IDs in a Redis Sorted Set (ZADD retailer_likes_zset:{retailer_id} <timestamp> <product_id>).
Read Path 2: Search Result Batch Enrichment
When a search service outputs 30 product IDs [p1...p30] for user r99:
- Fetch Total Counts: Call Redis
MGET like_count:p1 like_count:p2 ... like_count:p30.- On cache misses, query DB
product_like_countersin a batch, return counts, and backfill Redis.
- On cache misses, query DB
- Fetch User Reaction: Call Redis
HMGET retailer_likes:r99 p1 p2 ... p30.- On cache misses, execute
SELECT product_id FROM product_likes WHERE retailer_id = 'r99' AND product_id IN (...) AND status = 1and populate Redis.
- On cache misses, execute
- Merge & Return: Zip both maps into the final search response payload.
Async Counter Aggregation Pipeline
+----------------+ +-------------------+ +----------------------+
| Kafka Topic | ---> | Counter Consumer | ---> | Redis (INCRBY/DECRBY)|
| (Like Events) | | Worker Pool | +----------------------+
+----------------+ +---------+---------+ |
| | Periodic Batch Flush
v v
+-------------------------------------------------+
| DB Table: product_like_counters (Batch Upsert) |
+-------------------------------------------------+
- Consumer Worker: Reads like events from Kafka.
- In-Memory Buffer / Redis: Updates Redis counters immediately (
INCRBY like_count:{product_id} 1or-1). - Durable Persistence: Flushes aggregated batch increments to
product_like_counterstable every 5 seconds to guarantee durability against Redis evictions or restarts.
5. Edge Cases, Scale & Fault Tolerance
Counter Drift Reconciliation
Network partitions or uncommitted Redis writes can cause drift between global Redis counts and actual DB rows.
- Reconciliation Job: A daily background batch job executes count aggregations directly from
product_likesintoproduct_like_countersand refreshes Redis keys where discrepancies exist.
Data Deletions (Products & Retailer Accounts)
- Soft Deletes: Product deletion sets a
deleted_atflag in the Product Catalog. The Likes Service filters out inactive products during retrieval routines. - Account Removal (GDPR/Compliance): Retailer account deletion triggers an asynchronous Kafka event
RetailerDeletedEvent. A batch worker deletes rows fromproduct_likesand dispatches counter decrements for every active like held by that retailer.
Bottlenecks & Optimization Trade-Offs
| Optimization Area | Applied Strategy | Trade-off / Complexity |
|---|---|---|
| Hot Products (High Likes) | Redis atomic counters + Read replicas | Cache invalidations require careful synchronization |
| Search Enrichment ($N+1$ prevention) | Batch enrichment endpoint (HMGET + MGET) | Clients must perform a 2-step call if search engine is decoupled |
| Database Writes | Upserts on single table primary keys | Requires careful indexing strategy for timeline vs product lookups |
| Consistency | Read-your-own-writes via local Redis; eventual consistency for counts | Global counts can lag by 1–3 seconds, acceptable for UX |