Friday, April 09, 2021

Apollo GraphQL Client: The order of Persisted Query Link & Retry Link Matters

We enabled automatic persisted query on an app that uses Apollo GraphQL client to query GraphQL. GraphQL persisted query is implemented by Apollo as an effort to save bandwidth from avoiding submitting the query both every time: https://www.apollographql.com/docs/apollo-server/performance/apq/ This was easily enabled with

    link = createPersistedQueryLink().concat(link)

Though at most of time the queries were submitted with persisted query hash, strangely there are times when full requests without query hash are still submitted, and the error cannot be recreated following the referer page of the unexpected request. It suggests the unexpected requests happened only occasionally.

I noticed that our link included the RetryLink feature.

         link = concat(new RetryLink({attempts: {max:2}}), new HttpLink({uri, fetchOptions}))

 Since Retry Link concatenated only with HttpLink, it will only know to send full request. Thus, the correct concatenated order is RetryLink on the outside of the PersistedQueryLink.

          link = concat(new RetryLink({attempts: {max:2}}), createPersistedQueryLink(), new HttpLink({uri, fetchOptions}))

After reordering the link concatenation, the client started to work correctly with persisted query hash all the time.