Redis KEEPTTL: reject persistent cache entries
An illustrative display cache changes its presentation without extending freshness. An unexpected persistent entry must be rejected rather than preserved forever.
Quick answer
Redis `KEEPTTL` preserves an existing expiry; it does not require the key to have one. If a cache entry must remain time limited, distinguish a missing key from a persistent key before replacing it. Use an atomic check when that expiry requirement must hold at the same moment as the write.
On this page
Redis KEEPTTL preserves an existing expiry; it does not require the key to have one. If a cache entry must remain time limited, distinguish a missing key from a persistent key before replacing it. Use an atomic check when that expiry requirement must hold at the same moment as the write. [1][2][6]
Scenario: a product display cache stores a price summary with a fixed freshness deadline. A presentation update changes the currency label but must not extend the underlying price’s lifetime. The developer adds KEEPTTL, observes an occasional persistent entry and assumes Redis lost the expiry. Trace the writer that created the persistent entry before changing the preservation update.
The worked case treats the cache as disposable derived data. It does not use expiry as a payment, authorization or inventory guarantee. The same commands can appear in those systems, but their correctness needs durable business checks beyond a cache deadline. Examples use Redis command-line syntax and a short Lua script; client libraries need their own option and reply handling verified.
What does TTL minus one tell you?#
For modern Redis, a TTL result of minus one means the key exists without an expiry. Minus two means the key does not exist. A nonnegative result describes remaining lifetime, and PTTL exposes the remaining duration in milliseconds. These states must remain distinct in diagnostics and application code. [1][4]
# Disposable example keys only.
SET demo:price:plain "summary-a"
TTL demo:price:plain
# Expected: -1, persistent key.
TTL demo:price:missing
# Expected: -2, missing key.
SET demo:price:expiring "summary-a" EX 600
PTTL demo:price:expiring
# Expected: a positive remaining duration near the configured expiry.Treat the expected positive duration as a range. The command does not freeze time between requests, and a test that demands an exact duration after several round trips is testing its own timing assumption. Capture both the value and expiry observation when investigating a write path, and preserve the actual server reply rather than a client’s simplified boolean.
The observation is also a snapshot. A later writer can replace the key or change its deadline. A diagnostic read can tell you that an entry was persistent at that moment; it cannot identify the writer without application traces or other relevant evidence. Avoid turning a persistent-key observation into an unsupported claim that Redis randomly removed a deadline.
Begin with the commands your application sends. Successful plain SET discards an existing time to live unless an expiry option or preservation option changes that behavior. Review cache warmers, repair scripts and administrative writes as well as the main request handler. A single writer that creates persistent data can invalidate the assumption behind every later preservation update. [2]
Choose a freshness rule before changing SET#
Choose whether this write represents fresh underlying data, a presentation-only edit, or a repair of an invalid entry. Those actions need different deadline behavior. A command option cannot decide whether the new value was recomputed from an authoritative source or merely reformatted from an older cached value.
| Write intent | Intended expiry behavior | Suitable starting point |
|---|---|---|
| Fresh authoritative recomputation | Start a new bounded lifetime | SET with an explicit positive expiry |
| Presentation edit of accepted cached data | Preserve the existing deadline | KEEPTTL with an accepted-entry guard |
| Missing cache entry | Recompute or decline the edit | Explicit miss branch |
| Persistent entry in an expiring-only namespace | Reject or repair deliberately | Explicit invariant-failure branch |
| Sliding activity window | Extend according to its own rule | A separately documented update contract |
Scenario: the original price summary expires after its configured freshness window. Changing “EUR” to a localized label cannot justify a fresh price window because no authoritative price was fetched. Conversely, a successful recomputation can justify a new deadline even if the previous entry had almost expired. Keep that distinction visible in function names and review notes.
Do not read the remaining duration and send it back as a new relative expiry in a later request. Even without another writer, elapsed time between the read and write can move the effective deadline. With another writer, the duration can belong to a different value. Use a server-side operation that matches the intended preservation rule, or explicitly model version identity when the value itself must also be protected.
EXPIRE is useful when the operation genuinely changes a deadline. It is not an automatic repair for every persistent key. Redis documents how expiry behaves, including conditions and commands that retain or clear it. Decide whether repairing the deadline without recomputing the value can make stale data appear valid before applying such a fix. [3]
For the display cache, our rule is strict: a presentation edit succeeds only for a currently existing, expiring entry. Missing means there is no accepted input. Persistent means the cache write invariant was violated. Both outcomes return control to a recomputation or investigation path; neither silently creates a fresh-looking value.
Why is XX KEEPTTL still insufficient?#
XX requires an existing key, while KEEPTTL retains its deadline. Existence and expiry are separate conditions. An existing persistent key satisfies the existence condition, so combining these options can still preserve persistence. A preservation command should not be credited with creating an invariant it never checks. [1][2]
SET demo:price:persistent "summary-a"
SET demo:price:persistent "summary-b" XX KEEPTTL
TTL demo:price:persistent
# Expected: -1. Existence was required; expiry was not.
SET demo:price:new "summary-a" KEEPTTL
TTL demo:price:new
# With no prior key, expected: -1.
SET demo:price:missing "summary-b" XX KEEPTTL
# Expected: nil. Check this reply rather than reporting success.Keep these failures separate in the test report. The persistent case shows that XX is not an expiry test. The missing case without XX shows that there may be no old deadline to preserve. Keep both in a regression suite because either path can create the symptom that prompted the investigation.
Do not combine a new relative expiry and KEEPTTL as if Redis would choose one based on whether the key existed. These expiry options are alternatives. The SET documentation defines them, and your client should send a single intended expiry policy. Test the wire command or documented client call rather than assuming an option object means what its property names suggest. [2]
Wrapping commands in a transaction also needs precision. Redis transactions execute queued operations together, but Redis does not provide relational-style rollback for runtime errors. A failed command does not turn the whole sequence into an all-or-nothing business validation mechanism. Inspect each reply and validate inputs before mutation. [5]
An atomic guard for an expiring entry#
A short script can check remaining lifetime and replace the value without allowing another client command between those steps. Redis guarantees atomic script execution, and the blocking nature of scripts is a reason to keep this operation small. The script below touches a single key and performs no scan or unbounded loop. [6]
-- KEYS[1]: the display-cache entry
-- ARGV[1]: replacement presentation value
-- Result codes are this application's contract, not Redis status names.
local remaining = redis.call('PTTL', KEYS[1])
if remaining == -2 then
return {0, 'missing'}
end
if remaining == -1 then
return {0, 'persistent'}
end
if remaining <= 0 then
return {0, 'deadline-reached'}
end
local written = redis.call('SET', KEYS[1], ARGV[1], 'XX', 'KEEPTTL')
if not written then
return {0, 'missing'}
end
return {1, 'updated'}Scenario: a key whose remaining lifetime has reached the boundary is declined rather than reformatted. That is our application policy, not a claim that every cache must treat the boundary identically. The caller can recompute from authoritative data. Rejecting an almost-dead entry may cost extra recomputation, but it avoids reporting an edit on data whose accepted lifetime has ended.
This script protects the expiry condition at the write boundary. It does not compare the old payload with the version the caller read. A concurrent recomputation can finish before the script begins, and the presentation edit may then replace that newer value. If this matters, pass an expected version and compare it inside the same atomic operation. Do not describe expiry preservation as stale-write prevention.
Likewise, script atomicity is not rollback after arbitrary application mistakes. Keep all validation before the mutation and avoid adding later commands that might fail after SET. Validate argument shape in the client and review any future extension of the script as a change to the write contract. Redis’s transaction and scripting guarantees answer specific ordering questions, not every persistence question. [5][6]
An application can package the script using its chosen Redis deployment and client facilities. Verify the exact supported command options against the server and service you operate. The example’s purpose is the guard and reply contract. It does not require adopting a new cache client or changing the rest of the application’s serialization format.
How should clients verify and recover?#
The client must distinguish an accepted replacement from each rejected state. Reporting success after any script reply would discard the benefit of the guard. Return the result code and reason to the caller. Define which reply starts recomputation and which also records a broken cache invariant.
For the worked case, a missing or deadline-reached entry follows the recomputation path. A persistent entry produces the same safe user-facing fallback but also records a cache-invariant failure for investigation. Log the namespace and write-path identity without dumping price payloads or sensitive keys. Repeated persistence failures should lead to the writer that omitted expiry, rather than a job that repeatedly masks the symptom.
Test the accepted path with a before-and-after deadline observation. The value should change while the remaining lifetime continues toward the original deadline instead of restarting. Use a generous test window and tolerate elapsed time. In rejection cases, assert that the original value and persistence state remain unchanged, or that a missing entry remains missing.
An accepted edit can expire before the caller performs a later read. Do not convert that observation into an automatic retry of the presentation write. The operation accepted a value within its existing freshness window; it did not promise a new window. A later miss belongs to the ordinary recomputation path, and the response should avoid implying a lasting cache reservation.
Consider whether the presentation value should be cached separately at all. If formatting is cheap and deterministic from the accepted price payload, computing it on read removes this write path. If localization is expensive or shared across consumers, the guarded edit can be reasonable. Compare the extra cache coordination with the actual formatting cost before adding a script to a system that could simply avoid the update.
Add a separate version test if the application supplies an expected payload revision. Arrange for a new revision to appear before the edit, then verify that the stale presentation update is rejected. Keep this distinct from the expiry tests so a successful deadline check does not conceal a missing concurrency requirement.
The most useful production diagnostic is often a compact inventory of write contracts: recompute starts expiry, presentation edit preserves accepted expiry, invalid persistent entry is rejected, and deletion is explicit. Review each cache writer against that inventory. An observability dashboard cannot compensate for two writers implementing contradictory freshness rules.
For other cache boundaries, see expired refresh ownership and generation-aware cleanup. Neither mechanism is supplied by KEEPTTL; they address who may write and which generation may be removed.
Frequently asked questions#
- Does TTL minus one mean the key expired?
- In modern Redis it means the key exists without an expiry. A missing key has a different reply. Preserve those states in your diagnostic output, because treating persistence as a cache miss can hide a writer that stopped assigning deadlines. [1]
- Does KEEPTTL make a missing key expire?
- KEEPTTL preserves an existing deadline. A missing entry has no prior deadline to preserve, so it does not establish the expiring-only invariant. Require the intended state explicitly or create the value with a deliberate positive expiry. [2]
- Is XX KEEPTTL enough for an expiring-only cache?
- It requires existence and preserves the current expiry state, including persistence. If the cache contract forbids persistent entries, check for an accepted remaining lifetime together with the replacement. Otherwise a persistent value can continue to be persistent after a successful write. [1][2][6]
- Does the script prevent stale writes?
- The example guards expiry, not payload identity. A newer value written before the script begins can still be replaced. If your operation depends on the version previously read, include that expected version in the atomic comparison and test the mismatch branch. [6]