Skip to content
Edit this page View source of this page

Share the cache with the SQL store

The SQL store from mankai-cache-sql keeps cache entries in a database table, so every process and server that uses the database shares them. This guide shows how to install the SQL store, use a separate database for it, and tune how it deletes old entries. For every option and how the store works, see the mankai-cache-sql reference.

Before you begin

You need the following:

  • A Hanami app with the cache provider registered. See Installation.
  • A configured database (DATABASE_URL) on PostgreSQL, MySQL 8 or later, MariaDB, or SQLite.

Install the SQL store

  1. Add both gems to your Gemfile:

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

    bundle install
    
  3. Add the table's migration to your app:

    bundle exec ruby -e 'require "mankai/cache/sql"; Mankai::Cache::SQL::Migration.install(root: ".")'
    

    The command prints the path of the new file, such as Created config/db/migrate/20260101120000_create_mankai_cache_entries.rb.

  4. Run the migration:

    bundle exec hanami db migrate
    

    The database now has a cache_entries table.

  5. In config/providers/cache.rb, select the SQL store for every environment except test:

    # config/providers/cache.rb
    require "mankai/cache"
    require "mankai/cache/sql"
    
    Hanami.app.register_provider(:cache, from: :mankai_cache) do
      configure do |config|
        config.store = Hanami.env?(:test) ? :memory : Mankai::Cache::SQL.store(max_age: 7 * 86_400)
      end
    end
    

    With max_age: 7 * 86_400, the store deletes each entry a week after its last write.

  6. Start the app and load a page that writes to the cache. The cache_entries table gets a row for each entry.

The store deletes old entries in the background, so you don't need a cleanup job.

Set a busy handler for SQLite

If you use SQLite, set a busy handler. By default, a SQLite connection that waits for a database lock holds Ruby's global VM lock (GVL), which stops every other thread in the process for up to 5 seconds. To let other threads run while the connection waits, add an after_connect option to the database provider:

# config/providers/db.rb
Hanami.app.configure_provider :db do
  config.gateway :default do |gw|
    gw.connection_options after_connect: ->(conn) { conn.busy_handler_timeout = 5000 }
  end
end

Until the connection has an after_connect option, mankai-cache-sql prints a warning to standard error when it creates the store.

Use a separate database

A cache table grows quickly, and its rows change often, so you might want to keep it out of the app's main database. Hanami connects one database per gateway and reads a gateway's URL from DATABASE_URL__GATEWAY, where GATEWAY is the gateway name in uppercase.

  1. Add the cache database's URL to .env:

    # .env
    DATABASE_URL=postgres://localhost/bookshelf
    DATABASE_URL__CACHE=postgres://localhost/bookshelf_cache
    
  2. Install the migration for the cache gateway. hanami db migrate runs each gateway's migrations from its own directory, so the command writes the file to config/db/cache_migrate:

    bundle exec ruby -e 'require "mankai/cache/sql"; Mankai::Cache::SQL::Migration.install(root: ".", gateway: :cache)'
    
  3. Create and migrate the databases:

    bundle exec hanami db create
    bundle exec hanami db migrate
    
  4. Point the store at the gateway:

    config.store = Mankai::Cache::SQL.store(gateway: "db.gateways.cache")
    

In the test environment, Hanami adds _test to the database names in these URLs.

Tune expiry

The store deletes old entries in passes. After every expiry_batch_size / 2 writes, a pass examines the oldest expiry_batch_size entries and deletes them by age or by the table's size. Adjust the options as follows:

  • Set max_age at least as long as your longest expires_in. max_age counts from an entry's last write and takes precedence over expires_in, so with the default of two weeks, an entry written with expires_in: 30 * 86_400 is still deleted after two weeks. To delete entries only for space, set max_age: nil together with max_entries or max_size.
  • To cap the table, set max_entries or max_size (in bytes). The store estimates both, so the table stays near, not exactly at, the limit.
  • If a few keys are rewritten very often, such as counters, set max_entries or max_size, or raise expiry_batch_size above the number of those keys. Otherwise, they can fill every pass and stop expiry by age.
  • To run expiry in the writing thread instead of a background thread, set expiry: :inline.

The following store keeps entries for at most 30 days and caps the table at about 500 MB:

config.store = Mankai::Cache::SQL.store(max_age: 30 * 86_400, max_size: 500 * 1024 * 1024)

To run an expiry pass immediately, call Hanami.app["cache"].cleanup. For the details of each caveat, see Expiry caveats.

Test against the SQL store

To run your tests against the table instead of the memory store, follow these steps:

  1. In config/providers/cache.rb, use the SQL store in every environment:

    config.store = Mankai::Cache::SQL.store
    
  2. Create and migrate the test database:

    HANAMI_ENV=test bundle exec hanami db prepare
    
  3. Clear the cache before each example:

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

What's next