Investigating GraphQL Fragment Caching Issues

Last week, we lost time to a GraphQL bug; we could see the expected query requested with the correct data returned. The problem was that the data shown on the page did not relate to the data returned by the query. If we turned off caching for the query, we saw the correct data, so we knew we had a caching error. The data in question were two fields of a common fragment type, and after a bit more investigation, we determined that the page was always returning the data stored in the last field it read, regardless of what field was requested.

After much more digging around, we found that in our (in-memory GraphQL) cache, the code was setting up a custom “dataIdFromObject” function, overriding the default behaviour for this fragment because, as it had no default “id” or “_id“.

The code in question was fragmentname::${nested_id} but we were not returning nested_id in our query, so this was resolving to “fragmentname::undefined” for every fragment that was being resolved, so only the most recently read fragment was being cached.

Looking at the definition of “defaultDataIdFromObject“, we noticed that it could return a string or undefined, and if it returns undefined, the fragment was not cached. Updating our code to ensure we only used nested_id if it was provided and returned undefined otherwise resolved the problem straight away.

Leave a Reply

Your email address will not be published. Required fields are marked *