Video in progress

You're caching the catalog of a large online store. At what granularity do you cache product cards, category pages and search results, and how do you invalidate lists?

I cache each product under its own key and cache lists only as IDs, so when a price changes, a single product key is updated, not the lists. I invalidate lists with a category version, and from search I cache only the most-requested queries, with a short TTL.

📖 Answer

The most common mistake is caching a category page as ready-made JSON (40 full products). When one product's price changes, you don't know which pages it's on: there are hundreds of combinations by sorting, filters and page number. As a result you either clear everything or the old price stays.

The layers I use:

  1. Entity level: product:{id}, the full card, with a TTL of a few hours. When a product changes, only this key is deleted.

  2. Lists, IDs only.

List<Long> ids = listCache.get("cat:" + catId + ":v" + version + ":" + sort + ":p" + page,
        () -> repo.findIds(catId, sort, page));
List<ProductDto> items = productCache.getAll(ids);   // MGET, the missing ones from the DB

If a price or name changes, you don't touch the list cache, because it holds only IDs.

  1. If list membership changes, use a version: a product was added to or removed from a category: INCR cat:{id}:ver. New requests go to the new key, and the old ones die on their own through the TTL. No SCAN and no mass deletes.

  2. Fast-changing fields kept separate: stock count and promo price change a hundred times a day. I don't put them in the card; I keep them under a separate key with a short TTL, or fetch them directly from the DB/service. Otherwise the whole card cache gets cleared for nothing.

  3. Search: the combinations of free-text queries are endless. Caching all of them fills memory and the hit ratio is low. I cache only the most popular queries for 1-5 minutes, and the rest the search engine (Elasticsearch/OpenSearch) serves fast on its own.

In a cluster, MGET lands on different slots. Lettuce splits it up by node and sends the parts, which is normal. And a separate hit ratio metric for each layer: that's how you see which cache isn't paying off.