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 "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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.