Design a News Feed (Facebook / Twitter style)

A frontend system design walkthrough for an infinite news feed. You will learn how to load pages with cursors, keep thousands of posts smooth with virtualization, update likes instantly, and log what users really saw.

Frontend system design · Classic design question

After this page you can design the client side of a social feed end to end. You can explain the component tree, the store shape, the API contract, and the four or five deep dives an interviewer expects.

Correctness contract: the feed never shows a post twice and never skips a post between pages. It never jumps while the user reads. It never keeps a rejected like without telling the user.

Assumptions: a web client built with React or a similar library. The backend already ranks the feed. Users range from a high end laptop to a three year old Android phone on 4G.

A news feed looks like a simple list. It is one of the hardest frontend screens to get right. The list has no end. Every item has a different height. Items contain images and videos that load late and change size. Users tap like and expect the heart to turn red at once. New posts arrive while the user reads. The product team wants to know which posts were truly seen, not only rendered. All of this must stay at 60 frames per second on a cheap phone. This page breaks the problem into parts and shows how each part fits.

Contents

  1. Concepts to understand first
  2. 1. Clarifying questions and requirements
  3. 2. Scope and budgets
  4. 3. High-level architecture
  5. 4. Data model
  6. 5. Interface and API
  7. 6. Deep dive: infinite scroll and cursor pagination
  8. 7. Deep dive: virtualization and mixed post types
  9. 8. Deep dive: media loading
  10. 9. Deep dive: new posts, optimistic actions, and the cache
  11. 10. Deep dive: impression logging and prefetching
  12. 11. Deep dive: accessibility and server rendering
  13. 12. Failure modes
  14. 13. Trade-offs
  15. 14. 45-minute interview walkthrough
  16. 15. Summary
  17. 16. Common mistakes
  18. Worked example: one scroll session
  19. Code lab: a cursor feed with dedupe
  20. Check yourself
  21. Key terms
  22. Further reading

Concepts to understand first

Cursor pagination

The server returns a page of items plus an opaque token called a cursor. The client sends that token back to get the next page. The cursor marks a position in the ranked list, not a page number. So new posts at the top do not shift what the next page contains.

Example. The first call returns 10 posts and endCursor: "c_8f2a". The next call is GET /feed?after=c_8f2a&limit=10.

Limit. You cannot jump to page 40 with a cursor. That is fine for a feed. It is wrong for a search result table where users want page numbers.

Virtualization (windowing)

Only the rows near the viewport exist in the DOM. Rows far above or below are removed and replaced by empty space of the same height. The DOM stays small, so layout, style, and memory costs stay flat as the user scrolls.

Example. A user scrolls past 500 posts. The DOM holds about 15 post nodes at any time, not 500.

Limit. Browser find in page (Ctrl+F) cannot see removed rows. Screen readers also lose them. You must design around both.

Normalized cache

Each entity is stored once, keyed by type and id. Lists hold ids, not copies. When one post changes, every place that shows it updates, because they all read the same record.

Example. The same post appears in the home feed and in a profile tab. A like updates posts["p_91"] once. Both views re-render.

Limit. Normalizing costs CPU on every response. For a tiny app with one list, a plain array is simpler.

Optimistic update

The UI applies the expected result of an action before the server confirms it. If the server fails, the UI rolls back and tells the user. This hides network latency for actions that almost always succeed.

Example. Tap like. The heart turns red and the count goes from 41 to 42 in the same frame. The request finishes 300 ms later.

Limit. Do not use it for actions that often fail or that move money. A wrong "Payment sent" message is worse than a spinner.

IntersectionObserver

A browser API that tells you when an element enters or leaves the viewport, or crosses a visibility ratio. It runs off the main scroll path, so it is far cheaper than reading getBoundingClientRect() in a scroll handler.

Example. A sentinel div sits 2 screens below the last post. When it intersects, the client fetches the next page.

Limit. Callbacks are asynchronous and batched. They are not exact to the pixel or the millisecond.

Impression

An event that says a user actually saw a post. A common rule is: at least 50 percent of the post was visible for at least 1 second while the tab was visible. Ranking, ads billing, and "seen" state all depend on it.

Example. A user flings past 30 posts in one second. None of them count as impressions.

Limit. Impressions are best effort. Some events are lost when the tab dies. The server must dedupe and tolerate gaps.

1. Clarifying questions and requirements

Start by asking questions. Each answer removes a branch of the design. Good questions for a feed:

Functional requirements

Non-functional requirements

Interview

Say out loud which parts you treat as backend concerns. Ranking, fan out, and storage belong to the server. Your job is the client: rendering, data flow, caching, and the API shape the client needs.

2. Scope and budgets

Numbers turn vague goals into design rules. Work them out early.

Devices and network

Frame budget

At 60 Hz the browser has 16.7 ms per frame. The browser itself needs about 6 ms for style, layout, paint, and compositing. So your JavaScript gets roughly 10 ms per frame during scroll. On a 120 Hz screen the whole frame is 8.3 ms. Mounting one complex post card can cost 3 to 8 ms on a slow phone. So you can mount at most one or two new cards per frame without dropping frames. This single number is why virtualization and memoized cards matter.

Data size

DOM size

One post card has 50 to 150 DOM nodes. Without virtualization, 300 posts means 15,000 to 45,000 nodes. Lighthouse warns above 1,400 nodes. Style recalculation scales with node count. With a window of 15 rendered posts, the DOM stays near 2,000 nodes.

Bundle budget

Tip

Quote the 16 ms frame and the 4.7 MB decoded image in the interview. They show you know where the real costs live: main thread time and decoded memory, not JSON size.

3. High-level architecture

Split the client into four layers. Each layer has one job.

Client architecture of a news feed: FeedPage renders a virtual list of post cards that read from a normalized store. An IntersectionObserver triggers the feed query, which calls the API and merges results into the store. Media loads from a CDN, a realtime channel feeds the new posts banner, and an impression logger batches events.
Figure 1. Client architecture. Components read from one normalized store. Observers drive paging and impressions.

The key idea is a one way flow. The network writes into the store. The store drives the view. The view never talks to the network directly. It calls actions such as loadMore() or toggleLike(id). This makes caching, rollback, and testing simple, because there is one source of truth.

Intuition

Think of the store as a warehouse and the feed as a shelf label list. The list says "p_91, p_88, ad_3". The warehouse holds the actual boxes. Many shelves can point to the same box.

4. Data model

The client store has three parts: entities, lists, and pending work.

type ID = string

interface User { id: ID; name: string; avatarUrl: string; verified: boolean }

interface Media {
  id: ID
  kind: "image" | "video"
  width: number            // intrinsic size, known before load
  height: number
  blurhash?: string        // tiny placeholder
  srcset: { url: string; w: number }[]
  posterUrl?: string       // video only
}

type PostKind = "text" | "photo" | "video" | "link" | "shared" | "ad"

interface Post {
  id: ID
  kind: PostKind
  authorId: ID
  createdAt: string
  text: string
  mediaIds: ID[]
  likeCount: number
  commentCount: number
  likedByMe: boolean
  sharedPostId?: ID
  trackingToken: string    // opaque, sent back with impressions
}

interface FeedState {
  ids: ID[]                // ordered, deduped
  seen: Set<ID>            // fast dedupe check
  endCursor: string | null
  hasMore: boolean
  status: "idle" | "loading" | "error"
  pendingNewIds: ID[]      // arrived live, not yet shown
}

interface Store {
  users: Record<ID, User>
  posts: Record<ID, Post>
  media: Record<ID, Media>
  feeds: Record<string, FeedState>   // "home", "profile:u_7"
  pendingMutations: Record<ID, { kind: "like"; desired: boolean; attempt: number }>
}

Three details matter here. First, media carries width and height from the server. The client can reserve space before the image loads, so nothing shifts. Second, seen lets the client drop a duplicate post in constant time. Ranked feeds do send duplicates sometimes, for example when the ranking shifts between two page calls. Third, trackingToken lets the server join an impression back to the ranking decision without the client knowing what it means.

5. Interface and API

Server API

GET /api/feed?after=<cursor>&limit=10
200 {
  "items": [ { "id": "p_91", "kind": "photo", ... } ],
  "users": { "u_7": { ... } },          // side loaded, not nested
  "media": { "m_3": { ... } },
  "pageInfo": { "endCursor": "c_8f2a", "hasMore": true }
}

POST /api/posts/:id/like          Idempotency-Key: <uuid>
DELETE /api/posts/:id/like        Idempotency-Key: <uuid>
POST /api/posts/:id/comments      { clientId, text }
POST /api/impressions             [ { postId, trackingToken, visibleMs, ts } ]

Side loading users and media avoids repeating the same author 10 times per page. It also maps directly into the normalized store. GraphQL with Relay style connections gives the same shape: edges, node, and pageInfo.

Real-time channel

Use Server-Sent Events through EventSource for one way signals. A feed only needs server to client messages, so a full WebSocket is not required. Messages are small:

event: new_posts      data: {"count": 3, "topId": "p_120"}
event: counts         data: {"p_91": {"likeCount": 57, "commentCount": 9}}

Send counts only for posts the client says are on screen. Otherwise a viral post would push thousands of updates to every client.

Component props

<VirtualFeedList
  feedKey="home"
  estimateHeight={(post) => number}   // first guess before measuring
  overscan={3}                        // extra rows above and below
  onEndReached={loadMore}
  renderItem={(id) => <PostCard id={id} />}
/>

<PostCard id="p_91" />    // reads post, author, media from store

Passing only an id keeps PostCard memoizable. It re-renders only when its own entity changes, not when the list grows.

6. Deep dive: infinite scroll and cursor pagination

Why not offset pagination

With ?page=3&size=10 the server returns items 20 to 29. If 2 new posts arrive at the top between calls, items shift down by 2. The user sees 2 posts again on page 3. If a post is deleted, one post is skipped. A cursor encodes the last item position, such as a ranking session id plus the last score. The server continues from that point, so inserts at the top do not matter.

Triggering the next page

Place a sentinel element after the last rendered row. Observe it with IntersectionObserver and a large rootMargin, for example "0px 0px 1500px 0px". The fetch starts when the user is still about two screens away. With a 300 ms page fetch and a fast fling at 3,000 pixels per second, 1,500 pixels gives about 500 ms of lead time. That is enough on 4G, and the user rarely sees a spinner.

Guarding against double loads

Restoring position

When the user opens a post and presses back, they expect to land on the same post. Store the feed state in memory, keyed by feed name. Also store the id of the first visible post and its pixel offset. On return, render from cache, then scroll so that post sits at the same offset. Restoring by id is more robust than restoring by scrollY, because row heights may have changed. Set history.scrollRestoration = "manual" so the browser does not fight your logic.

Mistake

Using a scroll event listener that checks scrollTop + clientHeight >= scrollHeight - 200. It runs on every scroll event, forces layout reads, and fires many times near the bottom. IntersectionObserver does the same job off the hot path.

7. Deep dive: virtualization and mixed post types

How a virtual list works

The list keeps an array of row heights and a running sum of offsets. On scroll, it finds the first row whose bottom is below scrollTop, using binary search over the offset array. It renders from that row until rows fill the viewport, plus an overscan of 2 to 4 rows on each side. A spacer above and a spacer below hold the total scroll height, so the scrollbar stays correct.

Variable heights

Feed rows do not have fixed heights. A text post may be 120 pixels. A photo post may be 600 pixels. The list must:

  1. Estimate a height before a row renders. Use the post kind and media aspect ratio. A photo post with a 4:5 image at 500 pixels wide is about 625 pixels of image plus about 140 pixels of header and actions.
  2. Measure the real height after render with ResizeObserver.
  3. Store the measured height by post id, not by index. Then the measurement survives list changes.
  4. When a row above the viewport changes height, adjust scrollTop by the same delta. This is scroll anchoring. Without it, the content jumps.

Modern browsers have native scroll anchoring through the CSS overflow-anchor property. It works well for normal flow content. With a spacer based virtual list you often need to do it yourself, because the browser does not know your spacer is fake.

An alternative: content-visibility

CSS content-visibility: auto tells the browser to skip layout and paint for off screen elements. Pair it with contain-intrinsic-size: auto 600px so the browser reserves a guessed size and then remembers the real one. The DOM nodes still exist, so find in page and screen readers still work. But memory still grows with the number of posts, and JavaScript objects for each card stay alive.

A practical hybrid works well. Use content-visibility for the first 100 to 200 posts. Switch to true windowing, or drop the oldest pages from the DOM, for very long sessions.

Mixed post types

Use a registry that maps kind to a renderer. Common types live in the main bundle. Rare types load lazily with React.lazy. Every renderer must reserve its final height on first paint. A lazy renderer shows a skeleton with the same estimated height. Unknown kinds render a safe fallback, such as "This post type is not supported", instead of crashing the list. Wrap each card in an error boundary. One bad post must not blank the whole feed.

Intuition

A virtual list is a short conveyor belt under a long painted backdrop. The backdrop is as tall as the whole feed. Only the boxes in front of the user are real. As the user walks, boxes move from the back of the belt to the front.

8. Deep dive: media loading

Images

Video

Memory

Virtualization removes the DOM node. Removing the <img> lets the browser drop the decoded bitmap. This is a big reason to window long feeds on mobile. Mobile Safari will kill a tab that uses too much memory, and the user sees a reload.

9. Deep dive: new posts, optimistic actions, and the cache

Banner or live insert

When the server signals new posts, you have two choices.

A good rule: insert live only if scrollTop is under about 50 pixels. Otherwise, add the ids to pendingNewIds and show the banner. When the user taps the banner, prepend, dedupe, and smoothly scroll to the top. Move focus to the first new post so keyboard users land in the right place.

Optimistic like

Sequence for an optimistic like: tap queues a mutation, saves a snapshot, patches the store, re-renders, and sends the request. On success the server count is reconciled. On error the snapshot is restored and a polite live region announces the failure.
Figure 2. Optimistic like with snapshot and rollback.
  1. On tap, save the old likedByMe and likeCount.
  2. Patch the store: flip likedByMe and add or subtract 1.
  3. Send the request with an Idempotency-Key header. A retry after a timeout will not double count.
  4. On success, accept the server count. It may differ because other users liked too.
  5. On failure, restore the snapshot and show a short toast in an aria-live="polite" region.

Rapid taps are a classic bug. A user taps like, unlike, like in one second. Three requests race. The responses can arrive out of order. Fix it by keeping only the desired final state per post. Send at most one request at a time per post. When it returns, compare server state with desired state. Send one more request only if they differ. This "latest intent wins" queue makes the final state correct whatever the order.

Optimistic comment

Create a temporary comment with a clientId such as a UUID. Show it with a "Sending" style. The server echoes the clientId with the real id. The client swaps the temporary record for the real one. If it fails, keep the text and show "Retry", because losing typed text is the worst outcome.

Cache policy

10. Deep dive: impression logging and prefetching

Measuring visibility

Create one IntersectionObserver with threshold: [0, 0.5]. When a post crosses 50 percent, record the start time. When it drops below 50 percent, compute the visible duration. If it is at least 1,000 ms, emit an impression. Pause the timers when document.visibilityState becomes "hidden". A post on screen in a background tab was not seen.

Very tall posts break the 50 percent rule. A long text post 2,000 pixels tall can never be 50 percent visible on a 700 pixel screen. Use a rule like "50 percent of the post or 50 percent of the viewport, whichever is smaller". The intersectionRect.height and rootBounds.height fields give you both values.

Sending events

Prefetching

Interview

Interviewers love the impression question because it mixes product, browser APIs, and data quality. Mention the 50 percent and 1 second rule, tab visibility, tall posts, beacon on hide, and server side dedupe.

11. Deep dive: accessibility and server rendering

The feed pattern

WAI-ARIA defines a feed role for exactly this case. The container gets role="feed" and an accessible name. Each post is an <article> with aria-posinset and aria-setsize. If the total is unknown, set aria-setsize="-1". While a page loads, set aria-busy="true" on the feed. Screen readers then wait instead of reading a half built list.

Server rendering the first page

Server side rendering (SSR) of the first page sends HTML with the first 5 to 10 posts. The user sees content before the JavaScript loads. This usually improves LCP by hundreds of milliseconds on slow phones.

12. Failure modes

13. Trade-offs

Virtualization versus full DOM

Banner versus live insert

SSE versus WebSocket versus polling

Normalized store versus query cache by key

SSR versus client only

14. 45-minute interview walkthrough

  1. Minutes 0 to 5. Clarify post types, ranked or chronological, freshness, actions, platforms, and SEO. Write the functional and non-functional lists.
  2. Minutes 5 to 10. State budgets: 16 ms frame, LCP 2.5 s, CLS 0.1, 150 KB JS, DOM under 2,000 nodes. Do the decoded image math.
  3. Minutes 10 to 18. Draw the architecture: view, data, platform, network layers. Explain one way data flow.
  4. Minutes 18 to 23. Show the normalized store and the feed API with cursor and side loaded entities.
  5. Minutes 23 to 38. Deep dives. Pick three based on the interviewer's interest: cursor pagination and dedupe, virtualization with variable heights, optimistic likes with a latest intent queue, impression logging.
  6. Minutes 38 to 42. Accessibility with role="feed" and SSR of the first page.
  7. Minutes 42 to 45. Failure modes and trade-offs. Close with what you would measure in production: LCP, INP, CLS, scroll jank, and impression loss rate.

15. Summary

16. Common mistakes

Mistake

Spending 20 minutes on ranking algorithms. That is a backend question. In a frontend round, say "the server ranks" and move on to rendering, data flow, and user experience.

Worked example: one scroll session

Follow one user through a short session on a mid range phone.

  1. The user opens the app. The server streams HTML with the header and 8 posts. The first image has fetchpriority="high". LCP happens at 1.9 s.
  2. JavaScript loads. The store hydrates from the embedded JSON. ids has 8 entries, and endCursor is "c_a1". No second fetch happens.
  3. The virtual list takes over. It measures the 8 rendered posts with ResizeObserver and stores heights by id.
  4. The user scrolls. The sentinel enters the 1,500 pixel root margin when post 4 is on screen. The client calls GET /feed?after=c_a1.
  5. The response arrives in 280 ms with 10 posts. One of them, p_77, is already in seen. It is dropped. 9 ids are appended. endCursor becomes "c_b2".
  6. Posts 1 and 2 scroll far above the viewport. The list unmounts them. Their images are released. Spacer height grows to keep the scrollbar right.
  7. Post 6 is a photo. It was 52 percent visible for 1.4 s. The impression logger queues { postId: "p_60", visibleMs: 1400 }.
  8. The user taps like on post 9. The heart fills in the same frame. The count shows 42. The request returns 200 with a count of 44. The store accepts 44.
  9. An SSE message says 2 new posts exist. The user is scrolled down, so the banner shows "2 new posts". Nothing moves.
  10. The user switches to another app. visibilitychange fires. The logger sends 6 queued impressions with sendBeacon.
  11. The user returns 3 minutes later. The feed is still in memory. The same post sits at the same offset. The user taps the banner. Two posts are prepended and focus moves to the first one.

Code lab: a cursor feed with dedupe

This model shows the core paging logic without a browser. It simulates a server whose ranking inserts new posts at the top and sometimes repeats an item. It shows that cursor paging plus a seen set keeps the list clean, and that concurrent loadMore calls share one request. Save it as feed.mjs and run node feed.mjs with Node 18 or newer.

// Fake server: ranked list, cursor is the index after the last item sent.
const db = Array.from({ length: 35 }, (_, i) => ({ id: "p" + (100 - i) }))
let calls = 0
async function fetchPage(after, limit) {
  calls++
  await new Promise((r) => setTimeout(r, 50))
  const start = after ?? 0
  const items = db.slice(start, start + limit)
  if (start > 0) items.unshift(db[start - 1])     // ranking drift: repeat one item
  const next = start + limit
  return { items, endCursor: next, hasMore: next < db.length }
}

function createFeed(limit = 10) {
  const state = { ids: [], seen: new Set(), cursor: null, hasMore: true }
  let inflight = null
  async function loadMore() {
    if (!state.hasMore) return
    if (inflight) return inflight                 // share one request
    const requested = state.cursor
    inflight = fetchPage(requested, limit).then((page) => {
      if (requested !== state.cursor) return      // stale after a reset
      for (const item of page.items) {
        if (state.seen.has(item.id)) continue     // dedupe
        state.seen.add(item.id)
        state.ids.push(item.id)
      }
      state.cursor = page.endCursor
      state.hasMore = page.hasMore
    }).finally(() => { inflight = null })
    return inflight
  }
  return { state, loadMore }
}

const feed = createFeed()
await Promise.all([feed.loadMore(), feed.loadMore()])   // double trigger
db.unshift({ id: "p999" })                               // new post at top
while (feed.state.hasMore) await feed.loadMore()

const unique = new Set(feed.state.ids).size
console.log("items:", feed.state.ids.length, "unique:", unique, "calls:", calls)
console.log(unique === feed.state.ids.length ? "PASS no duplicates" : "FAIL")

Expected output: the item count equals the unique count, and the two first calls share one request. The new post p999 does not appear in the middle of the list. In a real app it would wait behind the banner. Now remove the seen check and run again. You will see the repeated items that ranking drift creates.

Check yourself

  1. Why does offset pagination cause duplicates in a live feed, and how does a cursor fix it?
    Answer

    Offsets count from the top. A new post at the top shifts every item down by one, so the next page repeats the last item. A cursor names a position after a specific item, so inserts above it do not change what comes next.

  2. A photo post loads its image 400 ms after the text. The feed jumps. What is the root cause and fix?
    Answer

    The image box had no reserved size. Send intrinsic width and height from the server and set width, height, or aspect-ratio on the element. The browser reserves space before load, so CLS stays near zero.

  3. The user taps like three times fast. How do you guarantee the final state is correct?
    Answer

    Track only the desired final state per post. Keep at most one request in flight per post. When it returns, compare server state with desired state and send one more request only if they differ. Use idempotency keys so retries do not double count.

  4. When should a new post be inserted live instead of behind a banner?
    Answer

    When the user is already at the top of the feed, or the product is a live event or chronological stream. If the user is reading further down, use a banner so content does not move.

  5. Why is a post that rendered not always an impression?
    Answer

    It may have been rendered in overscan, flung past in milliseconds, or shown in a background tab. A real impression needs a visibility ratio, a minimum duration, and a visible tab.

  6. What does content-visibility: auto give you that windowing does not, and what does it cost?
    Answer

    It keeps all nodes in the DOM, so find in page, anchors, and screen readers work. It still skips layout and paint off screen. It costs memory, because nodes and JavaScript state for every post remain alive.

  7. Name two accessibility attributes for the feed pattern and what they do.
    Answer

    role="feed" on the container tells assistive tech it is a scrolling list of articles. aria-busy="true" during loading tells the screen reader to wait. Also aria-posinset and aria-setsize give position.

Key terms

Cursor
An opaque token that marks a position in a list, used to fetch the next page.
Sentinel
An invisible element near the end of the list that triggers loading when observed.
Virtualization
Rendering only the rows near the viewport, with spacers for the rest.
Overscan
Extra rows rendered just outside the viewport to avoid blank space during fast scroll.
Scroll anchoring
Keeping visible content in place when content above it changes size.
Normalized store
A cache where each entity is stored once by id and lists hold ids.
Optimistic update
Applying the expected result before the server confirms, with rollback on failure.
Idempotency key
A unique request id that lets the server ignore repeats of the same action.
Impression
A logged event meaning the user really saw an item, by ratio, time, and tab visibility.
sendBeacon
A browser API that queues a small POST that survives page unload.
LCP
Largest Contentful Paint, the time when the largest visible element finishes rendering.
CLS
Cumulative Layout Shift, a score of how much visible content moves unexpectedly.
role="feed"
The WAI-ARIA role for a dynamic, scrollable list of articles.
Hydration
Attaching client side behavior and state to HTML that the server rendered.

Further reading

Primary references