System Design: Twitter Feed Architecture and Scalability

A Twitter/X-like feed design exercise covering fan-out, timeline consistency, and capacity estimates from explicit workload assumptions.

published: reading time: 37 min read author: Geek Workbench updated: June 17, 2026
Quick Summary

This hypothetical Twitter/X-like feed design compares fan-out on write and fan-out on read, then works through a celebrity-post path and the consistency choices for new posts, edits, and deletes. Its latency, availability, and workload figures are labeled assumptions; the capacity worksheet shows how active users, posting rate, and follower distribution affect fan-out. It is not a description of current company internals.

System Design: Twitter Feed Architecture and Scalability

This is a hypothetical Twitter/X-like system design exercise, not a description of current company internals. It uses a hybrid feed model to explore how a product might trade write amplification for read latency.

This is an advanced system design topic. If you are new to distributed systems, start with our Database Scaling and Caching Strategies guides.

Introduction

The example follows a post through storage, fan-out, and feed reads. Its scale and performance targets are assumptions to replace with product requirements and load-test results.

Requirements Analysis

Functional Requirements

Users should be able to:

  • Post tweets (text, images, videos)
  • Follow/unfollow other users
  • View a timeline of tweets from followed users
  • Search for tweets and users
  • Like, retweet, and reply to tweets
  • Receive notifications for interactions

Exercise targets

Use these as target assumptions for the exercise, not as measured Twitter/X service objectives:

  • Timeline latency under 200ms for 99th percentile
  • Support the daily-active and posting volumes used in the capacity worksheet
  • 99.99% availability

The under-200 ms p99 and 99.99% values are target assumptions to validate with a defined request mix, region, cache state, and measurement window. The worksheet below uses a separate, explicitly hypothetical traffic sample; none of these values describe current platform traffic.

Data Models

Core Entities

-- Users table
CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    username VARCHAR(15) NOT NULL UNIQUE,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    display_name VARCHAR(50),
    bio TEXT,
    avatar_url VARCHAR(500),
    follower_count BIGINT DEFAULT 0,
    following_count BIGINT DEFAULT 0,
    verified BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Tweets table
CREATE TABLE tweets (
    id BIGSERIAL PRIMARY KEY,
    author_id BIGINT NOT NULL REFERENCES users(id),
    parent_id BIGINT REFERENCES tweets(id),  -- For replies
    content TEXT NOT NULL,
    media_urls JSONB DEFAULT '[]',
    retweet_of BIGINT REFERENCES tweets(id),
    like_count BIGINT DEFAULT 0,
    retweet_count BIGINT DEFAULT 0,
    reply_count BIGINT DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    deleted BOOLEAN DEFAULT FALSE,

    INDEX idx_tweets_author (author_id),
    INDEX idx_tweets_created (created_at DESC)
);

-- Follows table
CREATE TABLE follows (
    follower_id BIGINT NOT NULL REFERENCES users(id),
    following_id BIGINT NOT NULL REFERENCES users(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    PRIMARY KEY (follower_id, following_id)
);

-- Likes table
CREATE TABLE likes (
    user_id BIGINT NOT NULL REFERENCES users(id),
    tweet_id BIGINT NOT NULL REFERENCES tweets(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    PRIMARY KEY (user_id, tweet_id)
);

NoSQL Alternative

For extreme write throughput, use a wide-column store:

{
  "table": "tweets",
  "key": "tweet_id",
  "columns": {
    "author_id": "bigint",
    "content": "text",
    "created_at": "timestamp",
    "media": ["list of urls"]
  },
  "clustering": ["created_at DESC"]
}

Timeline Architecture

The feed has two common construction choices: push (fan-out on write) and pull (fan-out on read).

Push Model (Fan-out on Write)

When a user posts a tweet, push it to all followers’ timelines immediately:

sequenceDiagram
    participant U as User Posts Tweet
    participant API as API Server
    participant FF as Fan-out Service
    participant Q as Message Queue
    participant TM as Timeline Cache

    U->>API: POST /tweets {content: "Hello"}
    API->>DB: Store tweet
    DB-->>API: Tweet created
    API->>FF: Fan-out tweet
    FF->>DB: Get followers (10K)
    FF->>Q: Enqueue fan-out jobs
    Q->>TM: Push to each timeline cache

This approach provides fast reads but expensive writes. For celebrities with millions of followers, fan-out becomes problematic.

Pull Model (Fan-out on Read)

When a user loads their timeline, aggregate tweets from all followed users:

sequenceDiagram
    participant U as User Views Timeline
    participant API as API Server
    participant TM as Timeline Cache
    participant DB as Tweet DB
    participant MR as Merge & Rank

    U->>API: GET /timeline
    API->>TM: Get cached timeline IDs
    TM-->>API: Timeline IDs (200 tweets)
    API->>MR: Request tweet details
    MR->>DB: Batch fetch tweets
    DB-->>MR: Tweet objects
    MR-->>API: Enriched tweets
    API-->>U: Timeline response

Hybrid approach combines both: pull for celebrities, push for regular users.

Feed Generation

Timeline ordering and consistency

The hybrid design combines precomputed feed entries with posts fetched at read time. This exercise uses one explicit ordering key to merge those lists; an ID format alone does not define when a post becomes visible or how later edits and deletes behave.

The Problem

When a user loads their timeline, they receive:

  1. Pre-computed tweets from regular users (cached in timeline store)
  2. On-demand tweets from celebrities (fetched at read time)

These two sources arrive separately and must be merged. The merge must preserve reverse-chronological order without comparing actual timestamps.

One possible ordering key

One Snowflake-style 64-bit layout may encode:

  • 41 bits: timestamp (milliseconds from a chosen epoch)
  • 5 bits: datacenter ID
  • 5 bits: worker ID
  • 12 bits: sequence number

These bit widths are an example layout, not a specification of Twitter/X IDs. Worker identifiers must be unique, clock skew and clock rollback need handling, and generated ID order does not prove database commit order or immediate feed visibility. Use an explicit server ordering key and a stable tie-breaker for this exercise. The merge algorithm:

def merge_timeline(pushed_tweets, pulled_tweets, limit=200):
    # Both lists pre-sorted by Snowflake ID descending
    merged = []
    p_idx, pu_idx = 0, 0

    while len(merged) < limit:
        p_tweet = pushed_tweets[p_idx] if p_idx < len(pushed_tweets) else None
        pu_tweet = pulled_tweets[pu_idx] if pu_idx < len(pulled_tweets) else None

        if p_tweet is None:
            merged.append(pulled_tweets[pu_idx])
            pu_idx += 1
        elif pu_tweet is None:
            merged.append(pushed_tweets[p_idx])
            p_idx += 1
        elif p_tweet.id > pu_tweet.id:  # exercise ordering key, with a stable tie-breaker
            merged.append(p_tweet)
            p_idx += 1
        else:
            merged.append(pu_tweet)
            pu_idx += 1

    return merged

Consistency Guarantees:

  • New posts: Acknowledge only after the post is durably committed; asynchronous fan-out means some follower feeds may show it later. A read-your-writes path can include the author’s own post before fan-out finishes.
  • Pulled posts: The source may be a replica or cache, so state its freshness guarantee instead of calling the read strongly consistent by default.
  • No duplicate tweets: The timeline service deduplicates by tweet ID during merge
  • Edits and deletes: Write a versioned update or tombstone, publish cache/index invalidation, and filter stale feed entries at read time. Define what users see while those updates propagate.

Cache Invalidation Strategy:

When a user unfollows someone, their cached timeline retains old tweets from that user until TTL expiry. This is acceptable because:

  1. The user explicitly chose to unfollow
  2. The stale data naturally ages out
  3. Forced cache invalidation would be expensive

For scenarios requiring stronger guarantees (like blocking), use write-through invalidation: when you block a user, explicitly remove their tweets from your timeline cache.

Timeline Service

class TimelineService:
    def __init__(self, cache: RedisCluster, db: Database):
        self.cache = cache
        self.db = db

    async def get_timeline(
        self,
        user_id: int,
        limit: int = 200,
        cursor: str = None
    ) -> TimelineResponse:
        # Try cache first
        cached = await self.cache.get(f"timeline:{user_id}")
        if cached and not cursor:
            return self._parse_cached_timeline(cached)

        # Fetch from multiple sources
        following = await self._get_following(user_id)
        tweets = await self._fetch_tweets(user_id, following, limit, cursor)

        return TimelineResponse(
            tweets=tweets,
            cursor=self._generate_cursor(tweets)
        )

    async def _fetch_tweets(
        self,
        user_id: int,
        following: List[int],
        limit: int,
        cursor: str
    ) -> List[Tweet]:
        # Split into celebrities and regular users
        celebrities, regular = await self._categorize_users(following)

        # Fetch in parallel
        celebrity_tweets = await self._fetch_celebrity_tweets(celebrities, limit)
        regular_tweets = await self._fetch_regular_tweets(
            user_id, regular, limit - len(celebrity_tweets), cursor
        )

        # Merge and rank
        merged = self._merge_tweets(celebrity_tweets, regular_tweets)
        return self._rank_tweets(merged)[:limit]

Caching Timeline

Cache timelines with user-specific keys:

CACHE_CONFIG = {
    "timeline_ttl": 3600,        # 1 hour
    "max_timeline_size": 800,    # Store 800 tweets, return 200
    "high_follower_policy": "pull_on_read"  # threshold comes from workload measurements
}

async def cache_timeline(user_id: int, tweets: List[Tweet]):
    key = f"timeline:{user_id}"
    serialized = serialize_tweets(tweets)

    await self.cache.setex(
        key,
        CACHE_CONFIG["timeline_ttl"],
        serialized
    )

Fan-out Service

The fan-out service distributes tweets to follower timelines:

High-Follower Handling

class FanoutService:
    async def fanout_tweet(self, tweet: Tweet):
        author_id = tweet.author_id
        follower_count = await self.db.fetch_val(
            "SELECT follower_count FROM users WHERE id = $1",
            author_id
        )

        if follower_count > CACHE_CONFIG["min_followers_for_fanout"]:
            # Celebrity: skip fan-out, users pull on read
            await self._mark_tweet__celebrity(tweet)
        else:
            # Regular user: fan-out to all followers
            await self._fanout_to_followers(tweet)

    async def _fanout_to_followers(self, tweet: Tweet):
        async with self.db.pool.acquire() as conn:
            async for row in conn.cursor(
                "SELECT follower_id FROM follows WHERE following_id = $1",
                tweet.author_id
            ):
                follower_id = row["follower_id"]
                await self._push_to_timeline(follower_id, tweet)

    async def _push_to_timeline(self, user_id: int, tweet: Tweet):
        key = f"timeline:{user_id}"
        tweet_preview = {
            "id": tweet.id,
            "author_id": tweet.author_id,
            "created_at": tweet.created_at.isoformat()
        }

        # Add to front of list
        await self.cache.lpush(key, serialize_tweet_preview(tweet_preview))
        # Trim to max size
        await self.cache.ltrim(key, 0, CACHE_CONFIG["max_timeline_size"] - 1)

Search Architecture

At the scale assumed for this exercise, search requires indexing the post corpus and defining how quickly new posts become searchable.

Elasticsearch Mapping

{
  "mappings": {
    "properties": {
      "tweet_id": { "type": "long" },
      "author_id": { "type": "long" },
      "content": {
        "type": "text",
        "analyzer": "twitter_analyzer",
        "fields": {
          "keyword": { "type": "keyword" }
        }
      },
      "hashtags": { "type": "keyword" },
      "mentions": { "type": "keyword" },
      "created_at": { "type": "date" },
      "engagement_score": { "type": "integer" }
    }
  },
  "settings": {
    "analysis": {
      "analyzer": {
        "twitter_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": ["lowercase", "stop", "snowball"]
        }
      }
    }
  }
}

Search Query

async def search_tweets(
    query: str,
    limit: int = 20,
    since_id: str = None,
    max_id: str = None
) -> SearchResponse:
    must_clauses = [
        {"match": {"content": query}}
    ]

    filter_clauses = [
        {"range": {"created_at": {"gte": "2020-01-01"}}}
    ]

    if since_id:
        filter_clauses.append({"range": {"tweet_id": {"gt": int(since_id)}}})

    result = await es.search(
        index="tweets",
        body={
            "query": {
                "bool": {
                    "must": must_clauses,
                    "filter": filter_clauses
                }
            },
            "sort": [
                {"_score": "desc"},
                {"tweet_id": "desc"}
            ],
            "size": limit
        }
    )

    return SearchResponse(
        tweets=[Tweet(**hit["_source"]) for hit in result["hits"]["hits"]],
        count=result["hits"]["total"]["value"]
    )

Notification System

Notification Types

Type Trigger Delivery
Mention @username in tweet Immediate
Reply Reply to user’s tweet Immediate
Like Someone likes your tweet Batch (hourly)
Follow Someone follows you Batch (hourly)
Retweet Someone retweets your tweet Batch (hourly)

Notification Pipeline

graph LR
    A[Tweet Event] --> B[Event Router]
    B --> C[Real-time Queue]
    B --> D[Batch Queue]
    C --> E[Push Service]
    C --> F[WebSocket]
    D --> G[Batch Processor]
    G --> H[Email Service]
    G --> I[Push Notifications]

Notification Service

class NotificationService:
    def __init__(self, queue: KafkaProducer, db: Database):
        self.queue = queue
        self.db = db

    async def notify_mention(self, tweet: Tweet, mentioned_users: List[int]):
        for user_id in mentioned_users:
            await self.queue.send("notifications", {
                "type": "mention",
                "user_id": user_id,
                "tweet_id": tweet.id,
                "author_id": tweet.author_id,
                "created_at": datetime.utcnow().isoformat()
            })

    async def notify_followers(self, follower_ids: List[int], event: Dict):
        batch = {
            "type": "follow",
            "user_ids": follower_ids,
            "actor_id": event["actor_id"],
            "created_at": datetime.utcnow().isoformat()
        }
        await self.queue.send_batch("notifications-batch", [batch])

Caching Patterns

Multi-Layer Caching

CACHE_LAYERS = [
    {"name": "tweet", "ttl": 86400, "size": "16MB"},
    {"name": "timeline", "ttl": 3600, "size": "100MB"},
    {"name": "user", "ttl": 900, "size": "16MB"},
    {"name": "social-graph", "ttl": 300, "size": "50MB"}
]

Cache-Aside for Tweets

async def get_tweet(tweet_id: int) -> Optional[Tweet]:
    # L1: Memcached
    cached = await mc.get(f"tweet:{tweet_id}")
    if cached:
        return Tweet(**json.loads(cached))

    # L2: Redis cluster
    cached = await redis.get(f"tweet:{tweet_id}")
    if cached:
        tweet = Tweet(**json.loads(cached))
        await mc.set(f"tweet:{tweet_id}", json.dumps(tweet.dict()))
        return tweet

    # Database
    tweet = await db.fetch_one(
        "SELECT * FROM tweets WHERE id = $1", tweet_id
    )

    if tweet:
        await redis.setex(f"tweet:{tweet_id}", 3600, json.dumps(tweet))
        await mc.set(f"tweet:{tweet_id}", json.dumps(tweet.dict()))

    return tweet

Write Path Optimization

Write-Behind Cache

async def post_tweet(user_id: int, content: str) -> Tweet:
    # Write to database
    tweet = await db.create(
        "INSERT INTO tweets (author_id, content) VALUES ($1, $2) RETURNING *",
        user_id, content
    )

    # Update timeline cache asynchronously
    asyncio.create_task(self._update_timeline_caches(user_id, tweet))

    # Index for search asynchronously
    asyncio.create_task(self._index_tweet(tweet))

    return tweet

Tweet ID Generation

Use snowflake IDs for tweet ordering:

class SnowflakeID:
    def __init__(self, datacenter_id: int = 0, worker_id: int = 0):
        self.datacenter_id = datacenter_id
        self.worker_id = worker_id
        self.timestamp = 0
        self.sequence = 0

    def generate(self) -> int:
        timestamp = int(time.time() * 1000) - 1609459200000  # Epoch offset

        if timestamp == self.timestamp:
            self.sequence = (self.sequence + 1) & 4095
        else:
            self.sequence = 0

        self.timestamp = timestamp

        return (
            (timestamp << 22) |
            (self.datacenter_id << 17) |
            (self.worker_id << 12) |
            self.sequence
        )

API Design

Core Endpoints

Method Endpoint Description
POST /api/v2/tweets Create tweet
DELETE /api/v2/tweets/:id Delete tweet
GET /api/v2/users/:id/timeline Get user timeline
GET /api/v2/timelines/home Get home timeline
GET /api/v2/tweets/search Search tweets
POST /api/v2/users/:id/follow Follow user
DELETE /api/v2/users/:id/follow Unfollow user

Response Format

{
  "data": {
    "id": "1234567890",
    "text": "Hello, Twitter!",
    "author_id": "9876543210",
    "created_at": "2026-03-22T10:30:00Z",
    "like_count": 1523,
    "retweet_count": 342,
    "reply_count": 89
  },
  "meta": {
    "result_count": 1,
    "next_token": "b26v89c19zqg8o3fosdk7n9l"
  }
}

Scalability Challenges

The Celebrity Problem

Assume one creator has 10 million followers. Fanning a single post to every follower would create 10 million timeline writes, so the exercise keeps high-follower posts out of the broad write fan-out. This is a workload example, not a claim about any named account or platform.

When the post is committed, publish a durable fan-out event. For this assumed high-follower account, mark it for pull-on-read instead of enqueuing one write per follower. When a follower opens the feed, fetch recent posts from followed pull accounts, merge them with the precomputed timeline by the chosen ordering key, and deduplicate by post ID. Measure the extra read work and set the push/pull threshold from write cost, follower activity, and timeline latency; there is no universal follower count.

Rate limiting adds another layer of protection. Celebrity accounts get stricter per-window rate limits on tweet publication. This prevents coordinated posting bursts from high-profile accounts during events like product launches or breaking news. The limit is a sliding window counter stored in Redis, keyed by author_id with a tier-based cap.

For media, upload to durable object storage before publishing a post that references the asset, then use a CDN for delivery if the asset and privacy policy allow it. Read-time feed fan-out should not cause each follower to retrieve the original upload from the application server.

Hot Keys

Popular tweets create hot spots in the database. When a tweet goes viral, every like, retweet, and reply hits the same database row or partition. If 100,000 people like a tweet within a minute, that partition handles about 1,700 writes per second for a single row. That partition becomes a bottleneck while others sit idle.

Sharding by hash(tweet_id) spreads hot tweets across partitions. The hash function maps each tweet_id to a random partition. A celebrity tweet ends up on a different partition than the author’s other tweets. This prevents one user’s popularity from overloading a single partition. The tradeoff is that range queries, like fetching all tweets from a specific user, become scatter-gather operations across multiple partitions.

If counts are updated asynchronously, document their freshness and reconcile them from the authoritative interaction records when needed. This is an option for the exercise, not a claim about Twitter/X’s current counters.

Client-side rate limiting prevents abuse amplification. If a single script sends 10,000 likes per second for a tweet, the server limits that client before the hot key problem worsens. Rate limiting is applied per user_id and per IP, with stricter limits on actions that trigger notifications or timeline updates.

Write Amplification

Fan-out multiplies write load. A post from an account with F eligible followers creates up to F timeline writes before retries and indexing. Use the capacity worksheet below to estimate this load from the assumed follower distribution rather than using a universal write-amplification factor.

Async fan-out via message queues decouples the write path from the fan-out path. The API server writes the tweet to the database and publishes a fan-out event to Kafka. A pool of fan-out workers consumes these events and writes to timeline caches. If a worker fails, the Kafka offset stays uncommitted and another worker retries. The queue itself acts as a buffer. During traffic spikes, the queue depth grows but no data is lost.

The hybrid push/pull model reduces broad fan-out for high-follower accounts. Low-follower posts can be pushed; posts with higher write cost can be pulled on read or pushed only to recently active followers. Set the transition point from measured follower distribution and service budgets.

Periodic batch updates help with the long tail of inactive users. Instead of writing to every follower’s timeline cache immediately, the system writes to caches of recently active users first. Inactive users, those with no login in 30 days, get their timeline rebuilt on next login instead of kept fresh in cache. This cuts the fan-out volume significantly since most users are inactive on any given day.

Trade-off Analysis

Factor Push (Fan-out on Write) Pull (Fan-out on Read) Hybrid Approach
Read latency Low (pre-computed) High (compute on read) Medium
Write latency High (fan-out to all) Low (single write) Medium
Memory usage High (all timelines) Low (compute on need) Medium
Celebrity posts Problematic (fan-out storm) Efficient (pull) Efficient
Consistency Eventual (async fan-out) Strong (read own) Tunable
Implementation Complex (queues, workers) Simpler Moderate

Production Failure Scenarios

Failure Scenario Impact Mitigation
Fan-out queue backlog Timeline updates delayed for hours Auto-scale fan-out workers; prioritize active users
Celebrity tweet viral Massive fan-out burst crashes servers Rate limit celebrity tweets; pre-compute popular timelines
Timeline cache miss Cold start: timeline loads from DB, high latency Pre-warm caches for trending users; use background refresh
Search index lag New tweets not appearing in search Accept search lag; prioritize by engagement
Hot tweet partition Single partition overloaded by likes/retweets Shard by tweet_id; use eventual consistency for counts
Tweet DB primary failure Writes fail; no new tweets Use multi-primary replication; promote read replica

Common Pitfalls / Anti-Patterns

Pitfall 1: Fanning Out to All Followers Synchronously

Problem: Synchronous fan-out on every tweet creates massive latency spikes for users with many followers.

With synchronous fan-out, the posting request can end up waiting for follower writes. If those writes are serial, the time on that path grows with follower count; if they run in parallel, they can instead exhaust worker, connection, or storage capacity. In this exercise, the API acknowledges a post after durable storage and queues fan-out separately, so follower count affects queue work and feed freshness rather than directly multiplying request latency. Size the queue from measured worker throughput and the follower distribution.

Fan-out workers still compete with other writes for database connections and I/O. Reserve capacity for post creation and other critical operations, bound the queue, and define what happens when workers fall behind. A backlog should be visible as stale feed delivery, not silently reported as a completed fan-out.

Solution: Use async fan-out via message queues. Return success to user immediately, fan-out in background.

The fix is to decouple the write path from the fan-out path. When a tweet arrives, the API writes it to the database and publishes a single event to a message queue. That event contains the tweet and the author ID. The API returns success to the user right away. A pool of background workers consumes queue events and performs the actual fan-out writes. If a worker crashes, Kafka redelivers the message — no data lost, no user-facing error. The queue acts as a buffer during traffic spikes. During a celebrity event, queue depth grows but the API stays responsive.

Pitfall 2: Not Handling the Celebrity Problem

Problem: In this exercise, a creator account with 10 million assumed followers would generate a large fan-out burst if every post were pushed to every follower.

The danger is that celebrity accounts sneak up on you. Most feature work targets the happy path: regular users posting, fans following, timelines updating. Nobody writes a ticket for “handle when someone with more followers than our entire old architecture can handle posts during a live event.” But at scale, this is the scenario that actually breaks production.

The failure mode is subtle. A celebrity posting does not immediately crash anything. The fan-out queue depth starts climbing. Workers fall behind. Timelines for everyone, not just followers of the celebrity, start getting stale because queue workers are saturated writing to celebrity timelines instead of processing regular users. The symptom is broad degradation, not a single account error.

Solution: Implement hybrid model. Skip fan-out for users above a follower threshold; their tweets are pulled on read.

Pitfall 3: Storing Full Tweets in Timeline Cache

Problem: Caching 800 tweets × 5KB each = 4MB per user timeline in cache.

Cache memory depends on representation. Measure bytes per stored timeline entry, including allocator and index overhead, rather than assuming one object size. If an entry stores the full post, account for payload and metadata; if it stores only an ID and ordering key, fetch the post separately.

Estimate cache memory from measured bytes per stored timeline entry, retained entries per active user, active cache population, and the replication factor chosen for the deployment: entry_bytes × entries_per_timeline × cached_users × replicas. Price it from current provider quotes and a defined region; a fixed per-terabyte figure is not a useful general estimate.

The irony is that most of that data is already cached elsewhere. Tweet objects for popular content sit in a separate tweet cache layer. When a user loads their timeline, the system needs the full tweet objects anyway for rendering. Storing full tweets in the timeline cache does not save a database round-trip — it just duplicates data that already exists in a dedicated cache tier.

Solution: Store only tweet IDs and timestamps in timeline cache; fetch full tweet objects separately with multi-get.

The compact representation uses 16 bytes per tweet (8-byte tweet ID, 8-byte timestamp). A timeline of 800 tweets takes 12.8KB instead of 4MB — a 300x reduction. The timeline cache returns tweet IDs only, and the API fetches the full tweet objects with a single multi-get operation against the tweet cache layer. Tweet cache hits are fast (memory). Tweet cache misses fall through to the database. This pattern works because tweet objects for active content are almost always in cache — the working set of recent tweets is exactly what the tweet cache is sized for.

Pitfall 4: Ignoring Engagement Calculation Cost

Problem: Calculating “trending” or “ranked” timeline requires scanning engagement data on every read.

A ranked timeline may combine recency and relevance. Estimate its work from accounts considered per feed × candidate posts per account × feed reads per second; use representative distributions and measure scoring cost. Do not assume every read scans every followed account or that a ranking model needs to run synchronously on the request path.

The cost of on-demand ranking depends on how many candidate posts are scored per feed and how often those feeds are requested. Estimate it as candidates per feed × feed reads per second, then measure the query plan and CPU cost on the expected data distribution. A database join may be acceptable for a small candidate set and a poor choice for a large one; do not assume every feed scans all followed accounts or that one query shape fits every workload.

Solution: Pre-compute engagement scores; update asynchronously; use Redis sorted sets for real-time ranking.

The fix is to move the scoring work offline. A background job computes an engagement score for each tweet periodically (every 5-15 minutes) and stores it in a sorted set keyed by tweet_id with the score as the score. Redis sorted sets support efficient range queries — you can fetch the top K tweets by score in O(log N) time. When a timeline loads, the system scores tweets by their pre-computed engagement rather than computing on the fly.

The update frequency is tunable. Trending tweets change score quickly, so they need frequent updates (every 1-2 minutes). Most tweets see gradual score changes, so recomputing every 15 minutes is sufficient. The tradeoff is staleness — a tweet that goes viral between updates will be under-ranked temporarily. For most use cases, this is acceptable. If not, you can boost the score of tweets with recent engagement acceleration (a delta check) to catch viral content faster.


Hypothetical failure exercises

These are test cases for the proposed system, not reports of Twitter/X incidents.

Fan-out queue falls behind

Publish a burst that exceeds worker capacity. Confirm that the write API still acknowledges only durable posts, queue age is visible, and a high-follower post cannot starve regular-user fan-out. Define an explicit freshness target and a recovery rate that does not overload the timeline store.

Edit or delete races with feed cache

Write a post into a user’s cached timeline, then edit or delete it while the feed cache is stale. Verify that the post revision or tombstone wins, stale copies are filtered before rendering, and the search index receives the same update.

Search index loses its consumer

Stop the indexer after the database commit. Confirm that the outbox or durable event can be replayed, index lag is alerted, and the product communicates that search may lag behind the timeline without dropping the post.

Quick Recap

  • Timeline delivery: Hybrid push/pull
  • Celebrity handling: Pull on read (skip fan-out)
  • Tweet ordering: Snowflake IDs (time-sortable)
  • Cache strategy: Multi-layer (L1 Memcached, L2 Redis)
  • Write path: Write-behind caching
  • Fan-out: Async via message queues
  • Search: Elasticsearch with custom analyzer
  • Notifications: Real-time (mentions) + batch (likes/follows)

Copy/Paste Checklist

- [ ] Implement hybrid push/pull for celebrity accounts
- [ ] Cache timeline IDs, not full tweet objects
- [ ] Use async fan-out via message queue
- [ ] Partition by tweet_id for hot tweet handling
- [ ] Monitor fan-out queue depth and auto-scale workers
- [ ] Pre-warm caches for trending users
- [ ] Implement rate limiting on tweet publication
- [ ] Use snowflake IDs for ordering

Observability Checklist

Metrics to Capture

  • tweets_published_total (counter) - By author tier (celebrity vs regular)
  • timeline_load_duration_seconds (histogram) - P50, P95, P99
  • timeline_cache_hit_ratio (gauge) - Hit vs miss rate
  • fanout_queue_depth (gauge) - Messages pending fan-out
  • search_indexing_lag_seconds (gauge) - Time from tweet to searchable
  • engagement_events_total (counter) - Likes, retweets, replies by tier

Logs to Emit

{
  "timestamp": "2026-03-22T10:30:00Z",
  "event": "tweet_published",
  "author_id": "123456",
  "author_tier": "celebrity",
  "follower_count": 15000000,
  "fanout_queued": true,
  "fanout_queue_depth": 50000
}

Alerts to Configure

Alert Threshold Severity
Timeline P99 > 500ms 500ms for 5 min Warning
Fan-out queue > 1M 1000000 pending Critical
Cache hit ratio < 80% 80% for 10 min Warning
Search lag > 5 min 300s Warning

Security Checklist

  • Rate limiting on tweet publication (prevent spam)
  • Tweet content moderation (pre-scan for abuse)
  • Anti-scraping measures (limit bulk reads)
  • DM encryption (end-to-end for private messages)
  • OAuth 2.0 for all API access
  • IP-based access controls for internal services
  • Audit logging of admin operations

Capacity worksheet

Use an explicit follower distribution because a single average hides the high-follower tail. This example is illustrative, not measured platform traffic:

Input Assumption for this exercise
Daily active users 1,000,000
Share who post each day 5%
Posts per posting user per day 2
Average eligible followers for push accounts 200
Eligible followers active in the feed cache 25%
Peak multiplier over daily average 6×

The scenario produces 1,000,000 × 5% × 2 = 100,000 posts/day. Estimated push writes are 100,000 × 200 × 25% = 5,000,000 timeline entries/day, or about 58 per second on average. Applying the assumed 6× peak multiplier gives about 348 push writes/second. High-follower accounts use the pull path and must be sized separately from their follower count and feed-read rate.

For a real design, replace each input with measured distributions, include retries and deletion/edit events, and size queue workers from peak arrival rate plus the backlog recovery target. Measure timeline reads separately; the cache entry write rate is not the same as request QPS or bandwidth.

Storage can be estimated with posts/day × average stored bytes × retention days × replication/index overhead. Keep media bytes in a separate estimate if media is stored in object storage or delivered through a CDN.


Interview Questions

1. How does this design handle a high-follower account?

In this design, low-follower posts are pushed to eligible timelines, while high-follower posts are pulled when a user loads the feed. Choose the threshold from follower activity, fan-out cost, queue capacity, and read latency; 10,000 is not a universal boundary.

2. When should a feed cache store post IDs instead of full post objects?

Compare memory per entry and cache population using measured values. Storing IDs plus an ordering key can keep timeline entries small and lets the post cache handle object hydration separately. Full objects can reduce reads in some workloads, but duplicate data and make invalidation harder. Use entry bytes × retained entries × cached users × replicas to estimate the difference.

Storing only IDs keeps the cache compact. The feed service can batch-fetch post objects from a separate cache or store. This reduces duplicated state, but it adds a hydration step and requires a clear policy for deleted or inaccessible posts.

3. How does this design order entries from push and pull paths?

Assign a server ordering key that both paths can use and add a stable tie-breaker. A Snowflake-style ID is one possible input, but clock skew and commit visibility mean the ID alone is not a consistency guarantee. State whether the feed is eventually consistent and how it handles a post while fan-out is pending.

Merge on the server using the ordering key assigned by the feed design, and include a stable tie-breaker. If generation uses worker clocks, account for skew and rollback; a sortable ID does not guarantee transaction or replication order. State how new posts and late fan-out events affect the feed.

4. What happens when you like a tweet?

Persist the like as an idempotent interaction, then update derived counts and notifications asynchronously if the product can tolerate delay. Return success only when the chosen durable write boundary has completed. A failed write should not leave a success state in the client.

Notifications follow from that: if the tweet author has immediate notifications enabled, they get a push right away. If they've chosen batched notifications, they get a digest later. The distinction matters because a celebrity with millions of followers can't afford immediate fan-out of every like notification.

5. What is the trade-off between push (fan-out on write) and pull (fan-out on read) timeline models?

Push (fan-out on write) means timelines are pre-computed. When you post, the system fans out your tweet to everyone's cached timelines. Reads are fast — the timeline is ready. But writes are expensive, especially for users with many followers.

Pull (fan-out on read) means you write once (to the tweet database) and everyone reads your tweet when they load their timeline. Writes are cheap. Reads are expensive — every timeline load requires merging tweets from everyone you follow.

The hybrid model splits the difference: regular users get pushed, celebrities get pulled. You get fast reads for most content without the fan-out cost for high-follower accounts.

6. What does a Snowflake-style ID provide in this design?

A Snowflake-style format combines time bits with worker identity and a per-worker sequence. Bit allocation and epoch are design choices, not a universal standard. Workers need unique identifiers, clock rollback handling, and a limit on IDs per time unit. The resulting IDs can be sortable, but they do not replace a database consistency or feed-ordering rule.

7. How would you design full-text search for the post corpus?

Choose a search engine from the corpus size, query needs, and operations budget. Index text and the product's relevant metadata, then define how to handle updates and deletes. Time partitions or tiered retention are options, not requirements.

For this exercise, rank search results using a defined mix of text relevance and recency, with engagement as an optional signal. Make ranking behavior explicit and test freshness separately from relevance.

For performance, results are cached for popular queries. The index itself is eventually consistent — there will be a small lag (seconds to minutes) between when a tweet is posted and when it becomes searchable.

8. How would you design notifications for the exercise?

Notifications get split into two paths based on urgency. Immediate notifications (mentions, replies) go through a real-time queue and get pushed via WebSocket or push notification immediately. Batched notifications (likes, follows, retweets) accumulate in a batch queue and get processed hourly.

The notification service itself is stateless — it reads from Kafka and writes to a notification store (a distributed database with user-specific partitions). The store indexes notifications by user_id and created_at for efficient retrieval.

Classify which events need immediate delivery and which can be batched. Store durable notification state, make consumers idempotent, and treat cached unread counts as derived values that can be rebuilt. Set batch windows and delivery targets from user needs and measured load.

9. What is the hot key problem in Twitter's database and how do you solve it?

Popular tweets (think viral content or a celebrity post) create hot spots — a single partition receives way more traffic than others. Reads for that tweet's data overwhelm the database.

Solutions include: sharding by hash(tweet_id) so hot tweets spread across partitions, using eventual consistency for like/retweet counts (not requiring strong consistency), and adding a caching layer specifically for popular tweets. You can also rate-limit clients to prevent a single tweet from causing a cascade.

10. How does write-behind caching work and when would you use it?

Write-behind (also called write-back) caches write to the database first, then asynchronously update the cache. The user gets a fast response, and the cache population happens in the background.

In this design, a post is committed before a durable outbox event updates timeline caches and search indexes. If a consumer fails, retry the event idempotently and expose the lag; do not rely only on cache TTL to repair a missed update.

The tradeoff is that if the database write succeeds but the cache update fails, you have inconsistency. You need monitoring to detect and recover from these cases.

11. Explain the timeline merge problem. How do you correctly merge tweets from push and pull sources?

The merge problem: your timeline has pre-computed tweets from regular users (pushed) and needs to pull celebrity tweets on read. The challenge is sorting them together correctly.

The exercise can use a server-assigned ordering key to merge pushed and pulled entries. A Snowflake-style ID may help approximate creation order, but worker clock skew and commit visibility still need explicit handling. Use a stable tie-breaker and do not treat the ID format as a consistency guarantee.

The practical challenge is ensuring you get enough tweets. If you're pulling celebrity tweets at read time, you need to know which celebrities a user follows to fetch the right tweets. That follow-graph lookup adds latency, which is why there's a social graph cache.

12. How would you design the follower/following data model at scale?

The follows table is a many-to-many relationship: user_id → many → user_id. The primary access patterns are "who does user X follow?" and "who follows user Y?" Both queries need to be fast.

Sharding strategy: partition follows by follower_id for "who does user X follow" queries, and by following_id for "who follows user Y" queries. Or use a hybrid approach where some data is replicated for both access patterns.

The counts (follower_count, following_count) are denormalized for fast access. They're updated asynchronously because they don't need strong consistency — you can accept temporary inaccuracies while the system catches up.

13. Which cache layers might this design use?

A feed service could use an in-process cache for local hot data, a shared cache across workers, and durable storage behind them. Choose layers based on measured hit rate, invalidation needs, and recovery behavior; a particular cache product is not required.

Different data has different cache strategies: tweets cache for high-read, timeline cache for user-specific timelines, user cache for profile data, and social graph cache for the follower/following relationships. Each layer has its own TTL based on how often the data changes.

The social graph cache is particularly important because the follow relationships don't change as often as tweet content, but they're queried on every timeline load.

14. Where should rate limits apply in a social feed?

Apply limits at actions that can trigger costly reads or writes, such as timeline fetches, post creation, search, or fan-out. Pick scopes and windows from abuse risk and service capacity, and return a clear retry policy.

Implementation: a token bucket or sliding window counter per user_id, stored in a fast cache (Redis). When a request comes in, you check if the user has tokens left. If not, you reject with a 429 response.

Rate limiting is especially important for celebrity tweets — without it, a single viral tweet could cause a fan-out burst that overwhelms the system. Limiting how often a single user can post also helps reduce spam and coordinate attacks.

15. How would you estimate storage for posts over a retention period?

Use `posts per day × retention days × measured bytes per stored post × replication and index overhead`. Separate text and metadata from media objects, which are usually stored and delivered through a different path. Do not use subscriber or post counts unless they are explicit workload assumptions.

Storage is tiered by age. Recent tweets (last 30-90 days) are kept in fast storage (SSD) for quick access. Older tweets move to cheaper storage (HDD or cold storage). This is called tiered storage or data aging.

Data is partitioned by time period (monthly or weekly partitions). This makes it easy to drop old data or move it to cheaper storage. Queries for recent tweets hit recent partitions; queries for old tweets span more partitions but are less frequent.

16. How would you handle a scenario where the fan-out queue backs up?

Queue backup means timeline updates are delayed — users might not see new tweets for hours. The impact is visibility, not data loss.

Mitigations: auto-scaling fan-out workers based on queue depth, prioritizing active users (people who login frequently) over inactive ones, and using backpressure to slow down new tweet ingestion when the queue is overwhelmed.

For the user experience, you might show a "timeline may be outdated" warning or load tweets directly from the database instead of the cache. The key is that the timeline remains functional even if it's stale — you don't fail completely, you degrade gracefully.

17. What role can a message queue play in this design?

A durable queue or outbox can decouple post persistence from fan-out, indexing, and notification work. Choose the broker from throughput, ordering, retention, and operational needs; it is not part of the user-facing consistency contract by itself.

Queues provide three benefits: buffering (absorb spikes without overwhelming downstream services), decoupling (write path doesn't wait for fan-out to complete), and fault tolerance (failed messages can be retried). If a fan-out worker crashes, the message stays in the queue and another worker picks it up.

18. How could the design compute trending topics?

Trending is computed from engagement velocity — how fast a topic is gaining likes, retweets, and replies. A simple approach counts mentions in the last N minutes and ranks by velocity. More sophisticated systems weight by follower count and engagement quality.

The pipeline: tweets are streamed through Kafka, a storm or flink job computes rolling mention counts for hashtags and search queries, results are stored in a sorted set (like Redis sorted sets) with time-based expiry, and the top K trending items are served to clients.

The main tradeoff is between sensitivity (detecting trends quickly) and noise (avoiding spikes from scheduled events or coordinated campaigns). Geographic segmentation also matters — what's trending globally might differ from what's trending in Tokyo.

19. How might the API expose a user's timeline?

Expose a cursor-based endpoint such as GET /api/timelines/home?cursor=.... Return a bounded page and an opaque next cursor so pagination does not depend on large offsets. The exact route and page size are product choices.

The feed service can check a timeline cache, merge pull-path posts, hydrate the selected post IDs, and return the next cursor. On a cache miss, rebuild or query from durable sources according to the latency and freshness budget.

20. What happens when the hypothetical creator with 10 million followers posts?

For this exercise, commit the post and return success only after durable storage. Mark it for pull-on-read instead of generating one timeline write per follower; the threshold is derived from measured follower activity and worker capacity.

At read time, fetch recent posts from followed pull accounts, merge them with pushed entries using the chosen ordering key, and deduplicate by post ID. This shifts work from writes to reads, so measure the extra feed-query cost and define how edits and deletes invalidate stale copies.


Further Reading

For more on caching patterns, see Caching Strategies. For database sharding, see Horizontal Sharding. For a related real-time design exercise, see Design Chat System.


Conclusion

The example balances write fan-out against feed-read cost with a hybrid push/pull model. Its main decisions are:

  • Push for regular users, pull for celebrities
  • Multi-layer caching throughout
  • Eventual consistency for non-critical data
  • Async processing for expensive operations

Category

Related Posts

System Design: Netflix Architecture for Global Streaming

A hypothetical streaming architecture exercise informed by public Open Connect material, with explicit assumptions for capacity, delivery, and playback design.

#system-design #case-study #netflix

System Design: URL Shortener from Scratch

A URL shortener design exercise with collision-safe code allocation, redirect caching semantics, abuse controls, and an explicit capacity worksheet.

#system-design #case-study #url-shortener

Amazon Architecture: History and Service Design

Separate documented Amazon and AWS milestones from popular retellings, then apply the lesson about service boundaries to a current request flow.

#microservices #amazon #architecture