ruby 85 lines · 3 tabs

Cache Key Versioning with a Single “namespace”

Shared by codesnips Jan 2026
3 tabs
class CacheNamespace
  attr_reader :name

  def initialize(name, store: Rails.cache)
    @name = name.to_s
    @store = store
  end

  def version
    @store.fetch(version_key, expires_in: nil) { 1 }
  end

  def key_for(*parts)
    digest = Digest::SHA1.hexdigest(parts.flatten.join("/"))
    [name, "v#{version}", digest].join(":")
  end

  def bump!
    next_version = @store.increment(version_key)
    return next_version if next_version

    # Key was absent (or not integer-backed): seed it explicitly.
    @store.write(version_key, 2)
    2
  end

  private

  def version_key
    "cache-namespace:#{name}:version"
  end
end
3 files · ruby Explain with highlit

This snippet shows a lightweight way to invalidate large groups of Rails cache entries at once without enumerating or deleting individual keys. The idea is a single indirection: every cache key for a domain is prefixed with a per-namespace version counter stored in the cache store itself. Bumping that counter changes every derived key, so old entries become unreachable and expire naturally under LRU. This is far cheaper than pattern-based deletes, which most stores (including Memcached and Redis at scale) cannot do efficiently.

In CacheNamespace, the class wraps a logical group such as "products" or a tenant scope. #version reads the counter from Rails.cache, seeding it to 1 via fetch when absent so the namespace is always valid on first use. #key_for composes the final cache key from the namespace name, the current version, and the caller-supplied parts, joined with Digest so long or user-derived fragments stay bounded in length. The crucial method is #bump!, which uses the store's atomic increment so concurrent writers never lose an update; when increment returns nil (key not yet present) it falls back to writing an initial value.

In Cacheable concern, the pattern is exposed to models with namespaced_cache, giving each record a stable namespace derived from its class and a scope. cached_fetch delegates to Rails.cache.fetch through the namespace's key_for, and invalidate_cache! simply calls bump!. Because the version lives in the key, invalidation is O(1) regardless of how many entries exist.

In ProductsController, show reads through cached_fetch so repeat requests skip the database, while update calls invalidate_cache! inside the success branch so a single write instantly retires every cached view of that record. The trade-off is that stale keys are not actively purged — they linger until evicted — so this suits high-read, bounded-key workloads rather than unbounded key spaces. A subtle pitfall is forgetting that the version key must itself survive eviction; keeping it small and hot generally keeps it resident. When a whole class of caches must drop together (deploys, schema changes, bulk imports), bumping one shared namespace beats tracking thousands of individual keys.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<form data-controller="query-sync" data-action="change->query-sync#apply">
  <select name="status" class="rounded border p-2">
    <option value="">Any</option>
    <option value="open">Open</option>
    <option value="closed">Closed</option>
  </select>

Filter UI that syncs query params via Stimulus (no front-end router)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Cache Key Versioning with a Single “namespace” — share card
Link copied