Design the home feed of Pinterest: an endless, responsive masonry grid of "pins" (an image with an optional title, author and a save button). Pins have different heights, so columns are filled unevenly, like bricks.
The interviewer asks you to cover:
Assume desktop and mobile web, and that a recommendation API already returns pins.
Pinterest is a feed question whose twist is layout. A normal feed is one column where each item's position depends only on the items above it. In masonry, an item's position depends on every column's current height, so layout, virtualization, resizing and scroll restoration all get harder. Make that the centre of the answer.
/pin/:id) with bigger image, description, comments and "More like this" (itself a
masonry feed). Back returns to the exact position.| Concern | Target |
|---|---|
| LCP | < 2.5 s p75 mobile |
| CLS | ≈ 0: pins never move after they are placed |
| Scroll | 60 fps after 2,000+ pins loaded; INP < 200 ms |
| DOM size | bounded (e.g. < 150 pin nodes mounted at any time) |
| Memory | bounded image decoding; long sessions on low-end Android must not crash |
| Data | first page ≤ ~25 pins; image bytes matched to column width |
Recommendation ranking, ads auction, creating pins, boards management UI beyond "save".
| Approach | How | Pros | Cons |
|---|---|---|---|
CSS multi-column (column-count) | browser flows items into columns | zero JS | order runs down each column, not across; appending items reshuffles everything |
| N flex columns | JS assigns items to column arrays | simple, no absolute positioning | resizing changes column count → full redistribution; hard to virtualize each column consistently |
| JS absolute positioning | compute x, y per item, position with transform | full control, stable, virtualizable | needs known heights; more code |
| Native CSS masonry | grid masonry proposal (syntax still being finalised in 2025) | browser does it | not shipped across browsers; no virtualization story |
I would choose JS-computed absolute positioning for production, with a note that native CSS masonry is a future simplification for small lists. This is roughly how large masonry sites work: the layout engine is plain TypeScript, independent of React, and the view renders only what's visible.
<HomePage>
<Header /> // search, profile
<MasonryFeed> // owns layout engine + virtualization
<PinCard style={{ transform: translate(x, y), width }}>
<PinImage /> // aspect-ratio box, placeholder color
<PinOverlay /> // Save, More (desktop hover / focus)
<PinFooter /> // title, author
</PinCard>
<LoadMoreSentinel />
</MasonryFeed>
<PinCloseupModal /> // rendered over the feed when navigated from it
<SaveToBoardPopover />
ResizeObserver corrects heights for text footers that differ from estimates.type ID = string;
interface Pin {
id: ID;
title?: string;
description?: string;
link?: string; // outbound URL
dominantColor: string;
image: {
width: number; // original dimensions: needed for layout
height: number;
urls: { w236: string; w474: string; w736: string; orig: string }; // fixed width buckets
alt?: string;
};
pinner: { id: ID; name: string; avatarUrl: string };
saveCount: number;
viewerSavedBoardId: ID | null;
type: 'image' | 'video' | 'ad';
}
interface LayoutItem {
id: ID;
column: number;
x: number;
y: number;
width: number;
height: number; // image height + footer height
measured: boolean; // footer height verified by ResizeObserver
}
interface MasonryLayout {
containerWidth: number;
columnCount: number;
columnWidth: number;
gutter: number;
items: LayoutItem[]; // same order as pins
columnHeights: number[]; // current bottom of each column
columns: number[][]; // item indices per column, sorted by y (for fast range queries)
}
interface FeedStore {
pins: Record<ID, Pin>; // normalized; a pin can appear in home and closeup feeds
homeFeed: { ids: ID[]; cursor: string | null; hasMore: boolean; loading: boolean };
closeupFeeds: Record<ID, { ids: ID[]; cursor: string | null; hasMore: boolean }>;
layoutSnapshots: Record<string, { layout: MasonryLayout; scrollY: number }>; // keyed by history entry key
}
Layout is derived state (from pins + width), but it is cached incrementally: appending 25 pins only places 25
new items starting from the current columnHeights; it doesn't recompute existing positions. Full recomputation
happens only when the column count or column width changes.
GET /api/feed/home?bookmark=Y2JVSG...&page_size=25
{
"pins": [
{
"id": "pin_1001",
"title": "Small balcony garden ideas",
"dominantColor": "#6b8f5a",
"image": { "width": 736, "height": 1104,
"urls": { "w236": "https://i.example.com/236x/ab/cd.jpg", "w474": "https://i.example.com/474x/ab/cd.jpg",
"w736": "https://i.example.com/736x/ab/cd.jpg", "orig": "https://i.example.com/originals/ab/cd.jpg" },
"alt": "Balcony with hanging planters" },
"pinner": { "id": "u_5", "name": "Lena", "avatarUrl": "https://i.example.com/u5_30.jpg" },
"saveCount": 1820,
"viewerSavedBoardId": null,
"type": "image"
}
],
"bookmark": "Y2JVSG...next",
"hasMore": true
}
Save:
POST /api/boards/b_9/pins { "pinId": "pin_1001", "clientMutationId": "s-71" }
-> 201 { "boardPinId": "bp_88", "board": { "id": "b_9", "name": "Garden" } }
Optimistic: mark "Saved to Garden" immediately; roll back on error.
interface MasonryFeedProps<T> {
items: T[];
getKey: (item: T) => string;
getAspectRatio: (item: T) => number; // height / width of the image
estimateFooterHeight?: (item: T, columnWidth: number) => number;
minColumnWidth?: number; // e.g. 236; column count derived from container width
gutter?: number; // 16
overscanPx?: number; // 1000
renderItem: (item: T, layout: LayoutItem) => React.ReactNode;
onEndReached: () => void;
restoreKey?: string; // history entry key for scroll restoration
}
interface PinCardProps {
pin: Pin;
width: number; // column width chosen by layout
priority?: boolean; // above-the-fold
onOpen: (pinId: ID) => void;
onQuickSave: (pinId: ID) => void;
}
The MasonryFeed is generic so the close-up's "More like this", search results and board pages reuse it.
function placeItems(layout: MasonryLayout, newItems: { id: ID; aspect: number; footer: number }[]) {
const { columnWidth, gutter } = layout;
for (const item of newItems) {
// shortest column first; ties broken by lowest index to keep left-to-right reading order
let col = 0;
for (let c = 1; c < layout.columnCount; c++) {
if (layout.columnHeights[c] < layout.columnHeights[col]) col = c;
}
const height = Math.round(columnWidth * item.aspect) + item.footer;
const y = layout.columnHeights[col];
const x = col * (columnWidth + gutter);
layout.columns[col].push(layout.items.length);
layout.items.push({ id: item.id, column: col, x, y, width: columnWidth, height, measured: false });
layout.columnHeights[col] = y + height + gutter;
}
}
max(columnHeights), set on the container so the scrollbar is right.Image height is known from the aspect ratio. The footer (title up to 2 lines, author row) is not. Options:
ResizeObserver, and if different,
update that item's height and shift only items below it in the same column. Because pins below are often
not yet visible, this causes no visible movement.-webkit-line-clamp: 2) — simplest and fully stable; Pinterest-like
UIs commonly clamp titles. I'd start here.With absolute positions known, virtualization is a range query: render items whose [y, y + height] intersects
[scrollTop - overscan, scrollTop + viewportHeight + overscan].
y, so binary search per column finds the first visible item: O(columns ×
log n) per scroll frame. A naive filter over 5,000 items every frame also works but wastes main-thread time.scroll listener, compute the range in requestAnimationFrame, and update state
only when the visible set changes, not on every pixel.transform: translate3d(x, y, 0) to position cards — layout-free moves. Keep stable keys so React reuses
nodes as pins enter/leave.content-visibility: auto on each card; it's simpler but still keeps thousands of
nodes and image elements in memory, which matters on low-end Android.floor((width + gutter) / (minColumnWidth + gutter)). Recompute only when width crosses a
breakpoint or column width changes; debounce with ResizeObserver + rAF.w474. Use srcset with w
descriptors and sizes set to the exact column width, so the browser picks correctly.aspect-ratio from the API and background: dominantColor, so blank space looks intentional and
nothing shifts.fetchpriority="high" for the first, eager for the rest of the first viewport; everything else
loading="lazy". Since cards are virtualized, unmounted images release decoded memory; that's a hidden benefit of
windowing on mobile./pin/:id with background state; the feed stays mounted (hidden or behind the overlay), so
"Back" is instant and positions are untouched.layoutSnapshots[history.state.key]:
restore pins from the query cache, the layout snapshot (no relayout needed if the width is the same) and then
scrollTo(scrollY). Set history.scrollRestoration = 'manual' so the browser doesn't scroll before content
exists.:hover, :focus-within) — no state updates on mouse move.requestIdleCallback / scheduler.postTask at
background priority.role="feed" with each pin an article labelled by its title/alt; aria-busy while loading;
aria-setsize="-1" (unknown total).:focus-within), not only on hover; touch devices show a
persistent save button or long-press menu with a visible alternative.dir="auto"; the grid itself places column 0 at the inline-start (right side in RTL)
by computing x from the right when dir="rtl".Intl.NumberFormat.rel="nofollow ugc noopener", and show the destination domain. Consider a
redirect service for malware checking.img-src to the image CDN.performance.measureUserAgentSpecificMemory is available).MasonryFeed API stays the same).Why not CSS column-count? Items flow top-to-bottom per column, so the first row isn't the top-ranked items, and
appending items can move existing ones between columns, causing visible jumps.
What if the API doesn't give image sizes? Use a fixed aspect-ratio crop (e.g. all 2:3), or load images before placing them (slow and janky), or have the server compute dimensions at ingestion time — the right fix.
How do you handle window resize with 2,000 pins? Recompute layout once per breakpoint change (fast — it's arithmetic), anchor to the first visible pin, and only render the visible slice.
How do you avoid a gap at the bottom of one column? You can't fully, but shortest-column-first minimizes it, and loading the next page early hides it. Some designs rebalance the last row; avoid moving already-visible pins.
How would you test the layout engine? Pure function snapshot tests with fixture aspect ratios, property tests (no overlaps, columns within one item height of each other), and incremental-vs-full equivalence.
Spotted a mistake or a rights concern? Report an issue