Blog>
Snippets

Optimizing Cache Configuration

Showcase configuring the cache time and stale time for a specific query to efficiently manage data.
const { ApolloServer, gql } = require('apollo-server');

// Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server.
const typeDefs = gql`
  type Query {
    book(id: ID!): Book
  }

  type Book {
    id: ID
    title: String
    author: String
  }
`;

// Resolvers define the technique for fetching the types in the
// schema. We'll retrieve books from the "books" array above.
const resolvers = {
  Query: {
    book: (_, { id }) => books.find(book => book.id === id),
  },
};

// In this example, we are setting up ApolloServer and applying a cache control directive on the book query.
const server = new ApolloServer({ typeDefs, resolvers, cacheControl: { defaultMaxAge: 5, // Cache for 5 seconds.
                                                                         staleWhileRevalidate: 30 // Data can be served stale for up to 30 seconds while revalidation occurs.
                                                                       } });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
This code snippet initializes an Apollo GraphQL server with a simple schema for book queries. It configures the server's cache policy, specifying a default maximum cache age of 5 seconds, and allows serving stale data for up to 30 seconds while the cache is being revalidated. This approach balances performance with data freshness, reducing load times for frequently accessed data while ensuring that updates are reflected in a timely manner.