Skip to content
Edit this page View source of this page

Choose a store and serializer

The cache keeps its entries in a store, and a serializer turns values into bytes. This guide shows how to choose a store for each environment, configure it, turn caching off, choose a serializer, and write a custom store. For a comparison table of the stores and every setting, see Stores in the reference.

Choose a store

Choose a store based on where your app runs:

  • If the app runs as one process, or you're developing locally, use the memory store (:memory). It's the fastest, but each process has its own entries, and they disappear on restart.
  • If the app runs several processes on one server, use the file store (:file). Every process on the machine shares it, and entries survive restarts.
  • If the app runs on several servers, or several hosts must see the same entries, use the SQL store. Every server that uses the database shares it. See Share the cache with the SQL store.
  • In tests, use the memory store. It keeps values, so a test can check that a value was stored and reused. See Test the cache.

To select a store, set config.store in config/providers/cache.rb. The following provider uses the memory store in tests and the file store everywhere else:

# 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
end

config.store accepts :memory, :file, :null, a store object, or a factory such as Mankai::Cache::SQL.store(...).

Set store options

The built-in stores take options through config.store_options:

  • To change the memory store's size limit, set size: in bytes. The default is 32 MiB. When the store grows past this size, it evicts the least recently used entries:

    config.store = :memory
    config.store_options = {size: 64 * 1024 * 1024}
    
  • To change the file store's directory, set path:. The default is the app's tmp/cache:

    config.store = :file
    config.store_options = {path: "/var/cache/bookshelf"}
    

Clean up the file store

The file store deletes an entry's file only when you overwrite or delete the entry. Expired files stay on disk. If your app writes many short-lived keys, run cache.cleanup regularly, for example from a recurring job:

Hanami.app["cache"].cleanup   # => the number of expired entries deleted

cleanup also deletes temporary and lock files that a crash left behind. The memory and SQL stores remove old entries on their own.

Turn caching off

To turn caching off in an environment without changing code, use the null store. It keeps nothing, so every read misses and fetch always runs its block:

config.store = Hanami.env?(:development) ? :null : :file

Don't use the null store in tests that check whether a value was stored or reused; those tests fail because nothing is kept. Use the memory store in tests instead.

Share one store between apps

If several apps use the same store, such as one SQL database, give each app a namespace. The cache adds the namespace to every key, so the apps' entries don't collide:

config.namespace = "bookshelf"

With this setting, the key "books/1" is stored as "bookshelf:books/1". cache.clear still deletes every entry in the store, including other apps' entries.

Choose a serializer

The serializer turns a value into bytes and back. Choose one based on who can write to the store:

  • If only your app can write to the store, keep the default :marshal serializer. It round-trips most Ruby values, including instances of your own named classes.
  • If anything else can write to the store, use :json. Loading Marshal data can create arbitrary Ruby objects, so anyone who can write to a :marshal store can make your app create objects of their choice. :json round-trips only plain data: hash keys, symbols, and times come back as strings.

To select a serializer, set config.serializer:

config.serializer = :json

Neither serializer can store the structs that Hanami repositories return. Cache book.to_h instead. For what each serializer round-trips, and how to write your own, see Serializers.

Changing the serializer doesn't migrate existing entries. Entries that the new serializer can't decode read as misses, and the cache recomputes them.

Write a custom store

To keep entries somewhere else, such as Redis, write a custom store.

  1. Create a class that includes Mankai::Cache::Store and implements read, write, delete, update, clear, and cleanup. The following store keeps entries in a hash, as a minimal example:

    class HashStore
      include Mankai::Cache::Store
    
      def initialize
        @entries = {}
        @lock = Monitor.new
      end
    
      def read(key) = @lock.synchronize { @entries[key]&.first }
    
      def write(key, data, expires_at:)
        @lock.synchronize { @entries[key] = [data, expires_at] }
        true
      end
    
      def delete(key) = @lock.synchronize { !@entries.delete(key).nil? }
    
      def update(key)
        @lock.synchronize do
          data, expires_at = yield(read(key))
          write(key, data, expires_at: expires_at)
        end
      end
    
      def clear
        @lock.synchronize { @entries.clear }
        true
      end
    
      def cleanup(now)
        @lock.synchronize do
          expired = @entries.select { |_, (_, expires_at)| expires_at && expires_at <= now }.keys
          expired.each { |key| @entries.delete(key) }
          expired.size
        end
      end
    end
    

    For what each method receives and returns, see Store interface.

  2. Check the store against the shared examples:

    require "mankai/cache/testing/store_examples"
    
    RSpec.describe HashStore do
      subject(:store) { HashStore.new }
    
      it_behaves_like "a mankai-cache store"
    end
    

    Every example passes when the store follows the interface.

  3. Pass an instance to the provider:

    config.store = HashStore.new
    

If the store needs the app's container, for example to look up a connection, pass a factory instead: an object whose call receives the container and returns the store.

What's next