A deep dive into designing a high-performance news feed — from virtual scrolling and cursor pagination to optimistic likes, real-time inserts, and accessibility.
System DesignComponentsFacebookFrontend
1. Requirements & Scoping
A news feed looks deceptively simple — a column of posts you scroll through. But once you account for thousands of items, variable-height media, optimistic interactions, and real-time updates, the feed becomes one of the most performance-sensitive surfaces in a social product. Get the rendering wrong and the scroll stutters; get the data wrong and likes vanish; get the accessibility wrong and the feed is unusable without a mouse.
We scope this as a Facebook-style single-column timeline: the user sees a reverse-chronological list of posts from people they follow, can like, comment, and share, and new posts stream in at the top without a full reload.
Key Insight
The feed's hardest constraint is not "show posts" — it is "keep scrolling buttery smooth while the dataset grows unbounded and users mutate it constantly." Every design decision flows from that tension.
Functional
Display a reverse-chronological list of posts
Infinite scroll — load more as the user nears the bottom
Like, comment, and share any post
Compose and prepend a new post
Stream new posts in real time at the top
Show threaded comments inline per post
Non-Functional
Smooth scroll: 60fps with 10,000+ posts in memory
Perceived latency: optimistic updates under 100ms
Bandwidth: only render and fetch what is visible
Resilience: graceful error recovery and retry
Accessibility: WCAG 2.1 AA, full keyboard + screen-reader support
Tip
Treat the feed as an infinite stream, not a page. Design the data model and rendering so that the number of items can grow without bound without degrading the experience.
2. Component Architecture & API
I split the feed into three layers. The FeedContainer owns the data store and side effects. The FeedList handles virtual scrolling and infinite loading. Each FeedItem renders a single post and is memoized so that liking one post never re-renders its siblings.
A separate FeedComposer handles writing new posts, and FeedHeader holds filters and the "new posts" pill. Keeping the composer decoupled means posting never disturbs the scroll position of the list.
The estimateItemHeight callback is the contract between the list and its items. The virtualizer needs a height estimate before measuring — get it roughly right and scroll position stays stable; get it wrong and items jump as they mount.
News feed component hierarchy — container, list, item, and its sub-pieces
The FeedItem is deliberately a leaf component. Its only job is to render one post and forward interactions upward. This isolation is what lets us memoize it aggressively — a like on post A produces a new object reference only for post A, so the virtualizer re-renders a single row instead of the whole visible window.
3. Data Model & State Shape
A feed is a list, but storing it as an array is a trap. The moment you need to update a like count on item #847, you are rebuilding the entire array and re-rendering every visible row. Instead I normalize the data into a record keyed by post id, with a separate ordered array of ids. Updates touch one record; the order array stays stable.
The optimisticLike flag is a transient piece of state. It marks a post whose like has been applied to the UI but not yet confirmed by the server. The LikeButton uses it to show a spinner or dimmed state while the request is in flight.
Normalized state is the single most impactful decision for a feed. It turns an O(n) array rebuild into an O(1) keyed update, which is the difference between a smooth like and a janky re-render at scale.
4. Interface Definition (API)
The feed API uses cursor-based pagination, not offset pagination. With offsets, inserting a new post at the top shifts every subsequent page and causes duplicates or gaps when the user scrolls. A cursor is an opaque token pointing to "the item after this one," so inserts at the top never disturb the next fetch.
Never expose the cursor as a readable offset like ?page=5. A readable cursor invites clients to skip ahead, which breaks when data shifts. Keep it opaque — a signed or base64-encoded token the server controls.
Likes and comments are simple REST mutations. Because they are idempotent-ish (a like is a toggle), they map cleanly to POSTand DELETE on a sub-resource. The server returns the authoritative count so the client can reconcile after the optimistic update.
Key Insight
In an interview, mention that you chose cursor pagination because a feed is an append-mostly, frequently-mutated stream where offset pagination breaks under concurrent inserts. That reasoning signals you have thought about the data, not just the UI.
5. Component Deep Dive
The two hardest pieces of the feed are the virtual scroller and the memoized item. Get both right and the feed feels instant no matter how many posts exist.
Virtual Scroller
Rather than mounting 10,000 DOM nodes, the virtualizer mounts only the items inside the viewport plus an overscan buffer. A spacer div holds the full scroll height so the scrollbar behaves naturally, and each visible item is absolutely positioned at its computed offset.
The overscan buffer — typically 3 to 5 items above and below — is what prevents flicker during fast scrolling. Without it, items pop in visibly as the viewport crosses their boundary. Tune it by measuring the tallest item height.
Memoized FeedItem
Each item is wrapped in memo with a custom comparator that checks reference equality on the item object. Because the store normalizes data, a like only creates a new reference for the liked post — every other row is referentially stable and skips re-rendering.
If you skip the custom areEqual and rely on default shallow comparison, a callback like onLikethat is recreated each render defeats the memo. Stabilize callbacks with useCallback or store them outside the render path.
6. Data Flow & Communication
Data flows one direction: the API populates a normalized cache, the store subscribes to that cache, and the FeedListsubscribes to the store. Mutations like likes take a shortcut — they update the store immediately (optimistically), then reconcile with the server, and revert if the request fails.
Data flow — API feeds a normalized cache and store; likes apply optimistically and reconcile or revert
Optimistic Likes
A like is the canonical optimistic update. The user taps the heart and expects it to fill instantly. Waiting for a network round trip feels broken. So we apply the change to local state first, fire the request, and either confirm or roll back.
Always reconcile with the server's returned count, not your local arithmetic. Two devices liking simultaneously can desync optimistic math; only the server knows the true count. Overwriting local state with the server response is the safe path.
Infinite Scroll States
Scrolling is a small state machine. The feed sits idle until a sentinel near the bottom intersects the viewport, transitions to loading, fetches the next page, appends items and advances the cursor, then returns to idle. A fetch failure diverts to an error state with a retry path.
Scroll state machine — idle, loading, loaded, with a recovery path through error and retry
Note
Guard the sentinel with the loadingState so a second scroll event cannot kick off a duplicate request. The classic bug is double-fetching the same page because the IntersectionObserver fires multiple times during a single scroll gesture.
7. Performance Optimization
Performance is where a feed lives or dies. The goal is to keep the main thread free during scroll so the browser can composite frames at 60fps. Every optimization below targets that single metric.
Virtual Scrolling
With 10,000 posts, rendering every DOM node would cost roughly 10,000 × ~8 nodes = 80,000 elements — far past the point where the browser struggles. Virtualizing to ~15 visible items plus a buffer keeps the DOM at under 200 elements while the scroll height stays accurate.
Virtual scrolling — only items in the viewport plus an overscan buffer are mounted to the DOM
Lazy Media Loading
Images and videos are the heaviest assets in a feed. I lazy-load them with an IntersectionObserver and a 200px root margin so media starts fetching just before it scrolls into view. Native loading="lazy" handles simple cases, but the observer gives finer control for videos that should not preload.
The composer, comment thread, and share sheet are not needed on first paint. I lazy-load them with next/dynamic at ssr: false, which trims the initial JS bundle by roughly 40-60 KB gzipped. The feed shell — list and item — loads first so users see content immediately.
Key Insight
The three numbers that matter: DOM node count under ~200, main-thread task under 4ms per frame, and initial JS under 150KB gzipped. Hit those and the feed will scroll at 60fps even on mid-range phones.
8. Security Considerations
A feed is a wall of user-generated content, which makes it a prime XSS surface. Every post body, comment, and link must be treated as untrusted until sanitized. The feed also performs mutations (likes, comments, shares) that need CSRF protection and rate limiting.
XSS in User Content
Never render raw user HTML with dangerouslySetInnerHTML. Sanitize every string with DOMPurifyusing an allowlist of tags and attributes. Force rel="noopener noreferrer nofollow" on every anchor to prevent tabnabbing and SEO spam.
example.ts
import DOMPurify from "dompurify";
function renderPostText(raw: string): string {
// Strip scripts, event handlers, and unsafe markup
return DOMPurify.sanitize(raw, {
ALLOWED_TAGS: ["b", "i", "em", "strong", "a", "br", "p"],
ALLOWED_ATTR: ["href", "target", "rel"],
ALLOW_DATA_ATTR: false,
});
}
// Link safety: force rel attributes on all anchors
DOMPurify.addHook("afterSanitizeAttributes", (node) => {
if (node.tagName === "A") {
node.setAttribute("target", "_blank");
node.setAttribute("rel", "noopener noreferrer nofollow");
}
});
// CSRF: attach token + SameSite cookie to every mutation
async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
const res = await fetch(path, {
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": getCsrfToken(),
...init.headers,
},
...init,
});
if (res.status === 429) throw new RateLimitError("Too many requests");
if (!res.ok) throw new ApiError(res.status);
return res.json();
}
CSRF & Rate Limiting
Every mutation carries a CSRF token in a header and relies on SameSite=Lax cookies. The API enforces rate limiting — returning 429 when a user hammers the like button — and the client surfaces a friendly "slow down" message rather than blindly retrying.
Warning
An unsanitized feed is the fastest path to account takeover. A single malicious post can inject a script that exfiltrates session tokens from everyone who scrolls past it. Sanitize on render, not just on write — the server is not the only trust boundary.
9. Testing Strategy
The feed has three behaviors that break silently: pagination, optimistic reconciliation, and virtual rendering. Tests target each layer — unit for the store, integration for the API contract, and e2e for the real scroll experience.
Unit & Integration
The store is tested with mocked API responses (via msw). Tests verify that pagination advances the cursor, that a successful like reconciles, and that a failed like reverts. These are the invariants that keep the feed honest under flaky networks.
example.ts
describe("useFeedStore", () => {
it("appends items and advances the cursor", async () => {
const { result } = renderHook(() => useFeedStore());
await act(() => result.current.fetchNextPage());
expect(result.current.order.length).toBeGreaterThan(0);
expect(result.current.hasMore).toBe(true);
expect(result.current.cursor).not.toBeNull();
});
it("optimistically likes then reconciles on success", async () => {
server.use(rest.post("/api/feed/:id/like", (req, res, ctx) =>
res(ctx.json({ liked: true, likeCount: 144 }))));
const { result } = renderHook(() => useFeedStore());
await act(() => result.current.toggleLike("p_1"));
expect(result.current.items["p_1"].likedByMe).toBe(true);
expect(result.current.items["p_1"].optimisticLike).toBe(false);
});
it("reverts the like when the request fails", async () => {
server.use(rest.post("/api/feed/:id/like", (req, res) =>
res.networkError()));
const { result } = renderHook(() => useFeedStore());
const before = result.current.items["p_1"].likedByMe;
await act(() => result.current.toggleLike("p_1"));
expect(result.current.items["p_1"].likedByMe).toBe(before);
expect(result.current.error).toBeTruthy();
});
});
// e2e (Playwright)
test("loads more on scroll", async ({ page }) => {
await page.goto("/feed");
const initial = await page.locator("article.feed-item").count();
await page.locator(".feed-scroll").evaluate((el) =>
el.scrollTo(0, el.scrollHeight));
await page.waitForResponse(/\/api\/feed/);
const after = await page.locator("article.feed-item").count();
expect(after).toBeGreaterThan(initial);
});
End-to-End
Playwright drives the real scroll. A test loads the feed, captures the item count, programmatically scrolls to the bottom, waits for the network request, and asserts that more items appeared. This catches regressions the unit tests cannot — broken IntersectionObserver wiring, sentinel placement, and stale cursors.
Tip
The most valuable e2e test: scroll deep, toggle a like, scroll back up, and confirm the like persisted. If that passes, your reconciliation and virtualization are working together correctly.
10. Accessibility
A feed is primarily a scrolling list, so it must be operable by keyboard and understandable by screen readers. The challenge is that virtual scrolling changes which items are in the DOM — focus management and live announcements must account for that.
example.tsx
<section aria-label="News feed" aria-busy={loadingState === "loading"}>
<article aria-labelledby="title-p_8821">
<h3 id="title-p_8821">Ada Lovelace</h3>
<time dateTime="2024-06-19T10:00:00.000Z">2h ago</time>
<button
type="button"
aria-pressed={item.likedByMe}
aria-label={`Like post by ${item.author.name}. ${item.likeCount} likes`}
>
<svg aria-hidden="true">…</svg>
<span>{item.likeCount}</span>
</button>
<button
type="button"
aria-expanded={commentsOpen}
aria-controls="comments-p_8821"
aria-label={`Comments on post by ${item.author.name}`}
>
💬 <span>{item.commentCount}</span>
</button>
</article>
</section>
// Live region announces new posts without stealing focus
<div role="status" aria-live="polite" className="sr-only">
{newCount > 0 && `${newCount} new post${newCount > 1 ? "s" : ""} available`}
</div>
ARIA Roles: The feed region uses aria-label="News feed" and aria-busy during loading. Each post is an article labelled by the author name heading.
Keyboard Navigation:Tab moves focus between interactive elements (like, comment, share). The list itself is not a tab stop — users navigate via the actions inside each item.
Screen Readers: The like button uses aria-pressed to convey toggle state and an aria-labelthat includes the count. Comments use aria-expanded and aria-controls to link the trigger to the thread.
Live Announcements: A polite aria-live region announces "N new posts available" without stealing focus, so screen-reader users learn about streamed content on their own terms.
Reduced Motion: Entrance animations and the "new posts" pill respect prefers-reduced-motion and appear instantly when the preference is set.
Tip
Virtual scrolling can strand focus: if a focused element scrolls out of the buffer and unmounts, focus drops to the body. Restore focus to the nearest still-mounted item on scroll, or keep the focused item pinned in the buffer.
Live Demo
Here is the news feed running live. Scroll to the bottom to trigger infinite loading, tap a like button to see the optimistic update apply instantly, and watch how only the visible items stay mounted in the DOM.
Try liking a post and then watch the count update instantly — the optimistic path runs before the network resolves.