RTK Query: condition-rejected queries decrement pendingRequestCount, so "delayed" invalidation fires early and misses in-flight queries

Author: bradford281Created Sep 25, 2026Updated Sep 25, 2026

Summary

With invalidationBehavior: "delayed" (the default), invalidationByTags tracks in-flight requests with pendingRequestCount: it increments on queryThunk.pending/mutationThunk.pending and decrements on every isQueryEnd action (fulfilled or rejected).

queryThunk is created with dispatchConditionRejection: true, so a query whose condition returns false (an identical query already running or cached, e.g. a second component subscribing to the same endpoint and args) dispatches rejected with meta.condition: true without ever dispatching pending. That rejection still decrements the counter, so each deduplicated subscription pulls pendingRequestCount one below the number of requests really in flight (Math.max(0, …) only hides it once it would go negative).

Once the counter reads 0 while a request is still in flight, a mutation's invalidation is applied immediately instead of being delayed. If the in-flight request is the first fetch for its cache key, it has no provided tags yet, so selectInvalidatedBy does not find it and it is never refetched. It then resolves with data the server read before the mutation committed, and stays stale.

Observed in practice

A list page with a count badge that several components subscribe to: the user types a search (new cache key, request in flight), then bulk-deletes rows. The delete succeeds, the count badges refetch, but the search result arrives afterwards with the deleted rows and is never refetched.

Reproduction (RTK 2.12.0, Jest)

typescript
import { configureStore } from "@reduxjs/toolkit";
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query";

test("list in flight across a mutation is refetched", async () => {
  const held = new Map<string, ((b: unknown) => void)[]>();
  const calls: string[] = [];
  const fetchFn = (input: RequestInfo | URL) => {
    const r = input as Request;
    const u = new URL(r.url);
    const key = `${r.method} ${u.pathname}${u.search}`;
    calls.push(key);
    return new Promise<Response>((resolve) => {
      held.set(key, [...(held.get(key) ?? []), (b) =>
        resolve(new Response(JSON.stringify(b), { headers: { "content-type": "application/json" } }))]);
    });
  };
  const release = (key: string, body: unknown) => held.get(key)!.shift()!(body);
  const flush = () => new Promise((r) => setTimeout(r, 0));

  const api = createApi({
    baseQuery: fetchBaseQuery({ baseUrl: "http://api.test/", fetchFn: fetchFn as typeof fetch }),
    tagTypes: ["Item"],
    endpoints: (b) => ({
      count: b.query<number, void>({ query: () => "count", providesTags: [{ type: "Item", id: "COUNT" }] }),
      list: b.query<string[], string>({ query: (q) => `list?q=${q}`, providesTags: [{ type: "Item", id: "LIST" }] }),
      remove: b.mutation<null, void>({
        query: () => ({ url: "items", method: "DELETE" }),
        invalidatesTags: [{ type: "Item", id: "LIST" }, { type: "Item", id: "COUNT" }],
      }),
    }),
  });
  const store = configureStore({
    reducer: { [api.reducerPath]: api.reducer },
    middleware: (gDM) => gDM().concat(api.middleware),
  });

  store.dispatch(api.endpoints.count.initiate());
  store.dispatch(api.endpoints.count.initiate()); // deduplicated: rejected(condition), no pending
  await flush();
  release("GET /count", 5);
  await flush();

  store.dispatch(api.endpoints.list.initiate("x")); // in flight, no tags yet
  await flush();

  const removal = store.dispatch(api.endpoints.remove.initiate());
  store.dispatch(api.endpoints.count.initiate()); // another deduplicated subscriber
  await flush();
  release("DELETE /items", null);
  await removal;
  await flush();

  release("GET /list?q=x", ["a", "b", "c"]); // stale: read before the delete
  await flush();

  expect(calls.filter((c) => c === "GET /list?q=x")).toHaveLength(2); // fails: 1
});

Removing the two deduplicated count.initiate() calls makes the test pass, which isolates the counter as the cause.

Suggested fix

Do not decrement for condition rejections, since they never incremented:

diff
-    if (isQueryEnd(action)) {
+    if (isQueryEnd(action) && !action.meta.condition) {
       pendingRequestCount = Math.max(0, pendingRequestCount - 1)
     }

We are carrying this as a patch-package patch; the reproduction above passes with it and our full test suite is unaffected. Happy to open a PR with the test if that is useful.