Subscription: Create Context per published value #80
Labels
kind/enhancement
New feature or request
stage/5-alpha-release-testing
The pull request is merged, an alpha release is available, to be tested
Is your feature request related to a problem? Please describe.
I have been thinking about how context and subscription behave after finding out that in almost every server implementation the context is retained for the whole subscription execution.
In a production app that somehow got slipped and lead to caching issues with DataLoaders, as each time the AsyncIterator of the subscription field published a new value the DataLoaders were hitting the cache (but the underlying data in the database had changed). The temporary solution was to disable the cache altogether and instead only use the DataLoaders for solving the n+1 database queries issue.
However, I don't think that this should be the way to go. A DataLoader cache should only be disabled in the context of a mutation operation as per spec definition a query and subscription operation do not change/mutate data and thus if a nested resolver tries to load the same data as a parent data using a cache instead of taking another roundtrip to the database server is perfectly fine.
Since a subscription can be long-running it makes sense to clear the cache after a value published by an AsyncIterator went through the resolver phase.
Describe the solution you'd like
Currently, there is no straightforward way to do this and I have the feeling that from a UX experience it would be the simplest to just dispose of the context after the resolver phase and re-create it once a new value is published by the AsyncIteraror (vs. calling a lot of cache.clear() functions for each DataLoader or other caching mechanism).
One unsolved question is how that might work if the AsyncIterator event source is attached to the context. Usually, the source is passed to the
subscribe
handler via the context, but instead of having one source for each incoming request the source is often only initiated once upon server start and them simply forwarded by attaching it to the context (which is usually created for each incoming operation). So that wouldn't be an issue I guess.Maybe, such behaviour could be a fit for
envelop
😊Describe alternatives you've considered
Currently, the only suboptimal solution would be to either disable caching completely (which could be expensive) or raise this question on the graphql-js reference implementation
Additional context
The text was updated successfully, but these errors were encountered: