That’s really cool and all, but what about CACHING!?

Yeah, so caching is an interesting subject, and before we can discuss how we implement caching for our GraphQL calls I want to take a second to distill any mysteries around caching and the differences between HTTP caching and application caching.

In the REST of the world (get it!), when caching is spoken of, often what people are referring to is HTTP caching. It can take many forms but Varnish is an example. In HTTP caching there is an outside source responsible for caching requests from your application and serving those cached resources to clients. This works great because almost any query you would want to cache is a GET request and those can be cached easily by HTTP caching tools. In the GraphQL world we are actually making POST requests instead of GET requests.

Since we are making POST requests with body params, normal HTTP caching software is of little to no use since they don’t cache POST requests based on body params. This means if you want to use GraphQL and not have each request make a full pass through your system, you have to cache responses yourself. Luckily for us, this is super easy with Hapi.

Hapi has a neat feature called server methods . Server methods are basically a way of handling async memoization. What makes them so fantastic is that you can define any caching options that Hapi supports, which means you can get Redis based caching or any other kind of caching you like with very few lines of code.

The other benefit is the advanced configuration you can define for server methods, things like expirations per method and stale timeouts (which allow you to refetch the data before the expiration hits helping prevent any client requests not receiving a cached response).

Let’s revisit our resolvers and see how we could improve them with server methods:

Just a few more lines of code and we have memoized GraphQL resolvers! 🎉