0
0
RailsHow-ToBeginner · 4 min read

How to Use Low Level Caching in Ruby on Rails

Use Rails.cache.fetch to store and retrieve data with low level caching in Rails. Wrap your expensive code inside the block passed to fetch, which caches the result and returns it on subsequent calls.
📐

Syntax

The basic syntax for low level caching in Rails uses Rails.cache.fetch. It takes a cache key and a block. If the key exists in cache, it returns the cached value. Otherwise, it runs the block, stores the result in cache, and returns it.

  • key: A unique string to identify the cached data.
  • expires_in: Optional time duration to expire the cache.
  • block: Code that generates the data to cache.
ruby
Rails.cache.fetch('unique_cache_key', expires_in: 5.minutes) do
  # Expensive operation here
  expensive_method_call
end
💻

Example

This example demonstrates caching the result of a method that simulates a slow operation. The first call runs the method and caches the result. Subsequent calls return the cached value instantly.

ruby
def slow_operation
  sleep 2 # Simulate slow work
  "Result at #{Time.now}"
end

puts "First call:"
result1 = Rails.cache.fetch('slow_op', expires_in: 10.seconds) do
  slow_operation
end
puts result1

puts "Second call (cached):"
result2 = Rails.cache.fetch('slow_op', expires_in: 10.seconds) do
  slow_operation
end
puts result2
Output
First call: Result at 2024-06-01 12:00:00 +0000 Second call (cached): Result at 2024-06-01 12:00:00 +0000
⚠️

Common Pitfalls

Common mistakes include using non-unique or dynamic keys that cause cache misses, forgetting to set expiration leading to stale data, and caching mutable objects that change unexpectedly.

Always use stable, unique keys and set expires_in to avoid stale cache. Avoid caching objects that can be modified after caching.

ruby
wrong_key = "user_#{Time.now.to_i}"
# This key changes every second, so cache never hits
Rails.cache.fetch(wrong_key) do
  expensive_method_call
end

# Correct approach: use a stable key
Rails.cache.fetch('user_123_profile', expires_in: 5.minutes) do
  expensive_method_call
end
📊

Quick Reference

MethodDescription
Rails.cache.fetch(key, options) { block }Fetches cached data or runs block to cache result
Rails.cache.write(key, value, options)Writes data to cache explicitly
Rails.cache.read(key)Reads data from cache without block
Rails.cache.delete(key)Removes data from cache
expires_in: timeOption to set cache expiration duration

Key Takeaways

Use Rails.cache.fetch with a unique key and block to implement low level caching.
Set expires_in option to avoid stale cached data.
Use stable keys that do not change dynamically to ensure cache hits.
Avoid caching mutable objects that can change after caching.
Low level caching improves performance by storing expensive results for reuse.