Skip to content

Request Ordering

The Course
•
20 min study

Completion order is not intent order

A person searches for web, then JavaScript. The first request may finish last. Rendering every fulfillment lets an older result replace the requested one. A current-request token protects the commit point: increment a generation number for each load, remember it locally, and update state only when the remembered number is still current.

In const mine = ++generation, the prefix ++ increments generation first and then supplies that new number to mine. The longer equivalent is generation = generation + 1; const mine = generation;. Do not replace it with postfix generation++ in this assignment: that would capture the old number.

A stale failure must also be ignored, not only stale success. Otherwise the UI can show an old error on top of a newer success. An unconditional finally that clears loading can cause the same defect. Every asynchronous completion path that changes state must check ownership.

Cancellation can ask a previous request to stop, but a transport may ignore it. Keep the generation check even when you use AbortController. A token prevents stale commits; it does not stop network activity or undo a completed server-side effect.

To test ordering without sleeps, make a deferred promise: keep the resolve function and choose when to fulfill it. The example creates two requests, fulfills the newer one first, then the older one. This is a controlled schedule rather than a timing guess. The callback in the Promise constructor runs immediately, so resolve has been assigned when deferred returns.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
async function main() {
  function deferred() {
    let resolve;
    const promise = new Promise(done => {
      resolve = done;
    });

    return { promise, resolve };
  }

  let generation = 0;
  let visible = "";

  async function load(promise) {
    const mine = ++generation;
    const value = await promise;

    if (mine === generation) {
      visible = value;
    }
  }

  const old = deferred();
  const recent = deferred();
  const a = load(old.promise);
  const b = load(recent.promise);

  recent.resolve("new");
  await b;
  old.resolve("old");
  await a;
  console.log(visible);
}

main();
Check your prediction
Text
new

The older completion is observed but cannot commit. Remove the comparison to see which output would reveal the defect.

Protect failure paths as well as successful results

A stale completion can be a rejection, not just a successful response. If an old error replaces a newer success, the interface is still wrong. The request identity must guard every asynchronous path that changes visible state.

Allocate the identity before starting or awaiting the dependency. Keep it captured for that attempt. Cancellation can reduce wasted work, but request ownership remains necessary when a dependency ignores a signal or finishes before cancellation takes effect.

Protect failure paths as well as successful results: trace JavaScript
async function main() {
  let generation = 0;
  let visible = "";
  let rejectOld;
  const old = new Promise((resolve, reject) => {
    rejectOld = reject;
  });

  async function load(work) {
    const mine = ++generation;

    try {
      const value = await work;

      if (mine === generation) {
        visible = value;
      }
    } catch {
      if (mine === generation) {
        visible = "error";
      }
    }
  }

  const first = load(old);

  await load(Promise.resolve("new"));
  rejectOld(new Error("old failure"));
  await first;
  console.log(visible);
}

main();
Check your prediction
Text
new

The old rejection has a handler attached before it is released. Its captured identity is stale, so it cannot replace new with error. No timer delay is needed to create this schedule.

Protect failure paths as well as successful results: contrast JavaScript
let current = 2;
let state = "loading new";

function finish(request, value) {
  if (request === current) {
    state = value;
  }
}

finish(1, "old");
console.log(state);
finish(2, "new");
console.log(state);
Check your prediction
Text
loading new
new

A completion must also be ignored while the newer request is still loading. Testing only after the newer success can miss a guard that happens to rely on a ready-state check instead of request identity.

Try the rule on new inputs

Test old success and old failure both before and after the new completion. Remove one identity comparison and identify which schedule exposes it. Keep loading ownership separate from transport cancellation.

Debug a plausible mistake

Exercise

Repair a stale completion

Keep the latest request result when completions arrive in reverse order. Print New. Then finish requests in ordinary order and ensure the same rule works. The steps are deterministic, with no guessed timer delays.

Predict the supplied program's actual behavior first. It runs without an error, but breaks the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.

Debugging workspace JavaScript
let latest = 0;
let title = "";

function start() {
  latest += 1;
  return latest;
}

function finish(request, value) {
  title = value;
}

const oldRequest = start();
const newRequest = start();
finish(newRequest, "New");
finish(oldRequest, "Old");

console.log(title);
Hint 1: the idea

A result may be valid data for a request that no longer owns the current view.

Hint 2: a first step

Only update the visible result when the completion belongs to the latest request.

Show one solution
JavaScript
let latest = 0;
let title = "";

function start() {
  latest += 1;
  return latest;
}

function finish(request, value) {
  if (request === latest) {
    title = value;
  }
}

const oldRequest = start();
const newRequest = start();
finish(newRequest, "New");
finish(oldRequest, "Old");

console.log(title);
Text
New

The original printed Old: finish accepted every completion, so whichever arrived last won, even though the newer request had already finished. Comparing request === latest makes ownership, not arrival order, decide what is shown. Finishing in the ordinary order (old, then new) still prints New, so the guard does not depend on any particular timing.

Trace the contract before building

A successful response can belong to an obsolete request. Assign an identity when the request starts, then check it before the completion changes current state. Validation of payload contents cannot answer whether that request still owns the screen.

Use a deterministic schedule where the new request finishes before the old one, then reverse it. Both should follow the same latest-started policy. Abort can reduce wasted work, but it is not a replacement for this commit guard when a collaborator ignores its signal. Keep relevance and cancellation as separate guarantees in the tests.

Build it yourself

Exercise

Request Ordering: practice

Write createGate(), with next() returning an increasing token and isCurrent(token) testing ownership. Print whether the first and second tokens are current after two starts.

Your working space JavaScript
// The generation belongs to one gate instance.
Hint 1: the idea

This is a closure with one changing number.

Hint 2: a first step

Increment in next, compare in isCurrent.

Show one solution
JavaScript
function createGate() {
  let generation = 0;

  return {
    next() {
      generation += 1;
      return generation;
    },
    isCurrent(token) {
      return token === generation;
    }
  };
}

const gate = createGate();
const first = gate.next();
const second = gate.next();

console.log(gate.isCurrent(first));
console.log(gate.isCurrent(second));
Text
false
true

Starting a third request invalidates both earlier tokens. Decide how cancel should invalidate the current token even when no replacement load starts.

Test a changed requirement

Starting a third request invalidates both earlier tokens. Decide how cancel should invalidate the current token even when no replacement load starts.

Explain before moving on

Which three completion paths need an ownership check? What does a token not cancel?

Was this article helpful?

Your response is saved on this device.