{
  "id": "ruby",
  "title": "Redis prefetch cache with redis-rb",
  "url": "https://redis.io/docs/latest/develop/use-cases/prefetch-cache/ruby/",
  "summary": "Implement a Redis prefetch cache in Ruby with redis-rb",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-05-14T08:58:05-05:00",
  "children": [],
  "page_type": "content",
  "content_hash": "ecf7396402d039b8b9c96af2f725d805d2b8eb4bd0439a8ab0d0e06490a2987b",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to implement a Redis prefetch cache in Ruby with [`redis-rb`](https://redis.io/docs/latest/develop/clients/ruby). It includes a small local web server built with the Ruby standard library `webrick` so you can watch the cache pre-load at startup, see a background sync worker apply primary mutations within milliseconds, and break the cache to confirm that reads never fall back to the primary."
    },
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Prefetch caching pre-loads a working set of reference data into Redis before the first request arrives, so every read on the request path is a cache hit. A separate sync worker keeps the cache current as the source of truth changes — there is no fall-back to the primary on the read path.\n\nThat gives you:\n\n* Near-100% cache hit ratios for reference and master data\n* Sub-millisecond reads for lookup-heavy paths at peak traffic\n* All reference-data reads offloaded from the primary database\n* Source-database changes propagated into Redis within a few milliseconds\n* A long safety-net TTL that bounds memory if the sync pipeline ever stops\n\nIn this example, each cached category is stored as a Redis hash under a key like `cache:category:{id}`. The hash holds the category fields (`id`, `name`, `display_order`, `featured`, `parent_id`) and the key has a long safety-net TTL that the sync worker refreshes on every add or update event. Delete events remove the cache key outright, so there is no TTL to refresh in that case."
    },
    {
      "id": "how-it-works",
      "title": "How it works",
      "role": "content",
      "text": "The flow has three independent paths:\n\n1. **On startup**, the demo server calls `cache.bulk_load(primary.list_records)`, which pipelines `DEL` + `HSET` + `EXPIRE` for every record in one round trip.\n2. **On every read**, the application calls `cache.get(entity_id)`, which runs `HGETALL` against Redis only. A miss is treated as an error, not a trigger to query the primary.\n3. **On every primary mutation**, the primary appends a change event to an in-process queue. The sync worker thread drains the queue and calls `cache.apply_change(event)`. For an `upsert`, the helper rewrites the cache hash and refreshes the safety-net TTL; for a `delete`, it removes the cache key.\n\nIn a real system the in-process change queue is replaced by a CDC pipeline — [Redis Data Integration](https://redis.io/docs/latest/integrate/redis-data-integration), Debezium plus a lightweight consumer, or an equivalent tool that tails the source's binlog/WAL and pushes events into Redis."
    },
    {
      "id": "the-prefetch-cache-helper",
      "title": "The prefetch-cache helper",
      "role": "content",
      "text": "The `PrefetchCache` class wraps the cache operations\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/prefetch-cache/ruby/cache.rb)):\n\n[code example]"
    },
    {
      "id": "data-model",
      "title": "Data model",
      "role": "content",
      "text": "Each cached category is stored in a Redis hash:\n\n[code example]\n\nThe implementation uses:\n\n* [`HSET`](https://redis.io/docs/latest/commands/hset) + [`EXPIRE`](https://redis.io/docs/latest/commands/expire), pipelined, for the bulk load and every sync event\n* [`HGETALL`](https://redis.io/docs/latest/commands/hgetall) on the read path\n* [`DEL`](https://redis.io/docs/latest/commands/del) for sync-delete events and explicit invalidation\n* [`SCAN`](https://redis.io/docs/latest/commands/scan) to enumerate the cached keyspace and to clear the prefix\n* [`TTL`](https://redis.io/docs/latest/commands/ttl) to surface remaining safety-net time in the demo UI"
    },
    {
      "id": "bulk-load-on-startup",
      "title": "Bulk load on startup",
      "role": "content",
      "text": "The `bulk_load` method pipelines a `DEL` + `HSET` + `EXPIRE` triple for every record. The pipeline is sent in a single round trip, so loading thousands of records takes one network RTT plus the time Redis spends executing the commands locally — typically tens of milliseconds even for a large reference table:\n\n[code example]\n\nThe `pipelined` block sends every command in one network round trip without `MULTI`/`EXEC`. This is intentional on the **startup** path: nothing is reading the cache yet, the records do not need to be applied atomically as a set, and skipping `MULTI`/`EXEC` keeps the bulk load fast. The same method is used for the live `/reprefetch` reload, which is safe because the demo pauses the sync worker around the clear-and-reload sequence — see [Re-prefetch under load](#re-prefetch-under-load) below. If you call `bulk_load` directly from your own code on a cache that is already serving reads, either pause your writers first or rewrite it with `multi` so callers cannot observe a half-loaded record."
    },
    {
      "id": "reads-from-redis-only",
      "title": "Reads from Redis only",
      "role": "content",
      "text": "The `get` method runs `HGETALL` and returns the cached hash. **It does not fall back to the primary on a miss.** In a healthy system, a miss never happens; if it does, the application surfaces it as an error and treats it as a sync-pipeline incident:\n\n[code example]\n\nThis is the key behavioural difference from [cache-aside](https://redis.io/docs/latest/develop/use-cases/cache-aside): the request path never touches the primary, so reference-data reads cannot contribute to primary database load."
    },
    {
      "id": "applying-sync-events",
      "title": "Applying sync events",
      "role": "content",
      "text": "The sync worker calls `apply_change` for every primary mutation. For an `upsert`, the helper rewrites the cache hash and refreshes the safety-net TTL in one `MULTI`/`EXEC` transaction so the cache never holds a stale mix of old and new fields. For a `delete`, it removes the cache key:\n\n[code example]\n\nThe `DEL` before the `HSET` ensures the cached hash contains exactly the fields the primary record has now — fields that have been dropped from the primary will not linger in Redis. The `Mutex` around `multi` is a redis-rb-specific guard: a single `Redis.new` connection is thread-safe for individual commands, but a `multi` block uses the underlying connection for the duration of the transaction, so concurrent transactions on the same client must be serialised by the caller (or you must use a connection pool). The demo uses one shared client plus a mutex; production code should use [`connection_pool`](https://github.com/mperham/connection_pool) and check out a connection per transaction instead."
    },
    {
      "id": "the-sync-worker",
      "title": "The sync worker",
      "role": "content",
      "text": "The `SyncWorker` runs a daemon thread that blocks on the primary's change queue with a short timeout. Every change is applied to Redis as soon as it arrives\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/prefetch-cache/ruby/sync_worker.rb)):\n\n[code example]\n\nIn production this loop is replaced by a CDC consumer reading from RDI's Redis output stream, Debezium's Kafka topic, or an equivalent change feed. The shape stays the same: drain events, apply them to Redis, advance the consumer offset."
    },
    {
      "id": "invalidation-and-re-prefetch",
      "title": "Invalidation and re-prefetch",
      "role": "content",
      "text": "Two helpers exist for testing and recovery:\n\n* `invalidate(entity_id)` deletes a single cache key. The demo uses it to simulate a sync-pipeline failure on one record.\n* `clear` runs `SCAN MATCH cache:category:*` and deletes every key under the prefix. The demo uses it to simulate a full cache loss.\n\nIn both cases, the recovery path is to call `bulk_load(primary.list_records)` again — re-prefetching from the primary. The demo exposes this as the \"Re-prefetch\" button so you can see the cache come back to a fully-warm state in one operation."
    },
    {
      "id": "re-prefetch-under-load",
      "title": "Re-prefetch under load",
      "role": "content",
      "text": "`clear` and `bulk_load` are not atomic against the sync worker. If a change event arrives between the snapshot (`primary.list_records`) and the bulk write, the bulk write can overwrite a newer value; if a change event arrives between `clear`'s `SCAN` and `DEL`, the cleared entry can immediately be recreated. The demo's `/clear` and `/reprefetch` handlers solve this by pausing the sync worker around the operation:\n\n[code example]\n\n`pause` waits for the worker to finish whatever event it is currently applying, parks the run loop on a `ConditionVariable`, and returns. Change events that arrive during the pause sit in the primary's `Queue` and apply in order once `resume` is called, so no event is lost."
    },
    {
      "id": "hit-miss-accounting",
      "title": "Hit/miss accounting",
      "role": "content",
      "text": "The helper keeps in-process counters for hits, misses, prefetched records, sync events applied, and the average lag between a primary change and its application to Redis. The demo UI surfaces these so you can confirm the cache is absorbing all reads and the sync worker is keeping up:\n\n[code example]\n\nIn production you would emit these as Prometheus counters and gauges. The sync-lag metric is the most important: a sudden rise indicates the CDC pipeline is falling behind."
    },
    {
      "id": "prerequisites",
      "title": "Prerequisites",
      "role": "content",
      "text": "Before running the demo, make sure that:\n\n* Redis is running and accessible. By default, the demo connects to `localhost:6379`.\n* Ruby 2.6 or later is installed (the demo uses `webrick`, which is stdlib in 2.x and is shipped as a bundled gem in 3.x).\n* The `redis` gem (`redis-rb` 5.x) is installed:\n\n[code example]\n\nIf your Redis server is running elsewhere, start the demo with `--redis-host` and `--redis-port`."
    },
    {
      "id": "running-the-demo",
      "title": "Running the demo",
      "role": "content",
      "text": ""
    },
    {
      "id": "get-the-source-files",
      "title": "Get the source files",
      "role": "content",
      "text": "The demo consists of four files. Download them from the [`ruby` source folder](https://github.com/redis/docs/tree/main/content/develop/use-cases/prefetch-cache/ruby) on GitHub, or grab them with `curl`:\n\n[code example]"
    },
    {
      "id": "start-the-demo-server",
      "title": "Start the demo server",
      "role": "content",
      "text": "From that directory:\n\n[code example]\n\nYou should see something like:\n\n[code example]\n\nAfter starting the server, visit `http://localhost:8789`.\n\nThe demo server uses only Ruby standard library features for HTTP handling and concurrency:\n\n* [`webrick`](https://docs.ruby-lang.org/en/master/WEBrick.html) for the web server\n* [`uri`](https://docs.ruby-lang.org/en/master/URI.html) and `req.query` for query and form decoding\n* [`Thread`](https://docs.ruby-lang.org/en/master/Thread.html), [`Mutex`](https://docs.ruby-lang.org/en/master/Mutex.html), [`ConditionVariable`](https://docs.ruby-lang.org/en/master/ConditionVariable.html), and [`Queue`](https://docs.ruby-lang.org/en/master/Thread/Queue.html) for the sync worker daemon\n\nIt exposes a small interactive page where you can:\n\n* See which IDs are in the cache and in the primary, side by side\n* Read a category through the cache and confirm every read is a hit\n* Update a field on the primary and watch the sync worker rewrite the cache hash\n* Add and delete categories and watch them appear and disappear from the cache\n* Invalidate one key or clear the entire cache to simulate a sync-pipeline failure\n* Re-prefetch from the primary to recover from a broken cache state\n* Watch the average sync lag, and confirm primary reads stay at one until you re-prefetch — each `/reprefetch` adds another primary read for the snapshot, but normal request traffic never reaches the primary at all"
    },
    {
      "id": "the-mock-primary-store",
      "title": "The mock primary store",
      "role": "content",
      "text": "To make the demo self-contained, the example includes a `MockPrimaryStore` that stands in for a source-of-truth database\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/prefetch-cache/ruby/primary.rb)):\n\n[code example]\n\nEvery mutation appends a change event to an in-process [`Queue`](https://docs.ruby-lang.org/en/master/Thread/Queue.html). The sync worker drains the queue with a 50 ms timeout and applies each event to Redis. Ruby's `Queue#pop` does not accept a timeout directly, so `next_change` wraps a non-blocking `pop(true)` in a short polling loop — that keeps the worker responsive to its stop flag.\n\nIn a real system this queue is replaced by a CDC pipeline — RDI on Redis Enterprise or Debezium with a Redis consumer on open-source Redis."
    },
    {
      "id": "production-usage",
      "title": "Production usage",
      "role": "content",
      "text": "This guide uses a deliberately small local demo so you can focus on the prefetch-cache pattern. In production, you will usually want to harden several aspects of it."
    },
    {
      "id": "replace-the-in-process-change-queue-with-a-real-cdc-pipeline",
      "title": "Replace the in-process change queue with a real CDC pipeline",
      "role": "content",
      "text": "The demo's in-process queue is the simplest possible stand-in for a CDC change feed. In production, the change feed lives outside the application process: an RDI pipeline configured against your primary database, Debezium connectors writing to Kafka or a Redis stream, or your application explicitly publishing change events from the write path. Whatever you choose, the consumer side stays the same — read events, apply them to Redis, advance the offset."
    },
    {
      "id": "use-a-long-safety-net-ttl-not-a-freshness-ttl",
      "title": "Use a long safety-net TTL, not a freshness TTL",
      "role": "content",
      "text": "The TTL on each cache key is a **safety net**: it bounds memory if the sync pipeline silently stops, so a stuck consumer cannot leave stale data in Redis indefinitely. The TTL is not the freshness mechanism — freshness comes from the sync worker, which refreshes the TTL on every add or update event (delete events remove the key). Pick a TTL that is comfortably longer than your worst-case sync lag plus your alerting window, so a transient sync hiccup never expires hot keys."
    },
    {
      "id": "decide-what-to-do-on-a-cache-miss",
      "title": "Decide what to do on a cache miss",
      "role": "content",
      "text": "A prefetch cache treats a miss as an error or a missing record. The two reasonable strategies are:\n\n* **Return a 404 to the user.** Appropriate when the cache is authoritative for the lookup — for example, when the user is asking for a category by ID and the ID is not in the cache.\n* **Page on-call.** A sustained miss rate on IDs you know exist is an incident: either the prefetch did not run, or the sync pipeline is broken.\n\nWhichever you choose, do not fall back to the primary on the read path — that is what cache-aside is for, and conflating the two patterns breaks the load-isolation guarantee that prefetch provides."
    },
    {
      "id": "bound-the-working-set-to-what-fits-in-memory",
      "title": "Bound the working set to what fits in memory",
      "role": "content",
      "text": "Prefetch only works if the entire dataset fits in Redis memory with headroom. Estimate the size of your reference data, multiply by a growth factor, and confirm the result fits within your Redis instance's `maxmemory` minus what other use cases need. If the working set grows beyond what Redis can hold, switch the dataset to a cache-aside pattern instead — the request path will pay miss latency, but you will not OOM."
    },
    {
      "id": "reconcile-periodically-against-the-primary",
      "title": "Reconcile periodically against the primary",
      "role": "content",
      "text": "CDC pipelines are eventually consistent: an event can be lost (broker outage, consumer crash, configuration drift) and the cache can silently diverge from the source. Run a periodic reconciliation job that re-reads all primary records, compares them against the cache, and either re-prefetches or fixes individual entries. Even running it once a day catches drift that ad-hoc inspection would miss."
    },
    {
      "id": "use-a-connection-pool-for-transactions-not-a-shared-client-mutex",
      "title": "Use a connection pool for transactions, not a shared client + mutex",
      "role": "content",
      "text": "A single `Redis.new` client is thread-safe for individual commands because Ruby's GIL serialises access to the C-level command pipeline. But `multi` blocks use the underlying connection for the duration of the transaction, so two threads cannot run `multi` blocks concurrently on the same client without interleaving. The demo gets away with one shared client guarded by a `Mutex`, which is fine for a small local server. In production, use [`connection_pool`](https://github.com/mperham/connection_pool) to keep a pool of `Redis` clients and check one out per transaction:\n\n[code example]\n\nThat gives you per-thread transactions without a global lock and reuses connections across requests."
    },
    {
      "id": "namespace-cache-keys-in-shared-redis-deployments",
      "title": "Namespace cache keys in shared Redis deployments",
      "role": "content",
      "text": "If multiple applications share a Redis deployment, prefix cache keys with the application name (`cache:billing:category:{id}`) so different services cannot clobber each other's entries. The helper takes a `prefix` argument exactly for this."
    },
    {
      "id": "inspect-cached-entries-directly-in-redis",
      "title": "Inspect cached entries directly in Redis",
      "role": "content",
      "text": "When testing or troubleshooting, inspect the stored cache keys directly to confirm the bulk load and the sync worker are writing what you expect:\n\n[code example]\n\nIf a key is missing for an ID that still exists in the primary, the prefetch did not run, the key expired without a sync refresh, or someone invalidated it. If a key is still present for an ID that was deleted in the primary, the delete event has not yet been applied. If the TTL is much lower than the configured safety-net value on a hot key, the sync worker is not keeping up."
    },
    {
      "id": "learn-more",
      "title": "Learn more",
      "role": "related",
      "text": "* [redis-rb guide](https://redis.io/docs/latest/develop/clients/ruby) - Install and use the Ruby Redis client\n* [HSET command](https://redis.io/docs/latest/commands/hset) - Write hash fields\n* [HGETALL command](https://redis.io/docs/latest/commands/hgetall) - Read every field of a hash\n* [EXPIRE command](https://redis.io/docs/latest/commands/expire) - Set key expiration in seconds\n* [DEL command](https://redis.io/docs/latest/commands/del) - Delete a key on invalidation or sync-delete\n* [SCAN command](https://redis.io/docs/latest/commands/scan) - Iterate the cached keyspace without blocking the server\n* [TTL command](https://redis.io/docs/latest/commands/ttl) - Inspect remaining safety-net time on a key\n* [Redis Data Integration](https://redis.io/docs/latest/integrate/redis-data-integration) - Configuration-driven CDC into Redis on Redis Enterprise and Redis Cloud"
    }
  ],
  "examples": [
    {
      "id": "the-prefetch-cache-helper-ex0",
      "language": "ruby",
      "code": "require \"redis\"\nrequire_relative \"cache\"\nrequire_relative \"primary\"\nrequire_relative \"sync_worker\"\n\nredis = Redis.new(host: \"localhost\", port: 6379)\nprimary = MockPrimaryStore.new\ncache = PrefetchCache.new(redis_client: redis, ttl_seconds: 3600)\n\n# Pre-load every primary record into Redis in one pipelined round trip.\ncache.bulk_load(primary.list_records)\n\n# Start the sync worker so primary mutations propagate into Redis.\nsync = SyncWorker.new(primary: primary, cache: cache)\nsync.start\n\n# Read paths now go to Redis only.\nrecord, hit, redis_ms = cache.get(\"cat-001\")",
      "section_id": "the-prefetch-cache-helper"
    },
    {
      "id": "data-model-ex0",
      "language": "text",
      "code": "cache:category:cat-001\n  id            = cat-001\n  name          = Beverages\n  display_order = 1\n  featured      = true\n  parent_id     =",
      "section_id": "data-model"
    },
    {
      "id": "bulk-load-on-startup-ex0",
      "language": "ruby",
      "code": "def bulk_load(records)\n  loaded = 0\n  @apply_lock.synchronize do\n    @redis.pipelined do |pipe|\n      records.each do |record|\n        entity_id = record[\"id\"] || record[:id]\n        next if entity_id.nil? || entity_id.to_s.empty?\n        cache_key = cache_key_for(entity_id)\n        pipe.del(cache_key)\n        pipe.hset(cache_key, stringify_record(record))\n        pipe.expire(cache_key, @ttl_seconds)\n        loaded += 1\n      end\n    end\n  end\n  @stats_lock.synchronize { @prefetched += loaded }\n  loaded\nend",
      "section_id": "bulk-load-on-startup"
    },
    {
      "id": "reads-from-redis-only-ex0",
      "language": "ruby",
      "code": "def get(entity_id)\n  cache_key = cache_key_for(entity_id)\n\n  started = monotonic_ms\n  cached = @redis.hgetall(cache_key)\n  redis_latency_ms = monotonic_ms - started\n\n  if cached && !cached.empty?\n    @stats_lock.synchronize { @hits += 1 }\n    [cached, true, redis_latency_ms]\n  else\n    @stats_lock.synchronize { @misses += 1 }\n    [nil, false, redis_latency_ms]\n  end\nend",
      "section_id": "reads-from-redis-only"
    },
    {
      "id": "applying-sync-events-ex0",
      "language": "ruby",
      "code": "def apply_change(change)\n  op = change[:op] || change[\"op\"]\n  entity_id = change[:id] || change[\"id\"]\n  return if entity_id.nil? || entity_id.to_s.empty?\n\n  cache_key = cache_key_for(entity_id)\n\n  case op\n  when \"upsert\"\n    fields = change[:fields] || change[\"fields\"]\n    return if fields.nil? || fields.empty?\n\n    @apply_lock.synchronize do\n      @redis.multi do |tx|\n        tx.del(cache_key)\n        tx.hset(cache_key, stringify_record(fields))\n        tx.expire(cache_key, @ttl_seconds)\n      end\n    end\n  when \"delete\"\n    @redis.del(cache_key)\n  end\n  # stats update omitted for brevity\nend",
      "section_id": "applying-sync-events"
    },
    {
      "id": "the-sync-worker-ex0",
      "language": "ruby",
      "code": "def run_loop\n  loop do\n    should_stop, should_pause = @state_mutex.synchronize { [@stop, @pause] }\n    break if should_stop\n\n    if should_pause\n      @state_mutex.synchronize do\n        @paused_idle = true\n        @state_cv.broadcast\n        while @pause && !@stop\n          @state_cv.wait(@state_mutex, @poll_timeout_s)\n        end\n        @paused_idle = false\n      end\n      next\n    end\n\n    change = @primary.next_change(@poll_timeout_s)\n    next if change.nil?\n    begin\n      @cache.apply_change(change)\n    rescue => exc\n      warn \"[sync] failed to apply #{change.inspect}: #{exc}\"\n    end\n  end\nend",
      "section_id": "the-sync-worker"
    },
    {
      "id": "re-prefetch-under-load-ex0",
      "language": "ruby",
      "code": "@sync.pause\nbegin\n  @cache.clear\n  @cache.bulk_load(@primary.list_records)\nensure\n  @sync.resume\nend",
      "section_id": "re-prefetch-under-load"
    },
    {
      "id": "hit-miss-accounting-ex0",
      "language": "ruby",
      "code": "def stats\n  @stats_lock.synchronize do\n    total = @hits + @misses\n    hit_rate = total.zero? ? 0.0 : (100.0 * @hits / total).round(1)\n    avg_lag = @sync_lag_samples.zero? ? 0.0 : (@sync_lag_ms_total / @sync_lag_samples).round(2)\n    {\n      \"hits\" => @hits,\n      \"misses\" => @misses,\n      \"hit_rate_pct\" => hit_rate,\n      \"prefetched\" => @prefetched,\n      \"sync_events_applied\" => @sync_events_applied,\n      \"sync_lag_ms_avg\" => avg_lag,\n    }\n  end\nend",
      "section_id": "hit-miss-accounting"
    },
    {
      "id": "prerequisites-ex0",
      "language": "bash",
      "code": "gem install redis webrick",
      "section_id": "prerequisites"
    },
    {
      "id": "get-the-source-files-ex0",
      "language": "bash",
      "code": "mkdir prefetch-cache-demo && cd prefetch-cache-demo\nBASE=https://raw.githubusercontent.com/redis/docs/main/content/develop/use-cases/prefetch-cache/ruby\ncurl -O $BASE/cache.rb\ncurl -O $BASE/primary.rb\ncurl -O $BASE/sync_worker.rb\ncurl -O $BASE/demo_server.rb",
      "section_id": "get-the-source-files"
    },
    {
      "id": "start-the-demo-server-ex0",
      "language": "bash",
      "code": "ruby demo_server.rb",
      "section_id": "start-the-demo-server"
    },
    {
      "id": "start-the-demo-server-ex1",
      "language": "text",
      "code": "Redis prefetch-cache demo server listening on http://127.0.0.1:8789\nUsing Redis at localhost:6379 with cache prefix 'cache:category:' and TTL 3600s\nPrefetched 5 records in 86.5 ms; sync worker running",
      "section_id": "start-the-demo-server"
    },
    {
      "id": "the-mock-primary-store-ex0",
      "language": "ruby",
      "code": "class MockPrimaryStore\n  def initialize(read_latency_ms: 80)\n    # ...\n  end\n\n  def list_records\n    sleep(@read_latency_ms / 1000.0)\n    # ...\n  end\n\n  def update_field(entity_id, field, value)\n    @lock.synchronize do\n      record = @records[entity_id]\n      return false if record.nil?\n      record[field] = value\n      emit_change_locked(CHANGE_OP_UPSERT, entity_id, record.dup)\n    end\n    true\n  end\nend",
      "section_id": "the-mock-primary-store"
    },
    {
      "id": "use-a-connection-pool-for-transactions-not-a-shared-client-mutex-ex0",
      "language": "ruby",
      "code": "require \"connection_pool\"\n\nREDIS = ConnectionPool.new(size: 16, timeout: 5) { Redis.new(host: \"localhost\") }\n\nREDIS.with do |redis|\n  redis.multi do |tx|\n    tx.del(cache_key)\n    tx.hset(cache_key, fields)\n    tx.expire(cache_key, ttl_seconds)\n  end\nend",
      "section_id": "use-a-connection-pool-for-transactions-not-a-shared-client-mutex"
    },
    {
      "id": "inspect-cached-entries-directly-in-redis-ex0",
      "language": "bash",
      "code": "redis-cli --scan --pattern 'cache:category:*'\nredis-cli HGETALL cache:category:cat-001\nredis-cli TTL cache:category:cat-001",
      "section_id": "inspect-cached-entries-directly-in-redis"
    }
  ]
}
