High-Throughput Counter System for Social Engagement
System DesignModel answerLast updated
Design a counting service that supports millions of concurrent engagement actions with eventual consistency and sub-50ms read latency.
Problem
Build a counter service for a social platform where users can engage with content items (posts, videos, profiles). The platform serves millions of active users, and popular content can receive thousands of engagements per second.
What You Need to Support
Your system must allow users to:
- Record an engagement action on an item
- Remove their engagement from an item
- Query the total engagement count for any item
The count can be slightly stale (a few seconds behind) but individual user actions must reflect immediately in their own view.
Performance & Reliability Targets
- Write volume: Handle 100,000+ engagement actions per second during peak traffic
- Read latency: Serve count queries in under 50ms
- Availability: Continue operating through partial infrastructure failures
- Hot content: A single viral item may receive 5,000-10,000 actions per second
What to Design
- API contracts for engagement actions and count retrieval
- Storage schema for tracking both individual actions and aggregated totals
- Architecture that absorbs write spikes without overloading your primary datastore
- Strategy for handling duplicate requests and client retries
Example Operations
PUT /items/{id}/engagement → records user's engagement
DELETE /items/{id}/engagement → removes user's engagement
GET /items/{id}/total → returns current count
Assume user identity comes from authentication context.
Hints
Hint 1
Think about what happens when 10,000 users simultaneously try to increment the same counter in a database
Hint 2
Consider storing the relationship (user engaged with item) separately from the aggregate count
Hint 3
Buffering and batching writes can reduce database load by orders of magnitude
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Asynchronous Aggregation Architecture
The critical insight is that each engagement is a user-item relationship, not just a number to increment. By storing relationships as your source of truth and deriving counts asynchronously, you solve deduplication, retries, and database contention in one design.
1. Scale Estimation and Requirements Analysis
Start by establishing concrete numbers:
- Active users: 10M concurrent, 100M+ daily active
- Write rate: ~100k engagements/disengagements per second globally; a viral item might hit 5-10k/sec alone
- Read rate: 10-50× higher than writes (1-5M/sec) since every feed tile displays a count
- Consistency model: Counts may lag by seconds, but a user's own engagement state must appear instantly
- Data volume: 10B relationships × ~30 bytes = 300GB raw (manageable with sharding)
The core challenge: synchronously updating a single counter row creates a serialization bottleneck. Every writer contending for the same row lock kills throughput.
2. API Design
PUT /items/{itemId}/engagement → {engaged: true}
DELETE /items/{itemId}/engagement → {engaged: false}
GET /items/{itemId}/total → {itemId, count, timestamp}
GET /items/{itemId}/engagement/status → {engaged: bool}
POST /items/totals:batch → {items: [{id, count}, ...]}
Key decisions:
- PUT/DELETE verbs make operations naturally idempotent (engaging twice = same state as engaging once)
- User ID from auth token prevents spoofing
- Batch endpoint for efficiently loading feed pages with 50+ items
- Separate status check so users see their own actions immediately
3. Data Model
Engagement Records (source of truth) — Store in Cassandra, DynamoDB, or sharded MySQL:
Primary Key: (user_id, item_id)
Partition: hash(user_id)
Fields:
- status: ENGAGED | DISENGAGED
- timestamp, version (for conflict resolution)
Partitioning by user distributes writes for hot items across all shards. It also makes "did I engage?" queries single-partition reads.
Aggregate Counters (derived view):
Primary Key: (item_id, shard_id)
Fields:
- total: int64
- last_processed_offset (per partition, for idempotency)
Cache Layer — Redis stores total:{itemId} for fast reads. CDN/edge cache adds another layer for extremely hot items (1-2 second TTL).
4. Architecture Components
Engagement Service (stateless API layer):
- Authenticates and rate-limits per user
- Executes conditional write:
UPDATE ... SET status=ENGAGED WHERE status != ENGAGED - Only emits delta event if state actually changed:
- DISENGAGED → ENGAGED: emit +1
- ENGAGED → DISENGAGED: emit -1
- No change: emit nothing
- Uses transactional outbox or CDC to guarantee event emission
Event Stream (Kafka or similar):
- Partitioned by
item_idso all deltas for one item go to same consumer - Provides at-least-once delivery guarantee
Aggregation Workers:
- Each worker consumes assigned partitions
- Maintains in-memory map:
itemId → accumulated_delta - Every 1-2 seconds (or every N events), flushes batched deltas:
UPDATE counters SET total = total + delta WHERE item_id = ?INCRBY total:{itemId} {delta}in Redis
- Stores
last_processed_offsetwith each counter update for replay protection
This buffering transforms 10,000 writes/second on a hot item into 1 write/second, protecting the database from collapse.
Read Path:
- CDN (for extremely hot items) → Redis → Database (fallback)
- All layers meet sub-50ms requirement
- User's personal engagement status comes from engagement records or user-specific cache
5. Handling Edge Cases
Deduplication at three levels:
- Client retries: Conditional write makes repeats no-ops; no spurious events emitted
- Event replay: Workers track
last_processed_offsetper partition and skip already-applied events; alternatively use Kafka transactions for exactly-once semantics - Concurrent user actions: Version/timestamp on engagement record resolves conflicts; net count remains correct since deltas derive from real state changes
Abuse prevention:
- One engagement per user per item enforced by primary key
- Rapid toggling throttled with token bucket (e.g., 10 toggles/minute)
- Suspicious patterns flagged and potentially excluded from public counts via async fraud detection
Failure handling:
- Worker crash: In-memory deltas lost but Kafka offset wasn't committed, so replacement replays
- Redis down: Circuit breaker fails over to database reads or serves last cached value
- Regional failure: Run multi-region active-active; each region maintains its own counter; reads sum across regions (CRDT PN-Counter pattern)
6. Key Trade-offs
| Approach | Benefit | Drawback |
|---|---|---|
| Async aggregation | High throughput, DB protection | Seconds of lag |
| Sync counter update | Immediate consistency | Lock contention kills scale |
| Store relationships | Enables dedup, undo, audit | Storage cost (~300GB+) |
| Counter only | Minimal storage | Cannot deduplicate or recompute |
| Longer batch window | Fewer DB writes | More lag, larger replay on failure |
7. What Strong Answers Include
- Recognition that concurrent updates to a single row is the fundamental bottleneck
- Modeling engagements as idempotent state rather than increment operations
- Clear separation between source of truth (relationships) and derived data (counts)
- Quantitative reasoning: "10k/sec becomes 1 write/sec through batching"
- Precise handling of at-least-once delivery semantics
Weak answers propose "just use Redis INCR" without addressing durability, deduplication, or disaster recovery.
8. Common Extensions
Near-real-time for trending content:
- Detect trending items from stream velocity
- Reduce flush interval to ~100ms for those items
- Push updates via WebSocket to clients viewing trending content
- Optionally write synchronously to Redis in API layer while maintaining async durable path
Extreme hotspot handling:
- Default: engagements sharded by
hash(user_id), stream byitem_id - When item exceeds threshold, shard its counter:
total:{itemId}:{0..N}with random assignment - Readers sum the shards (cached in Redis as single value)
- Distributes single-item write load across multiple database partitions
This design handles massive write volumes while maintaining read performance through careful separation of concerns and asynchronous aggregation.