When invalidating caches ensure every element that might vary is part of the key

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the caching category.

Last Updated: 2024-04-24

I have taxons that show all the digital notes I sell in a given category (e.g. "Medicine" or "French"). My website has multiple "stores" (e.g. UK, USA), each on its own domain name, and the products contained within each taxon vary dependent on the store.

I noticed that my caching was derping and displaying the Canadian store's products on my UK website. Here was my original buggy code:

# TaxonController

def show
  if stale? @taxon
    @products = @taxon.products.order(:name).in_store(current_store)
  end
end

The issue here was the @products variable was dependent on the current_store, as you can see in the chained methods above. Because @products depends on current_store, this dependency must also appear in the cache key, as I demonstrate below:

def show
  if stale? [@taxon, current_store]
    @products = @taxon.products.order(:name).in_store(current_store)
  end
end