Mutation-based cache invalidation

Hugo BarrigasHugo BarrigasJamie BartonJamie Barton
Mutation-based cache invalidation

Earlier this year Grafbase introduced GraphQL Edge Caching. Developers can configure strict cache rules for any connected data source, custom resolver or the Grafbase Database but relied on the configured maxAge and staleWhileRevalidate to purge cached responses.

We're excited to announce that you can now configure automatic cache invalidation!

The new mutationInvalidation property accepts multiple options, and works when configuring cachine globally or per type/database model:

  • entity — Triggered by mutations for the specified type, this will invalidate any cache entry containing the selected field. By default, it utilizes the id.
  • list — Triggered by mutations for the specified type, this will invalidate any cache entry containing lists of the corresponding type.
  • type — Triggered by mutations for the specified type, this will invalidate any cache entry containing the type.

In the example below there are two custom resolvers, products and product.

Since mutationInvalidation is set to entity it will assume the entity has an id field and use that to tag the cached entry.

import { config, graph } from '@grafbase/sdk' const g = graph.Standalone() export default config({ graph: g, cache: { rules: [ { maxAge: 10, types: "Product", mutationInvalidation: 'entity' } { maxAge: 10 types: [{ name: "Query", fields: ["products", "product"] }] } ] } })

If the products and product queries don't return entities with the id field in them then you can specify a custom field instead:

import { config, graph } from '@grafbase/sdk' const g = graph.Standalone() export default config({ graph: g, cache: { rules: [ { maxAge: 10, types: "Product", mutationInvalidation: { field: '_id' } }, { maxAge: 10 types: [{ name: "Query", fields: ["products", "product"] }] } ] } })

We've also introduced a new Purging API. This tool allows you to either perform a full cache purge on your project or target specific items for cache invalidation, providing you with greater flexibility and control.

The Admin API URL is available at: https://[project-slug].grafbase.app/admin and requires the usual x-api-key HTTP header and value to access.

We'd love to hear your feedback and ideas, so join us on Discord.