Caching with Node/Express
Working with payees and payments in node-billz I basically end up loading and reloading the same data on every page. The list of people paid each month will rarely change. The list of payments will grow over time but generally only a few payments are made per week. Basically, these are perfect candidates for caching so I thought I would see how difficult it would be to get this implemented in Node.
Searching GitHub I quickly found a few cache providers that would work with MongoDB and more specifically Mongoose since that is what I am using to work with backend data. There were a few false starts with downloading orphaned projects that were no longer supported, but finally I settled with cachegoose. It has been updated recently plus it gave me the option of an in-memory cache as well as caching with Redis and others.
The cache provider module selected, the next step was to get the app configured to use the cache. Two lines of code later everything was working. It does not get much easier. I opted to use the in-memory cache for the time being, but you can easily point cachegoose to a Redis server at initialization.
The final step was to wire the cache to the queries. You can specify the number of seconds you would like to cache a query or you can cache it indefinitely with a custom cache key. If a cache needs to be purged, call the clearCache method with the custom cache key to clear it. I opted to go the second route since the data only changes occasionally. When a payee is modified or a payment is made I clear the cache keys so the data can be re-cached the next time it is queried.
It was incredibly easy to setup caching, aside from the false steps I had at first. Given the size of the ecosystem though I suppose I should not be surprised to find some dead projects out there.
I would be interested in learning about any other libraries or tools you guys are using. Feel free to drop me a line.