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
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
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.