Skip to the code

A fetch queue with priorities

After its first paint, the tea shop's menu page fetches a lot: the details of the teas on screen, then reviews and photos for further down. Browsers order their own requests, but every fetch() a script makes starts at once and competes for the same bandwidth. Write createFetchQueue(limit), which returns { request(url, options) } and runs at most limit fetches at a time, the important ones first.

request(url, { priority }) takes a priority of "high" or "low" ("low" when it isn't given) and returns a promise that settles as fetch(url, { priority }) does: with its response, or with its error. Pass the priority on: fetch's priority option tells the browser how to order the request among the page's others, as the fetchpriority attribute does on an element.

When fewer than limit fetches are running, start the new one at once, in the same call. Otherwise it waits. Each time a fetch settles, start the next: the high request that has waited longest, or, when no high one is waiting, the low one that has waited longest. A running fetch is never stopped for a newer one. A fetch counts as running until its promise settles, which is when the response's headers arrive or the fetch fails, and a failure frees its place just as a response does. A limit that isn't a whole number of 1 or more is a RangeError.

The JavaScript problem Map with a concurrency limit (map-with-concurrency-limit) runs one list of calls with a limit. This is a queue that keeps taking requests as the page makes them, and orders them by priority.

const queue = createFetchQueue(2);
queue.request("/api/teas/oolong", { priority: "high" }); // starts at once
queue.request("/api/reviews?page=2"); // starts at once: there's still room
queue.request("/api/reviews?page=3"); // waits
queue.request("/api/teas/mint", { priority: "high" }); // waits, but goes before page 3

What the tests check

  1. starts up to limit fetches in the same call, and holds the rest
    const clock = useFakeTimers();
    const network = useFetch(() => ({ body: {}, delay: 100 }));
    const queue = createFetchQueue(2);
    for (const tea of ["green", "mint", "oolong", "black"]) queue.request("/api/teas/" + tea);
    expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/green", "/api/teas/mint"]);
    await clock.tickAsync(99);
    expect(network.calls).toHaveLength(2);
    
  2. starts the next request as soon as one settles
    const clock = useFakeTimers();
    const delays = { "/api/teas/green": 100, "/api/teas/mint": 300 };
    const network = useFetch((url) => ({ body: { url }, delay: delays[url] ?? 50 }));
    const queue = createFetchQueue(2);
    for (const tea of ["green", "mint", "oolong", "black"]) queue.request("/api/teas/" + tea);
    await clock.tickAsync(100);
    expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/green", "/api/teas/mint", "/api/teas/oolong"]);
    await clock.tickAsync(50);
    expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/green", "/api/teas/mint", "/api/teas/oolong", "/api/teas/black"]);
    
  3. a waiting high request goes ahead of every waiting low one, and each priority is first come, first served
    const clock = useFakeTimers();
    const network = useFetch(() => ({ body: {}, delay: 100 }));
    const queue = createFetchQueue(1);
    queue.request("/api/reviews?page=1");
    queue.request("/api/reviews?page=2");
    queue.request("/api/teas/oolong", { priority: "high" });
    queue.request("/api/reviews?page=3", { priority: "low" });
    queue.request("/api/teas/mint", { priority: "high" });
    for (let step = 0; step < 5; step++) await clock.tickAsync(100);
    expect(network.calls.map((call) => call.url)).toEqual([
      "/api/reviews?page=1",
      "/api/teas/oolong",
      "/api/teas/mint",
      "/api/reviews?page=2",
      "/api/reviews?page=3",
    ]);
    
  4. a high request waits for a place like any other: a running fetch is never stopped
    const clock = useFakeTimers();
    const network = useFetch(() => ({ body: {}, delay: 100 }));
    const queue = createFetchQueue(1);
    const reviews = queue.request("/api/reviews?page=2");
    queue.request("/api/teas/oolong", { priority: "high" });
    expect(network.calls.map((call) => call.url)).toEqual(["/api/reviews?page=2"]);
    await clock.tickAsync(100);
    expect((await reviews).ok).toBe(true);
    expect(network.calls.map((call) => call.url)).toEqual(["/api/reviews?page=2", "/api/teas/oolong"]);
    
  5. passes the priority on to fetch, and a request without one is low
    const network = useFetch(() => ({ body: {} }));
    const queue = createFetchQueue(4);
    queue.request("/api/teas/oolong", { priority: "high" });
    queue.request("/api/reviews?page=2", { priority: "low" });
    queue.request("/api/photos/oolong");
    expect(network.calls.map((call) => call.priority)).toEqual(["high", "low", "low"]);
    
  6. each promise settles with its own fetch's response or error, and a failure frees its place
    const clock = useFakeTimers();
    const network = useFetch((url) => {
      if (url === "/api/teas/broken") throw new TypeError("Failed to fetch");
      return { body: { url }, delay: 100 };
    });
    const queue = createFetchQueue(1);
    const broken = queue.request("/api/teas/broken", { priority: "high" });
    const oolong = queue.request("/api/teas/oolong");
    await expect(broken).rejects.toThrow("Failed to fetch");
    await clock.tickAsync(100);
    expect(await (await oolong).json()).toEqual({ url: "/api/teas/oolong" });
    expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/broken", "/api/teas/oolong"]);
    
  7. once the queue has emptied, a new request starts at once again
    const clock = useFakeTimers();
    const network = useFetch(() => ({ body: {}, delay: 100 }));
    const queue = createFetchQueue(1);
    queue.request("/api/teas/green");
    await clock.tickAsync(100);
    queue.request("/api/teas/mint");
    expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/green", "/api/teas/mint"]);
    
  8. the limit must be a whole number of 1 or more
    expect(() => createFetchQueue(0)).toThrow(RangeError);
    expect(() => createFetchQueue(1.5)).toThrow(RangeError);
    expect(() => createFetchQueue("2")).toThrow(RangeError);
    expect(() => createFetchQueue(1)).not.toThrow();
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).