Design a Social Feed Service with Real-Time Updates
System DesignModel answerLast updated
Build a high-scale microblogging system supporting post creation, social connections, and personalized feeds with near real-time delivery.
Problem Statement
You need to architect a social microblogging service where people can publish short messages, create connections with other accounts, and consume a personalized stream of content from their network.
Core Functionality
- Publishing messages with a 280-character limit
- Creating and removing connections between accounts
- Displaying a personalized content stream showing messages from connected accounts, ordered newest-first
Performance and Scale Targets
- Read availability is paramount—feed retrieval must be highly reliable
- New content should reach feeds within seconds of publication
- System should handle 100 million active users daily with write spikes reaching 50,000 messages per second
What to Cover
Design the system architecture including:
- Key API endpoints with request and response formats
- Storage layer design and technology choices (relational vs non-relational trade-offs)
- Content delivery approach for feed construction (compare different strategies and explain how to handle accounts with massive followings)
- Performance optimization through caching
Scale Context
- Typical account connects to 100 other accounts
- Content distribution operations should finish within 5 seconds for 95% of scenarios
Hints
Hint 1
Calculate read versus write volumes—which operation dominates and by how much?
Hint 2
Consider whether it's cheaper to do work when content is published or when feeds are requested
Hint 3
Think about what happens when someone with millions of connections publishes new content
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Social Feed Service Architecture
Step 1: Quantify the Scale
Before selecting technologies, establish the workload characteristics through back-of-envelope calculations.
Traffic volumes:
- 100M daily active users
- Publication rate: assume 5 messages per active user daily = 500M messages/day
- Average: ~6,000 messages/second
- Peak: 50,000 messages/second (given)
- Feed refresh rate: 100M users × 20 views/day = 2B feed loads/day
- Average: ~23,000 requests/second
- Peak: easily 100K+ requests/second
- Distribution writes: 50K messages/s × 100 connections = 5 million feed insertions per second at peak
Storage requirements:
- Message data: 1 KB each × 500M daily = 500 GB/day, roughly 180 TB annually (pre-replication)
- Feed cache: 800 entries per user × 16 bytes × 100M users ≈ 1.3 TB in-memory, distributed across cache clusters
Critical observation: reads exceed writes by 5–20×, making read path optimization the primary concern.
Step 2: API Structure
POST /v1/messages body: {content, attachments?} → {id, timestamp}
DELETE /v1/messages/{message_id}
POST /v1/connections/{target_id} → 204
DELETE /v1/connections/{target_id} → 204
GET /v1/feed?cursor=&count=50 → {items:[], next_cursor}
GET /v1/accounts/{id}/messages?cursor=&count= → author's messages
Design decisions:
- Use cursor-based pagination rather than page offsets, since feeds shift continuously as new content arrives
- Generate message identifiers using time-ordered distributed IDs (timestamp + machine + sequence), enabling sort-by-ID without coordination
- Accept
Idempotency-Keyheaders on POST to handle safe retries - Extract account identity from authentication token, never trust client-provided IDs
Step 3: Storage Architecture
Match storage technology to access patterns:
Accounts table (account_id, username, metadata, joined_date):
- Low write volume, needs unique constraints on username
- PostgreSQL or MySQL with sharding by account_id
Messages store (message_id PRIMARY, author_id, content, media_urls, created_at):
- Append-only, high write throughput, simple key lookups
- Cassandra or ScyllaDB with partition key on message_id
- Alternative: sharded MySQL if you have strong operational expertise there
Author index (author_id PARTITION, message_id CLUSTERING DESC):
- Supports profile page queries and pull-based feed merging
Connection graph (store both directions for single-partition queries):
outbound(source_id, target_id): "who I'm connected to"inbound(target_id, source_id): "who connects to me" (needed for distribution)- For accounts with massive followings, paginate through in batches
Personalized feeds:
- Redis sorted sets or lists, storing only message IDs and author IDs
- Capped at 800 most recent entries per account
- Full message objects retrieved separately during hydration
Media files: blob storage with CDN delivery
Step 4: Feed Construction Strategy
Pull approach (merge on read):
- At request time, query recent messages from all ~100 connections and merge
- Advantage: writes stay cheap
- Problem: 100 queries per feed load × 100K loads/s = 10M lookups/second, increasing latency and cost
Push approach (distribute on write):
- When a message is published, insert its ID into every connected account's feed cache
- Advantage: feed requests become a single cache lookup
- Problem: an account with 10 million connections generates 10 million writes per message, violating the 5-second requirement
Hybrid strategy (recommended):
- Standard accounts (below 10K–100K connections): use push distribution
- High-reach accounts (above threshold): skip distribution, store only in author index
- Read-time merge: retrieve the pre-computed feed from cache, then fetch recent messages from any connected high-reach accounts (usually 5–10 accounts, heavily cached), merge by ID, and hydrate
- Dormant accounts (30+ days inactive): exclude from distribution to save writes and memory; rebuild feed via pull when they return
Write flow:
- Message service generates ID and persists to durable storage (synchronous)
- Publish
MessageCreatedevent to Kafka partitioned by author - Distribution workers fetch the author's connections in 1K-sized chunks
- Workers batch-write to Redis (pipelined), trim each feed to 800 entries
- Client receives success after step 1; distribution happens asynchronously
Meeting the 5-second target:
- Typical author has ~100 connections: completes in milliseconds
- High-reach authors skip distribution entirely
- Large-but-not-celebrity fan-outs process chunks in parallel
- Auto-scale worker pools based on Kafka lag
Connection changes:
- Adding a connection: update both graph tables, then asynchronously backfill ~20 recent messages from the target into the requester's feed
- Removing a connection: delete the edge; stale entries filtered at read time or cleaned asynchronously
Deletions: mark messages as deleted rather than removing from millions of feeds; filter during hydration
Step 5: Caching Layers
| Layer | Purpose | Implementation Notes |
|---|---|---|
| Feed cache | Message IDs per account | Redis with replication; rebuild via pull on miss |
| Message cache | Full message objects | Memcached/Redis; batch-fetch during hydration; extremely high hit rate on recent content |
| Profile cache | Account metadata | Read-heavy, rarely changes |
| Hot content cache | Recent messages from high-reach accounts | Replicate across multiple nodes to distribute load |
| Graph cache | Connection lists for smaller accounts | Speeds up read-time merging |
| Aggregate counters | Engagement metrics | Eventually consistent, never block writes |
| CDN | Media assets | Edge caching |
Read path resilience:
- Multi-region Redis replication with read replicas
- On cache miss or shard failure, degrade gracefully to pull-based reconstruction instead of errors
- Serve slightly stale data rather than rejecting requests
- Store IDs in feeds, not full objects, so edits and deletions appear correctly after hydration
Step 6: Key Trade-offs
Hybrid vs pure push/pull: The hybrid model adds complexity (two code paths plus merge logic) but bounds write amplification while keeping reads fast. The threshold value requires tuning based on distribution cost versus merge cost.
Eventual consistency: Feeds arrive asynchronously, typically within 1–3 seconds. For this use case, users tolerate slight delays more than they tolerate errors or slow page loads.
Memory versus compute: The push model uses ~1.3 TB of RAM but makes reads trivial. The pull model saves memory but increases database load and latency. Given read dominance, spending memory to optimize reads is correct.
Celebrity threshold placement: Setting it too low wastes memory and write capacity on accounts that could be merged efficiently. Setting it too high creates read-time merges that are expensive. Monitor p95 fan-out time and p95 read latency, then adjust.
Common mistakes:
- Using offset pagination (breaks as feed shifts)
- Attempting full consistency (unnecessary and expensive for this domain)
- Not sharding Redis by account ID (creates hot spots)
- Forgetting to cap feed cache size (unbounded memory growth)
- Ignoring inactive accounts during distribution (wastes 30–50% of writes)