Skip to content
Edit this page View source of this page

Cache data and views

This guide shows how to cache the results of expensive work and view fragments, build keys that change when your data changes, and invalidate stale entries. For the full list of methods and options, see the mankai-cache reference.

Before you begin

Register the cache provider, as described in Installation. The examples use Bookshelf as the app module and assume a books relation with a repos.book_repo repository.

Cache the result of expensive work

  1. Inject the cache into the class that does the work:

    include Deps["cache", "repos.book_repo"]
    
  2. Wrap the work in fetch, with a key and a lifetime in seconds. Return plain data, such as a Hash, instead of a struct:

    def count
      cache.fetch(["books", "count"], expires_in: 300) { book_repo.count }
    end
    
    def find(id)
      cache.fetch(["books", id], expires_in: 600) { book_repo.find(id)&.to_h }
    end
    

The first call runs the block and stores the result. Later calls return the stored value until it expires. To expire an entry at a fixed time, pass expires_at: with a Time instead of expires_in:. To skip storing nil, for example when a record isn't found, pass skip_nil: true.

For why structs can't be cached, see What you can cache.

Use a record as a key

To use a struct directly as a key, define cache_key on its struct class. To replace the entry when the record changes, also define cache_version:

# app/structs/book.rb
module Bookshelf
  module Structs
    class Book < Bookshelf::DB::Struct
      def cache_key = "books/#{id}"
      def cache_version = updated_at.to_i
    end
  end
end

With these methods, cache.fetch(book) { ... } stores the entry under "books/1" for book 1. When the book's updated_at changes, the version changes, so the next fetch misses and recomputes the value. If you don't define cache_key, the cache raises Mankai::Cache::InvalidKeyError for a struct key; build the key from its ID instead, such as ["books", book.id, book.updated_at].

For every type a key can contain, see Keys.

Cache a view fragment

  1. Include Mankai::Cache::ViewHelpers in app/views/helpers.rb:

    # app/views/helpers.rb
    module Bookshelf
      module Views
        module Helpers
          include Mankai::Cache::ViewHelpers
        end
      end
    end
    
  2. Inject the cache into app/views/context.rb:

    # app/views/context.rb
    module Bookshelf
      module Views
        class Context < Hanami::View::Context
          include Deps["cache"]
        end
      end
    end
    
  3. In a template, wrap the fragment in the cache view helper. Include a template version, the records that the fragment shows, and anything else the HTML depends on:

    <% books.each do |book| %>
      <%= cache ["v1", book, locale] do %>
        <%= render "books/card", book: book %>
      <% end %>
    <% end %>
    

    This example assumes that the view exposes books and locale, and that the Book struct defines cache_key and cache_version.

  4. When you change the fragment's markup, change the template version in the key, for example from "v1" to "v2". The helper doesn't track template changes.

The helper accepts the same options as fetch, such as expires_in:. It stores entries under "views/", so they don't collide with your own keys.

Invalidate entries

Choose the cheapest strategy that keeps results correct. The following table compares the strategies:

Strategy Use it when
Delete the key after a write Writes are rare, and you know the key.
Put updated_at or cache_version in the key The record changes often, and you can derive the key from it.
Change a version string in a fragment key You changed the template, and the old HTML can be discarded.
Let the entry expire A short window of stale data is acceptable.

To delete an entry after a write, call delete with the same key that you cached it under:

book_repo.update(id, title: title)
cache.delete(["books", id])

To delete several entries, use delete_multi. cache.clear deletes every entry in the store, including entries that other namespaces wrote, so don't use it to invalidate one feature's data.

When a popular entry expires, every request that misses it recomputes the value at the same time. To let one request recompute while the others get the old value, pass race_condition_ttl: with a few seconds:

cache.fetch("homepage/stats", expires_in: 300, race_condition_ttl: 10) do
  expensive_stats
end

Set race_condition_ttl a little longer than the block takes to run.

Read and write several entries at once

To fetch several entries in one call, use fetch_multi. The block runs once for each missing key, and the result is a Hash in the order of the keys:

cards = cache.fetch_multi(*ids.map { |id| ["books", id, "card"] }) do |key|
  render_card(key[1])
end

In this example, render_card stands for your own method that returns a String. With a store that supports batches, such as the SQL store, fetch_multi reads all keys in one query.

Count events across processes

To keep a counter, use increment and decrement. Each call updates the value atomically and returns the new Integer:

cache.increment(["signups", Date.today], expires_in: 86_400)   # => 1

Whether a counter is shared across processes depends on the store. The SQL store locks the row, so counters are consistent across processes and servers. The file store holds a lock file, so counters are consistent on one machine. The memory store keeps a separate counter in each process.

Log cache hits and misses

The cache publishes an event for each operation. To log hits and misses, subscribe to the :"mankai.cache.fetch" event in the provider's after(:start) callback:

# config/providers/cache.rb
require "mankai/cache"

Hanami.app.register_provider(:cache, from: :mankai_cache) do
  configure do |config|
    config.store = Hanami.env?(:test) ? :memory : :file
  end

  after(:start) do
    target["notifications"].subscribe(:"mankai.cache.fetch") do |event|
      payload = event.payload
      target["logger"].debug(
        "cache #{payload[:hit] ? "hit" : "miss"} #{payload[:key]} (#{payload[:time]}ms)"
      )
    end
  end
end

For each fetch, the log shows whether it was a hit or a miss, the stored key, and how long the call took. For every event and its payload, see Events.

What's next