With Rails.cache.increment, what happens when the key is missing or expired, and why use it rather than read-then-write for a counter?
answer
- missing key starts at the amount
- returns the new value
- atomic in the store
- raw counters: write_counter, read_counter
- :null_store returns nil
basics
~20 sRails.cache.increment adds to an integer in the store and returns the new value; a missing or expired key starts at the amount. It is atomic in the store, whereas reading, adding and writing back loses updates when processes race.
solid answer
~40 s`Rails.cache.increment(key, 1, expires_in: 2.minutes)` returns the updated integer. When the key is missing or expired, the store starts it at the amount, so the first call returns 1. The change happens inside the store as one operation: Redis's `INCRBY`, Memcached's `incr`, a locked row in Solid Cache, a mutex in the memory store, so two processes can never both read 41 and both write 42. With `read` plus `write`, that race silently loses counts. `expires_in:` applies when the counter is created; existing counters keep their expiry, so a key per time window gives a fixed-window count. On the Redis and Memcached stores the value must be raw, so seed it with `write_counter` and read it with `read_counter`. `:null_store`, the generated test store, does nothing and returns `nil`, and `decrement` mirrors all of this.
code
ruby · 7 linesRails.cache.increment("fx-calls") # => 1 (key was missing)
Rails.cache.increment("fx-calls", 5) # => 6
Rails.cache.decrement("fx-calls") # => 5
Rails.cache.write_counter("fx-budget", 300) # raw value, safe to increment on Redis
Rails.cache.decrement("fx-budget") # => 299
Rails.cache.read_counter("fx-budget") # => 299go deeper
Recall that increment returns the new number and that a missing key starts at the amount.
Explain why increment is atomic in the store while read-then-write loses updates, and how expires_in applies only on creation.
Show the per-store differences: raw values on Redis and Memcached, per-process memory stores, nil from the null store, eviction resetting counts.
Decide which counts may live in a cache that can forget them and which must be durable in the database.
## The call `Rails.cache.increment(name, amount = 1, options)` adds `amount` to an integer stored under `name` and **returns the new value**. `Rails.cache.decrement` subtracts. In the travel-booking app, the exchange-rate provider allows a fixed number of requests per minute, so the app counts its own calls: ```ruby class FxQuota LIMIT = 300 def self.allow? window = Time.current.to_i / 60 count = Rails.cache.increment(["fx-quota", window], 1, expires_in: 2.minutes) count.nil? || count <= LIMIT # nil: the store could not count end end ``` ## Missing and expired keys | State of the key | Result of `increment(key, 1)` | |---|---| | missing | stored as `1`, returns `1` | | expired | treated as missing, returns `1` | | holds `41` | stored as `42`, returns `42` | `decrement` on a missing key starts at the negative amount. In the memory and file stores a version mismatch also restarts the counter. `expires_in:` matters **only when the counter is created**: - the Redis store sets the expiry only if the key has none yet; - the memory store and Solid Cache keep the existing entry's expiry when adding; so a key per time window, as above, gives a **fixed window** that resets when the key expires, not a sliding one. ## Why not read, add and write back ```ruby count = Rails.cache.read(key).to_i Rails.cache.write(key, count + 1) # two processes can both read 41 and both write 42 ``` Between the `read` and the `write`, another process can do the same, and one increment is lost. Under load this undercounts badly. `increment` performs the change **inside the store** as one operation: 1. **Redis cache store**: `INCRBY`, atomic on the server. 2. **Memcached store**: `incr`, atomic on the server. 3. **Solid Cache**: a transaction that locks the entry's row, adds and writes. 4. **Memory store**: a mutex, which is atomic only **within one process**, so each Puma worker has its own count. 5. **File store**: a file lock serializes updates to an existing counter on one machine, but creating the counter is unlocked and separate servers do not share files, so it is a poor home for shared counters. ## Raw values and reading a counter Most stores serialize values, but the Redis and Memcached stores increment the **raw** stored number. A value written with an ordinary `write` is not a raw integer there, and incrementing it fails and returns `nil`. Use the counter helpers instead: - `Rails.cache.write_counter(key, 100)` seeds a counter with `raw: true`; - `Rails.cache.read_counter(key)` reads it back as an integer. Pair them: counters seeded and read through these helpers stay raw integers on every store. ## Building a window key 1. Pick the window length the limit is defined over, for example one minute. 2. Derive a window number from the clock, `Time.current.to_i / 60`, and put it in the key. 3. Call `increment` with an `expires_in:` comfortably longer than the window, so old windows clean themselves up. 4. Compare the returned value with the limit; never read the counter separately first. 5. Decide what a `nil` result means: fail open (allow the call) or fail closed (refuse it). Two adjacent windows can each allow the full limit around the boundary, which is the known weakness of fixed windows; that trade-off is usually acceptable for courtesy quotas toward a provider. ## The null store The generated test environment uses `:null_store`, whose `increment` and `decrement` do nothing and return **`nil`**. Code that compares the result with a limit must treat `nil` deliberately, as `FxQuota.allow?` does; otherwise every test sees a counter that never moves, or a `NoMethodError` on `nil`. Tests that check counting need a real store. ## When a cache counter is the wrong tool - Cache entries can be **evicted** under memory pressure, which silently resets a counter. Fine for quotas and throttles, wrong for anything you bill or report. - Durable totals belong in the database. Active Record's counter caches and `update_counters` are the persistent equivalents. - Request throttling in controllers has its own Rails API built on the cache store; this call is the general-purpose primitive underneath patterns like the quota above.
- Why can a memory-store counter undercount in production?`:memory_store` lives inside one Ruby process. Its mutex makes `increment` safe across threads in that process, but each Puma worker or server has its own copy, so the app holds several independent counters. Shared counts need a shared store such as Solid Cache or Redis.
- What does Rails.cache.increment return in a generated Rails test environment?`nil`. The test environment uses `:null_store`, whose `increment` and `decrement` are no-ops. Code must handle `nil`, and tests that check counting must configure a real store.
- increment raises when the key does not exist yet.
- Reading, adding one and writing back is just as safe as increment.
- Each call to increment with expires_in: pushes the expiry forward.
- A :memory_store counter is shared by every Puma worker.
- Rails.cache.increment returns true on success.