Implementing Rails Fragment Cache with Redis and Session Storage

This article explains how to enable Rails fragment caching, use HTML fragment cache helpers, understand cache digests, observe read/write fragment logs, and migrate the cache store from file system to Redis by adding redis-namespace and redis-rails gems, configuring cache_store, and handling cache invalidation on data changes.

Architect
Architect
Architect
Implementing Rails Fragment Cache with Redis and Session Storage

Rails provides a built‑in cache mechanism that stores data in files by default; the article shows how to switch the cache (and session storage) to Redis, referencing the relevant source files in the Rails repository.

To enable caching in the development environment, edit config/environments/development.rb and set config.action_controller.perform_caching = true, then restart the server.

For HTML fragment caching, the tutorial demonstrates wrapping the "Recent Articles" section with the cache helper. Example view code:

.row
- cache do
  .col-md-6
    .panel.panel-default
      .panel-heading
        div 最近的文章
      .panel-body
        - @articles.each do |article|
          p.clearfix
            span.pull-right = datetime article.created_at
            = link_to article.title, article_path(article)

Running the page shows log entries such as Cache digest, Read fragment and Write fragment. The digest is an MD5 hash generated from the fragment name, which identifies the cached HTML.

Cache files are stored under /tmp/cache. Changing the HTML fragment (e.g., renaming "最近的文章" to "最新的文章") changes the digest, causing a new Write fragment entry and regeneration of the cached file.

However, modifying underlying data (adding a new article) does not automatically refresh the fragment unless the first argument to cache changes. By passing @articles as the cache key, the fragment updates when the collection changes, but each request still triggers a database query.

To eliminate the database hit, the cache store is switched to Redis. Add the gems:

gem 'redis-namespace'
gem 'redis-rails'

and configure the cache store in config/application.rb:

config.cache_store = :redis_store, {host: '127.0.0.1', port: 6379, namespace: "rails365"}

Fetch articles with Redis caching:

class HomeController < ApplicationController
  def index
    @articles = Rails.cache.fetch "articles" do
      Article.except_body_with_default.order("id DESC").limit(10).to_a
    end
  end
end

Invalidate the Redis cache when a new article is created:

class Admin::ArticlesController < Admin::BaseController
  def create
    @article = Article.new(article_params)
    Rails.cache.delete "articles"
    # ...
  end
end

After these changes, subsequent page loads retrieve the article list from Redis without executing SQL queries, unless an article is added or updated, which triggers cache invalidation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

cacheRedisRubyFragmentCacheRails
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.