Using Elasticsearch results to generate cache keys in Rails
A pretty neat thing I realized while building the search for Supplybunny is that you can use the results from elastic search to generate the cache keys that rails generates.
The default format of cache key that rails would generate for a Post
model would be of the format posts/<id>-<updated_at>
where <id>
is the actual ID and <updated_at>
is post.updated_at.utc.strftime("%Y%m%d%H%M%S000000000")
.
So, <%cache post%>
is equivalent to <%cache "posts/#{post.id}-#{post.updated_at.utc.strftime("%Y%m%d%H%M%S000000000")}%>
.
If we are caching a fragment, for instance :comments
, that isn’t tied directly to the Post
cache key, we just need to add that as a string to that cache key. For the post above the cache line would end up being: <%cache "posts/#{post.id}-#{post.updated_at.utc.strftime("%Y%m%d%H%M%S000000000")}/comments%>
.
All segments are joined with /
so we can push keys into an array and then .join("/")
them.
Putting all of the above together, we get something like this:
This made a big difference in preformance, especially in JSON requests that could be cached in a similar way.