A like should never make you wait.
The heart lights up the instant you tap, even with no signal. The like is saved on the device and sent to the server by itself once the connection comes back.
Under the Thames on the Elizabeth line, zero bars. Apps that still work in tunnels: thank you.
Under the Thames on the Elizabeth line, zero bars. Apps that still work in tunnels: thank you.
A's outbox localStorage["likes.outbox"]
Server database mock
Leave this page?
Your like hasn't been saved yet.
This is B asking. A never needs to: its like is already stored on the device.
What the network sees, and what Delaney sees.
B is honest. A is honest too, because it keeps its promise.
Immediate Intent argues that an optimistic update "lies to you as long as that result isn't actually persisted", and that even a lost like is not harmless. Example B is that approach, built as fairly as we can: a grey beating heart, "Still trying…", retries until it gets through, and you can cancel by tapping again. It is a good answer to optimistic UI without a queue. A durable queue changes the question.
Where it's right
- Optimistic UI with no queue is a lie. X lights the heart offline, then drops the like.
- A like that's shown, then quietly retracted, costs trust.
- Anything the server might refuse (payments, bookings, medication) should show intent, not a result.
Where a queue changes the answer
- "Not persisted." It is: on the device, before the heart lights. Only delivery is outstanding, and that happens the next time the page runs.
- "Then retracted." Almost never. A like is only refused if the post has gone, so failures are temporary and the queue retries instead of rolling back.
- "Leave this page?" B has to ask, because its like lives only in memory. A never asks: leaving loses nothing.
- "A queue doesn't sync across devices." True for a few seconds. For a like, that's a fair price for never making anyone wait.
The queue is one key in localStorage.
Each tap overwrites a single entry per post under localStorage["likes.outbox"] (the live panel in the demo shows it). A small sync loop sends whatever is there and deletes it once the server accepts it.
const KEY = `likes.outbox.${userId}`; // per account: never send one user's likes as another const DEVICE = (localStorage.device ??= crypto.randomUUID()); const read = () => JSON.parse(localStorage.getItem(KEY) ?? '{}'); const write = (outbox) => localStorage.setItem(KEY, JSON.stringify(outbox)); export function toggleLike(postId, liked) { const outbox = read(); // re-read: another tab may have written const rev = Number(localStorage.rev ?? 0) + 1; // rises on every tap from this device localStorage.rev = rev; outbox[postId] = { liked, rev, device: DEVICE }; // final state only: replaces earlier taps write(outbox); // stored before this function returns renderHeart(postId, liked); // instant, never waits schedule(300); // fast taps collapse into one request } let timer, sending = false, retryMs = 2000; const schedule = (ms) => { clearTimeout(timer); timer = setTimeout(flush, ms); }; export async function flush() { if (sending || navigator.onLine === false) return; // one sender at a time; "online" wakes us sending = true; try { let pending; while ((pending = Object.entries(read())).length) { // until empty, so taps made meanwhile go too for (const [postId, entry] of pending) { const res = await fetch(`/api/posts/${postId}/like`, { method: 'PUT', // set, never toggle: safe to repeat headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(entry), keepalive: true, // can finish even if the page closes }); if (res.status === 401) return signInAgain(); // keep it queued until signed in if (res.status === 429 || res.status >= 500) throw new Error(res.status); // temporary // 2xx: delivered. Other 4xx (post deleted, author blocked you): final, so drop it. const now = read(); if (now[postId]?.rev === entry.rev) { delete now[postId]; write(now); } } } retryMs = 2000; } catch { schedule(retryMs); // one timer only: 2s, 4s, 8s ... 30s retryMs = Math.min(retryMs * 2, 30000); } finally { sending = false; } } // Every way the page can wake up is a chance to sync. addEventListener('online', flush); addEventListener('focus', flush); document.addEventListener('visibilitychange', () => document.hidden || flush()); flush(); // on load: send anything left over from last time
Why localStorage
setItem is synchronous: the like is in the browser's storage before the click handler returns, so closing or reloading the tab can't lose it. The data is tiny: one small object per post.
When to use IndexedDB
If the queue can grow large, you need a write you can await until it is durable, or a service worker should send it with Background Sync after the tab has closed. Service workers can't read localStorage.
What the server must do
Treat the PUT as "set liked to X". Keep the last rev per device and ignore older ones, so a late duplicate can't undo a newer tap. Across devices, the latest to arrive wins, which is fine for a like.
Be optimistic about small things. Wait for big ones.
Show it instantly
Cheap, reversible, never refused.
Wait for the server
Costly, irreversible, or might be refused.