What you'll learn: By the end of this case study you will be able to design the client side of a ranked social feed: explain why a ranked list needs a frozen snapshot cursor instead of an offset, show new posts as a count that the reader chooses to insert, make a like button instant with one request per post on the wire and the last tap winning, recover when a ranking expires, batch "seen" reports, keep the feed accessible, and test every one of these rules without a browser.
Think of a conveyor belt of dishes at a restaurant where the kitchen, not you, decides the order. If the kitchen reshuffles the belt every time you reach for a plate, you grab the same dish twice and miss others. A good belt is cut once, then moves in a fixed order for as long as you sit. New dishes are announced with a light at the end of the belt; you decide when to look. A social feed is that belt, and the client's job is to make a list that someone else keeps re-ordering behave like a list that stays put.
This is an educational reference design, not the verified internal architecture of Instagram, X (Twitter) or any other company. The names appear only in the title to say what kind of product is meant. The design is built from public web platform documentation and a runnable lab with a toy ranking. Every number in it is an illustrative assumption, labelled as such, and the lab measures no scrolling, layout or speed.
The running example is the community tab of a grocery marketplace: short posts from merchants and shoppers with a photo, a caption and a like button, shown in an order chosen by the server. The previous case study, Infinite Scroll Feed, handles the list itself: how a long list is bounded, how a page comes back and how a place is restored. This one starts from a ranked list and handles what is different: the order is not stable, new posts arrive, and the main interaction is a tap that must feel instant.
The core idea
- Ranking is the server's decision; stability is the client's problem. The server may score the same posts differently a minute from now. If every page request re-ranks, the reader sees repeats and gaps. The first request cuts a ranking and names it; later pages come from that frozen ranking.
- Freshness is a count first and an insert second. Putting new posts above the reader moves everything they are looking at. Showing "3 new posts" and letting them choose keeps control with the reader and keeps the list stable.
- A like is a state, not a toggle, and the screen shows the reader's last tap. Send "liked is true", not "flip it". Keep one request per post on the wire. Show the last tap on top of what the server last confirmed, and replace both with the server's answer when it arrives.
The rest of the lesson takes each in turn, with the lab's output as evidence.
Requirements
| Kind | Requirement | Why it matters here |
|---|---|---|
| Functional | Posts in a server-chosen order, loaded a page at a time | A cursor over a ranking |
| Functional | Like and unlike, with a visible count | Instant feedback, a write path |
| Functional | A notice when newer posts exist | Freshness without reshuffling |
| Functional | "Seen" reports for the ranking model | Batching, privacy of the user's attention |
| Quality | A like feels instant, and never ends up wrong | Optimistic update with reconciliation |
| Quality | No post twice in one scroll, none lost to a reshuffle | A frozen ranking, dedupe |
| Quality | Works with a keyboard and a screen reader | The feed pattern, toggle buttons |
| Quality | Testable without a browser | Pure reducer, thin component |
Out of scope: how the server ranks, comments, media upload, stories, and the list-bounding techniques of the previous case study.
What a ranked list does to paging
The paging lesson (see pagination) shows why a cursor beats an offset when items are added or removed: a cursor names an item. That works when the order is fixed, such as newest first. A ranking breaks it in a new way. Suppose the cursor says "after post 5 in the current ranking". A minute later post 5 may have a lower score and sit on page three, so "after post 5" now means something different, and the reader sees some posts again and misses others.
The fix is to freeze the ranking. The first request, which has no cursor, makes the server cut an ordered list of post ids and give it a name, a snapshot. Every later cursor is the snapshot name plus a position in that frozen list. Because the list no longer changes, a position in it is safe. In the lab, the cursor is the text s1:4: snapshot s1, offset 4. The client treats it as opaque.
Figure 1. The client, the feed API and a frozen ranking
How to read this: the store sits between the UI and three server surfaces. Pages and the cheap "anything newer?" question go to the feed API. Likes go to a write endpoint, one at a time per post. Seen reports go out in batches, off the critical path (dashed).
Figure 2. Cutting a ranking and reading it page by page
How to read this: only the request without a cursor is allowed to re-rank. Everything after it reads from the frozen list, so the reader's scroll is consistent even though the live ranking moves.
Illustration 1: the minimal example, a ranking that moves under the reader
The lab's fake server scores posts with a toy formula (likes, age and a bonus for a close friend). It is not a real ranking model, only something predictable. A reader loads page one (four posts). Then other readers like an old post, post 2, twenty times, and a new post arrives. The reader loads page two. A second reader opens the feed afterwards.
Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/social-feed, copied from examples/frontend/golden/social-feed.txt):
=== a ranked page list is cut once and then frozen (pages of 4)
page 1 : 11 9 7 5
page 2, same ranking : 11 9 7 5 3 1 12 10
a new session, page 1 : 2 13 11 9 (the ranking cut now differs)
server: feed (first) -> s1 [11 9 7 5]
server: feed s1:4 -> s1 [3 1 12 10]
server: feed (first) -> s2 [2 13 11 9]
The first reader's second page continues the order they started with, 3 1 12 10, although post 2 is now very popular. The new session gets a different ranking, snapshot s2, which puts post 2 first. Neither reader sees a post twice.
The price is that a snapshot is state the server must keep and must eventually throw away. That has a consequence the client must handle.
When the ranking expires
A snapshot cannot live forever. When one is gone, the server refuses its cursor; the lab's code for that is cursor_expired. The reader has been on the page for an hour, comes back to the tab and scrolls. What should the client do?
Not discard the list. The reader has seen those posts. The recovery in the lab is: cut a fresh ranking, keep what is already shown, continue from the fresh ranking's second page onward and skip any post whose id is already in the list. The reshuffle shows up as the order of the next pages, not as repeats.
Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/social-feed, the expiry scenario):
=== the ranking expired while the reader was away (a page request is refused)
page 1 : 11 9 7 5
next page : status error, code cursor_expired
after recovering : 11 9 7 5
one more page : 11 9 7 5 3 1 12 10
status idle, no post twice: true
The refused request moves the store to an error state with a code the UI can recognise. "Refresh feed" calls recover(), which keeps the four posts and continues on the new ranking. Here the new ranking happens to start with the same four posts, so nothing visibly changes; if it had not, the posts the reader had not yet seen would have been appended, and the ones they had seen would have been dropped by id. A refused cursor is an expected event, with its own message ("This feed has changed since you opened it") and a single action, not a generic error.
Freshness: a count, not an insert
A feed that updates while you read it has to decide where new posts go. There are three honest options.
Figure 3. Where do new posts go?
at the very top?"} A -->|"yes"| B["Insert directly
nothing moves under them"] A -->|"no, scrolled down"| C["Show a banner:
N new posts"] C --> D["Insert on request,
keep their place"] D --> E{"Is the feed ranked?"} E -->|"yes"| F["The count can exceed what
appears: the ranking decides"] E -->|"no, newest first"| G["Count equals inserted"]
How to read this: the first question is about the reader, not the data. Content inserted above someone who is looking at something moves what they are looking at; that is a layout shift the reader did not ask for.
The web.dev guide to Cumulative Layout Shift says that dynamically injected content closer to the top of the viewport usually causes greater layout shifts than content lower down. A banner that the reader taps keeps the shift deliberate.
How does the client know there is something new? It asks a cheap question on a timer or when the tab comes back: "how many posts are newer than the ranking I hold?". In the lab that is fetchHead, which takes the snapshot name and returns a count, not the posts. The lesson on polling, server-sent events and WebSockets (transports) compares ways to deliver that signal; for a feed that is read for minutes at a time, a slow poll is often enough, and a push channel is an optimisation you add after measuring. A failed head check is ignored: the next one will try again, and an error banner for "could not check for new posts" is worse than silence.
Illustration 2: the realistic example, the banner
Two close-friend posts arrive while the reader is looking at four posts. The head check reports two newer posts; the list is unchanged. The reader taps the banner, the client fetches a fresh first page and puts the posts it does not already have above the list.
Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/social-feed, the freshness scenario):
=== freshness: count the new posts, insert them only when the reader asks
list : 11 9 7 5
after a head check : list unchanged, banner says 2 new posts
after tapping the banner: 14 13 11 9 7 5
2 posts went above the old first one, banner now 0
a second head check : banner 0
Two details are worth noticing. The store records how many posts it put above the list (lastPrepended: 2), because the view must then move the scroll position by the height of those posts, exactly the correction the previous case study works out for a page that returns above the reader. And the head check after the insert asks about the new ranking's name, which is why the banner goes back to zero instead of counting the same two posts again.
Illustration 3: the edge case, the count says more than the list shows
In a ranked feed the banner counts posts that are newer, but the server's new first page shows only what ranks high enough. A low-scoring new post is newer and does not appear.
The lab has a test for exactly that. A new post from an author with no bonus (id 13) and one from a close friend (id 14) are published. The head check says 2. After the banner is tapped, only post 14 is on top, and post 13 is not in the list at all.
This is not a bug in the client; it is a decision to make. If the banner says "2 new posts" and one appears, the reader may feel something is missing. The options are to count only what a fresh page would show (the server can compute it), to word the banner so it does not promise ("New posts"), or to make the first page of a fresh ranking always include the newest few posts. Which to choose is a product question; what the client must do is not assume the two numbers match.
Likes: a state, not a toggle
A like is the most frequent write on the page, and it must feel instant. The design has three parts.
The request sets a state. setLike(postId, liked) says "the reader's like on this post is true". The server applies it only if it changes something, and answers with the current like count and the reader's like state. Repeating the request changes nothing, which is what "idempotent" means in HTTP: RFC 9110 defines an idempotent method as one where "the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request", and lists PUT and DELETE among them. A "flip it" request is not like that, and a retried flip undoes the like.
The screen shows the reader's last tap on top of the server's last answer. The store keeps confirmed (what the server said) and, per post, an intent (what the reader last asked for) and whether a request is on the wire. The like button shows intent.desired if there is one, else confirmed. The count is the server's count adjusted by the difference between the two. The general model, with confirmed data plus a pending list, is in the optimistic updates lesson (optimistic updates) and its lab, optimistic-update; this lab specialises it to one boolean per post.
One request on the wire per post, and the last tap wins. A reader who taps like, unlike, like in a second creates three intents. Sending three requests invites a race: the answers can arrive in any order. The store sends one. While it is in flight, further taps only change desired. When the answer comes back, if it agrees with desired the intent is finished; if it does not, one more request is sent with the latest value.
Figure 4. The life of one like
How to read this: there is never more than one request per post in the Sending state. A tap never starts a second request; it only changes what the next one will say.
Illustration 4: likes in the lab
The lab's server holds responses until the script releases them, so the order is chosen by the script. The reader taps three times quickly, the server answers once, then a later tap fails.
Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/social-feed, the likes scenario):
=== likes: one request on the wire per post, the last tap wins
post #11 at start : not liked, 0 likes
tap 1 (request sent) : liked, 1 likes
tap 2 (no new request) : not liked, 0 likes
tap 3 (no new request) : liked, 1 likes
requests on the wire : like 11=true
server answered : liked, 1 likes, requests left 0
server: like #11 set to true -> 1 likes
a like that fails is rolled back:
tap 4, optimistic : not liked, 0 likes
after the failure : liked, 1 likes, failures [11]
The screen answers each tap at once. Three taps produce one request, like 11=true, and the server logs exactly one write. The fourth tap is shown as "not liked" immediately; when its request fails the screen returns to the confirmed "liked, 1 like" and the post is recorded as a failure so the card can say "Could not save your like. It was undone." That message matters: a silent revert looks like a bug.
The test suite also covers the case this output cannot show in one line: the reader taps like then unlike while the first request is in flight. When the answer says "liked", the screen must stay on "not liked" (the reader's last tap), and one more request, like 11=false, must follow. Without that rule the like button flickers back to the older answer.
React 19 has a hook for the simplest form of this, useOptimistic: its optimistic state equals the real value unless an action is pending, and when the action finishes, or throws, React renders with whatever the real value is. That is the same shape as "intent over confirmed", for a single action at a time. The lab keeps its own reducer because several posts can have different intents at once and because the rules (single flight, last tap wins) need to be tested without React.
Count arithmetic, and other people's likes
If other people like the post while the request is in flight, the server's answer carries a count that is higher than the reader's screen expected. The reducer replaces the confirmed post with the answer and then applies the intent on top, so the screen shows the server's number with the reader's own tap included. The lab has a test for it (five other likes, then the reader's: six). Do not keep a local counter that only ever goes up by one.
Impressions: report once, in batches
The ranking model usually wants to know which posts a reader actually saw. The client records a post the first time it becomes visible, using an observer, and sends the new ids in one request. In the lab, visible(id) records the id once and flushSeen() sends everything not yet sent, then sends nothing more until something new becomes visible.
Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/social-feed, the last scenario):
=== impressions are reported once, in one batch
server: seen [11 9 7]
server: seen [5]
The first batch holds three posts even though the first was reported visible twice; the second flush found nothing new and sent nothing; the later fourth post went out alone. Two decisions are left to the product. The batches are best effort: a lost batch is not retried in the lab, because a missing impression is cheaper than a retry storm. And the last batch before the reader leaves needs a reliable exit. MDN's page for Document visibilitychange says that the transition to hidden "is the last event that's reliably observable by the page", and the navigator.sendBeacon() page describes a method that sends a small amount of data asynchronously "without delaying unload or the next navigation", limited to 64 KiB of queued data. The lab does not use either; its flushSeen is an ordinary request. In a real page you would call the flush from visibilitychange and send the batch with sendBeacon.
Accessibility of a social feed
The feed pattern from the previous case study applies unchanged: a feed of article elements with aria-posinset, aria-setsize (-1 when the total is unknown) and aria-busy. Three things are particular to this design.
- The like button is a toggle button.
aria-pressedturns abuttoninto a toggle, with the valuestrueandfalse. MDN's guidance is not to change the label when the state changes: the label stays "Like" andaria-pressedcarries the state. The lab's button does that. - The banner is a button, and it must not take focus. The text "2 new posts" is a button the reader can reach and press. If you also announce it, a
statusrole is a live region with an implicitaria-liveofpolite, and it should not be given focus when its content updates. Moving focus to a banner would pull the reader out of whatever they were reading. - A failed like is announced. The lab shows an
alertin the card: the reader must learn that the like was undone.
Trade-offs
| Choice | Good | Bad | Choose it when |
|---|---|---|---|
| Frozen ranking (snapshot cursor) | No repeats or gaps while paging | The server keeps state; cursors expire | The order is not a stable key |
| Re-rank on every page | Stateless server | Repeats and gaps for the reader | Never for a long scroll |
| Banner (count, insert on tap) | The reader's place is stable | One more tap; count can exceed what appears | The reader is scrolled down |
| Insert new posts at once | Always current | Layout shifts the reader did not ask for | The reader is at the very top |
| Tap sets a state, one request per post | No race between taps; safe to retry | A small state machine per post | Always for like-style toggles |
| Optimistic like | Feels instant | A revert and a message to design | The write rarely fails |
| Batched impressions | Few requests | A batch can be lost | The data is best effort |
Build it
The lab for this lesson is examples/frontend/labs/social-feed. It reuses ideas, not code, from two existing labs: pagination-infinite-scroll (cursor paging, races and the sentinel, which are tested there and not repeated) and optimistic-update (the general confirmed-plus-pending model). Its parts:
src/fakeSocialServer.ts: a fake server with a toy ranking, snapshots that can expire, an idempotent like and responses released by the caller.src/feed.ts:socialReducer(pure) andSocialController(the store that sends requests).src/SocialFeed.tsx: a thin component: afeed, toggle-button likes, the banner, an error with a refresh.src/demo.ts: five scenarios, whose output is shown above.
cd examples/frontend/labs/social-feed
../../node_modules/.bin/vitest run
../../node_modules/.bin/tsc -p tsconfig.json
node src/demo.ts
Verified. The 22 tests in two files passed with Vitest 5.1.0 and the type check passed. They cover: walking a whole frozen ranking once, a different ranking for a new session, one request at a time, recovery from an expired ranking, the banner count and insert, the count exceeding what appears, an ignored failed head check, the likes rules (instant, single flight, last tap wins, the second request, rollback, other people's likes), the reducer's no-op cases and the component's roles and states. The captured demo output is identical to the golden file.
The ranking in the lab is a toy formula; nothing here says how a real ranking behaves. jsdom does no layout, so scroll correction after an insert, the real time a head check takes and how a screen reader announces the banner are not tested.
Break it. In src/feed.ts, in the "likeConfirmed" case, replace the current.desired === action.result.likedByMe ? ... : ... expression with withoutKey(state.intents, action.id), so every confirmation settles the intent. The test "sends a second request when the last tap disagrees with the answer" fails: the reader's last tap is lost. The change was reverted and the tests re-run.
In practice: a community tab in a marketplace app
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A grocery marketplace adds a community tab where merchants and shoppers post photos and short captions, ranked by the server. In the first weeks, shoppers report seeing the same post twice in one scroll, the like button sometimes shows the wrong state for a moment, and a banner that says "12 new posts" leads to only three.
Starting architecture
Figure 5. A feed that re-ranks on every page and toggles likes
How to read this: the three warning boxes are the three problems. Re-ranking on each call repeats posts, a flipping like API cannot be retried safely, and the client expects the banner count to equal what it inserts.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Dedupe by id on the client | Visible repeats | Nothing on the server | Gaps stay; order still jumps |
| Frozen ranking (snapshot cursor) | Repeats and gaps | A server snapshot store and expiry handling | Expired cursors need a UI path |
| Set-state like with one request per post | Races and retry hazards | A small state machine per post | A revert needs a message |
| Insert new posts above at once | Always fresh | Moves what the reader looks at | Layout shifts, lost place |
The decision
| Field | Decision record |
|---|---|
| Context | A ranked feed pages by offset, likes are flipped and new posts are inserted as they arrive. |
| Decision | Cut a snapshot on the first request and read later pages from it, with an expiry code the client handles by refreshing and keeping what was shown. Make likes a set-state request with one request per post. Show new posts as a banner that counts, and word it so it does not promise a number. Keep dedupe by id as a safety net. |
| Consequences, good | No repeats or gaps while scrolling; instant likes that settle on the server's answer; a stable list. |
| Consequences, bad | The server keeps snapshots; the client has an expiry path, a banner and a rollback message to design and test. |
| Revisit when | Snapshots cost more than the repeats did, or a real-time channel replaces the head check. |
Rollout and verification
- Add the snapshot cursor behind the same client interface, and keep the old endpoint working for old clients until their share is small.
- Make the like endpoint idempotent before changing the client. The old client keeps working, and the new one can retry safely.
- Test the cases that hurt: a ranking that changes between pages, an expired cursor, two taps in flight, a like that fails, a banner count larger than the insert.
- Release the banner separately and compare reports of "missing posts" before and after.
- Watch the rate of
cursor_expired. A high rate means the snapshot lifetime is shorter than real reading sessions.
The 2 a.m. failure
After an evening campaign, many shoppers see "This feed has changed since you opened it" on almost every scroll. The snapshot lifetime on the server was shortened to protect memory during the spike, and sessions now outlive it.
First three checks: (1) chart the rate of expired-cursor responses against the snapshot lifetime setting; (2) confirm the client uses the refresh path and keeps the shown posts instead of resetting the list; (3) confirm the refresh asks for a fresh first page, not the stale cursor again. Mitigation: restore the lifetime, and make the client refresh transparently when the reader scrolls, with the message only on a second consecutive failure. Follow-up: a test that expires the snapshot between every two pages.
Architect's notes
- Decide who owns order. The server ranks; the client never re-sorts. The client's job is to hold a stable view of a moving ranking.
- Make expiry a first-class state. A cursor that can expire needs a code, a message and a recovery that keeps what the reader has seen.
- Likes are state, and state is retryable. Design the write so a repeat is harmless, then the client can be simple.
- Never trust two numbers to match. A banner count and an inserted count come from different questions.
- Best-effort data stays best effort. Impressions are batched and lost without drama; likes are not.
Common mistakes
- Re-ranking on every page request, then deduping and calling it fixed.
- Flipping a like instead of setting it, so a retry undoes it.
- One request per tap, so answers race and the button flickers.
- A local counter that only adds one, ignoring the server's count.
- Inserting new posts above a reader who is scrolled down.
- Treating
cursor_expiredas a generic error and clearing the list. - A silent revert when a like fails.
- Changing the like button's label when it is pressed, instead of using
aria-pressed.
Key takeaways
- A ranked list needs a frozen ranking: the first request cuts it, later cursors read from it, and it expires.
- Show freshness as a count; let the reader insert. The count and the inserted posts need not match in a ranked feed.
- A like is "set to this", not "flip". With one request per post and the last tap winning, taps cannot race.
- Show the reader's last tap on top of the server's last answer, and replace both with the server's answer.
- Recover from an expired ranking by refreshing and keeping what the reader has seen.
- Batch best-effort reports and flush them when the page is hidden.
- Use a toggle button with
aria-pressed, and do not take focus for a banner.
Practice exercises
Exercise 1: Starter (30 min). In the demo's first scenario, predict the second page of the first reader if post 5 had been liked 30 times instead of post 2, then check by changing the demo.
Exercise 2: Intermediate (2 hours). Add a visibilitychange listener that calls checkHead when the tab becomes visible and flushSeen when it becomes hidden, and write down which part you could test in jsdom and which you could not.
Exercise 3: Advanced (half day). Combine the two labs: after showNew inserts posts above the list, use lastPrepended and the measured heights from the feed-window lab to compute the scroll correction, and write the test with made-up heights.
Related reading
In this course:
- Pagination: Offset, Cursor and Infinite Scroll: the cursor contract and race rules this feed builds on.
- Optimistic Updates and Rollback: the general confirmed-plus-pending model.
- Polling, Server-Sent Events and WebSockets: ways to learn that new posts exist.
- CLS and Layout Stability: why content inserted above the reader is a layout shift.
- HTTP Semantics: idempotent methods and retries.
- Error, Loading and Empty States: designing the refresh and rollback messages.
Official documentation
- RFC 9110: HTTP Semantics, idempotent methods: the definition of an idempotent method.
- React: useOptimistic: optimistic state while an action is pending, and how it reverts.
- MDN: aria-pressed: toggle buttons and the label caution.
- MDN: status role: a polite live region that should not take focus.
- MDN: Navigator.sendBeacon(): sending small analytics data without delaying navigation.
- web.dev: Optimize Cumulative Layout Shift: content injected near the top of the viewport.