For developers: optimistic UI, done properly

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.

1Tap the pink-ringed hearts in A and B
2Change Throttling to 3G or Offline, then tap again
3Like A while Offline, press Reopen tab, then turn throttling off
x.example/delaneystardust/status/1
AOptimistic, with an outboxTap the heart ↓
Delaney Stardust@delaneystardust · 2h

Under the Thames on the Elizabeth line, zero bars. Apps that still work in tunnels: thank you.

48 212 18K
BImmediate intent: waits for the serverTap the heart ↓
Delaney Stardust@delaneystardust · 2h

Under the Thames on the Elizabeth line, zero bars. Apps that still work in tunnels: thank you.

48 212 18K
ElementsConsoleNetworkApplication
Preserve logFetch/XHR
Try a slower connection →
NameStatusInitiatorPayloadTime

A's outbox localStorage["likes.outbox"]


          

Server database mock


        
The tunnel, frame by frame

What the network sees, and what Delaney sees.

⚠NetworkApplication
NameStatusInitiatorPayloadTime
♥Tap. Heart turns pink. Saved to outbox.08:14:02
like(failed) net::ERR_INTERNET_DISCONNECTEDA · outbox.js{"liked":true,"rev":1}0.6 s
like(failed) net::ERR_INTERNET_DISCONNECTEDA · outbox.js{"liked":true,"rev":1}0.5 s
⏸Offline. Retries pause. The like waits in the outbox.08:14:10
●Signal back: "online" event. Outbox flushes.08:19:47
like200 OKA · outbox.js{"liked":true,"rev":1}143 ms
08:14:02Taps like. Sparkles, pink heart. Done.
08:14:03Scrolls on. No idea anything failed.
08:19:47Out of the tunnel. The like lands. Delaney is none the wiser.
A reply to Immediate Intent

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.
B asks the person to watch the heart. A asks the code to keep a promise.For a like, the code should do the work.
Under the hood

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.

outbox.js
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.

The honest limits. The queue survives closing the tab, reloads, a crashed page and long spells offline. It is lost if the person clears site data, closes a private window before the like is sent, or (in Safari) doesn't use the site for 7 days of browsing, after which Safari deletes the site's storage. A like that the server refuses for good (the post was deleted) is dropped, and the heart should then show the server's answer.

Knowing when not to

Be optimistic about small things. Wait for big ones.

Show it instantly

Cheap, reversible, never refused.

LikeBookmarkFollowMark as readTick a to-do

Wait for the server

Costly, irreversible, or might be refused.

PaymentBooking a seatSending moneyPlacing an order