Skip to content
Edit this page View source of this page

New to caching? Read How the cache works and follow Cache your first view fragment before this reference.

Mankai

mankai-cache

mankai-cache adds a key-value cache to Hanami apps. You inject the cache as a component, and it keeps entries in the store you choose: memory, files, or a SQL table through mankai-cache-sql.

Use mankai-cache when your app repeats expensive work, such as a slow query, an API call, or rendering a view fragment, and a recent result is good enough. A read that finds a stored value is a hit. A read that finds nothing, or finds an expired value, is a miss. To learn how the cache works, see How the cache works.

The following action caches a book for 10 minutes:

# app/actions/books/show.rb
module Bookshelf
  module Actions
    module Books
      class Show < Bookshelf::Action
        include Deps["cache", "repos.book_repo"]

        def handle(request, response)
          id = request.params[:id]
          response[:book] = cache.fetch(["books", id], expires_in: 600) { book_repo.find(id)&.to_h }
        end
      end
    end
  end
end

The cache stores the block's return value, so the value must be something the serializer can encode. Cache plain data, such as book.to_h, instead of the struct that a repository returns. For details, see Serializers.

Installation

To add the cache to a Hanami app, follow these steps:

  1. Add the gem to your Gemfile:

    # Gemfile
    gem "mankai-cache"
    
  2. Install the bundle:

    bundle install
    
  3. Create config/providers/cache.rb and register the provider:

    # 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
        config.expires_in = 3600
      end
    end
    

    The provider registers a Mankai::Cache instance as the "cache" component. In this configuration, the test environment uses the memory store, and every other environment uses the file store. Entries expire after one hour unless you pass another lifetime.

  4. In each class that uses the cache, add include Deps["cache"].

To cache view fragments, also set up the cache view helper.

Configuration

The provider accepts the following settings:

Setting Default Description
store :memory The store for entries. Accepts :memory, :file, or :null; a store object that responds to read and write; or a factory that the provider calls with the container, such as Mankai::Cache::SQL.store(...). Any other value raises ConfigurationError.
store_options {} Keyword options for a built-in store: size: for :memory, in bytes (default 32 * 1024 * 1024), or path: for :file (default: the app's tmp/cache). The provider ignores them for store objects and factories.
namespace nil A prefix for every key, for example to share a store between apps. With "bookshelf", the key "books/1" is stored as "bookshelf:books/1".
expires_in nil The default lifetime of entries, in seconds. If nil, entries stay until the store evicts or deletes them.
serializer :marshal How values become bytes: :marshal, :json, or an object with dump and load. See Serializers.
compress true If true, compresses values with Deflate when that makes them smaller.
compress_threshold 1024 The smallest value, in bytes, that the cache tries to compress.
max_key_size 250 The longest stored key, in bytes. The cache shortens longer keys and adds a SHA-256 digest suffix.
notifications_key "notifications" The container key of the notifications bus that receives events. If the container has no such key, the cache publishes no events.
clock -> { Time.now } An object whose call returns the current Time. The cache uses it to compute expiry.

To use the cache outside Hanami, create an instance directly. Mankai::Cache.new accepts store:, namespace:, expires_in:, max_key_size:, clock:, and a coder: built with Mankai::Cache::Coder.new(serializer:, compress:, compress_threshold:). Its default store is a memory store:

cache = Mankai::Cache.new(store: Mankai::Cache::Stores::Memory.new, expires_in: 300)

API reference

Methods

The following table lists the methods of Mankai::Cache:

Method Returns Description
read(key, version:) The value, or nil on a miss Reads one entry.
read_multi(*keys, version:) A Hash of the values found, by the keys given Reads several entries. Misses are left out.
write(key, value, expires_in:, expires_at:, version:) true Writes one entry.
write_multi(values, expires_in:, expires_at:, version:) true Writes every entry in the values hash.
fetch(key, force:, skip_nil:, race_condition_ttl:, expires_in:, expires_at:, version:) { ... } The stored or computed value Returns the stored value on a hit. On a miss, runs the block with the key, stores its result, and returns it. Raises ArgumentError without a block.
fetch_multi(*keys, skip_nil:, expires_in:, expires_at:, version:) { ... } A Hash of values, by key, in the order given Like fetch for several keys. Runs the block once with each missing key.
exist?(key, version:) true or false Checks for a usable entry without reading its value.
delete(key) true if there was an entry Deletes one entry.
delete_multi(keys) The number of entries deleted Deletes several entries.
increment(key, amount = 1, expires_in:) The new Integer value Adds to an integer entry, starting from 0. An existing entry keeps its expiry; a new entry gets expires_in.
decrement(key, amount = 1, expires_in:) The new Integer value Subtracts from an integer entry.
clear true Deletes every entry in the store, including entries that other namespaces wrote.
cleanup The number of entries deleted Deletes expired entries from stores that keep them until asked. On the SQL store, runs an expiry pass.
close Not specified Releases the store's resources. The provider calls it when it stops.
key_for(key) String Returns the string that the cache stores the key under.

The following examples show the main methods:

cache.write("greeting", "hello", expires_in: 60)
cache.read("greeting")                                  # => "hello"
cache.exist?("greeting")                                # => true
cache.delete("greeting")                                # => true

cache.fetch(["books", id]) { book_repo.find(id).to_h }  # runs the block only on a miss
cache.fetch(key, force: true) { ... }                   # always runs the block and stores the result
cache.fetch(key, skip_nil: true) { ... }                # doesn't store nil

cache.write_multi({"a" => 1, "b" => 2})
cache.read_multi("a", "b", "c")                         # => {"a" => 1, "b" => 2}
cache.fetch_multi("a", "b", "c") { |key| key * 2 }      # => {"a" => 1, "b" => 2, "c" => "cc"}
cache.delete_multi(["a", "b"])                          # => 2

cache.increment("signups")                              # => 1
cache.decrement("signups")                              # => 0

Options

The following table lists the keyword options that the methods accept:

Option Accepted by Description
expires_in: write, write_multi, fetch, fetch_multi, increment Seconds until the entry expires. Defaults to the cache's expires_in.
expires_at: write, write_multi, fetch, fetch_multi A Time when the entry expires. Takes precedence over expires_in:.
version: read, read_multi, write, write_multi, fetch, fetch_multi, exist? The entry's version. See Versions.
force: fetch If true, runs the block even on a hit and stores the result.
skip_nil: fetch, fetch_multi If true, doesn't store a nil result.
race_condition_ttl: fetch Seconds to keep serving an expired value while one caller recomputes it. See Stampede protection.

Keys

A key can be any of the following:

  • A String, Symbol, number, boolean, nil, Time, or Date.
  • An object that responds to cache_key. The cache uses the return value of cache_key.
  • An Array or Hash of these.

The cache joins array parts with /, so ["books", 1, :en] is stored as "books/1/en". It sorts hash pairs by name and joins them as name=value, so {page: 2, locale: :en} is stored as "locale=en/page=2". It converts a Time to UTC.

Any other key raises Mankai::Cache::InvalidKeyError. Most objects' to_s includes a memory address, so a key built from it never matches a stored entry. The cache raises an error instead of missing every time.

Versions

If you write an entry with a version, reading it with a different version, or with no version, returns a miss. The cache compares versions as strings, so version: 3 and version: "3" match:

cache.write("settings", settings, version: 3)
cache.read("settings", version: 3)   # => settings
cache.read("settings", version: 4)   # => nil

An object that defines cache_version supplies its own version. Its key stays the same while its version changes, so updating the record replaces the entry instead of adding a new one. If an array key has several versioned parts, the cache joins their versions with /. A version: option overrides the key's version.

In a Hanami app, add the methods to the struct class:

# 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) { ... } recomputes the value after the book is updated. The struct is only the key; the cached value is whatever the block returns.

Stampede protection

When a popular entry expires, every request that misses it recomputes the value at the same time. This is called a cache stampede. To prevent it, pass race_condition_ttl: to fetch:

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

The first caller that finds the expired entry writes the old value back for race_condition_ttl seconds, and then recomputes it. Other callers get the old value until the new one is stored.

cache view helper

The cache view helper caches part of a template, called a view fragment. To set it up, follow these steps:

  1. Include Mankai::Cache::ViewHelpers in app/views/helpers.rb, which Hanami generates:

    # app/views/helpers.rb
    module Bookshelf
      module Views
        module Helpers
          include Mankai::Cache::ViewHelpers
        end
      end
    end
    
  2. Inject the cache into the view context in app/views/context.rb. The helper reads the cache from there:

    # 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 helper:

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

cache(key, **options) accepts the same options as fetch and returns the HTML marked as safe. It stores entries under "views/", so the preceding fragment for book 1 is stored as "views/v1/books/1". If the view context has no cache method, the helper raises Mankai::Cache::ConfigurationError.

The key follows the same key rules as fetch. In the preceding example, book needs a cache_key method, or the helper raises InvalidKeyError. If the struct has no cache_key, build the key from its ID and update time: cache ["v1", "books", book.id, book.updated_at].

The key must change whenever the HTML changes. Build it from the following parts:

  • The records that the HTML shows, with their versions or update times.
  • Anything else that the HTML depends on, such as the locale or the current user's role.
  • A version string that you change when you edit the markup, like "v1" in the preceding example. The helper doesn't track template changes.

To cache whole responses, use HTTP caching instead. Hanami responses already provide cache_control, expires, and fresh(etag:, last_modified:).

Stores

The following table compares the stores:

Property Memory File SQL (mankai-cache-sql) Null
Shared between processes No On one machine Yes Not applicable
Survives restarts No Yes Yes Not applicable
Removes entries Evicts the least recently used entries when over size Only when overwritten or on cleanup Deletes the oldest entries by age, count, and size Not applicable
Atomic increment Within one process Across processes on one machine Across servers Not applicable
Suited to Development, tests, single-process apps One server Several servers Turning caching off

Memory (Stores::Memory.new(size: 32 * 1024 * 1024)) keeps entries in a hash in the process. When the store grows past size bytes, it evicts the least recently used entries until it's down to three-quarters of size. It keeps entries encoded, so changing a value that you read never changes the cached copy. Each process, such as each Puma worker, has its own memory store.

File (Stores::File.new(path: "tmp/cache")) keeps one file per entry. It names each file by the key's SHA-256 digest, in two levels of subdirectories (ab/cd/abcd...). Writes go to a temporary file that the store renames into place, and increment holds a lock file. The store deletes an entry only when you overwrite or delete it, or when cleanup runs. cleanup also deletes temporary and lock files that a crash left behind. With the provider, the path defaults to the app's tmp/cache. Outside Hanami, path: is required.

Null (Stores::Null.new) keeps nothing, so every read misses and fetch always runs its block. increment returns amount every time.

SQL keeps entries in a database table. When entries are older than max_age (two weeks by default), or the table exceeds max_entries or max_size, the store deletes the oldest entries in batches. See mankai-cache-sql.

Store interface

A store keeps encoded entries, which are binary strings, under string keys. The cache handles keys, expiry checks, versions, serialization, and compression. A custom store includes Mankai::Cache::Store and implements the following methods:

read(key)                       # => String or nil
write(key, data, expires_at:)   # => true; expires_at is seconds since the epoch, or nil
delete(key)                     # => whether there was an entry
update(key) { |data| ... }      # atomically yields the current data (or nil) and writes the
                                #   [data, expires_at] that the block returns
clear                           # deletes every entry
cleanup(now)                    # deletes entries expired at `now`, if the store keeps them

A store can use expires_at to evict entries, but it doesn't have to: the cache checks expiry when it reads. Mankai::Cache::Store provides default read_multi, write_multi, and delete_multi methods that handle one key at a time, and a close method that does nothing. Override them where your store can do better.

To check a custom store, see Testing helpers.

Serializers

The serializer turns a value into bytes and back. The following table compares the built-in serializers:

Serializer Round-trips Security
:marshal (default) String, numbers, Symbol, Time, Array, Hash, and instances of your own named classes. Not ROM structs, Proc, or IO objects. Anyone who can write to the store can make the app create arbitrary Ruby objects. Keep the store private to the app.
:json Plain data only. Hash keys, symbols, and times come back as strings. Other objects are stored as their to_s. Safe to read from a store that other systems can write to.

The :marshal serializer can't store ROM structs, which are the objects that Hanami repositories return. ROM builds struct classes at runtime, so Marshal can't refer to them by name. Writing one raises Mankai::Cache::SerializationError. Cache plain data instead:

cache.fetch(["books", id]) { book_repo.find(id).to_h }        # a Hash
cache.fetch(["books", "count"]) { book_repo.count }           # an Integer

After a deploy, reading an entry whose class no longer exists returns a miss.

A custom serializer is any object with dump(value), which returns a String, and load(string). To reject a value, raise TypeError from dump. The cache turns it into SerializationError.

Events

The cache publishes events on the app's notifications bus. Hanami registers the bus as the "notifications" component, a dry-monitor notifier. Event names are symbols. The following table lists the events and their payloads:

Event Payload
:"mankai.cache.read" key:, hit:
:"mankai.cache.read_multi" keys:, hits: (the keys that hit)
:"mankai.cache.fetch" key:, hit:
:"mankai.cache.write" key:
:"mankai.cache.write_multi" keys:
:"mankai.cache.delete" key:
:"mankai.cache.delete_multi" keys:
:"mankai.cache.increment" key:, amount: (negative for decrement)
:"mankai.cache.clear" None besides time:
:"mankai.cache.cleanup" None besides time:

Keys in payloads are the stored strings, after namespacing. Every event also includes time:, in milliseconds. When the operation raises an error, the event includes exception: and might not include hit:.

The provider registers the events when it starts. Subscribing earlier raises Dry::Events::InvalidSubscriberError, so subscribe 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

To read a key that might be missing, use event.payload[:key]. event[:key] raises KeyError when the payload doesn't include the key.

Errors

All errors inherit from Mankai::Cache::Error. The following table lists them:

Error Raised when
Mankai::Cache::ConfigurationError The provider or a store is set up incorrectly: an unknown store or serializer, a :file store without a path outside Hanami, or a view context without the cache for the cache helper.
Mankai::Cache::InvalidKeyError A key part isn't a String, Symbol, number, boolean, nil, Time, Date, Array, or Hash, and has no cache_key method.
Mankai::Cache::SerializationError The serializer can't dump a value, such as a ROM struct with :marshal. The original error is its cause.

If the cache can't decode stored data, for example because the class was removed or the data is corrupted, the read returns a miss instead of raising an error.

Testing helpers

The memory store starts empty in each process. To keep examples from reading each other's entries, clear the cache before each example:

# spec/support/cache.rb
RSpec.configure do |config|
  config.before { Hanami.app["cache"].clear }
end

To test expiry without sleeping, create a cache with a clock that you control, and pass it to the object under test. The clock is any object whose call returns a Time:

now = Time.utc(2026, 1, 1, 12)
cache = Mankai::Cache.new(clock: -> { now })

cache.write("a", 1, expires_in: 60)
now += 61
cache.read("a")   # => nil

To check a custom store against the store interface, use the shared examples. Pass cleanup: false if your store's cleanup doesn't delete entries by their expiry time:

require "mankai/cache/testing/store_examples"

RSpec.describe MyStore do
  subject(:store) { MyStore.new }

  it_behaves_like "a mankai-cache store"
end

For more testing patterns, see Test the cache.