Architect a Scalable Microblogging Platform

Medium · System Design · Software Engineer · Technical Screen

Prompt

Architect a large-scale social microblogging platform where members broadcast brief text updates to an asymmetric social graph. Walk through your architecture with clear structure and concrete back-of-the-envelope reasoning.

Your platform must support three core user workflows under heavy global read and write traffic:

  • Publishing short text updates (with optional media attachments) and deleting one's own updates.
  • Subscribing to (following) and unsubscribing from (unfollowing) other public creators.
  • Loading a personalized home feed showing recent updates authored by followed accounts.

Scope & Expectations

  • Interfaces and persistence: Define the external API endpoints, identifier scheme, and database schemas for accounts, social edges, and posts, paired with appropriate storage engines and in-memory caches.
  • Timeline assembly and browsing: Evaluate push-based (write-time), pull-based (read-time), and blended timeline generation strategies across skewed follower counts, along with cursor pagination and chronological vs. ranked ordering.
  • Freshness and consistency contracts: Specify latency and visibility guarantees for publishing, timeline propagation, unfollowing, and post deletion.
  • Production readiness: Cover traffic throttling, spam and abuse mitigation, hot-key scaling, and key operational metrics and alerts.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Begin by pinning down the product scope and the one structural property that shapes the entire architecture: the extreme skew of the follow graph, where most accounts have a few hundred followers while a few thousand accounts have tens of millions.

    Functional requirements

    1. Create and delete posts: Post a short message (up to 280 characters, optionally with attached images/video) and delete your own posts.
    2. Follow and unfollow: Follow or unfollow any public account (blocking self-follows).
    3. Home timeline: View a paginated feed of recent posts from accounts you follow (plus your own posts), newest first, with a "12 new posts" indicator and an optional ranked mode.
    4. User (profile) timeline: View one specific author's posts, newest first.

    Out of scope (mention briefly that they subscribe to the same Kafka post-event stream): full-text search, push notifications, direct messages, trending hashtags, and ads.

    Scale and product assumptions

    • Users and traffic: 300M registered users, 150M daily active users (DAU), 100M new posts/day, and ~10 home-timeline loads per active user per day (1.5B timeline reads/day).
    • Follow graph shape: A user follows 150 accounts on average, while active posters average ~200 followers. Crucially, the distribution has a heavy tail: 99%+ of authors have < 10,000 followers, whereas celebrities, news outlets, and sports leagues have 1M–50M+ followers.
    • Freshness & consistency: An author sees their own new post immediately (read-your-writes); followers see a new post within 5 seconds at p99. Once POST /v1/posts returns 201 Created, a post is never lost.
    • Latency & availability: Home timeline server latency < 200 ms at p99. Reads prioritize availability (serving a feed 2 seconds stale beats returning 500), while post creation prioritizes durability.
  2. Back-of-the-envelope numbers

    Metric                     Calculation                                        Result
    -----------------------------------------------------------------------------------------------
    Post writes                100M / 86,400 s                                    ~1,200 /s avg
                               3x daily peak / ~8x live-event spike               ~3,500 /s (10k/s spike)
    Home timeline reads        150M DAU x 10 loads / 86,400 s                     ~17,400 /s avg
                               3x daily peak (Read : Write ratio = 15 : 1)        ~50,000 /s peak
    
    Follow graph storage       300M users x 150 edges = 45B edges
                               Stored in 2 directions x ~30 B/row                 ~2.7 TB raw (~8.1 TB 3x)
    
    Pure push (fan-out write)  100M posts/day x 200 avg followers = 20B/day       ~230,000 inserts/s avg
                               3x peak                                            ~700,000 inserts/s peak
    One 50M-follower post!     50M inserts / 700,000 peak cluster capacity        ~71 seconds of WHOLE fleet!
    
    Pure pull (fan-out read)   50,000 peak reads/s x 150 followed authors         7,500,000 lookups/s!
    
    Post DB storage            100M/day x 365 = 36.5B posts/yr x ~300 B           ~11 TB/yr raw (~33 TB 3x)
    Hot post cache (last 2d)   200M posts x ~300 B                                ~60 GB raw (~120 GB RAM)
    Timeline cache (active)    150M active users x 800 entries x 16 B             ~1.92 TB raw payload
                               x2 Redis metadata overhead x2 replicas             ~8 TB RAM (~125 x 64GB nodes)
    

    Three takeaways anchor the design:

    1. Reads outnumber writes 15 : 1, so a timeline load must be a couple of fast in-memory cache reads, not a 150-way database scatter-gather.
    2. Pure push breaks on celebrities: Pushing every ordinary post is manageable, but one post from a 50M-follower account generates 50M writes at once (~71 seconds of the entire cluster's peak write budget) and burns 50M × 16 B = 800 MB of RAM on copies of one ID.
    3. RAM capacity, not write QPS, sizes the Redis timeline cluster: 125 Redis nodes needed to hold ~8 TB of timelines easily absorb 700,000 pipelined list inserts/s (< 6,000 ops/s per node).
  3. Core APIs

    Expose a REST/HTTPS API behind an API Gateway handling authentication and rate limiting:

    POST   /v1/posts
           Header: Idempotency-Key: <client-uuid>
           Body:   {"text": "Hello world", "media_ids": ["m_91"], "reply_to_id": null}
           -> 201  {"post_id": "1859283019283019264", "created_at": "2026-11-30T15:00:00Z"}
    
    DELETE /v1/posts/{post_id}                     -> 204 No Content (author only)
    
    PUT    /v1/me/following/{target_user_id}       -> 204 No Content (idempotent; rejects target == me)
    DELETE /v1/me/following/{target_user_id}       -> 204 No Content (idempotent)
    
    GET    /v1/users/{user_id}/posts?cursor=&limit=20
    GET    /v1/timeline/home?cursor=&limit=20&mode=latest|ranked
           -> 200  {"posts": [ ...hydrated post objects... ],
                    "next_cursor": "eyJtYXhfaWQiOi...",
                    "newest_id": "1859283019283019264"}
    GET    /v1/timeline/home/new_count?since_id=1859283019283019264 -> {"count": 12}
    

    Key API details to call out:

    • Idempotency-Key on POST /v1/posts: An idempotency key is a client-generated UUID cached on the server ((user_id, key) -> post_id for 24 h) so mobile network retries return the original 201 response instead of publishing duplicate posts.
    • Return 64-bit post_ids as JSON strings: JavaScript numbers lose integer precision above 2^53 - 1, whereas 64-bit IDs reach 2^63 - 1; serializing IDs as strings prevents silent rounding bugs in web clients.
    • Opaque cursors instead of page numbers: An opaque cursor is a base64-encoded token (max_id for chronological feeds; (snapshot_id, offset) for ranked feeds) that clients pass back untouched, letting the server evolve pagination internals freely.
    • Hydrated responses: Hydration means turning bare post_ids into complete UI objects (post text, author handle/avatar, like counts, and "liked_by_me") on the server so mobile apps render a page in one round trip.
  4. Data model and storage choices

    1. Time-ordered 64-bit Snowflake post_ids

    Instead of a single bottlenecked SQL AUTO_INCREMENT counter, application servers generate 64-bit Snowflake IDs independently:

    +------+------------------------------------------+---------------+------------------+
    | 1b 0 | 41 bits: ms since custom epoch (~69 yrs) | 10b worker ID | 12b seq (4096/ms)|
    +------+------------------------------------------+---------------+------------------+
      bit 63                                                                        bit 0
    

    Because the 41 timestamp bits sit at the top (with bit 63 fixed to 0 so signed 64-bit integers stay positive), sorting posts by integer post_id automatically sorts them newest-first (1 + 41 + 10 + 12 = 64 bits).

    2. Schemas and storage engines

    Relational DB (sharded PostgreSQL / MySQL)
      users         (user_id PK, handle UNIQUE, display_name, avatar_url,
                     follower_count, following_count, trust_score, last_active_at)
    
    Wide-Column / Sharded KV Store (e.g., Cassandra or ScyllaDB — zero cross-shard joins)
      posts         PK (post_id) -> author_id, text, media_ids[], created_at, status (ACTIVE|DELETED|LIMITED)
      author_posts  Partition (author_id, year_month), Clustering (post_id DESC) -> profile timeline
      following     Partition (follower_id), Clustering (followee_id)  # "who do I follow?"
      followers     Partition (followee_id), Clustering (follower_id)  # "who follows this author?"
    
    In-Memory Caches (Redis & Memcached)
      home:{user_id}     Redis List of (post_id, author_id) 16-byte pairs, capped at 800 entries
      recent:{author_id} Redis List of last 100 post_ids for every posting author
      post:{post_id}     Memcached hydrated post payload (hot 2-day working set ~60 GB)
    

    Why each store fits its access pattern:

    • Wide-column store (a distributed database where a partition key picks which machine holds the data and a clustering key keeps rows pre-sorted on disk within that partition): author_posts reads an author's newest 20 posts in one sequential disk read; bucketing by (author_id, year_month) prevents hyper-active bot accounts from creating unbounded partitions.
    • Storing the follow graph twice (following + followers): Read-time merging asks "who does user U follow?" (following), while write-time fan-out asks "who follows author A?" (followers). Updating both tables asynchronously reconciles via a lightweight background repair job if the second write fails.
    • Redis home:{user_id} stores 16-byte (post_id, author_id) pairs — strictly as derived data: Including author_id lets the read path immediately filter out someone you just unfollowed before hydrating posts, and keeping only IDs (16 B vs. 300 B full posts) shrinks RAM by ~19× while ensuring every lost cache shard can be rebuilt from following + author_posts.
  5. High-level architecture

                                 Mobile / Web Clients
                                          |
                            [ API Gateway: Auth, Rate Limits ] ---------> [ CDN + Object Store ]
                           /                 |                \             (images / video)
                          v                  v                 v
                 [ Post Service ]    [ Graph Service ]   [ Timeline Service ] ---> [ Ranker ]
                    |         |              |              |            |         (optional)
                    v         |              v              v            v
            [ Post Store + ]  |       [ Graph Store ]  [ Timeline ] [ Post & User ]
            [ Outbox Table ]  |      (following/ers)   [  Redis   ] [  Memcached  ]
                    |         |
           (Outbox Relay)     +---> updates recent:{author_id} synchronously
                    v
         [ Kafka "post-events" ]  (partitioned by author_id)
            /                 \                        \
           v                   v                        v
     [ Fan-out Workers ]  [ Abuse / Spam ]    [ Search, Notifications, ]
     (push < 100k authors  [ Classifiers  ]    [ Sharded Like Counters  ]
      to Timeline Redis)
    

    Write path (POST /v1/posts): Post Service checks Idempotency-Key, generates a Snowflake post_id, performs a quorum write (waiting for 2 of 3 storage replicas to confirm durability) to posts, author_posts, and a transactional outbox row (saving the outgoing event inside the same local write so a server crash between DB write and Kafka publish can never leave an orphaned post that never fans out), prepends post_id to recent:{author_id}, and returns 201 in ~20 ms. Fan-out happens asynchronously in the background so posting speed never depends on follower count.

  6. Deep dive 1: Hybrid feed generation (push vs. pull)

    Comparing the two pure strategies reveals why neither works alone at scale:

    Dimension Fan-out on Write (Push) Fan-out on Read (Pull)
    When an author posts Push (post_id, author_id) into every follower's Redis list Append only to author_posts and recent:{author_id}
    When a user opens home feed 1 Redis read (LRANGE home:{uid}) Fetch recent lists of all ~150 followees and merge
    Read p99 latency Fast and predictable (~5 ms cache read) Tail-heavy (waits on the slowest of ~150 lookups)
    Where it breaks Celebrity posts (50M writes = 71 s queue spike + 800 MB RAM) High read QPS (7.5M lookups/s) and users following 5,000 accounts

    Notice a counter-intuitive fact: for ordinary accounts, push actually performs ~10× fewer total daily operations than pull! If an average author posts once a day and each follower opens the app 10 times a day, pushing costs 1 × F writes/day whereas pulling costs 10 × F reads/day. Push only breaks on celebrity burst size and duplicated RAM — which is exactly where pull shines because a celebrity's recent:{author_id} list is a single ultra-hot key cached in every Timeline server's local RAM!

    Our 4-rule Hybrid Feed Architecture

    Author posts (followers = F)
      |-- F < 100,000  --> [ Fan-out Workers ] --> push to active-30d followers' home:{uid}
      |-- F >= 100,000 --> skip push! Keep only in recent:{author_id}
    
    Viewer U reads Home Timeline:
      merge( home:{U} [pushed <100k authors]
           + recent:{C} for each followed celebrity C >= 100k
           + recent:{U} [viewer's own posts -> instant read-your-writes!] )
    
    1. Push ordinary authors (followers < T, where T = 100,000): Fan-out workers page through followers in chunks of 5,000, splitting large authors into parallel worker subtasks and pipelining LPUSH + LTRIM 0 799 by Redis shard so even a 99,000-follower post finishes well under 1 second.
    2. Pull large/celebrity authors (followers >= T): Zero fan-out writes on post creation. At read time, Timeline Service fetches recent:{author_id} for the ~10–30 large accounts the viewer follows (cached in-process on Timeline servers with a 1–2 s TTL).
    3. Skip inactive followers (> 30 days idle): Skipping the ~50% of accounts inactive over the past month cuts fan-out writes and Redis RAM in half; if a dormant user logs back in, we rebuild home:{user_id} once on demand.
    4. Always merge recent:{viewer_id}: Merging the viewer's own recent list guarantees instant read-your-writes even before async workers run.

    Guarding the threshold boundary with hysteresis: If an account hovers around 100,000 followers, flipping modes every hour is dangerous when crossing downward (100,005 -> 99,990), because its recent posts while >= T were never pushed into followers' Redis lists! Use hysteresis (switching to pull at 100,000, switching back to push only below 80,000) and keep pulling any recently downgraded account for 7 days until its unpushed posts age past active feeds.

    from typing import Dict, List, Optional, Tuple
    
    
    def get_home_timeline_page(
        viewer_id: int,
        max_id: Optional[int],
        limit: int,
        timeline_cache,
        recent_posts_cache,
        graph_service,
    ) -> List[Tuple[int, int]]:
        """Merge pushed entries and pulled celebrity/self lists, returning newest (post_id, author_id) pairs."""
        # Full set of all followed author IDs (both regular and celebrity followees).
        followed_ids = graph_service.get_following_set(viewer_id)
    
        # Deduplicate by post_id (at-least-once fan-out retries may LPUSH an ID twice).
        candidates: Dict[int, int] = {}
        for post_id, author_id in timeline_cache.get_list(viewer_id):
            candidates[post_id] = author_id
    
        # Pull recent posts from followed celebrity accounts (>= T) plus the viewer's own posts.
        pulled_authors = graph_service.get_celebrity_followees(viewer_id) + [viewer_id]
        for author_id in pulled_authors:
            for post_id in recent_posts_cache.get_list(author_id):
                candidates[post_id] = author_id
    
        # Snowflake post_ids are time-ordered, so sorting descending gives newest-first order.
        newest_first_ids = sorted(candidates.keys(), reverse=True)
    
        page: List[Tuple[int, int]] = []
        for post_id in newest_first_ids:
            author_id = candidates[post_id]
            # Cursor check: strictly < max_id avoids repeating the last post of the previous page.
            if max_id is not None and post_id >= max_id:
                continue
            # Instant unfollow enforcement: drop pushed posts from accounts the viewer unfollowed.
            if author_id != viewer_id and author_id not in followed_ids:
                continue
    
            page.append((post_id, author_id))
            if len(page) == limit:
                break
    
        return page
    

    Deep-scroll edge case: recent:{author_id} caches only an author's newest 100 IDs. If a prolific news account posts 120 times today and a reader scrolls deep enough that max_id is older than the 100th cached ID of that account, Timeline Service queries author_posts (post_id < max_id LIMIT 20) for that author so older posts never vanish silently.

  7. Deep dive 2: Pagination, hydration, and feed ranking

    Why OFFSET pagination breaks on live feeds — and how max_id cursors fix it

    Page 1 loaded at 12:00:00 (limit = 3):  [418, 415, 410]   -> next_cursor encodes max_id = 410
    Two new posts [425, 421] arrive at 12:00:04 -> list is now [425, 421, 418, 415, 410, 404, 399]
      - Broken OFFSET 3 : returns [415, 410, 404]  (duplicates 415 and 410!)
      - Cursor < 410    : returns [404, 399, ...]  (exact, zero duplicates!)
    

    Batched hydration and zero-fan-out deletes

    Once get_home_timeline_page picks ~25 candidate IDs (slightly over-fetching above limit = 20 in case a post was deleted), Timeline Service issues three parallel batched MGET calls: post:{post_id} (Memcached), user:{author_id}, and viewer interaction state (liked_by_me). When an author deletes a post, Post Service marks status = DELETED (tombstone — a soft-delete marker) in posts and invalidates post:{post_id} in Memcached; hydration automatically drops tombstoned posts on the very next read without hunting through 100,000 Redis timelines!

    Extending to a ranked timeline (mode=ranked)

    1. Candidate pool: Reuse the exact same ~800 pushed IDs + pulled celebrity lists (~1,000–1,500 candidates).
    2. Scoring: Extract lightweight features (post age, viewer-to-author interaction affinity, early likes-per-minute velocity, media presence, author trust score) and score all ~1,000 candidates in ~15–25 ms using logistic regression or gradient-boosted trees.
    3. Snapshot pagination: Because live engagement scores shift every second, max_id cursors do not apply to ranked order. Instead, cache the ranked ID list under a short-lived snapshot:{snapshot_id} key (10-minute TTL) and paginate cleanly via (snapshot_id, offset) until the user pulls to refresh. If the Ranker times out (> 60 ms), fall back transparently to chronological order.
  8. Deep dive 3: Consistency expectations across operations

    Rather than claiming vague "eventual consistency" everywhere, specify the exact contract per user action:

    User Action Consistency Contract Mechanism
    Create post Durable before 201; instant read-your-writes for author Quorum DB write + Idempotency-Key; read path always merges recent:{viewer_id} (and routes author's own profile reads to primary for 5 s to mask replica lag)
    Follower sees post < 5 s p99 (pushed) / < 2 s (pulled) Async Kafka fan-out workers (< T); 1–2 s local cache TTL on recent:{celebrity_id} (>= T)
    Follow account Immediate graph state; feed backfilled in < 3 s Graph write + async worker backfilling followee's last 20 posts into home:{viewer_id}
    Unfollow account Immediate on next refresh Read-time check author_id in followed_ids drops old pushed entries immediately
    Delete post Immediate on next refresh Tombstone in posts + Memcached post:{id} invalidation drops post during hydration
    Like / repost count Eventual (1–3 s) Stream-aggregated sharded counters flushed once per second

    Note one subtle ordering property: Snowflake clocks across servers can differ by a few milliseconds via NTP, and a delayed fan-out batch can insert a post slightly below the very top of a feed. For microblogging, millisecond-approximate ordering is an accepted trade-off in exchange for coordination-free ID generation.

  9. Rate limiting, abuse defense, scaling, and observability

    Rate limiting and spam mitigation ("accept writes fast, gate distribution")

    • Gateway token buckets: Enforce per-user and per-IP token buckets (counters that refill steadily up to a small burst limit and return HTTP 429 with Retry-After when empty) — e.g., 50 posts/hour (burst 10), 400 follows/day, and 300 timeline loads/15 min.
    • Asynchronous spam gating: Running heavy ML spam classifiers synchronously inside POST /v1/posts would slow every writer. Instead, assign each user a trust_score (account age, verified contact, report history). High-trust users fan out immediately; new or low-trust accounts save their post (so the spammer sees their own post and cannot easily probe rules) while holding back fan-out for 2–5 seconds until the Kafka spam classifier checks duplicate-text hashes and malicious URLs — marking abusive posts LIMITED before they ever reach a follower!

    Scaling hotspots, failure recovery, and observability

    • Consistent hashing & stampede protection: Shard Redis and Memcached via consistent hashing (mapping keys onto a hash ring so adding or losing one of 125 nodes remaps < 1% of keys). Protect viral posts and celebrity recent:{id} lists with 1–2 s local in-process caches on Timeline servers plus single-flight request coalescing (merging concurrent cache misses on the same server into one backend fetch so a cache expiry never causes a cache stampede against storage).
    • Load-shedding knob (T): If breaking news spikes post creation 10× and Kafka fan-out lag climbs toward 5 s, dynamically lower T from 100,000 to 20,000 — seamlessly shifting work from background push writes to cached read-time pulls until the spike subsides. If both replicas of a Redis timeline shard die, rate-limit on-demand timeline rebuilds while immediately serving partial feeds from pulled accounts.
    • Observability (SLIs & SLOs): Track Service Level Indicators (SLIs) against Service Level Objectives (SLOs): POST /v1/posts availability (99.99%), GET /v1/timeline/home latency (p99 < 200 ms), and end-to-end fan-out lag (p99 < 5 s from post_created timestamp to final Redis LPUSH), verified continuously by an external synthetic canary author account polled by synthetic followers.

    Summary of key trade-offs

    • Hybrid push/pull (T = 100k) + active-user filter: Eliminates celebrity write storms and halves timeline RAM while keeping ordinary reads fast, at the cost of maintaining two code paths and merging ~10–30 lists on read.
    • 16-byte (post_id, author_id) derived Redis lists + read-time hydration: Cuts cache RAM ~19× and makes unfollows and deletes instantaneous without fan-out, trading one batched Memcached MGET per page load.
    • Time-ordered Snowflake cursors (max_id) + frozen ranking snapshots: Guarantees duplicate-free scrolling on live feeds without central ID coordination.

Intuition & how it works

Think of building a social microblogging feed as running a neighborhood mail service for 150 million daily readers. When an ordinary person with 200 friends writes a short note, the fastest way to make reading instant is to drop a tiny index card carrying just the note's ID into each active friend's personal mailbox right after the note is written (fan-out on write, or push) — when a friend opens the app, their mailbox is already waiting in memory! When a global celebrity with 50 million followers posts, however, printing and stuffing 50 million mailbox cards at once would clog the entire mailroom for over a minute; instead, the celebrity pins new notes onto one public bulletin board in memory, and fans quickly glance at that board and mix those notes into their mailbox whenever they refresh (fan-out on read, or pull).

Either pure strategy fails badly on its own. Pure fan-out on read (querying all ~150 accounts a user follows on every timeline open) triggers 50,000 peak reads/s × 150 = 7.5 million author lookups per second and forces every feed load to wait on the slowest of 150 reads. Pure fan-out on write makes reads a single lookup, but a single post from a 50-million-follower celebrity triggers 50 million cache writes at once (~71 seconds of peak cluster capacity) and wastes 800 MB of RAM duplicating one post ID.

Walk through a tiny concrete trace to see how our hybrid feed combines the best of both. Suppose user Nina follows her friend Omar (300 followers, pushed) and global athlete Serena (20 million followers, pulled):

  1. Omar posts (post_id = 410): Saved durably to the post store, and background Kafka workers push (410, Omar) into home:Nina in Redis within ~1 second.
  2. Serena posts (post_id = 415): Saved durably and prepended only to recent:Serena — zero fan-out workers run.
  3. Nina posts (post_id = 418): Saved durably and prepended to recent:Nina.
  4. Nina opens her Home Timeline: Timeline Service reads home:Nina ([(410, Omar), (399, Omar)]), merges recent:Serena ([415, 404]) and recent:Nina ([418]), sorts by Snowflake ID (a 64-bit time-ordered integer where larger IDs are newer) to get [418, 415, 410, 404, 399], filters out anyone Nina unfollowed, and hydrates (fetches full text, author avatars, and like counts in one batched cache call) that page in under 50 ms.

Key trade-offs

  • Fan-out on write (push) vs. fan-out on read (pull). For ordinary authors who post ~1×/day while followers read ~10×/day, push actually performs ~10× fewer total daily operations than pull and keeps read latency tiny; switching to pull above a celebrity threshold T (such as 100,000 followers) eliminates massive write bursts and duplicated RAM at the modest cost of merging ~10–30 cached celebrity lists on read.
  • Dynamic celebrity threshold T and hysteresis. Lowering T shrinks fan-out lag during live-event traffic spikes at the price of slightly more read-time merging; adding hysteresis (switching to pull at 100k and back to push only below 80k, while continuing to pull for 7 days) prevents accounts oscillating near T from losing unpushed recent posts.
  • Pushing only to active users (last 30 days). Skipping dormant followers cuts Redis RAM (~8 TB instead of ~16 TB) and write load in half, trading a one-time rate-limited pull rebuild when a long-inactive user returns.
  • Caching 16-byte (post_id, author_id) pairs vs. full 300-byte posts. Storing bare IDs plus author_id cuts timeline memory ~19×, enforces unfollows immediately before hydration, and makes post edits/deletes take effect on the next read via post-cache invalidation, in exchange for one batched Memcached lookup per page.
  • Redis Lists (LPUSH + LTRIM) vs. Redis Sorted Sets. Lists use far less memory per entry across 120 billion cached pointers, trading read-time deduplication by post_id when at-least-once worker retries insert an ID twice.
  • Cursor pagination (max_id) vs. OFFSET pagination. max_id cursors never repeat or skip posts when new items arrive at the top of a live feed, while ranked feeds freeze a 10-minute snapshot_id list so changing ML scores do not scramble page 2.
  • Availability on reads vs. strong durability on writes. Serving a timeline 2 seconds stale (or falling back from ML ranking to chronological order) keeps feeds fast and available during partial outages, while quorum writes (confirming 2 of 3 replicas) plus client idempotency keys (UUIDs preventing duplicate creates on retry) protect user posts from data loss.

Common mistakes

  • Picking 100% push or 100% pull without doing the math, missing either the 50M-follower celebrity write explosion or the 50,000 × 150 = 7.5M/s read scatter-gather bottleneck.
  • Running follower fan-out synchronously inside POST /v1/posts, making post creation time out for popular users instead of decoupling via Kafka.
  • Writing to the post database and publishing to Kafka as two separate uncoordinated calls, where a process crash in between saves a post that never reaches followers — solved by a transactional outbox (writing the event row atomically alongside the post and relaying it) or change-data capture.
  • Using SQL LIMIT 20 OFFSET 20 on a live feed, causing users to see duplicate posts every time new posts arrive while they read page 1.
  • Treating the Redis timeline cache as the primary database, losing timelines permanently when a shard fails instead of designing home:{user_id} as derived state rebuildable from following + author_posts.
  • Indexing the follow graph in only one direction, forgetting that read-time merging queries follower -> followees while write-time fan-out queries followee -> followers.
  • Breaking read-your-writes, where an author posts, refreshes immediately, and panics because async Kafka fan-out hasn't reached their own timeline yet (solved by always merging recent:{viewer_id} and routing the author's profile reload to primary storage briefly).
  • Fanning out deletes across millions of cached timelines, instead of marking a tombstone (soft-delete flag) on the post record, invalidating post:{id} in Memcached, and dropping it cleanly during hydration.
  • Returning raw 64-bit Snowflake integers as JSON numbers to browsers, where JavaScript silently corrupts IDs above 2^53 - 1 unless serialized as strings.

Follow-up questions

  • Walk through the end-to-end write and read flow when a creator with tens of millions of followers publishes during a live global event. Post Service writes the post once to posts and author_posts (quorum write), prepends the ID to recent:{author_id}, and publishes post_created to Kafka. The fan-out worker sees follower_count >= 100,000 and immediately skips fan-out, so ordinary users' fan-out queues experience zero extra load. As millions of fans refresh their feeds over the next few seconds, Timeline servers read recent:{author_id} and post:{post_id} from their own local in-process memory caches (1–2 s TTL) backed by single-flight request coalescing (merging simultaneous misses per server into a single Redis/Memcached call), absorbing millions of reads/s with only a few dozen backend cache hits per second.
  • How would you adapt this timeline pipeline to power a personalized recommendation feed that surfaces posts from unfollowed creators? Split feed assembly into Candidate Generation (~1,500 posts) and Two-Stage Ranking. Keep ~700 in-network candidates from our hybrid home:{user_id} + pulled followees, and blend in ~800 out-of-network candidates retrieved from social-graph co-engagement ("liked by people you follow"), approximate nearest-neighbor embedding search (matching vector representations of topics/posts the user engages with), and regional trending pools. A fast lightweight model prunes 1,500 candidates down to ~200, a richer neural ranker predicts positive actions (like, reply, meaningful read time) minus negative signals (mute, block, report), diversity rules prevent five posts in a row from one author, and the final ordered IDs are stored in a 10-minute snapshot:{id} cache for stable cursor paging.
  • How does the system recover a timeline when a dormant user returns after months away, or when a cache shard loses all replicas? Because we skip pushing to users inactive > 30 days, home:{user_id} is empty (cache miss). Timeline Service checks following, fetches the newest ~20 posts from author_posts across the user's followed accounts in parallel with bounded concurrency, writes the merged top 800 pairs into home:{user_id}, and updates last_active_at so future posts push normally. To prevent a cache stampede (thousands of cold rebuilds overwhelming author_posts simultaneously after a shard loss or a global push notification), cold rebuilds pass through a concurrency-limited queue: if the queue is saturated, waiting users immediately receive a fast degraded feed assembled from pulled popular accounts while their full background rebuild completes within a few seconds.

Follow-up questions

Similar questions

More Asana interview questions

All 24 Asana questions →