
Rails Caching With Solid Cache: Keys, Expiry, and Stampedes
We tested two things which hurt with caching in Rails, many small reads from a database cache and many requests missing the same key, on Rails 8.1 with Solid Cache on our local Postgres.
We wrote 40 cards of 2 kB into Solid Cache and read them back. One by one it made 41 queries and took 3.15 ms, with read_multi it was 1 query and 0.42 ms, about seven times faster for changing one line, and this is on a database sitting on the same machine, over network the difference will be only bigger. In views the cached true on collection render does this for you. fetch_multi on 40 keys, 2 queries when cold, 1 when warm.
<%= render partial: "products/card", collection: @products, cached: true %>
totals = Rails.cache.fetch_multi(*accounts, expires_in: 10.minutes) do |account|
account.invoices.unpaid.sum(:amount_cents)
end
Stampede we tested like this, one key which dies in 1 second and costs 300 ms to build, we let it die and attack with 50 threads, how many times do you think it was computed? 50. All of them, together, doing the same job like nobody sees each other. Then we put race_condition_ttl 10 seconds near expires_in and repeated: 1 computing, and the 49 others took the old value and went, only this was memory store in single process, on Solid Cache we didn't try it, so for us now each expensive key has this option and the very heavy ones a scheduled job writes, then nobody waits on the page.
Rails.cache.fetch("stats/daily", expires_in: 5.minutes,
race_condition_ttl: 10.seconds) do
DailyStats.compute
end
See also: scheduled job and Active Record patterns.