ruby
41 lines · 5 steps
Caching patterns with Rails.cache.fetch
A catalog service that wraps expensive queries in Rails.cache.fetch, showing how keys, expiry, and invalidation work together.
Explained by
highlit
1class ProductCatalog
2 def featured_products
3 Rails.cache.fetch("catalog/featured_products", expires_in: 12.hours) do
4 Product.where(featured: true)
5 .where("stock_count > 0")
6 .order(popularity: :desc)
7 .limit(20)
8 .to_a
9 end
10 end
11
12 def revenue_for(store, on:)
13 Rails.cache.fetch(["catalog/revenue", store.id, on.iso8601], expires_in: 1.hour) do
14 store.orders
15 .completed
16 .where(completed_on: on.all_day)
17 .sum(:total_cents)
18 end
19 end
20
21 def category_tree
22 Rails.cache.fetch("catalog/category_tree", race_condition_ttl: 10.seconds) do
23 Category.includes(:subcategories).roots.map do |root|
24 { id: root.id, name: root.name, children: root.subcategories.pluck(:id, :name) }
25 end
26 end
27 end
28
29 def price_for(product)
30 Rails.cache.fetch([product, "computed_price"]) do
31 base = product.base_price_cents
32 discount = product.active_promotions.sum(:discount_cents)
33 [base - discount, 0].max
34 end
35 end
36
37 def invalidate(store)
38 Rails.cache.delete("catalog/featured_products")
39 Rails.cache.delete_matched("catalog/revenue/#{store.id}/*")
40 end
41end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Rails.cache.fetch runs its block only on a cache miss and stores the return value under the given key.
- 2Cache keys should encode every input that changes the result, and array keys with model objects auto-version on update.
- 3Expiry, race_condition_ttl, and explicit deletion are complementary tools for keeping cached data fresh.
Related explainers
ruby
require "csv" class SalesReport def initialize(path)
Aggregating CSV sales data in Ruby
data-aggregation
memoization
group_by
Intermediate
6 steps
ruby
module DurationFormatter UNITS = [ ['week', 604_800], ['day', 86_400],
Turning seconds into human-readable durations in Ruby
greedy-decomposition
modular-arithmetic
formatting
Intermediate
7 steps
ruby
class Comment < ApplicationRecord belongs_to :post belongs_to :author, class_name: "User"
Live-updating comments with Turbo in Rails
turbo-streams
callbacks
associations
Intermediate
8 steps
ruby
require 'json' require 'set' class SensitiveScrubber
Recursively scrubbing secrets from JSON
recursion
data-masking
pattern-matching
Intermediate
7 steps
rust
use std::collections::HashMap; pub struct Memoizer<K, V, F> { cache: HashMap<K, V>,
A generic memoizer in Rust
memoization
generics
caching
Intermediate
6 steps
ruby
class ReportBatcher BATCH_SIZE = 500 def initialize(account)
Batching monthly email summaries in Rails
batching
service-object
background-jobs
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/caching-patterns-with-rails-cache-fetch-explained-ruby-d44e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.