Caching
suggest changeA cache keeps the result of an expensive operation (a database query, an HTTP call, a slow calculation) so the next request for the same data can skip the work. Ruby has no single caching library built in. You build caches from plain objects: an instance variable, a Hash, a Mutex. When you need expiry, size limits or a shared store, use a gem such as ActiveSupport::Cache.
Every cache forces three decisions:
| Question | Typical answers |
|---|---|
| What is the key? | method arguments, a URL, [model, id, updated_at] |
| When does an entry become stale? | never, after a TTL, when the source changes |
| How big can it grow? | unbounded, max N entries (LRU), max bytes |
Measure before you add a cache (see Profiling and Benchmarks). A cache adds memory use, stale data and invalidation bugs, so it should pay for itself.
Memoizing a method with ||=
The simplest cache stores a value in an instance variable the first time a method runs:
class Report
def initialize(rows) = @rows = rows
def total
@total ||= begin
puts "computing total..."
@rows.sum
end
end
end
r = Report.new([10, 20, 30])
puts r.total
puts r.total
computing total...
60
60
@total ||= expr means @total || (@total = expr). See Or-equals (||=) conditional assignment. The cache lives as long as the object does, so it suits per-request or per-object data.
The nil / false trap
||= treats nil and false as "not cached yet". If the computed value can be nil or false, the expensive work runs again on every call. Use defined? to check whether the variable has been set at all:
class User
def initialize(id) = @id = id
# BROKEN: nil result is recomputed on every call
def avatar_bad
@avatar_bad ||= lookup_avatar
end
# Correct: remember that we already looked
def avatar
return @avatar if defined?(@avatar)
@avatar = lookup_avatar
end
private
def lookup_avatar
puts " querying avatar for #{@id}"
nil # this user has no avatar
end
end
u = User.new(7)
puts "bad:"; 2.times { u.avatar_bad }
puts "good:"; 2.times { u.avatar }
bad:
querying avatar for 7
querying avatar for 7
good:
querying avatar for 7
Caching results per argument with a Hash
When a method takes arguments, use a Hash keyed by those arguments. A Hash with a default block computes and stores missing keys by itself. That makes a short memoized Fibonacci:
fib = Hash.new do |cache, n|
cache[n] = n < 2 ? n : cache[n - 1] + cache[n - 2]
end
puts fib[90]
puts fib.size
2880067194370816120
91
Without the cache, fib(90) would make about 1019 recursive calls. With it, each value is computed once.
For several arguments, use an array as the key. Arrays hash by their contents, so ["A1", "USD"] built twice gives the same key. Check with key? instead of truthiness so that cached nils count as hits:
class PriceService
def initialize = @prices = {}
def price(sku, currency: "USD")
key = [sku, currency]
return @prices[key] if @prices.key?(key)
puts " fetching #{sku} in #{currency}"
@prices[key] = fetch(sku, currency)
end
private
def fetch(sku, currency) = currency == "USD" ? 9.99 : 9.49
end
s = PriceService.new
p s.price("A1")
p s.price("A1")
p s.price("A1", currency: "EUR")
fetching A1 in USD
9.99
9.99
fetching A1 in EUR
9.49
Keys must not be mutated after they are inserted. If you put a mutable string or array in a key and change it later, the hash can no longer find the entry. Hash dups and freezes unfrozen String keys for you, but it does not do this for arrays or other objects.
A reusable memoize helper
Writing the cache check by hand in every method gets repetitive. def returns the method name as a symbol, and prepend puts a module in front of the class. Together they make a small, general memoize macro:
module Memoize
def memoize(name)
cache_ivar = :"@__memo_#{name}"
wrapper = Module.new do
define_method(name) do |*args, **kwargs|
cache = instance_variable_get(cache_ivar) ||
instance_variable_set(cache_ivar, {})
key = [args, kwargs]
return cache[key] if cache.key?(key)
cache[key] = super(*args, **kwargs)
end
end
prepend wrapper
name
end
end
class Geo
extend Memoize
memoize def distance(a, b)
puts " computing #{a}->#{b}"
(a - b).abs * 111
end
memoize def country(code, upcase: false)
puts " looking up #{code}"
name = { "pl" => "Poland", "de" => "Germany" }[code]
upcase ? name&.upcase : name
end
end
g = Geo.new
p g.distance(10, 13)
p g.distance(10, 13)
p g.country("pl")
p g.country("pl", upcase: true)
p g.country("xx")
p g.country("xx")
computing 10->13
333
333
looking up pl
"Poland"
looking up pl
"POLAND"
looking up xx
nil
nil
The wrapper method calls super, which reaches the original method in the class. Each instance gets its own cache in its own instance variable. Keyword arguments are part of the key, and nil results are cached too. The memo_wise gem offers a faster, production-ready version of this pattern.
Expiring entries after a time (TTL)
Data from outside the process (exchange rates, API responses, configuration) goes stale. A TTL (time-to-live) cache stores an expiry time with each value. Use the monotonic clock, not Time.now, because the wall clock can jump when the system time is adjusted. Here the clock is injectable, so the example can fake the passage of time:
class TTLCache
Entry = Data.define(:value, :expires_at)
def initialize(ttl:, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
@ttl = ttl
@clock = clock
@store = {}
end
def fetch(key)
now = @clock.call
entry = @store[key]
return entry.value if entry && entry.expires_at > now
value = yield(key)
@store[key] = Entry.new(value, now + @ttl)
value
end
def delete(key) = @store.delete(key)
def prune
now = @clock.call
@store.delete_if { |_, e| e.expires_at <= now }
end
def size = @store.size
end
now = 0.0
cache = TTLCache.new(ttl: 60, clock: -> { now })
load_rate = ->(pair) { puts " fetching #{pair}"; 4.03 }
p cache.fetch("USD/PLN", &load_rate) # miss
now = 30
p cache.fetch("USD/PLN", &load_rate) # hit
now = 61
p cache.fetch("USD/PLN", &load_rate) # expired -> miss
cache.fetch("EUR/PLN") { 4.27 }
now = 200
cache.prune
p cache.size
fetching USD/PLN
4.03
4.03
fetching USD/PLN
4.03
0
Expired entries are only replaced when someone asks for them again. Call prune now and then, for example from a background thread, so that keys nobody requests anymore don't pile up.
Bounding memory with an LRU cache
An unbounded Hash cache is a memory leak if the set of keys is open-ended (user IDs, URLs, search queries). An LRU (least recently used) cache keeps at most N entries and evicts the one that was used longest ago.
Ruby's Hash remembers insertion order, so an LRU cache needs no linked list. On every access, delete the key and insert it again to move it to the end. The first key is then always the least recently used:
class LRUCache
def initialize(max_size)
@max_size = max_size
@store = {}
end
def [](key)
return nil unless @store.key?(key)
value = @store.delete(key) # move key to the end (most recent)
@store[key] = value
end
def []=(key, value)
@store.delete(key)
@store[key] = value
@store.delete(@store.first[0]) while @store.size > @max_size
value
end
def fetch(key)
return self[key] if @store.key?(key)
self[key] = yield(key)
end
def keys = @store.keys
end
lru = LRUCache.new(3)
lru[:a] = 1
lru[:b] = 2
lru[:c] = 3
lru[:a] # touch :a, now :b is least recently used
lru[:d] = 4 # evicts :b
p lru.keys
p lru[:b]
p lru.fetch(:e) { |k| k.to_s * 2 }
p lru.keys
[:c, :a, :d]
nil
"ee"
[:a, :d, :e]
All operations are O(1). You can combine this with the TTL idea by storing Entry objects instead of raw values.
Thread safety
A plain Hash cache shared between threads has a race. Several threads can see a miss at the same moment, and each runs the expensive computation. This is the "thundering herd" or cache stampede problem. Thread-safety basics are covered in Race conditions. The fix for a cache is to do the check and the fill under a Mutex:
class SafeCache
def initialize
@store = {}
@lock = Mutex.new
end
def fetch(key)
@lock.synchronize do
return @store[key] if @store.key?(key)
@store[key] = yield(key)
end
end
end
calls = 0
slow_square = ->(n) { calls += 1; sleep 0.1; n * n }
unsafe = {}
threads = 5.times.map do
Thread.new { unsafe[4] ||= slow_square.(4) }
end
threads.each(&:join)
puts "unsafe: computed #{calls} times"
calls = 0
cache = SafeCache.new
threads = 5.times.map { Thread.new { cache.fetch(4, &slow_square) } }
p threads.map(&:value)
puts "safe: computed #{calls} times"
unsafe: computed 5 times
[16, 16, 16, 16, 16]
safe: computed 1 times
A single lock has a cost: while one key is being computed, lookups of every other key wait. Give each key its own mutex so that only callers of the same key wait for each other:
class KeyLockedCache
def initialize
@store = {}
@locks = Hash.new { |h, k| h[k] = Mutex.new }
@meta = Mutex.new # guards @locks and @store
end
def fetch(key)
lock = @meta.synchronize { @locks[key] }
lock.synchronize do
found, value = @meta.synchronize { [@store.key?(key), @store[key]] }
return value if found
value = yield(key) # only callers of this key wait here
@meta.synchronize { @store[key] = value }
end
end
end
cache = KeyLockedCache.new
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
threads = [1, 2, 3, 1, 2, 3].map do |n|
Thread.new { cache.fetch(n) { sleep 0.2; n * 10 } }
end
p threads.map(&:value)
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
puts "took ~#{elapsed.round(1)}s"
[10, 20, 30, 10, 20, 30]
took ~0.2s
With SafeCache the same code takes about 0.6s, because the three computations run one after another.
Freeze cached values
A cache hands the same object to every caller. If one caller mutates it, every later caller sees the change:
CACHE = {}
def tags_for(post_id)
CACHE[post_id] ||= ["ruby", "perf"]
end
tags = tags_for(1)
tags << "oops" # caller mutates the cached array
p tags_for(1)
CACHE.clear
def safe_tags_for(post_id)
CACHE[post_id] ||= ["ruby", "perf"].map(&:freeze).freeze
end
tags = safe_tags_for(1)
begin
tags << "oops"
rescue FrozenError => e
puts e.message
end
p safe_tags_for(1)
["ruby", "perf", "oops"]
can't modify frozen Array: ["ruby", "perf"]
["ruby", "perf"]
Freeze cached values deeply, or return a dup, so a bug in one caller can't corrupt shared state. See Immutability.
Caching to disk
An in-memory cache is lost when the process exits. For a CLI tool or a script that reruns often, you can cache results in files. Marshal serializes almost any Ruby object. A SHA-256 digest turns any key into a safe file name, and the file's modification time works as the TTL:
require "digest"
require "fileutils"
require "tmpdir"
class DiskCache
def initialize(dir, ttl: 3600)
@dir = dir
@ttl = ttl
FileUtils.mkdir_p(dir)
end
def fetch(key)
path = File.join(@dir, Digest::SHA256.hexdigest(key))
if File.exist?(path) && Time.now - File.mtime(path) < @ttl
return Marshal.load(File.binread(path))
end
value = yield
tmp = "#{path}.#{Process.pid}.tmp"
File.binwrite(tmp, Marshal.dump(value))
File.rename(tmp, path) # atomic replace: readers never see half a file
value
end
def clear = FileUtils.rm_rf(Dir.glob(File.join(@dir, "*")))
end
Dir.mktmpdir do |dir|
cache = DiskCache.new(dir, ttl: 600)
2.times do
stats = cache.fetch("stats:2026-10") do
puts " crunching numbers..."
{ visits: 18_432, signups: 211 }
end
p stats
end
p Dir.children(dir).size
end
crunching numbers...
{visits: 18432, signups: 211}
{visits: 18432, signups: 211}
1
Writing to a temporary file and then renaming it means a crash or a concurrent reader never sees a half-written file. Marshal.load can create arbitrary objects, so only use it on files your own program wrote. For data that crosses a trust boundary, or that other languages need to read, store JSON instead.
ActiveSupport::Cache
For real applications, use ActiveSupport::Cache (gem install activesupport). It works outside Rails too. It gives you one API over several backends: MemoryStore (in-process, thread-safe, LRU-bounded by size), FileStore, MemCacheStore and RedisCacheStore. All of them support expiry, counters and batch operations:
require "active_support"
require "active_support/cache"
require "active_support/core_ext/numeric/time"
cache = ActiveSupport::Cache::MemoryStore.new(size: 32.megabytes, expires_in: 10.minutes)
def load_user(id)
puts " SELECT * FROM users WHERE id = #{id}"
{ id: id, name: "Ann" }
end
2.times { p cache.fetch("user/42") { load_user(42) } }
cache.write("counter", 0)
cache.increment("counter")
cache.increment("counter", 5)
p cache.read("counter")
p cache.fetch("short", expires_in: 1.second) { "temp" }
p cache.exist?("short")
cache.delete("user/42")
p cache.read("user/42")
p cache.fetch_multi("a", "b") { |key| key.upcase }
p cache.read_multi("a", "b", "c")
SELECT * FROM users WHERE id = 42
{id: 42, name: "Ann"}
{id: 42, name: "Ann"}
6
"temp"
true
nil
{"a" => "A", "b" => "B"}
{"a" => "A", "b" => "B"}
If several processes or servers need the same cache, switch the store and keep the rest of the code as it is:
# requires the redis gem and a running Redis server
cache = ActiveSupport::Cache::RedisCacheStore.new(
url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0"),
namespace: "myapp",
expires_in: 1.hour
)
cache.fetch("homepage/stats", race_condition_ttl: 10.seconds) do
compute_stats # expensive
end
race_condition_ttl fights stampedes across processes. When an entry expires, the first process to notice extends the stale value's life for a few seconds and recomputes it. Meanwhile the other processes keep serving the old value instead of all recomputing at once.
Invalidation with versioned keys
Deleting cache entries every time the underlying data changes is error-prone. A more robust approach puts a version in the key, such as an updated_at timestamp, a schema version or a content digest. When the data changes, the key changes. The old entry is simply never read again, and expiry or LRU eviction removes it:
def product_card(product)
key = ["product-card", "v2", product.id, product.updated_at.to_i]
cache.fetch(key) { render_card(product) }
end
ActiveSupport::Cache accepts arrays as keys and joins them into a string. Bumping "v2" to "v3" invalidates every card at once, which is useful when the rendering code changes.
Summary
- Use
@var ||= ...for per-object memoization, anddefined?(@var)orHash#key?whennilorfalseare valid results. - Use a
Hashkeyed by the arguments to cache per-argument results. Never mutate keys. - Add a TTL (with the monotonic clock) for data that goes stale, and a size limit (LRU) for open-ended keys.
- Guard shared caches with a
Mutexto avoid duplicate work. Use per-key locks if computations are slow. - Freeze or dup cached values so callers can't corrupt them.
- For production apps, use
ActiveSupport::Cacheand put versions in keys instead of deleting entries by hand.