Skip to content

Redis SCAN cleanup: check the key generation

A discovered key name is a candidate; the current value decides whether removal is allowed.

Dopstack Engineering

· 9 min read

Original conceptual illustration: a diagonal retirement stencil crosses a cache ledger; the retired row is removed while the new-generation row remains intact.

Quick answer

Redis `SCAN` is an iterator over key names, not a snapshot or a deletion authorization. A cleanup worker must tolerate repeated names and empty batches, then check that the value currently stored at each name is still eligible for removal. A small atomic generation check can protect replacement values while keeping each mutation bounded.

Redis SCAN is an iterator over key names, not a snapshot or a deletion authorization. A cleanup worker must tolerate repeated names and empty batches, then check that the value currently stored at each name is still eligible for removal. A small atomic generation check can protect replacement values while keeping each mutation bounded. [1][2]

Why can a correct delete remove the wrong value?#

A key name can identify different values between discovery and deletion. Even if deleting a missing key is harmless, deleting a newly replaced value is not. Deduplicating names in the cleanup worker does not resolve that race. The decision must be checked where the deletion happens, against the value that exists then.

Scenario: a fictional report service stores disposable hash entries under a tenant prefix. Each hash records an immutable generation field identifying the report revision that produced it. The team retires revision g7 after readers have switched to g8. A sweep discovers candidate keys for the retired revision while normal traffic continues using the service.

The race happens between the observation and the command. The worker discovers a name and reads a hash belonging to g7. A writer replaces that name with a hash belonging to g8. The worker sends an unconditional delete using its old observation. The command deletes the current hash, even though the worker's earlier observation referred to a different generation.

Redis explicitly permits SCAN to return an element repeatedly. That is an iteration guarantee, not an explanation for every incorrect deletion. The replacement race would still exist if discovery returned every name exactly once. Treat these as separate test cases: repeated discovery, and a name whose current value changed after discovery. [1]

The rule for the worked example is that deleting the same eligible generation repeatedly is acceptable, while deleting an ineligible replacement is forbidden. It is narrower than saying every UNLINK call is safe to retry. The result depends on what value now occupies the name and on whether the writer contract permits that value to be recreated.

Which generation is eligible for deletion?#

A generation becomes eligible only after the application has stopped using and producing it. Start with that application-level retirement boundary. If an old process can recreate g7 entries after the sweep passes, a completed cursor cycle does not establish that the retired generation stays absent. Redis cannot infer whether a report revision is still needed.

Prefer generation-specific names when the application can support them. A name such as reports:{tenant}:g7:item makes the cleanup scope visible. Still verify the stored generation before mutation if the key schema allows replacement or migration. A prefix pattern selects candidates; it does not establish the current value's ownership or the correctness of every writer.

Write the retirement record before starting the sweep. It should name the tenant scope, retired generation, writer cutover evidence, reader cutover evidence and the process allowed to approve deletion. For a small service this can be a reviewed operation record. For automated retention it should be a durable lifecycle state with a documented transition.

Do not use this approach for primary records that happen to be stored in Redis unless the domain explicitly allows deletion under the same rules. The worked case assumes reconstructible report cache entries. If an entry is the only copy of a customer decision, the retention and recovery problem is materially different from disposable cache cleanup.

An entry with no generation field, an unexpected type or an unrecognized generation is outside the approved set. Skip and record it. Treating malformed metadata as old data would make the cleanup script more aggressive exactly when the evidence is weakest. Leave malformed entries in place and hand their names to a separate repair.

A small atomic check at the mutation boundary#

Use a script that checks a single supplied key and unlinks it only when its generation matches the retired generation. Redis scripts execute atomically relative to other server activity. Keep the operation short: putting the entire keyspace sweep inside a script would block server work throughout the scan and deletion loop. [2]

lua
-- KEYS[1]: one candidate hash key
-- ARGV[1]: the approved retired generation
local k = KEYS[1]
if redis.call('TYPE', k).ok ~= 'hash' then
  return 0
end
local generation = redis.call('HGET', k, 'generation')
if generation ~= ARGV[1] then
  return 0
end
return redis.call('UNLINK', k)

HGET supplies the field value used by the predicate. UNLINK removes the key from the keyspace and reclaims its memory asynchronously; it ignores a key that does not exist. The worker should count an actual removal separately from a skipped candidate, rather than treating every successful script invocation as deleted data. [3][4]

Pass the candidate through the script's explicit key argument. Do not construct additional key names inside the script or discover them from another record. Redis's scripting contract requires keys to be supplied as key arguments; the single-key design also keeps this mutation local to the key it evaluates. [6]

There is deliberately no client-side HGET, followed later by a separate unconditional UNLINK. Such a preview is useful for estimating the scope, but the script must repeat the predicate at execution time. A preview can become stale. It is not a reservation that prevents writers from changing the key.

The return value does not say why a candidate was skipped. If operators need to distinguish missing keys, wrong types and generation mismatches, introduce bounded status codes and test each branch. Keep that observability change separate from expanding deletion eligibility. Returning a more detailed explanation should not weaken the predicate.

When is a sweep actually complete?#

The cursor cycle finishes when Redis returns cursor zero, after processing that response's keys. An empty array with a nonzero cursor is not completion. COUNT is a work hint rather than a guaranteed batch size, so the worker cannot use the number of returned names as a substitute for cursor handling. [1]

text
cursor := initial zero cursor
repeat:
    next_cursor, candidates := SCAN(cursor, approved_pattern, count_hint)
    for each candidate in candidates:
        run the generation-check script for that single key
        record removed, skipped, or unresolved outcome
    persist next_cursor only after this page has been reconciled
    cursor := next_cursor
until cursor is zero

This is orchestration pseudocode, not a portable client implementation. Clients represent cursors differently; preserve the exact opaque value supplied by the selected client and server. Apply explicit request and run budgets so a maintenance job cannot occupy the service indefinitely. If the budget expires, record an interrupted sweep rather than a completed cleanup.

Checkpointing after a page leaves an ambiguous interval: some mutations may have succeeded before the worker crashed, while the next cursor was not saved. Replaying that page is acceptable under the retired-generation contract because an already-removed entry is absent and an ineligible replacement fails the predicate. It does not create an exactly-once deletion guarantee.

The reverse order is worse for completeness. Saving the next cursor before completing the current page can abandon candidates after a crash. Persist enough context to know which page was being processed, which generation was approved and which outcomes remain unresolved. A cursor by itself is not a complete maintenance journal.

After the first cycle, perform an independent verification pass over the retired scope. In a quiescent, properly retired generation, remaining eligible entries indicate unfinished work or an error. If writers are still creating entries in that scope, fix the cutover first. Repeated sweeping is not evidence that the writer boundary is correct.

How do restarts and Cluster change the procedure?#

A saved cursor should not be treated as a durable snapshot identifier across arbitrary server restarts or topology changes. The narrow guarantees of iteration do not supply that stronger recovery contract. Record server and scope information, and restart discovery from the beginning when you cannot establish that the previous traversal is still meaningful. Replay-safe mutations make that conservative recovery practical. [1]

Redis Cluster requires separate attention to discovery. A cursor from a node should not be assumed to enumerate the whole cluster through a convenient connection endpoint. Use the selected client's documented cluster iteration behavior, account for relevant primaries and topology changes, and verify coverage. This article's local script checks do not establish cluster-wide discovery correctness. [5]

The mutation remains single-key, which avoids introducing a cross-slot comparison-and-delete transaction. Cluster supports single-key commands; complex multi-key operations have slot restrictions. Adding a separate receipt key or shared counter inside the script would change that property and would require an explicit key-placement design. [5][6]

Connection loss also deserves a distinct outcome. If the script may have run but its response was lost, retrying the same eligible generation can be safe under the stated writer contract. Count the event as ambiguous until reconciled. Do not report the number of attempts as the number of keys actually deleted.

Our cache refresh article addresses another stale-observation problem: a worker writing after its authority expires. Here the protected operation is deletion rather than refresh. The common lesson is to evaluate the current predicate at the mutation boundary, while keeping the application's ownership rules explicit.

Close the sweep's client iterator and release its connection before shutting down the connection pool. An interrupted scan still owns local resources even when its deletion journal is recoverable. The async generator cleanup guide shows how early exit can leave cleanup outside the expected resource lifetime. That is a separate verification task from proving generation eligibility.

What evidence belongs in the cleanup record?#

Save the retired generation, node scope, last reconciled page and unresolved outcomes together. The operator taking over an interrupted cleanup needs more than a log line saying that a scan completed. They need to know which generation was retired, which server scope was traversed, whether writer cutover remained valid, and whether unresolved candidates remain.

EvidenceWhat it establishesWhat it does not establish
Retirement recordWhich generation may be removedEvery writer has obeyed the cutover
Completed cursor cycleTraversal reached its terminal cursorSnapshot consistency under mutation
Script outcomesPredicate matched at each mutationExactly-once worker execution
Verification passWhat remains in the inspected scopeAbsence across uninspected cluster nodes
Decision evidence for the worked example.

Exercise the adverse paths before rollout. Recreate a candidate with a newer generation before the script runs. Repeat the same candidate after successful removal. Feed a missing key, a string at a hash name, and a hash without the generation field. Then interrupt the worker between mutation and checkpoint and demonstrate how its journal recovers.

Those tests should check preserved values as well as return codes. A script that returns a plausible removal count but deletes the replacement still fails the contract. Inspect the replacement's generation and payload after the sweep. Use disposable data for this verification, and keep any service-level load or Cluster coverage claims separate from the single-server functional result.

What else should you check?#

Should the worker keep a set of every discovered key?
A seen-key set can avoid redundant calls, but it consumes memory and does not prevent a name from identifying a newer value. The deletion predicate must still be checked atomically. For a retired generation, replay-safe mutations may make global name deduplication unnecessary.
Can a preview count authorize deletion?
A preview helps estimate scope and find unexpected types, but it can become stale before mutation. Approval should identify the generation and eligibility rule. The actual deletion must evaluate that rule against the current entry rather than trusting the earlier count.
What if the cleanup script returns an error?
Keep the candidate unresolved and classify the actual error before retrying. A successful connection does not prove a script succeeded, and a lost response may hide a completed mutation. Retain enough journal context to replay the same predicate safely.
Is this a point-in-time export procedure?
No. SCAN has weak iteration guarantees under changes, including duplicates and undefined treatment of elements that are not continuously present. Use a separately designed snapshot or export procedure if the reader needs a consistent inventory rather than a cleanup sweep. [1]

Technologies

  • Redis
  • Lua

Sources

  1. [1]
    SCAN, Redis

    Observed 2026-11-08; supports claim S1; rolling documentation, not a release-date claim.

  2. [2]
    Scripting with Lua, Redis

    Observed 2026-11-08; supports claim S2; rolling documentation, not a release-date claim.

  3. [3]
    UNLINK, Redis

    Observed 2026-11-08; supports claim S3; rolling documentation, not a release-date claim.

  4. [4]
    HGET, Redis

    Observed 2026-11-08; supports claim S4; rolling documentation, not a release-date claim.

  5. [5]
    Redis Cluster specification, Redis

    Observed 2026-11-08; supports claim S5; rolling documentation, not a release-date claim.

  6. [6]
    EVAL, Redis

    Observed 2026-11-08; supports claim S6; rolling documentation, not a release-date claim.

Written by

Dopstack Engineering

Engineering team

The engineering team at Dopstack. Illustrative scenarios are composites written to explain a pattern, not accounts of client work.

All articles Website

Get new articles by email

Engineering notes on AI, cloud and SaaS. Occasional, never sold or shared.

Send me new Dopstack Insights articles by email. I can unsubscribe at any time. We’ll email you once to confirm. Privacy

Continue reading