How to Use Caching in Rails for Faster Web Apps
In Rails, you use
caches_action, caches_page, or low-level caching methods like Rails.cache.fetch to store data or views temporarily. This reduces repeated work and speeds up your app by reusing stored results instead of recalculating them.Syntax
Rails provides several caching methods:
Rails.cache.fetch(key) { block }: Stores and retrieves cached data by a key.caches_action :action_name: Caches the entire output of a controller action.caches_page :action_name: Caches the full HTML page for an action (legacy, less used).
Use Rails.cache.fetch for flexible, low-level caching of any data.
ruby
Rails.cache.fetch('my_key') do
# Expensive operation
User.count
endExample
This example shows how to cache a list of users count to avoid hitting the database repeatedly.
ruby
class UsersController < ApplicationController def index @user_count = Rails.cache.fetch('user_count', expires_in: 5.minutes) do User.count end end end
Output
When you visit the index page, the first request queries the database and caches the count. Subsequent requests within 5 minutes use the cached count, speeding up response time.
Common Pitfalls
Common mistakes when using caching in Rails include:
- Not setting expiration times, causing stale data.
- Using page caching (
caches_page) in apps with dynamic content or authentication. - Forgetting to expire or clear cache when data changes.
- Over-caching complex objects that consume too much memory.
Always plan cache expiration and invalidation carefully.
ruby
## Wrong: No expiration, stale data Rails.cache.fetch('user_count') { User.count } ## Right: Set expiration to refresh cache Rails.cache.fetch('user_count', expires_in: 10.minutes) { User.count }
Quick Reference
| Caching Method | Use Case | Notes |
|---|---|---|
| Rails.cache.fetch | Cache any data with a key | Flexible, supports expiration |
| caches_action | Cache full controller action output | Good for static or rarely changing pages |
| caches_page | Cache full HTML page | Legacy, not recommended for dynamic content |
| expire_fragment | Expire cached fragments | Use to clear cache when data changes |
Key Takeaways
Use Rails.cache.fetch with expiration to cache data safely and efficiently.
Avoid page caching for dynamic or user-specific content.
Always plan cache expiration and invalidation to prevent stale data.
Use action caching for full action output when content changes infrequently.
Test caching behavior to ensure it improves performance without breaking updates.