Skip to main content
02

Design a news feed (like Facebook or X)

MediumInfinite scrollPaginationVirtualizationOptimistic updates

Design the news feed of a social network, like Facebook, LinkedIn or X: an endless list of posts from people and pages the user follows, where they can like and comment.

A typical framing: "Users open the app and scroll through hundreds of posts. Posts have text, images and videos. Users can like, comment and create posts. Focus on the web client."

TL;DR

The feed is a paginated list loaded with infinite scroll, using cursor-based pagination (not page numbers), because new posts keep arriving at the top. The client keeps posts in a normalized store so the same post or author is stored once and updates everywhere. Long sessions need list virtualization, so the DOM only holds the posts on screen. Likes and comments use optimistic updates with rollback on failure. Render the first page on the server for a fast first paint, lazy-load media, and show new posts with a "New posts" pill instead of shifting the content under the user's finger.

1. Requirements

Questions worth asking:

  • Is the feed ranked (an algorithm) or chronological? Who builds the ranking? (Usually the server.)
  • Which post types: text, images, video, links with previews, polls?
  • Do new posts appear in real time?
  • Which interactions are in scope: like, comment, share, create a post?
  • Web only, or also mobile web? Are slow devices and networks important?

Functional

  • Load the feed and keep loading more as the user scrolls.
  • Show posts with text, images and video. Like, comment, and create a post.
  • Tell the user about new posts without breaking their scroll position.

Non-functional

  • Fast first load: good LCP even on mobile.
  • Smooth scrolling for long sessions (hundreds of posts) at 60 fps.
  • Resilient: one broken post or image doesn't break the feed. Works on flaky networks.
  • Accessible: keyboard and screen reader friendly.

2. Architecture

Loading diagram...
  • Server-rendered first page: the HTML ships with the first ~10 posts, then the client hydrates and takes over.
  • Feed list: requests the next page when a sentinel element near the bottom becomes visible (IntersectionObserver), and virtualizes rows.
  • Normalized store: posts, users and comments in lookup tables by id. The feed itself is just an ordered list of post ids plus a cursor.
  • Data layer: a library like TanStack Query or Apollo handles caching, deduping, retries and optimistic updates. Mention it, but be ready to explain what it does under the hood.

3. Data model

ts
type User = { id: string; name: string; avatarUrl: string }

type Media = {
  type: 'image' | 'video'
  url: string
  width: number
  height: number
  blurhash?: string
}

type Post = {
  id: string
  authorId: string
  text: string
  media: Media[]
  createdAt: string
  likeCount: number
  likedByMe: boolean
  commentCount: number
}

// Normalized client store
type FeedStore = {
  users: Record<string, User>
  posts: Record<string, Post>
  feed: { postIds: string[]; nextCursor: string | null; hasMore: boolean }
}

Normalizing matters: when the user changes their avatar, or a post appears in two places (the feed and a modal), there is one copy to update. Media width and height come from the server so the client can reserve space and avoid layout shift (CLS).

4. Interface (API)

http
GET /api/feed?cursor=eyJpZCI6IjEyMyJ9&limit=10
json
{
  "posts": [{ "id": "p_9", "authorId": "u_1", "text": "...", "likeCount": 12 }],
  "users": [{ "id": "u_1", "name": "Noa", "avatarUrl": "..." }],
  "nextCursor": "eyJpZCI6IjExMyJ9"
}
http
POST   /api/posts               { text, mediaIds }
POST   /api/posts/:id/like
DELETE /api/posts/:id/like
GET    /api/posts/:id/comments?cursor=...

Why cursor pagination?

With offset pagination (?page=3), if 5 new posts are added at the top while the user scrolls, page 3 now starts 5 posts earlier, and the user sees duplicates. Deleted posts cause skipped posts. A cursor is an opaque pointer to "after this item" (often an encoded id or timestamp), so the next page always continues exactly where the last one ended. It's also cheaper for the database than large OFFSETs.

5. Optimizations and deep dives

Infinite scroll

ts
const sentinelRef = useRef<HTMLDivElement>(null)
useEffect(() => {
  const observer = new IntersectionObserver(
    ([entry]) => entry?.isIntersecting && hasMore && !isLoading && loadMore(),
    { rootMargin: '800px' }, // start loading before the user reaches the end
  )
  if (sentinelRef.current) observer.observe(sentinelRef.current)
  return () => observer.disconnect()
}, [hasMore, isLoading])

IntersectionObserver is much cheaper than listening to scroll events. Guard against double-loading the same cursor, and show skeleton posts while loading.

Infinite scroll has costs: the footer is unreachable, and returning from a post loses your place. Restore the scroll position and the loaded pages when the user navigates back (keep the data in the cache and the position in history state).

Virtualization

After 500 posts, the DOM holds thousands of nodes, and scrolling and memory suffer. Virtualization (windowing) renders only the posts in and near the viewport, with spacers for the rest. Feed posts have variable heights, so the virtualizer has to measure rows after they render (libraries like TanStack Virtual support this). Use it when sessions are long; for short feeds, content-visibility: auto on each post is a cheap alternative.

Optimistic updates

When the user taps Like, update the UI immediately and send the request in the background:

  1. Save the previous state, set likedByMe = true and likeCount + 1.
  2. Send POST /like.
  3. On failure, roll back to the saved state and show a small toast.

Make the operation idempotent on the server (liking twice is still one like), and debounce rapid toggles. A new post from the composer can be inserted at the top optimistically too, with a "posting..." state.

New posts

Poll every minute or get new post ids over SSE or a WebSocket. Don't insert them above the user while they read: show a "New posts" button, and when tapped, prepend them and scroll to the top. Inserting content above the viewport moves everything down, which is jarring and causes misclicks.

Performance

  • SSR or streaming the first page, then hydrate. Put the critical CSS inline and keep the initial JS small.
  • Images: responsive srcset, modern formats (AVIF, WebP), loading="lazy" except for the first post's image, which may be the LCP element (give it fetchpriority="high"). Reserve space with width and height, and show a blur placeholder.
  • Video: don't autoload. Load a poster image, and play only when mostly visible and muted.
  • Code splitting: load the composer, the comments panel and the share dialog on demand.

Accessibility

Use semantic <article> elements for posts, a role="feed" container with aria-busy while loading, and real buttons with labels ("Like post by Noa"). Make sure keyboard users can skip past a post's content and that loading more posts doesn't steal focus.

Common follow-ups

  • "How would you make it work offline?" Cache the last feed in IndexedDB and show it instantly on the next visit (stale-while-revalidate). Queue likes and posts made offline and send them later.
  • "How do you handle a post being edited or deleted?" Real-time events update the normalized store by id. A deleted post's card collapses or shows "This post was removed".
  • "How would you measure performance?" Core Web Vitals (LCP, INP, CLS) from real users, time to first post, and scroll jank (long tasks and frame drops).

What interviewers look for

  • Cursor pagination, and why offset pagination breaks for a live feed.
  • Virtualization and a plan for long sessions and memory.
  • Optimistic updates with rollback, and thought about idempotency.
  • A normalized client data model, not nested copies.
  • Care for perceived performance (SSR, skeletons, image strategy, CLS) and for scroll position.

Was this helpful?