ruby erb 73 lines · 3 tabs

Expiring Dashboard Fragment Caches with a Versioned Composite Cache Key in Rails

Shared by codesnips Jul 2026
3 tabs
class DashboardMetrics
  include ActiveModel::Model

  attr_reader :account

  def initialize(account)
    @account = account
  end

  def summary
    scope = account.orders
    row = scope.reorder(nil).pick(
      Arel.sql("COALESCE(SUM(total_cents), 0)"),
      Arel.sql("COUNT(*)"),
      Arel.sql("COUNT(*) FILTER (WHERE status = 'refunded')")
    )

    {
      gross_cents: row[0],
      order_count: row[1],
      refunded_count: row[2]
    }
  end

  def cache_key_with_version
    "dashboard/#{account.id}-#{fingerprint}"
  end

  def cache_key
    "dashboard/#{account.id}"
  end

  private

  def fingerprint
    stamp, count = account.orders.pick(
      Arel.sql("MAX(updated_at)"),
      Arel.sql("COUNT(*)")
    )
    "#{count}-#{stamp&.utc&.to_fs(:usec)}"
  end
end
3 files · ruby, erb Explain with highlit

This snippet shows how an expensive analytics query that powers a dashboard is cached with Rails fragment caching, keyed so that the cache expires automatically when the underlying data changes. The core idea is to never manually delete cache entries; instead the cache key embeds a version derived from the data, so a stale key is simply never read again and the old fragment ages out on its own.

In DashboardMetrics model, the heavy aggregation lives in #summary, which runs a single grouped SUM/COUNT over orders scoped to the account. That query is genuinely expensive, so the value most worth caching is the computed hash. The method #cache_key_with_version is the crux: it combines the account id, the latest orders.updated_at, and the row count. Because the maximum updated_at moves whenever any order is created or touched, and the count moves on inserts and deletes, the composite key changes exactly when the results could change. This is the same principle behind Rails' cache_versioning — the key is a fingerprint of the data, not a timestamp guess.

The DashboardsController fetches metrics but does no caching itself; caching is a view concern here, keeping the controller thin. It passes the plain object to the template.

In dashboard/show.html.erb, the cache helper wraps the expensive fragment and is handed @metrics directly. Rails calls cache_key_with_version on the object to build the fragment key, so the ERB block — including the call to metrics.summary — only executes on a miss. On subsequent requests with unchanged data, Rails serves the stored HTML and the SQL never runs. A one-hour expires_in acts as a safety net against unbounded growth.

The trade-off is a small MAX(updated_at)/COUNT(*) probe on every request, which is far cheaper than the full aggregation and cheaper than rendering. A pitfall to watch: aggregates that depend on other tables (say refunds) must also feed the key, or the fragment can go stale. This pattern shines for read-heavy dashboards where writes are comparatively rare, and pairs naturally with Russian-doll caching when the summary is composed of nested cached pieces.


Related snips

Share this code

Here's the card — post it anywhere.

Expiring Dashboard Fragment Caches with a Versioned Composite Cache Key in Rails — share card
Link copied