feat(query-core)!: gc at latest removal time #12680
query-v6 fromrefs/pull/12680/head·opened 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.
| Time | Event | Before (largest gcTime) | After (latest removal time) |
|---|---|---|---|
| 0:00 | A (gcTime 5 min) becomes inactive | 5:00 (target, not scheduled) | 5:00 (target, not scheduled) |
| 1:00 | B (gcTime 1 min) becomes inactive | 6: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
gcTimefield andupdateGcTime. - Adds
updateGcTimestamp(gcTime). It applies the defaultgcTime(5 minutes on the client,Infinityon the server) and keepsmax(previous, performance.now() + gcTime)in a private#gcAt. ANaNis ignored, so it can't make#gcAtNaNfor good. scheduleGc(gcTime)now takes thegcTime: 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 isInfinity.- Removal times use the monotonic
performance.now()clock, notDate.now(). Changing the system clock doesn't move them, as with the plain timers used before.
- Removes the public
QueryandMutationsetOptionsno longer touches garbage collection.removeObserver(observer, gcTime)records thegcTimethe 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 anundefinedgcTimewould silently fall back to the observer's current options. On observer removal,Queryschedules gc only when no observers are left.Mutationschedules 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 thegcTimefrom the options captured when that fetch started, because an observer may replace the query's options while it runs.
QueryObserverandMutationObserver- When an observer switches to another query key or mutation key, it passes the
gcTimefrom its previous options toremoveObserver. The observer replaces its options before it leaves the old entry, so without this the old entry would get the new key'sgcTime.MutationObserverdoes this through a private#reset(gcTime), which the publicreset()also uses with its currentgcTime.
- When an observer switches to another query key or mutation key, it passes the
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.gcTimeandmutation.gcTimeare removed. They were public fields on the exportedQueryandMutationclasses (throughRemovable). Readquery.options.gcTimeormutation.options.gcTimeinstead. Note that those are the entry's own options, not the effective time. Nothing inpackages/*/srcreads the field; earlier tests did, and users or devtools-like tooling may.Query.removeObserverandMutation.removeObservernow require the leaving observer'sgcTimeas a second argument. Both are marked@internal.- The effective gc time changes when several
gcTimevalues apply. Before, the largestgcTimeever passed tosetOptionswas used. Now the latest removal time recorded wins:- A long
gcTimefrom an earlier observer only counts while its removal time is still in the future. - A shorter
gcTimethat comes later can't bring the removal earlier.
- A long
- 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
gcTimeof 5 min (removal at 5:00), then subscribes again with agcTimeof 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 largestgcTime. Resetting on subscribe would give 2:00, which would let a short mount pull an earlier promise forward.scheduleGc(gcTime)records itsgcTimebefore scheduling, so removal is never earlier than now plus the currentgcTime. - The observer's
gcTimeat the moment it unsubscribes is what's recorded. AgcTimepassed toqueryClient.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 aMutationObserver'sgcTimechanges while its mutation is idle, the new value is what's recorded when it leaves. Before, an idle mutation kept thegcTimefrom its last options. This is the only case where removal can now happen later than before.
Open questions#
- A
NaNgcTimeadds 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, aNaNgcTimemeant no gc was scheduled until a later validgcTimereplaced it. Both are invalid input. - Should a getter, e.g.
gcAt, be exposed for devtools in place of the removedgcTime? - The docs need a migration note in the v6 migration guide. The generated reference
pages for
Query/Mutationstill listgcTime. CONTRIBUTING says not to rungenerate-docsin a PR, because the docs re-sync after merge. Onquery-v6it 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.setOptionssetsthis.optionsbefore#updateQuery()detaches it from the previous query, andMutationObserver.setOptionsdoes the same before it resets. Readingobserver.options.gcTimeinsideremoveObservergives the old entry the new key'sgcTime, so the previousgcTimehas to be passed in. - Don't use a default parameter for that
gcTime. An observer whose previous options had nogcTimepassesundefined, which triggers the default, and that reads the new options again. - A fetch must record the
gcTimeit started with. An observer can callquery.setOptionswhile a fetch is in flight, sothis.optionsat settle time may belong to someone else. Use the options captured for the fetch. - Every schedule needs a recorded removal time first.
#gcAtstarts 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
gcTimeis 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 overflowedsetTimeout(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. NaNsticks throughMath.max, so it has to be filtered before it reaches the stored time. Returning early from the scheduler onNaNinstead also cancels a removal that was already scheduled.Infinitysticks forever. That's the same as before, and it is what makes the server default work.- Normal mutation flows use one observer: the
MutationObserverthat built the mutation withmutate(). 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. AtoFakelist that only fakes timers andDategives misleading timelines.
✅ Verification#
New test in
query.test.tsx: observer A (gcTime5 min) unsubscribes at 0:30, and observer B (gcTime1 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'sgcTime. The table shows the same case shifted to start at 0:00:Time Event Highest wins Last wins Latest deadline wins 0:00 A becomes inactive 5:00 5:00 5:00 1:00 B becomes inactive 6:00 2:00 5:00 With the production changes reverted (
query-v6as 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.tsxand one inmutationObserver.test.tsx. An observer withgcTime1000 switches to another key withgcTime: Infinity, and the old entry must be removed after 1000 ms. Both pass onquery-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'sInfinity, and pass with the observer fix.Fetch test in
query.test.tsx: an existing query withgcTime10 is fetched withqueryClient.query({ gcTime: 1000 }), and an observer withgcTime10 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.tsxandmutationObserver.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 onquery-v6, where the largestgcTimerestarts 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 onquery-v6too.
- a removal time recorded at the end of a
Updated tests:
removable.test.tsxnow coversupdateGcTimestampandscheduleGc(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
NaNgcTimebeing 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 readingquery.gcTime.query.test-d.tsx/mutation.test-d.tsx:gcTimeis dropped from the public member lists, along with themutation.gcTimetype test. TheremoveObserverparameter types now include thegcTimeargument.
query-core:vitest rungives 44 files and 1626 tests passed, with no type errors.test:types(TS 5.7 to 7.1),test:oxlint,oxfmt --checkandgit diff --checkare clean.react-querypassed 38 files and 654 tests, andpreact-querypassed 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
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.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand. Run configuration-
- Source mode: Auto
- Repository: TanStack/query
- Branch: query-v6
- File: .coderabbit.yaml
- Commit: a257bef
- Layers: Repository YAML
- Review profile: CHILL
- Plan: Advanced
- Run ID:
a82d9c0f-eb4e-46f9-af42-b3297edd1ec5
You can disable this status message by setting the
reviews.review_statustofalsein 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.
-
tanstack-source added labelsfeature
View your CI Pipeline Execution ↗ for commit d87893435b94efdd470b8fc7b5dcfd74ebb72d9b
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 8m 31s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 35s View ↗
☁️ Nx Cloud last updated this comment at
2026-11-22 21:41:50UTCMore templates
- @tanstack/query-example-lit-algolia
- @tanstack/query-example-lit-auto-refetching
- @tanstack/query-example-lit-basic
- @tanstack/query-example-lit-basic-graphql-request
- @tanstack/query-example-lit-batching
- @tanstack/query-example-lit-chat
- @tanstack/query-example-lit-default-query-function
- @tanstack/query-example-lit-infinite-query-with-max-pages
- @tanstack/query-example-lit-load-more-infinite-scroll-lit-labs-router
- @tanstack/query-example-lit-offline-lit-labs-router
- @tanstack/query-example-lit-optimistic-updates
- @tanstack/query-example-lit-pagination
- @tanstack/query-example-lit-playground
- @tanstack/query-example-lit-prefetching-lit-labs-router
- @tanstack/query-example-lit-rick-morty-lit-labs-router
- @tanstack/query-example-lit-simple
- @tanstack/query-example-lit-ssr
- @tanstack/query-example-lit-star-wars-lit-labs-router
- @tanstack/query-example-preact-algolia
- @tanstack/query-example-preact-auto-refetching
- @tanstack/query-example-preact-basic
- @tanstack/query-example-preact-basic-graphql-request
- @tanstack/query-example-preact-batching
- @tanstack/query-example-preact-chat
- @tanstack/query-example-preact-default-query-function
- @tanstack/query-example-preact-devtools-panel
- @tanstack/query-example-preact-infinite-query-with-max-pages
- @tanstack/query-example-preact-load-more-infinite-scroll-preact-iso
- @tanstack/query-example-preact-offline-preact-iso
- @tanstack/query-example-preact-optimistic-updates
- @tanstack/query-example-preact-pagination
- @tanstack/query-example-preact-playground
- @tanstack/query-example-preact-prefetching-preact-iso
- @tanstack/query-example-preact-rick-morty-preact-iso
- @tanstack/query-example-preact-shadow-dom
- @tanstack/query-example-preact-simple
- @tanstack/query-example-preact-ssr
- @tanstack/query-example-preact-ssr-streaming
- @tanstack/query-example-preact-star-wars-preact-iso
- @tanstack/query-example-preact-suspense
- @tanstack/query-example-react-algolia
- @tanstack/query-example-react-auto-refetching-nextjs-pages-router
- @tanstack/query-example-react-basic
- @tanstack/query-example-react-basic-graphql-request
- @tanstack/query-example-react-batching
- @tanstack/query-example-react-chat
- @tanstack/query-example-react-contacts-react-router
- @tanstack/query-example-react-contacts-tanstack-router
- @tanstack/query-example-react-default-query-function
- @tanstack/query-example-react-devtools-panel
- @tanstack/query-example-react-eslint-plugin-demo
- @tanstack/query-example-react-hydration-nextjs-pages-router
- @tanstack/query-example-react-infinite-query-with-max-pages-nextjs-pages-router
- @tanstack/query-example-react-load-more-infinite-scroll-nextjs-pages-router
- @tanstack/query-example-react-offline-react-router
- @tanstack/query-example-react-offline-tanstack-router
- @tanstack/query-example-react-optimistic-updates-nextjs-app-router
- @tanstack/query-example-react-pagination-nextjs-pages-router
- @tanstack/query-example-react-playground
- @tanstack/query-example-react-prefetching-nextjs-app-router
- @tanstack/query-example-react-prefetching-nextjs-pages-router
- @tanstack/query-example-react-react-native
- @tanstack/query-example-react-rick-morty-react-router
- @tanstack/query-example-react-shadow-dom
- @tanstack/query-example-react-simple
- @tanstack/query-example-react-star-wars-react-router
- @tanstack/query-example-react-suspense
- @tanstack/query-example-react-suspense-streaming-nextjs-app-router
- @tanstack/query-example-solid-algolia
- @tanstack/query-example-solid-auto-refetching-solid-start2
- @tanstack/query-example-solid-basic
- @tanstack/query-example-solid-basic-graphql-request
- @tanstack/query-example-solid-batching
- @tanstack/query-example-solid-chat
- @tanstack/query-example-solid-contacts-solid-router
- @tanstack/query-example-solid-contacts-tanstack-router
- @tanstack/query-example-solid-default-query-function
- @tanstack/query-example-solid-devtools-panel
- @tanstack/query-example-solid-offline-solid-router
- @tanstack/query-example-solid-offline-tanstack-router
- @tanstack/query-example-solid-optimistic-updates-solid-start2
- @tanstack/query-example-solid-pagination-solid-start2
- @tanstack/query-example-solid-playground
- @tanstack/query-example-solid-prefetching-solid-start2
- @tanstack/query-example-solid-rick-morty-solid-router
- @tanstack/query-example-solid-shadow-dom
- @tanstack/query-example-solid-simple
- @tanstack/query-example-solid-ssr-astro
- @tanstack/query-example-solid-star-wars-solid-router
- @tanstack/query-example-solid-streaming-solid-start2
- @tanstack/query-example-solid-suspense
- @tanstack/query-example-svelte-algolia
- @tanstack/query-example-svelte-auto-refetching-sveltekit
- @tanstack/query-example-svelte-basic-graphql-request
- @tanstack/query-example-svelte-basic-sveltekit
- @tanstack/query-example-svelte-batching
- @tanstack/query-example-svelte-chat
- @tanstack/query-example-svelte-contacts-sveltekit
- @tanstack/query-example-svelte-default-query-function
- @tanstack/query-example-svelte-infinite-query-with-max-pages-sveltekit
- @tanstack/query-example-svelte-load-more-infinite-scroll-sveltekit
- @tanstack/query-example-svelte-offline-sveltekit
- @tanstack/query-example-svelte-optimistic-updates-sveltekit
- @tanstack/query-example-svelte-pagination-sveltekit
- @tanstack/query-example-svelte-playground-sveltekit
- @tanstack/query-example-svelte-prefetching-sveltekit
- @tanstack/query-example-svelte-rick-morty-sveltekit
- @tanstack/query-example-svelte-shadow-dom
- @tanstack/query-example-svelte-simple
- @tanstack/query-example-svelte-ssr-sveltekit
- @tanstack/query-example-svelte-star-wars-sveltekit
- @tanstack/query-example-vue-algolia
- @tanstack/query-example-vue-auto-refetching-nuxt4
- @tanstack/query-example-vue-basic
- @tanstack/query-example-vue-basic-graphql-request
- @tanstack/query-example-vue-batching
- @tanstack/query-example-vue-chat
- @tanstack/query-example-vue-contacts-tanstack-router
- @tanstack/query-example-vue-contacts-vue-router
- @tanstack/query-example-vue-default-query-function
- @tanstack/query-example-vue-dependent-queries
- @tanstack/query-example-vue-devtools-panel
- @tanstack/query-example-vue-infinite-query-with-max-pages-nuxt4
- @tanstack/query-example-vue-load-more-infinite-scroll-nuxt4
- @tanstack/query-example-vue-offline-tanstack-router
- @tanstack/query-example-vue-offline-vue-router
- @tanstack/query-example-vue-optimistic-updates-nuxt4
- @tanstack/query-example-vue-pagination-nuxt4
- @tanstack/query-example-vue-persister
- @tanstack/query-example-vue-playground
- @tanstack/query-example-vue-prefetching-nuxt4
- @tanstack/query-example-vue-rick-morty-vue-router
- @tanstack/query-example-vue-shadow-dom
- @tanstack/query-example-vue-simple
- @tanstack/query-example-vue-simple-nuxt3
- @tanstack/query-example-vue-simple-nuxt4
- @tanstack/query-example-vue-star-wars-vue-router
- @tanstack/query-example-vue-suspense
- @tanstack/query-example-angular-auto-refetching
- @tanstack/query-example-angular-basic
- @tanstack/query-example-angular-basic-angular-router
- @tanstack/query-example-angular-basic-persister
- @tanstack/query-example-angular-devtools-panel-angular-router
- @tanstack/query-example-angular-dynamic-devtools
- @tanstack/query-example-angular-dynamic-queries
- @tanstack/query-example-angular-infinite-query-with-max-pages
- @tanstack/query-example-angular-optimistic-updates
- @tanstack/query-example-angular-pagination
- @tanstack/query-example-angular-query-options-from-a-service-angular-router
- @tanstack/query-example-angular-rxjs
- @tanstack/query-example-angular-simple
- @tanstack/query-example-angular-ssr
- @tanstack/query-example-angular-ssr-persist
- @tanstack/query-example-angular-to-resource-signal-forms
@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@12680commit:
d878934
Sign in to join this conversation.
🦋 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
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