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-sql

mankai-cache-sql is a SQL store for mankai-cache. It keeps cache entries in a database table, so every process and server that uses the database shares them. It supports PostgreSQL, MySQL 8 and later, MariaDB, and SQLite.

Use the SQL store when several processes, such as Puma workers, or several hosts must see the same cache. If your app runs as one process, or on one server, the memory or file store in mankai-cache is enough. For a step-by-step guide, see Share the cache with the SQL store.

Installation

Before you begin, make sure that your Hanami app has a configured database (DATABASE_URL). The store uses the app's default database gateway.

To install the SQL store, follow these steps:

  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 Created config/db/migrate/<timestamp>_create_mankai_cache_entries.rb. If the app already has the migration, it prints Migration already exists and changes nothing.

  4. Run the migration:

    bundle exec hanami db migrate
    
  5. In config/providers/cache.rb, select the SQL store:

    # 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
    

    In this configuration, the test environment uses the memory store. For the other options, see Options.

  6. If you use SQLite, set a busy handler.

The migration is a file in your app, so you can edit it. It's idempotent: if the table exists, the migration leaves it alone. To use a different table name, pass the same table: option, for example table: :my_cache, to both Migration.install and Mankai::Cache::SQL.store.

SQLite busy handler

By default, a SQLite connection that waits for a database lock also holds Ruby's global VM lock (GVL). While it waits, for up to 5 seconds, every other thread in the process stops, including web requests and background expiry. To let other threads run while the connection waits, set a busy handler in 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

mankai-cache-sql doesn't change your connection settings. If a SQLite connection has no after_connect option, the gem prints a warning to standard error when it creates the store.

Options

Mankai::Cache::SQL.store accepts the following options:

Option Default Description
gateway "db.gateway" A container key, a ROM gateway, or a Sequel::Database. For a separate database, use a key such as "db.gateways.cache".
table :cache_entries The table name. Use the same table: as Migration.install.
max_age 14 * 86_400 (two weeks) The maximum age of an entry, in seconds since its last write. Expiry deletes older entries regardless of their expires_in. If nil, entries stay until max_entries or max_size requires room.
max_entries nil The approximate maximum number of entries. If nil, there's no limit.
max_size nil The approximate maximum number of bytes of keys and values. If nil, there's no limit.
expiry_batch_size 100 The number of oldest entries that each expiry pass examines. A pass runs every expiry_batch_size / 2 writes.
expiry :thread Where expiry passes run: :thread runs them in a background thread, and :inline runs them in the writing thread.
clock -> { Time.now } An object whose call returns the current Time. The store uses it for created_at and max_age.
on_error Prints a warning to standard error An object whose call receives each error that a background expiry pass raises.

When the provider starts, an unknown option raises ArgumentError, and an invalid gateway or expiry raises Mankai::Cache::ConfigurationError.

For a separate cache database, see Use a separate database.

Expiry caveats

The following caveats apply to expiry:

  • max_age counts from the entry's last write (created_at), not from its expires_in. An entry written with expires_in: 30 * 86_400 is still deleted after max_age. Set max_age at least as long as your longest expires_in, or set it to nil.
  • The cache checks expires_in when it reads. An expired entry stays in the table until an expiry pass deletes it by age or size.
  • A pass examines only the oldest expiry_batch_size entries, ordered by row ID. An overwritten entry keeps its row ID, so keys that are rewritten often (hot keys), such as a counter or a popular fragment, stay at the front with a recent created_at. If the whole batch is hot keys, passes delete nothing by age. Entries behind them are deleted only after max_entries or max_size is reached. If you have a few hot keys, set max_entries or max_size, or raise expiry_batch_size above the number of hot keys.
  • With max_entries or max_size, a key that was first written long ago might be deleted before newer keys, even if it was overwritten recently.

Migration API

Mankai::Cache::SQL::Migration provides the following methods:

Method Description
install(root:, table: :cache_entries, gateway: nil) Writes the migration into config/db/migrate, or into config/db/<gateway>_migrate for another gateway, unless the app already has it. Returns the migration's path.
render(table: :cache_entries) Returns the migration's source as a String.
apply(db, direction = :up, table: :cache_entries) Applies the migration to a Sequel::Database directly, for tests and apps outside Hanami. Pass :down to drop the table.

How it works

The store works as follows:

  • Lookups. Each row has a key_hash column, the first 8 bytes of the key's SHA-256 digest, with a unique index. Lookups use it, so the index stays small however long keys are. The store also keeps the full key and compares it on read.
  • Writes. Each write is one upsert, for one entry or many. The store uses ON CONFLICT on PostgreSQL and SQLite, and ON DUPLICATE KEY on MySQL and MariaDB.
  • Increments. increment locks the row with FOR UPDATE, or with an immediate transaction on SQLite. If there's no row yet and another process inserts one first, the increment retries on top of that row.
  • Expiry. The store doesn't delete entries when they expire; the cache checks expiry when it reads. Instead, after every expiry_batch_size / 2 writes, an expiry pass examines the oldest expiry_batch_size entries by row ID, so no index on times is needed. If the table is over max_entries or max_size, the pass deletes all of them. Otherwise, it deletes the ones older than max_age. Passes can delete up to twice as fast as entries are written, so the table stays near its limits.
  • Estimates. To keep checks cheap on large tables, the store estimates the entry count from the difference between the highest and lowest row ID. It estimates the size from that count and the average size of the newest 1,000 entries.

cache.cleanup runs an expiry pass immediately. With expiry: :thread, cache.close waits for a running pass. The provider calls close when it stops.

Testing

You can test with the memory store, as in the installation example. To test against the table instead, use the SQL store in the test environment and clear it before each example:

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

clear deletes every row in the table.

Outside Hanami, create the table with Migration.apply and pass the database to the store:

require "sequel"
require "mankai/cache/sql"

db = Sequel.sqlite
Mankai::Cache::SQL::Migration.apply(db)
cache = Mankai::Cache.new(store: Mankai::Cache::SQL::Store.new(db: db, expiry: :inline))