skip to content

When a hot Rails.cache.fetch entry with expires_in: expires under load, what does race_condition_ttl: do, and where does it not help?

level: seniorimportance: should knowfreq 40%

answer

  1. first reader extends the stale entry
  2. others keep the old value briefly
  3. needs an expiring entry
  4. pass it on every fetch
  5. no help for cold or evicted keys

basics

~20 s

With race_condition_ttl:, the first fetch to find a recently expired entry writes it back with a short extension and regenerates, while concurrent callers keep the old value. Missing, evicted or version-mismatched entries get no help.

solid answer

~50 s

Without it, every request that reads an expired hot key runs the block at once. With `race_condition_ttl: 10.seconds`, `fetch` checks whether the expired entry expired less than 10 seconds ago; if so it writes the same stale entry back with an expiry 10 seconds ahead and runs the block itself, while other processes reading the shared store see a live entry and return the old value. When the new value lands, everyone switches to it; if the regenerating process fails, another one retries after the window. It only works on entries that can expire and still be read: the Redis and Memcached stores keep such entries five minutes past `expires_in`, but only when the write carried `race_condition_ttl`, so pass it on every `fetch` for that key. It cannot help a cold key, an evicted or version-mismatched entry, `force: true`, or `fetch_multi`.

code

ruby · 10 lines
ruby
class ExchangeRates
  OPTIONS = { expires_in: 10.minutes, race_condition_ttl: 20.seconds }.freeze

  def self.rate(from, to)
    # Same options on every call, so every write carries race_condition_ttl
    Rails.cache.fetch(["fx", from, to], **OPTIONS) do
      FxProvider.quote(from, to)
    end
  end
end

go deeper

for a junior

Recall that race_condition_ttl lets callers reuse an expired value briefly while one caller recomputes it.

for a middle

Explain the steps: expired entry within the window is written back with an extension, the first reader regenerates, others get the old value.

for a senior

Show the preconditions and gaps from production: entries must expire and still be stored, the option on every write, no help for cold, evicted or mismatched keys.

for a principal

Decide when a refresh job, a longer expiry or accepting staleness is cheaper than tuning race windows for each hot key.

## The moment a hot entry expires In the travel-booking app, the EUR/USD rate is read on almost every search page and cached for ten minutes. At the instant the entry expires, every request that calls `fetch` finds an expired entry, treats it as a miss and runs the block, so dozens of processes call the slow rates provider at once. The general theory of this pile-up belongs to cache-aside design; the Rails-specific answer is one option on `fetch`. ```ruby Rails.cache.fetch(["fx", "EUR", "USD"], expires_in: 10.minutes, race_condition_ttl: 10.seconds) do FxProvider.quote("EUR", "USD") end ``` ## What `race_condition_ttl:` does When `fetch` reads an entry that has **expired**, Active Support's `handle_expired_entry` decides what to do: 1. If `race_condition_ttl` is positive and the entry expired **less than that many seconds ago**, it sets the entry's expiry to now plus `race_condition_ttl` and **writes the stale entry back** to the store. 2. The process that did this treats the read as a miss and **runs the block** itself. 3. Other processes that read the key during the window find a **live** entry, the old value, and return it without running the block. 4. When the first process finishes, it writes the new value; later readers get it. 5. If the first process raises, nothing new is written; once the extended window passes, the next reader finds the entry expired again, extends it once more and regenerates in its turn. Because the extended entry is written back to the store, the protection reaches every process that shares that store. On a per-process `:memory_store` it only coordinates threads within one process. ## Conditions for it to work - **The entry must expire.** It needs `expires_in:` or `expires_at:`; an entry with no expiry never reaches this code path. - **The stale entry must still be readable.** The Redis and Memcached stores set the server-side lifetime to `expires_in` **plus five minutes**, but only when the write itself carried `race_condition_ttl`. A key written once without the option disappears exactly at expiry, leaving nothing stale to serve. Pass the option on **every** `fetch` for that key. - **The window must cover regeneration.** Choose a value at least as long as the slowest realistic block run; if the provider takes 15 seconds and the window is 10, a second process will start regenerating while the first is still waiting. - On the Redis and Memcached stores, a window longer than five minutes buys nothing, because the stale entry is gone from the server by then. ## Where it does not help | Situation | Why | |---|---| | Cold key never written | there is no stale entry to serve | | Entry evicted by the store's size limit | the entry is gone, not expired | | Version mismatch | a mismatch is a plain miss and every caller regenerates | | `force: true` | the read is skipped entirely | | `Rails.cache.read` or `fetch_multi` | expired entries are deleted on those paths; only single-key `fetch` with a block applies the option | | A deploy that changes the key | the new key is cold | ## A worked timeline With `expires_in: 10.minutes, race_condition_ttl: 20.seconds` and a provider that takes about five seconds: 1. **09:00:00** the rate is written; it expires at 09:10:00. 2. **09:10:01** request A reads the expired entry, which expired one second ago, inside the 20-second window. A writes the old entry back with an expiry of 09:10:21 and calls the provider. 3. **09:10:01 to 09:10:06** requests B to Z read a live entry and return the old rate at once. 4. **09:10:06** A writes the new rate, expiring at 09:20:06; later readers get it. Without the option, every request between 09:10:00 and 09:10:06 would have called the provider. ## Practical choices - Keep `race_condition_ttl` **small relative to `expires_in`**; the old value is served for up to the window after expiry, so it adds staleness. - For values that must never be served cold, pair it with a **refresh job** that calls `fetch(..., force: true)` before expiry, so web requests almost never miss. - Instrumentation helps: `cache_read.active_support` and `cache_generate.active_support` notifications show how often the block really runs. ## How to explain it in an interview Name the mechanism (stale entry rewritten with a short extension by the first reader), the precondition (an expiring entry that the store still holds, written with the option), and the gaps (cold keys, evictions, version changes, bulk reads). That separates knowing the option from having relied on it.

  • Does the process that extends the entry get the stale value?
    No. The first reader writes the stale entry back with a short extension and then treats its own read as a miss, so it runs the block and returns the fresh value. Only concurrent readers during the window get the old value.
  • Why might race_condition_ttl seem to do nothing on a Redis store?
    The Redis store keeps an entry five minutes past `expires_in` only when the write included `race_condition_ttl`. If some code path writes that key without the option, the server deletes it exactly at expiry, so there is no stale entry to extend and every reader regenerates.

A bakery shelf labelled 'fresh until 9:00': when the label runs out, the first baker to notice writes 'fresh until 9:02' on it and starts a new batch, so customers keep taking the old loaves for two minutes instead of every customer heading to the oven. If the shelf is already empty, the label trick does nothing.

  • race_condition_ttl locks the key so only one process can run the block.
  • race_condition_ttl also protects keys that were never cached.
  • Passing race_condition_ttl only on the first fetch is enough.
  • Every caller during the window waits for the new value.
  • race_condition_ttl works the same with read_multi and fetch_multi.