Race condition near query cancellation/invalidation while implementing optimistic update #5968
Send to my agentDescribe the bug#
Requirements: Assume the application has multiple entities present such as docs, slides, etc. We should now add a bookmarking ability to the system.
Implementation: I have implemented an optimistic update approach near bookmarking an entity in the application and have also made use of the abort signal for query cancellations.
Issue: Let's say I bookmark certain docs while on the docs page and quickly move to the bookmarks page, I see that the bookmarks list API-related query is getting canceled and is stuck in isFetching: true. Because of this, we are left with the entries added by the UI optimistic update and not the ones from the server.
Your minimal, reproducible example#
https://codesandbox.io/p/sandbox/loving-forest-2t69p7
Steps to reproduce#
In the example, we have 2 routes -> Add Items and Item List. I have added a mock service that mocks an API call with a ~1-second delay.
I differentiate the UI-added entry and the mock service-added entry by having a different pattern for IDs. All the entries added through optimistic updates will have a prefix "__UI__ " in their IDs. All the entries from the mock service will have the prefix "From Service" in their IDs.
- Go to the Add Items page and add 3-4 items by pressing the Add Item button again and again before even the re-fetch can finish (this is to trigger the query cancellation). We can see the optimistic update-related logic at
src/useItems.ts. - After the last addition of the items, move to Item List before the fetch can finish
- We can now see that the last re-fetch that is triggered due to the query invalidation written in the onSettled method is getting canceled. And now we end up with entries added by UI optimistic update and not the actual server state.
Expected behavior#
How do we ensure we can always have the server state in this scenario? I am guessing that component unmount is causing this query cancellation. Please watch the video attached as this race condition doesn't happen every single time. And if we give it enough time near the Add Items page, there won't even be any issue popping up.
Without having the actual server state [actual IDs assigned by BE], we won't be able to act upon those entries.
How often does this bug happen?#
Often
Screenshots or Videos#
https://github.com/TanStack/query/assets/12635717/b4580697-387b-468b-aebe-4ba00c8b5809
Platform#
- macOS 13.2
- Chrome 112.0.5615.137
Tanstack Query adapter#
None
TanStack Query version#
4.32.6
TypeScript version#
No response
Additional context#
No response
oh and here's a fork of your sandbox with that
mutationKeysolution: https://codesandbox.io/p/sandbox/react-query-cancelllation-race-condition-forked-4cd8lt?file=/src/useItems.ts:48,1if you can still reproduce the issue with this one, please let me know
thank you @TkDodo for the workaround
I have one doubt about mutation-keys. I tried finding in the documentation for the same as well, but couldn't find info on the same -
If a mutationKey is not unique for multiple mutations, will it have some unwanted behavior ?Assuming we dont have any unwanted side effects due to mutation key not being unique, can u also comment on the below code maintanence (I tried applying the coding patterns discussed in #8: Effective React Query Keys) -
export const bookmarksMutationKeys = { all: ['bookmarksMutation'] as const, addBookmark: () => [...bookmarksMutationKeys.all, 'add'] as const, deleteBookmark: () => [...bookmarksMutationKeys.all, 'delete'] as const, }I use addBookmark() and deleteBookmark() mutation keys in their respective useMutations and I use
bookmarksMutationKeys.allas below ->onSettled: () => { if (queryClient.isMutating({ mutationKey: bookmarksMutationKeys.all }) === 1) { queryClient.invalidateQueries(bookmarksQueryKeys.all); } }mutationsKeys don't really need to be unique because if you call
mutate()multiple times in a row, you get a new mutation entry with the same key. That's actually what makes my solution work :)If you use
bookmarksMutationKeys.all, it will target bothaddanddeletemutations. If you don't want that, you'd need to be more specific.You can also do:
queryClient.isMutating({ mutationKey: bookmarksMutationKeys.all, exact: true })which will remove the fuzzy key matching, and only exact keys, in this case exactly
['bookmarksMutation']would match.thank you for the clarification 😃 This solves my issue.
Do u want this issue to be open for tracking the
isFetching being stuck due to query cancellation?Thank you for all of your efforts in maintaining this amazing library and your awesome blog @TkDodo
Lets keep the issue open but I won't really have much time in the near future to look into it. I'll add the appropriate labels.
TkDodo added labelsbug
TkDodo added labelshelp wanted
TkDodo added labelshas workaround
@KartheekJavvaji would you be able to record the bug using https://replay.io/ ? I could try to debug this then
@Andarist let me know if this works -> https://app.replay.io/recording/vite-react-ts--9659b354-4511-4974-9f76-2e8073b770fd
The internal
revertStateis not handled properly in this scenario: https://github.com/TanStack/query/blob/4d859e9ab16169da45b2f863c9380224301e6fb4/packages/query-core/src/query.ts#L416-L417It's possible to put a state with
fetchStatus: 'fetching'in it. Then when the component unmounts it unsubscribes from the query and tries to revert its state here: https://github.com/TanStack/query/blob/4d859e9ab16169da45b2f863c9380224301e6fb4/packages/query-core/src/query.ts#L304The revert itself is handled by the reducer here: https://github.com/TanStack/query/blob/4d859e9ab16169da45b2f863c9380224301e6fb4/packages/query-core/src/query.ts#L561-L563
So, in this scenario, a query stuck in a fetching state survives in the cache. When the new component mounts it reuses that query from the cache and when it tries to fetch it just returns the errored promise here: https://github.com/TanStack/query/blob/4d859e9ab16169da45b2f863c9380224301e6fb4/packages/query-core/src/query.ts#L331-L341
No error is raised by the runtime on it though since
.catch(noop)is attached to it here: https://github.com/TanStack/query/blob/4d859e9ab16169da45b2f863c9380224301e6fb4/packages/query-core/src/queryObserver.ts#L356And internally this error~ was already handled (remember, this is a reused promise that was already aborted by the library) so the library never handles this anyhow.
Perhaps the easiest fix would be to conditionally set
this.revertStateto what is worth reverting to in the first place. There are certainly edge case-y scenarios to consider here carefully. I could help out with this but I would need some guidance from @TkDodo to assess what's the proper fix here.oh this is a brilliant find, thank you @Andarist. Amazing what you can do with a replay 🤯.
I think a good first fix would be to always set the query back to
idlefetchStatus when reverting:if (isCancelledError(error) && error.revert && this.revertState) { - return { ...this.revertState } + return { ...this.revertState, fetchStatus: 'pending' } }Nothing else comes to mind that would be "invalid" when reverting back to it...
I will try to find some time in the coming days to craft a test case for this so I can wrap it up in a PR.
TkDodo closed this
Sign in to join this conversation.
thanks for the good reproduction and issue - it's an interesting case for sure. I narrowed it down to too many invalidations happening from too many onSuccess calls if you add multiple items. It never fails when just adding one item.
Here's what I did:
add itemsfetchingItems Listnow one immediate remedy is to not fire invalidations while another mutation that affects the same query is still running:
this is also a better UX with concurrent, optimistic updates because it won't give you "server values" in between, as the
queryClient.cancelQueries()might not catch all invalidations. Simple example:at best, this is a flash in the UI. It seems that if we add a route change to the mix, we get stuck somewhere. I'll try to investigate the "getting stuck" further, but this doesn't happen if you never fire the first invalidation, which my implementation / workaround assures.
side note: i wanted to add an
onAllSettledcallback, which is only called if there is no other mutation running for a given key. It would be better suited for invalidations of concurrently running mutations, but they would usually need a mutationKey, and the impl in user-land is just one line of code (like shown above), so we didn't add it.side note2: you might be interested in another optimistic update approach that we'll add in v5: https://tanstack.com/query/v5/docs/react/guides/optimistic-updates#via-the-ui
if you only need the optimistic update in the one list where you currently are, this approach is better suited, because it doesn't manipulate the cache at all. of course, your real situation might be more complex.