Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Fwiw I never really got this approach to caching b/c the keys are always based on calling the db, and calling the db is usually what you're specifically trying to avoid with caching, not just the transform of db content to json/html, which should be cheap?


The active record queries like User.all are lazily loaded, so it’s totally possible to pass them around like keys without them being executed.

That said, I wouldn’t use a query as a cache key since there may be more than one thing I want to cache about that query (GP’s example is their as_json representation, but what if I wanted something different to be computed? Like maybe html snippets? I would expect the cache key to mention everything about the thing it’s caching.)


> what if I wanted something different to be computed? Like maybe html snippets? I would expect the cache key to mention everything about the thing it’s caching.

This is exactly where you'd use something like ActiveSupport::Cache.expand_cache_key(["blog posts", blog.posts]). You can add bits of info to your cache keys to distinguish them from one another.

It's probably also worth mentioning that the `cache` view helper does parts of it for you already, and takes into account the digest of the view code itself among other things. Rails provides a really neat abstraction here that does make caching easier.

It has some rough edges, and some gotchas, but overall it's pretty smart.


Having used and written on this subject extensively, you are right but in practice these approaches mean something along the lines of making a single primary key lookup (like 0.1 to maybe 3ms in most cases) to save many tens or hundreds of queries (in addition to the cost of rendering/templating) to build the nested content, so it is still extremely practical.


To add to the excellent answer from SiliconAlley, it's definitely something to balance. What you cache needs to take a non-insignificant amount of time to be worth caching. Typically those DB queries for the cache key itself are single-digit ms and the stuff you want to cache is in the hundreds of ms.

Don't forget that even fetching the cache data itself takes time, even with fast cache storage like redis, especially over the network (where some cache layers live when they are shared).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: