RedisCLI icon
Docker icon
OutputValues icon
Log icon
If icon
Set icon
SlackIncomingWebhook icon
Pause icon
Loop icon
Fail icon
Schedule icon

Redis Unexpiring Key Growth Guard

Catch Redis key prefixes growing without a TTL before maxmemory is reached, alert Slack, then set a TTL with EXPIRE behind an approval and verify.

Categories
DataInfrastructure

A cache key written with SET and no EX never expires. One code path that forgets the expiry turns a cache into a permanent store. The instance keeps growing until it reaches maxmemory. At that point the eviction policy starts throwing away keys that do matter. Or writes start failing with OOM command not allowed. The keys are individually tiny, so nothing looks wrong. A memory alert only fires once the damage is done.

This blueprint reports the leading indicator instead: which key prefixes are accumulating keys with no expiry, how many bytes they hold and how fast they are growing against the previous run.

This blueprint was created by zkasuran.

Findings

Finding Rule Fix
GROWING_UNBOUNDED Over min_keys_to_flag unexpiring keys plus up by more than growth_warn_pct since the baseline. Also any prefix that is new since the baseline Fix the write path. EXPIRE behind an approval bounds what is already there
NO_TTL_STATIC Over min_keys_to_flag unexpiring keys, but flat against the baseline Allowlist it. Or give it a TTL
ALLOWLISTED Matches allow_prefixes, so it is meant to live forever Report only, never expired
OK Nothing unexpiring. Or below min_keys_to_flag None

Safety

  • The walk is SCAN with a COUNT per step and a max_keys ceiling. KEYS is never used: it builds the whole key list in one reply and blocks the server for as long as that takes, with no ceiling. A run that hits the ceiling does not score growth, because a partial walk returns a different slice of the keyspace each time. It alerts instead of reporting the keyspace as clean.
  • EXPIRE needs auto_remediate true, dry_run false, the prefix named in remediate_prefixes, a finding on that prefix, then a human answering the Pause. Five conditions, all of them, before a key gets a TTL.
  • EXPIRE only ever touches a key whose own prefix equals the target and whose TTL is already -1. The allowlist is passed into the script a second time, so an allowlisted prefix is refused inside Redis even if the flow asked for it.
  • A TTL means deletion later. The log says exactly how many keys were changed and when they will go. The re-scan fails the run if any targeted key still reports TTL -1.

How it works

  1. scan_keyspace (io.kestra.plugin.redis.cli.RedisCLI) runs one Lua script through redis-cli --eval. The script walks the keyspace with SCAN, buckets every key on its first prefix_depth segments, counts the keys whose TTL is -1, samples MEMORY USAGE on one key in memory_sample_every, then returns the whole table as JSON.
  2. read_memory and read_keyspace read INFO memory and INFO keyspace. The db line gives keys and expires for the whole database in constant time, so keys - expires is an exact count of unexpiring keys to check the sampled walk against.
  3. assess compares each prefix with the baseline in Kestra KV, classifies it, works out the growth in keys, percent and keys per hour, estimates the bytes each prefix holds and the hours of headroom left at that rate, then resolves which requested prefixes may actually be expired.
  4. summary logs the table. baseline_gate stores this run's counts with io.kestra.plugin.core.kv.Set for the next run, unless the walk was partial, in which case the previous baseline is kept.
  5. route (io.kestra.plugin.core.flow.If): a clean full scan logs it and stops. A finding or a partial scan sends alert to Slack. planned then prints what a remediation run would change.
    • remediate_gate opens only with auto_remediate true, dry_run false and a surviving target. hold (io.kestra.plugin.core.flow.Pause) waits for an answer.
    • On approval remediate_expire (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) runs EXPIRE one prefix at a time, reverify scans each targeted prefix again. verify_result fails the run if any key there still has no expiry. Without approval, declined records the decision and nothing changes.
  6. errors posts to Slack when the flow fails.

What you get

  • A per-prefix table of unexpiring keys with the bytes they hold, instead of one number for the whole instance.
  • The growth rate against the previous run, which is what separates a leak from a prefix that is simply permanent.
  • The hours of maxmemory headroom left if the measured growth continues.
  • A bounded way to put a TTL on a leaking prefix, with the before and after counts and a re-scan that fails the run when the change did not land.

Who it's for

  • Teams running Redis as a cache where one write path has started skipping EX.
  • SREs who have had an instance fill up, then evict session or lock keys or return OOM command not allowed.
  • Anyone who wants a prefix-level view of a keyspace without running KEYS on production.

Why orchestrate this with Kestra

The leading indicator is a difference between two points in time, so it needs somewhere to keep the previous measurement. Kestra KV holds the per-prefix baseline between runs, the schedule decides how far apart the two points are, the allowlist of permanent prefixes lives next to the flow instead of in somebody's head. The destructive half sits behind auto_remediate, dry_run and a Pause with the decision recorded on the execution.

Tested end to end

On Kestra 2.0.5 OSS against a Redis 7 container with maxmemory 8mb and a local HTTP sink standing in for Slack, on the final file. Seeded: session:web 400 keys at EX 3600, cache:render 1,150 and leak:hot 684 already bounded by an earlier run, cache:pages leaking with no expiry, idem:pay 250 permanent keys, config:app 300 keys, allowlisted. Every row was checked against redis-cli as well as the Kestra log.

Run Execution Inputs Result
1 tTT3jInqrR11WgY186TLe defaults, only the expiring prefixes and no leaking one 0 findings. 3,184 keys scanned, all 2,234 expiring keys counted, headroom 78.4%. A baseline is recorded
2 6OzCjKufNyUqpof22UbA6g defaults, after seeding cache:pages cache:pages GROWING_UNBOUNDED at 400 keys with no TTL, new since the baseline. idem:pay flat at 250, so NO_TTL_STATIC. config:app ALLOWLISTED
3 70gsyqHwz5Jbf1iAUwsJVP defaults, 300 more leaking keys cache:pages 700 unexpiring, +300 on the baseline, 75%, 7,297 per hour, 11.2 hours of headroom left at that rate
4 3f1g26e1pguYl6Lx4fZReZ auto_remediate: true, dry_run: true, remediate_prefixes: ["cache:pages"] planned reports it would set a TTL on cache:pages but nothing ran. TTL cache:pages:p1 and :p700 still -1, DBSIZE still 3,484
5 6Pdk9sHR7oojJ0Xzimg1Ek auto_remediate: true, dry_run: false, resumed with approved: false Paused, then declined. TTL cache:pages:p1 still -1, DBSIZE still 3,484
6 3BZZSzwjnonvahalCwkS6G the same, resumed with approved: true 700 keys expired, re-scan reports 0 unexpiring with all 700 keys still present. TTL returns 604787, DBSIZE still 3,484, expires up by exactly 700
7 1SDxAIzlJVRVUD2lqG5g3W defaults, after the remediation cache:pages back to OK, 0 of 700 unexpiring. 550 keys still have no expiry, all under config:app or idem:pay
8 4aTALYb9E2j456HRKpVXG8 allow_prefixes extended with idem:pay 0 findings. redis-cli TTL confirms both allowlisted prefixes are still -1
9 5jJ3DzFP9YcJFVTYsb4ejc unreachable host w19-nope scan_keyspace fails, the errors block posts to Slack, the execution is FAILED
10 2XrGV4WxdR3jz1vJrLnTxe max_keys: 500 500 of 3,484 keys examined. Reported as PARTIAL with the database-wide count of 550 unexpiring keys, alerted rather than called clean. The baseline was left alone
11 372wrIIznavlzPT1wNiBeB remediate_prefixes: ["leak:hot"], with a writer still creating keys with no TTL EXPIRE ran, the re-scan found 8 keys back at TTL -1, verify_result failed the run and errors alerted

Does the detector actually fail on a leak

Run 1 and run 2 isolate that. Nothing else on the instance changed between them except 400 new keys under cache:pages with no TTL. The report went from 0 findings to GROWING_UNBOUNDED on that prefix while idem:pay stayed flat at 250. redis-cli confirmed the leak directly: TTL cache:pages:p1 returned -1. INFO keyspace moved from 3,184 keys with 2,234 having an expiry to 3,484 keys with 2,234. Run 3 measured the growth at 300 more keys in 148 seconds, and run 6 removed it: 700 keys at TTL -1 before, 0 after, with DBSIZE unchanged.

Prerequisites

  • A Redis 6 or later instance reachable from the containers the RedisCLI tasks start. EVAL, SCAN, TTL, MEMORY USAGE and EXPIRE must be allowed for the user.
  • Key names with a separator, for example cache:render:<id>. Prefix bucketing needs one.
  • For a password-protected instance add password: "{{ secret('REDIS_PASSWORD') }}" to each RedisCLI task.
  • Local testing:
    • docker run -d --name redis-cache --network mynet redis:7-alpine redis-server --maxmemory 8mb;
    • seed a leak with for i in $(seq 1 600); do redis-cli SET cache:render:$i v; done;
    • run the flow twice with network: mynet so the second run has a baseline.

Secrets

  • SLACK_WEBHOOK_URL: used by alert and the errors block. In Kestra OSS, provide it as the base64-encoded environment variable SECRET_SLACK_WEBHOOK_URL.

Inputs

Input Default Purpose
host, port, database redis-cache, 6379, 0 The instance to read
delimiter : Separator between key segments
prefix_depth 2 Segments that make a prefix
scan_count 500 COUNT hint per SCAN step
max_keys 20000 Ceiling on keys examined per run
memory_sample_every 25 One key in N is measured with MEMORY USAGE
min_keys_to_flag 100 Smallest prefix worth reporting
growth_warn_pct 5.0 Growth since the baseline that counts as rising
allow_prefixes 3 examples Prefixes that are legitimately permanent
remediate_prefixes empty Prefixes allowed to be expired
expire_ttl_seconds 604800 TTL applied by EXPIRE
approval_timeout PT2H How long the pause waits
network empty Docker network for the redis-cli containers
auto_remediate false Allow EXPIRE
dry_run true Must be false for a change to apply

Quick start

  1. Add the SLACK_WEBHOOK_URL secret.
  2. Import the flow, set host and run it. The first run has no baseline, so it records one.
  3. Run it again after a few hours and read the growth column.
  4. Put the prefixes that are supposed to live forever into allow_prefixes.
  5. For a prefix that is leaking, fix the write path. If you also need to bound what is already there, set remediate_prefixes, expire_ttl_seconds, auto_remediate: true and dry_run: false, then answer the pause.
  6. Enable the every_six_hours trigger, which always runs in safe mode.

How to extend

  • Point it at several instances by wrapping the read tasks in a Loop over a host list.
  • Alert only when hours_to_full drops below a threshold, so a slow permanent prefix stays quiet and a real leak pages someone.
  • Write the baseline after remediation instead of before, if you would rather the next run compare against the fixed state.
  • Replace the Pause with a Slack approval. Or drop it for a prefix you are sure about.
  • Use io.kestra.plugin.redis.string.Ttl for a spot check on a single named key from the Kestra worker itself, without starting a container.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.