Skip to content
Source
Sign inSign up
TanStack/query

feat(query-core)!: gc at latest removal time #12680

Openbenjavicente(GitHub profile, opens in a new tab)wants to merge 1 commit intoquery-v6 fromrefs/pull/12680/headopened View on GitHub

🎯 Changes

Schedules garbage collection at the latest removal time any user of a query or mutation has been promised, instead of after the largest or latest gcTime. See this discussion.

TimeEventBefore (largest gcTime)After (latest removal time)
0:00A (gcTime 5 min) becomes inactive5:00 (target, not scheduled)5:00 (target, not scheduled)
1:00B (gcTime 1 min) becomes inactive6:00 (scheduled)5:00 (scheduled)

⚠️ Breaking: query.gcTime and mutation.gcTime are removed.

File order in Github is incredibly annoying for this change: Removable should be reviewed first, then the 2 observers, then query and mutation, and finally tests.

🤖 Agents summary and details: implementation, breaking changes, verification

Changes

Removable now remembers when an entry may be garbage collected, instead of the largest gcTime it has seen. When several gcTime values apply to one entry, the latest removal time wins, instead of the largest gcTime.

  • Removable
    • Removes the public gcTime field and updateGcTime.
    • Adds updateGcTimestamp(gcTime). It applies the default gcTime (5 minutes on the client, Infinity on the server) and keeps max(previous, performance.now() + gcTime) in a private #gcAt. A NaN is ignored, so it can't make #gcAt NaN for good.
    • scheduleGc(gcTime) now takes the gcTime: it records it, then sets its timeout for the time left until #gcAt, clamped at 0. Taking the value means a removal time is always recorded before scheduling. As before, nothing is scheduled when that time is Infinity.
    • Removal times use the monotonic performance.now() clock, not Date.now(). Changing the system clock doesn't move them, as with the plain timers used before.
  • Query and Mutation
    • setOptions no longer touches garbage collection.
    • removeObserver(observer, gcTime) records the gcTime the observer passes, every time an observer leaves. The observer passes the one from its defaulted options. The argument is required: with a default parameter, passing an undefined gcTime would silently fall back to the observer's current options. On observer removal, Query schedules gc only when no observers are left. Mutation schedules it on every removal, as before; in practice a mutation only ever has the one observer that created it.
    • When no observer is leaving, the entry's own options are used. The constructors and the pending mutation reschedule use the current options.gcTime. The end of a query fetch uses the gcTime from the options captured when that fetch started, because an observer may replace the query's options while it runs.
  • QueryObserver and MutationObserver
    • When an observer switches to another query key or mutation key, it passes the gcTime from its previous options to removeObserver. The observer replaces its options before it leaves the old entry, so without this the old entry would get the new key's gcTime. MutationObserver does this through a private #reset(gcTime), which the public reset() also uses with its current gcTime.

Motivation

Discussion: https://github.com/TanStack/query/discussions/12669#discussioncomment-19811344

With "largest gcTime wins", one long gcTime sticks to the entry forever, even after every observer that asked for it is gone. With "latest gcTime wins", a later short gcTime could cut short a longer one that was already promised. Taking the latest removal time avoids both problems: an entry is never collected before any time it was promised, and an old long finite gcTime does not stay around once that time has passed. Infinity still keeps an entry forever, as before.

⚠️ Breaking changes

  • query.gcTime and mutation.gcTime are removed. They were public fields on the exported Query and Mutation classes (through Removable). Read query.options.gcTime or mutation.options.gcTime instead. Note that those are the entry's own options, not the effective time. Nothing in packages/*/src reads the field; earlier tests did, and users or devtools-like tooling may.
  • Query.removeObserver and Mutation.removeObserver now require the leaving observer's gcTime as a second argument. Both are marked @internal.
  • The effective gc time changes when several gcTime values apply. Before, the largest gcTime ever passed to setOptions was used. Now the latest removal time recorded wins:
    • A long gcTime from an earlier observer only counts while its removal time is still in the future.
    • A shorter gcTime that comes later can't bring the removal earlier.
  • A removal time recorded earlier still counts after the entry is reused, until that time has passed. Subscribing again only clears the timer; it doesn't reset the removal time. For example: A unsubscribes with a gcTime of 5 min (removal at 5:00), then subscribes again with a gcTime of 1 min and unsubscribes at 1:00. The removal stays at 5:00. Before this change it was 6:00, because 5 min was still the largest gcTime. Resetting on subscribe would give 2:00, which would let a short mount pull an earlier promise forward. scheduleGc(gcTime) records its gcTime before scheduling, so removal is never earlier than now plus the current gcTime.
  • The observer's gcTime at the moment it unsubscribes is what's recorded. A gcTime passed to queryClient.query() counts for the removal time recorded when that fetch settles. It no longer raises the time applied when an observer unsubscribes later. The same goes for mutations: if a MutationObserver's gcTime changes while its mutation is idle, the new value is what's recorded when it leaves. Before, an idle mutation kept the gcTime from its last options. This is the only case where removal can now happen later than before.

Open questions

  • A NaN gcTime adds no removal time. The entry is then removed at the latest valid removal time recorded before, or right away if there is none or it has passed. Before, a NaN gcTime meant no gc was scheduled until a later valid gcTime replaced it. Both are invalid input.
  • Should a getter, e.g. gcAt, be exposed for devtools in place of the removed gcTime?
  • The docs need a migration note in the v6 migration guide. The generated reference pages for Query/Mutation still list gcTime. CONTRIBUTING says not to run generate-docs in a PR, because the docs re-sync after merge. On query-v6 it also rewrites about 1400 unrelated files.

Pitfalls for alternative implementations

Found while building and reviewing this change. They're worth checking in any other way of storing gc state:

  • Observers replace their options before they leave the old entry. QueryObserver.setOptions sets this.options before #updateQuery() detaches it from the previous query, and MutationObserver.setOptions does the same before it resets. Reading observer.options.gcTime inside removeObserver gives the old entry the new key's gcTime, so the previous gcTime has to be passed in.
  • Don't use a default parameter for that gcTime. An observer whose previous options had no gcTime passes undefined, which triggers the default, and that reads the new options again.
  • A fetch must record the gcTime it started with. An observer can call query.setOptions while a fetch is in flight, so this.options at settle time may belong to someone else. Use the options captured for the fetch.
  • Every schedule needs a recorded removal time first. #gcAt starts at 0, so scheduling without recording removes the entry right away. A pending mutation that reschedules without recording would loop on 0 ms timers.
  • An observer that leaves while others stay must still record its time, even though nothing is scheduled yet. Otherwise its longer gcTime is lost when a shorter one leaves last.
  • Use a monotonic clock. With Date.now(), a system clock change moves removal times; a large backwards jump even overflowed setTimeout (over 2³¹ ms) and fired after about 1 ms. Plain timers never had this, because they only count elapsed time. performance.now() is available in browsers, Node, React Native and Workers.
  • NaN sticks through Math.max, so it has to be filtered before it reaches the stored time. Returning early from the scheduler on NaN instead also cancels a removal that was already scheduled.
  • Infinity sticks forever. That's the same as before, and it is what makes the server default work.
  • Normal mutation flows use one observer: the MutationObserver that built the mutation with mutate(). Removing it leaves no observers.
  • performance.now() gives fractional delays, which timers truncate, so removal can happen up to 1 ms before the promised time. This is accepted.
  • Tests must fake performance. Vitest's default fake timers do. A toFake list that only fakes timers and Date gives misleading timelines.

✅ Verification

  • New test in query.test.tsx: observer A (gcTime 5 min) unsubscribes at 0:30, and observer B (gcTime 1 min) unsubscribes at 1:30. The query is still cached at 2:30 and at 5:29.999, and it is removed at 5:30. A unsubscribes 30 seconds in, so the test also catches A's removal time not being recorded; the query was created at 0:00 with A's gcTime. The table shows the same case shifted to start at 0:00:

    TimeEventHighest winsLast winsLatest deadline wins
    0:00A becomes inactive5:005:005:00
    1:00B becomes inactive6:002:005:00

    With the production changes reverted (query-v6 as is), this test fails at the final assertion, because the query is still cached at 5:30 (it is removed at 6:30). With the changes, it passes.

  • Key-switch tests, one in query.test.tsx and one in mutationObserver.test.tsx. An observer with gcTime 1000 switches to another key with gcTime: Infinity, and the old entry must be removed after 1000 ms. Both pass on query-v6, where the old entry never saw the new options. They fail on the first version of this change, where the old entry got the new key's Infinity, and pass with the observer fix.

  • Fetch test in query.test.tsx: an existing query with gcTime 10 is fetched with queryClient.query({ gcTime: 1000 }), and an observer with gcTime 10 subscribes while the fetch runs. The query must be kept until 1000 ms after the fetch settles. It fails when the end of the fetch reads the query's current options, and passes when it uses the options captured for the fetch.

  • Other new tests in query.test.tsx and mutationObserver.test.tsx:

    • a removal time recorded at the end of a queryClient.query() fetch stays when a later fetch records an earlier one. This fails on query-v6, where the largest gcTime restarts from the second fetch.
    • a pending mutation survives repeated gc checks and is removed at the next check after it settles: it settles at 45 ms and is collected at 50 ms with gcTime: 10. This passes on query-v6 too.
  • Updated tests:

    • removable.test.tsx now covers updateGcTimestamp and scheduleGc(gcTime):
      • the client and server defaults;
      • keeping a later removal time recorded before, and using a later one recorded after;
      • a system clock change not moving the removal time;
      • a NaN gcTime being ignored, and not discarding an earlier removal time.
    • query.test.tsx: the server test now checks that the query is still cached after 24h, instead of reading query.gcTime.
    • query.test-d.tsx / mutation.test-d.tsx: gcTime is dropped from the public member lists, along with the mutation.gcTime type test. The removeObserver parameter types now include the gcTime argument.
  • query-core: vitest run gives 44 files and 1626 tests passed, with no type errors. test:types (TS 5.7 to 7.1), test:oxlint, oxfmt --check and git diff --check are clean.

  • react-query passed 38 files and 654 tests, and preact-query passed 35 files and 570 tests, both including type tests.

  • Three review passes, by Claude Opus 5.5 and GPT-6.1 Sol. Their findings are fixed, or listed under "Pitfalls for alternative implementations" above.

  • Not run: the full pnpm run test:pr, and the other adapters.

  • Size limit comparison: pending (needs Preview CI on the PR).

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested code changes locally with pnpm run test:pr, or these tests do not apply to this pull request (there are red checks in devtools that are unrelated)
  • I have followed the AI contribution policy and fully understand the code in this pull request, including any code generated with AI assistance.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).
    1. 🦋 Changeset detected

      Latest commit: d87893435b94efdd470b8fc7b5dcfd74ebb72d9b

      The changes in this PR will be included in the next version bump.

      This PR includes changesets to release 25 packages
      NameType
      @tanstack/query-coreMajor
      @tanstack/angular-queryMajor
      @tanstack/lit-queryPatch
      @tanstack/preact-queryMajor
      @tanstack/query-async-storage-persisterMajor
      @tanstack/query-broadcast-client-experimentalMajor
      @tanstack/query-devtoolsMajor
      @tanstack/query-persist-client-coreMajor
      @tanstack/react-queryMajor
      @tanstack/solid-queryMajor
      @tanstack/svelte-queryPatch
      @tanstack/vue-queryMajor
      @tanstack/angular-query-devtoolsMajor
      @tanstack/angular-query-persist-clientMajor
      @tanstack/preact-query-devtoolsMajor
      @tanstack/preact-query-persist-clientMajor
      @tanstack/react-query-devtoolsMajor
      @tanstack/solid-query-devtoolsMajor
      @tanstack/svelte-query-devtoolsPatch
      @tanstack/vue-query-devtoolsPatch
      @tanstack/react-query-persist-clientMajor
      @tanstack/solid-query-persist-clientMajor
      @tanstack/svelte-query-persist-clientPatch
      @tanstack/react-query-next-experimentalMajor
      @tanstack/eslint-plugin-queryMajor

      Not sure what this means? Click here to learn what changesets are.

      Click here if you're a maintainer who wants to add another changeset to this PR

    2. Important

      Review skipped

      Auto reviews are disabled on base/target branches other than the default branch.

      Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      Run configuration

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • Trigger review
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      Share

    3. tanstack-source added labelsfeature

    4. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit d87893435b94efdd470b8fc7b5dcfd74ebb72d9b

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded8m 31sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded35sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-11-22 21:41:50 UTC

    5. More templates

      @tanstack/angular-query

      npm i https://pkg.pr.new/@tanstack/angular-query@12680

      @tanstack/angular-query-devtools

      npm i https://pkg.pr.new/@tanstack/angular-query-devtools@12680

      @tanstack/angular-query-persist-client

      npm i https://pkg.pr.new/@tanstack/angular-query-persist-client@12680

      @tanstack/eslint-plugin-query

      npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@12680

      @tanstack/lit-query

      npm i https://pkg.pr.new/@tanstack/lit-query@12680

      @tanstack/preact-query

      npm i https://pkg.pr.new/@tanstack/preact-query@12680

      @tanstack/preact-query-devtools

      npm i https://pkg.pr.new/@tanstack/preact-query-devtools@12680

      @tanstack/preact-query-persist-client

      npm i https://pkg.pr.new/@tanstack/preact-query-persist-client@12680

      @tanstack/query-async-storage-persister

      npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@12680

      @tanstack/query-broadcast-client-experimental

      npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@12680

      @tanstack/query-core

      npm i https://pkg.pr.new/@tanstack/query-core@12680

      @tanstack/query-devtools

      npm i https://pkg.pr.new/@tanstack/query-devtools@12680

      @tanstack/query-persist-client-core

      npm i https://pkg.pr.new/@tanstack/query-persist-client-core@12680

      @tanstack/react-query

      npm i https://pkg.pr.new/@tanstack/react-query@12680

      @tanstack/react-query-devtools

      npm i https://pkg.pr.new/@tanstack/react-query-devtools@12680

      @tanstack/react-query-next-experimental

      npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@12680

      @tanstack/react-query-persist-client

      npm i https://pkg.pr.new/@tanstack/react-query-persist-client@12680

      @tanstack/solid-query

      npm i https://pkg.pr.new/@tanstack/solid-query@12680

      @tanstack/solid-query-devtools

      npm i https://pkg.pr.new/@tanstack/solid-query-devtools@12680

      @tanstack/solid-query-persist-client

      npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@12680

      @tanstack/svelte-query

      npm i https://pkg.pr.new/@tanstack/svelte-query@12680

      @tanstack/svelte-query-devtools

      npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@12680

      @tanstack/svelte-query-persist-client

      npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@12680

      @tanstack/vue-query

      npm i https://pkg.pr.new/@tanstack/vue-query@12680

      @tanstack/vue-query-devtools

      npm i https://pkg.pr.new/@tanstack/vue-query-devtools@12680

      commit: d878934

Sign in to join this conversation.