New to caching? Read How the cache works and follow Cache your first view fragment before this reference.
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:
-
Add both gems to your
Gemfile: -
Install the bundle:
-
Add the table's migration to your app:
The command prints
Created config/db/migrate/<timestamp>_create_mankai_cache_entries.rb. If the app already has the migration, it printsMigration already existsand changes nothing. -
Run the migration:
-
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 endIn this configuration, the test environment uses the memory store. For the other options, see Options.
-
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_agecounts from the entry's last write (created_at), not from itsexpires_in. An entry written withexpires_in: 30 * 86_400is still deleted aftermax_age. Setmax_ageat least as long as your longestexpires_in, or set it tonil.- The cache checks
expires_inwhen 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_sizeentries, 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 recentcreated_at. If the whole batch is hot keys, passes delete nothing by age. Entries behind them are deleted only aftermax_entriesormax_sizeis reached. If you have a few hot keys, setmax_entriesormax_size, or raiseexpiry_batch_sizeabove the number of hot keys. - With
max_entriesormax_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_hashcolumn, 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 CONFLICTon PostgreSQL and SQLite, andON DUPLICATE KEYon MySQL and MariaDB. - Increments.
incrementlocks the row withFOR 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 / 2writes, an expiry pass examines the oldestexpiry_batch_sizeentries by row ID, so no index on times is needed. If the table is overmax_entriesormax_size, the pass deletes all of them. Otherwise, it deletes the ones older thanmax_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:
clear deletes every row in the table.
Outside Hanami, create the table with Migration.apply and pass the database to the store: