Automatic Cache Invalidation via Mutations

While Stellate offers a powerful Purging API, that allows you fine-grained control over which items are purged from the cache as well as when we also wanted our users to not have to think about purging most of the time.

That's why we implemented a feature that automatically invalidates any cached query results based on the responses to your mutations.

❗️

For this feature to work, you need to pass your mutations through Stellate as well. If you send mutations to your backend service directly, we can not pick up the changes and purge related objects from the cache.

For example, imagine this GraphQL schema:

type Post {
  id: ID!
  author: User!
  comments: [Comment!]!
}

type Mutation {
  updatePost: Post!
}

mutation {   
  updatePost {
    id
    comments {
      id
    }
    author {
      id
    }
  }
}

Once the mutation completes, any query result that contains the Post with the returned ID and any query result that contains the User with the returned ID (at Post.author) and any query result that contains any of the comments with the returned IDs (at Post.comments[n].id) will fully automatically be invalidated.

📘

Bypassing Automatic Cache Invalidation

If you need to bypass automatic cache invalidation for certain mutations, you can do so by specifying a Bypass Header.

Mutation Policies

Stellate offers you to customize how we go about automatically invalidating your cached queries. This is done through the mutationPolicy option in your configuration file, we offer three values:

  • Entity (default)
  • List
  • Type

The default policy is Entity which is described above. It will invalidate any cached documents that contain that specific entity (identified via its type and ID) returned by the mutation. If your mutation returns multiple Type/ID combinations, all of those will be invalidated.

List expands on Entity in that we will not only invalidate the specific entity but also all lists where the type of that entity has been seen. Imagine the previous example where we invalidate Post[x] this entity could have changed ordering, ... it could make sense to purge all lists where the type Post is present. This mutation policy helps work around the edge case regarding lists mentioned below.

The Type policy is the most strict one in that it will purge every cached response where that specific type has been seen. Expanding on the previous example, this would mean any cached results containing a Todo (disregarding the specific ID) would get invalidated automatically.

Edge cases

The most common case where automatic mutation invalidation does not automatically invalidate data is when items are added to a list. You can either look into manual invalidation, see our documentation on the Purging API, as well as the more specific article on how to invalidate lists .

Alternatively, you can also look into the List mutation policy, which is documented above.