Design the front end of a social news feed similar to the Facebook home feed.
Users open the app and see a personalised, ranked list of posts from friends, groups and pages. They scroll indefinitely, react to posts, open and write comments, and create new posts with text and images.
The interviewer gives you these constraints:
Focus on the client: architecture, data model, API contract with the backend, and the performance and UX techniques that make the feed fast and robust. You have about 45 minutes.
A news feed looks simple (a list of cards) but it is the single most performance-sensitive surface in a social product: it is the first thing users see, they spend most of their time in it, and every millisecond of input delay or layout shift is visible. Spend the first five minutes pinning scope down.
| Concern | Target |
|---|---|
| First load (LCP) | < 2.5 s at p75 on a mid-range phone over 4G |
| Interaction (INP) | < 200 ms at p75; reacting must feel instant (< 100 ms visual feedback) |
| Layout stability (CLS) | < 0.1, so no jumping posts while images load |
| Scroll | 60 fps on mid-range devices, even after 500+ posts |
| Memory | bounded; long sessions must not crash low-memory tabs |
| JS budget | < 200 KB gzipped critical JS for the feed route |
| Availability | degrade gracefully: cached feed if the network fails |
State your assumptions out loud: ranked feed, logged-in only (no SEO), streaming SSR for first paint, near-real-time counts via a subscription, ads are just another post type.
For a logged-in feed I would server-render the shell and the first 3–5 posts (streaming SSR with React 18/19
renderToPipeableStream or a framework like Next.js App Router) and hydrate on the client. Trade-offs:
After the first page, everything else is client-side: pagination, interactions, live updates.
<FeedPage>
<TopNav />
<Composer /> // create post, image picker, upload progress
<NewPostsPill /> // "12 new posts" -> scroll to top and merge
<FeedList> // virtualization, pagination trigger
<FeedItem kind="post"> // switch on post type
<PostHeader /> // author, timestamp, menu
<PostBody /> // text with mentions/links, see more
<PostMedia /> // image grid, video, link preview
<ReactionBar /> // counts, react button, share
<CommentsSection /> // lazy, collapsed by default
</FeedItem>
<FeedItem kind="ad" />
<FeedSentinel /> // IntersectionObserver target for next page
</FeedList>
</FeedPage>
useInfiniteQuery, Relay, or Apollo).Separate server state (owned by the backend, cached on the client) from client/UI state (owned by the browser).
| Data | Owner | Where it lives |
|---|---|---|
| Feed page list and cursor | server | server cache (useInfiniteQuery / Relay connection) |
| Post, User, Comment entities | server | normalized entity store |
| Viewer's own reaction | server, optimistically patched | entity store + pending mutation |
| Composer draft text and attachments | client | component state, persisted to sessionStorage |
| Which comment sections are expanded | client | UI state keyed by post id |
| Scroll position and virtualization offsets | client | in memory; restored on back navigation |
| Upload progress | client | mutation state |
type ID = string;
interface User {
id: ID;
name: string;
avatar: { url: string; width: number; height: number };
}
interface Media {
id: ID;
type: 'image' | 'video';
width: number; // intrinsic size so we can reserve space (CLS)
height: number;
blurhash?: string; // tiny placeholder
srcset: { url: string; w: number }[];
videoManifestUrl?: string; // HLS/DASH for video
alt?: string;
}
interface Post {
id: ID;
authorId: ID;
createdAt: string; // ISO 8601, format on the client per locale
text: string; // plain text + entity ranges, never HTML
entities: { type: 'mention' | 'link' | 'hashtag'; offset: number; length: number; ref: string }[];
media: Media[];
reactionSummary: { total: number; top: ReactionType[] };
viewerReaction: ReactionType | null;
commentCount: number;
previewCommentIds: ID[];
version: number; // monotonically increasing; reject stale updates
}
interface FeedState {
entities: {
posts: Record<ID, Post>;
users: Record<ID, User>;
comments: Record<ID, Comment>;
};
feed: {
itemIds: ID[]; // order defined by the server
endCursor: string | null;
hasMore: boolean;
pendingNewIds: ID[]; // buffered "new posts", not yet shown
};
}
Key decisions:
version per entity lets the store ignore a stale real-time event arriving after a fresher fetch.A ranked feed changes constantly. With ?offset=20, a post inserted at the top shifts everything and the user sees
duplicates (or misses posts). A cursor is an opaque token encoding "where I stopped" (often a ranking session id
plus position), so the next page is stable regardless of inserts. Offset pagination is only acceptable for static,
seekable lists (search results with page numbers).
GET /api/feed?cursor=eyJzZXNzIjoiYTEiLCJwb3MiOjIwfQ&limit=10
{
"items": [
{
"type": "post",
"post": {
"id": "p_981",
"authorId": "u_12",
"createdAt": "2025-03-02T10:15:00Z",
"text": "Trail run this morning with @Ana",
"entities": [{ "type": "mention", "offset": 23, "length": 4, "ref": "u_77" }],
"media": [{ "id": "m_1", "type": "image", "width": 1080, "height": 1350,
"blurhash": "LKO2?U%2Tw=w]~RBVZRi};RPxuwH",
"srcset": [{ "url": "https://cdn.example.com/m_1_480.avif", "w": 480 },
{ "url": "https://cdn.example.com/m_1_1080.avif", "w": 1080 }],
"alt": "Runner on a mountain trail" }],
"reactionSummary": { "total": 42, "top": ["like", "love"] },
"viewerReaction": null,
"commentCount": 5,
"previewCommentIds": ["c_1"],
"version": 7
}
},
{ "type": "ad", "ad": { "id": "ad_5", "creativeUrl": "…", "impressionToken": "…" } }
],
"users": { "u_12": { "id": "u_12", "name": "Sam", "avatar": { "url": "…", "width": 64, "height": 64 } } },
"comments": { "c_1": { "id": "c_1", "authorId": "u_77", "text": "Nice!", "createdAt": "…" } },
"pageInfo": { "endCursor": "eyJzZXNzIjoiYTEiLCJwb3MiOjMwfQ", "hasMore": true }
}
Side-loading users and comments at the top level keeps the payload deduplicated and maps directly onto the
normalized store. With GraphQL (Relay-style connections) you get the same thing via edges { node } + pageInfo
and fragment colocation: each component declares the fields it needs, which prevents over-fetching as the card
evolves. GraphQL is a strong fit here because the post card has many variants; REST is simpler to cache at the CDN.
Both are defensible.
PUT /api/posts/p_981/reaction { "type": "love", "clientMutationId": "m-7f3a" }
DELETE /api/posts/p_981/reaction
POST /api/posts/p_981/comments { "text": "Looks great", "clientMutationId": "m-7f3b" }
POST /api/posts { "text": "…", "mediaIds": ["up_1"], "clientMutationId": "m-7f3c" }
PUT for a reaction is idempotent (setting "love" twice is the same state), which makes retries safe. The
clientMutationId lets the server dedupe retried POSTs and lets the client match a server echo to its optimistic
placeholder. Image uploads go first to POST /api/uploads (or a pre-signed URL direct to object storage), which
returns an uploadId; the post creation references it.
// client -> server
{ "op": "subscribe", "topics": ["post:p_981:counts", "post:p_982:counts"] }
// server -> client
{ "op": "event", "topic": "post:p_981:counts", "data": { "reactionTotal": 43, "commentCount": 6, "version": 8 } }
{ "op": "event", "topic": "feed:new", "data": { "count": 3 } }
Subscribe only to posts currently in (or near) the viewport and unsubscribe as they scroll away; otherwise a long session would subscribe to hundreds of topics. SSE is enough because the traffic is server-to-client (mutations go over HTTP), works over HTTP/2 without connection-count issues, and reconnects automatically. A WebSocket is fine if the product already has one (e.g. for chat) — reuse it rather than open a second connection.
interface FeedListProps {
itemIds: ID[];
hasMore: boolean;
isFetchingNext: boolean;
onLoadMore: () => void;
renderItem: (id: ID) => React.ReactNode;
estimatedItemHeight?: number;
}
interface ReactionBarProps {
postId: ID; // reads summary + viewerReaction from the store
onReact: (type: ReactionType | null) => void;
}
interface PostMediaProps {
media: Media[];
priority?: boolean; // true for the first post: eager load + fetchpriority="high"
}
Components receive IDs and select from the store, so a count update re-renders only the affected ReactionBar,
not the whole list.
IntersectionObserver with a generous rootMargin
(e.g. 1500px 0px), so data arrives before the user reaches the end. Do not use scroll listeners.isFetchingNext) and dedupe by post id when merging pages.ResizeObserver. Biggest win, but complicates find-in-page, anchor links and scroll
restoration, and variable heights cause "scroll jumps" if estimates are poor.content-visibility: auto with contain-intrinsic-size: auto 600px: the browser skips rendering
off-screen cards but keeps them in the DOM, so find-in-page and accessibility still work. Cheaper to adopt,
but DOM node count and React memory still grow.content-visibility for the first ~100 posts, then unmount posts far above the viewport into
fixed-height placeholders. This is roughly what large feeds do in practice.FeedItem is memoized and subscribes to only its own entity (selector by id), so a real-time count change is
an O(1) re-render. With the React Compiler (React 19), much of the manual memo work disappears.startTransition) so a large page render never blocks a tap.React.lazy + intersection).scheduler.yield() where supported,
falling back to setTimeout.AbortController if they
navigate away.preconnect to the CDN.pendingNewIds until the user taps
the pill or is already at the top.Reacting must feel instant:
viewerReaction, adjust reactionSummary.total.clientMutationId.In React 19, useOptimistic expresses this for a component; for cross-component consistency the store-level
patch (TanStack Query onMutate/onError, Relay optimisticResponse) is better. Debounce rapid toggles (like,
unlike, like) so only the final state is sent.
New posts and comments use temporary ids (tmp_…) and show a "Posting…" state; the server echo replaces them.
srcset + sizes, AVIF/WebP with JPEG fallback via the CDN's content negotiation.loading="eager" and fetchpriority="high" (and a preload in SSR HTML); everything else
loading="lazy" and decoding="async".width/height attributes or aspect-ratio, plus a blurhash/LQIP placeholder: zero CLS.prefers-reduced-motion and data saver (navigator.connection.saveData where
available) by disabling autoplay. Use adaptive streaming (HLS/DASH) rather than MP4 for long clips.online (or via Background Sync where supported).
Reactions are idempotent so replay is safe.role="feed" container whose children are role="article" with aria-posinset and
aria-setsize (use -1 when the total is unknown) and aria-labelledby the author/time. Set aria-busy="true"
while loading more.j/k shortcuts, announced in help).aria-pressed).Intl.RelativeTimeFormat and Intl.NumberFormat (compact notation
"1.2K" is locale-aware).margin-inline-start) so RTL layouts flip for free; set dir="auto" on user text so
a Hebrew post in an English UI renders correctly.https: only) with
rel="noopener noreferrer ugc" on external links.script-src, object-src 'none'), Trusted Types if any HTML must be injected (e.g.
sanitised link previews via DOMPurify).HttpOnly, Secure, SameSite=Lax cookie; CSRF token on mutations.web-vitals library) segmented by device class and connection type.navigator.sendBeacon or fetch(..., { keepalive: true }) on
visibilitychange.content-visibility — let's measure DOM size and INP on a
Moto G-class device before choosing" rather than picking a library by default.How would you avoid showing the same post twice? Dedupe by post id when merging pages, and let the server use the cursor's ranking session to exclude already-served items. The client-side set is a cheap safety net.
User scrolls 1,000 posts, then hits back from a post detail page. How do you restore position? Keep the query
cache in memory (or history.state + IndexedDB for full reloads), restore the item list, then scroll to the
anchor post id plus offset after layout. The bfcache helps if you avoid unload handlers and Cache-Control: no-store.
How do you handle a post being deleted while on screen? The real-time channel sends a post:deleted event;
replace the card with a collapsed "This post is no longer available" placeholder rather than removing it, which
would shift content under the user.
Why not poll instead of SSE? Polling every 30 s across hundreds of millions of tabs is expensive and adds latency. Polling is a reasonable fallback when the streaming connection fails, and is fine for an MVP.
How do you render 20 image variants without a huge bundle? Code-split post-type renderers by type
(React.lazy keyed by post.type), with the common types in the main chunk and rare ones loaded on demand.
How do you measure success? Web Vitals at p75, time to first post, scroll FPS, and product metrics (session length, posts viewed) in A/B tests. A performance change that does not move a user metric is still worth shipping if it improves vitals, but you should know which one you are optimising.
Spotted a mistake or a rights concern? Report an issue