Skip to content

[release] feat(micronaut-cache-redis): list cache keys portably with ListableCache (0.4.0) - #134

Merged
pditommaso merged 3 commits into
masterfrom
feat/micronaut-cache-redis-listable
Sep 28, 2026
Merged

pditommaso merged 3 commits into
masterfrom
feat/micronaut-cache-redis-listable

Conversation

@pditommaso

Copy link
Copy Markdown
Contributor

Summary

Micronaut's SyncCache can read, write and invalidate entries, but it can't list them. Code that needs to walk a small cache, for example a periodic sweep over a registry, has had to bypass the cache and talk to Redis directly. Then it no longer works without Redis, e.g. with the default in-process cache for local runs and tests.

This adds that one missing capability behind a portable entry point, so the same code works whether the cache is backed by Redis or by Micronaut's Caffeine cache:

ListableCache.of(cacheManager.getCache("my-cache")).ifPresent(listing -> {
    for (String key : listing.keys()) {
        // an entry can expire or be removed after it is listed — read it and handle absence
        cache.get(key, MyValue.class).ifPresent(this::process);
    }
});

First consumer: the sched VM workload-identity GC. It records each use of an AWS VM instance role in a Micronaut cache, and a 6-hourly sweep lists that cache to find roles left unused for 30 days. The sched PR follows, stacked on seqeralabs/sched#1415.

What changes

  • New io.seqera.cache.ListableCache. One method, Set<String> keys(), which returns the keys a cache holds in string form.
  • RedisCache implements it. It walks the cache's keys with the same SCAN MATCH <cacheName>:* loop invalidateAll() already uses. That loop now lives in one private helper shared by both methods. Keys come back without the <cacheName>: prefix the default key serializer adds, with duplicates removed (SCAN can return a key more than once). invalidateAll() behaves as before; the CROSSSLOT-safe pipelined deletes from 0.3.1 are unchanged.
  • ListableCache.of(SyncCache) returns:
    • the RedisCache itself;
    • a view over the keys of the underlying Caffeine cache, for Micronaut's own Caffeine cache;
    • Optional.empty() for any other cache, so callers can decide to stay off.
  • Caffeine stays optional. It is a compileOnly dependency. Its classes are only touched after a class-presence check, and the Caffeine-typed code sits in a nested class the JVM loads only on that path. Consumers that only use Redis don't pull Caffeine in.
  • VERSION is 0.4.0 (a minor bump, additive only); changelog.txt and README.md are updated (new "Listing Keys" section, and the stale 1.0.0 install coordinate fixed).

Semantics and limits (documented in the Javadoc and README)

  • Weakly consistent. A key present for the whole call is returned; one written, removed or expiring during the call may or may not be.
  • Cost grows with the whole Redis database, not just this cache. SCAN reads every key and filters by prefix afterwards, exactly like invalidateAll(). Batch size is invalidate-scan-count.
  • Cluster-mode Redis with several shards: SCAN on one connection only sees one node's keys, the same limit invalidateAll() already has. With a single shard the listing is complete.
  • Custom key serializers: the prefix handling assumes the default key serializer, as getKeysPattern() / invalidateAll() already do.

Test evidence

  • Unit/integration tests added or updated
  • Relevant test suite run: ./gradlew :micronaut-cache-redis:test, 46 tests, 0 failures (Redis 7.0.4 Testcontainer)
  • No behavior regressions observed: the existing invalidateAll() tests, including the 100-key multi-page scan, still pass after the loop was shared

New tests (each was run against a stub and seen failing first):

  • RedisCacheTest:
    • lists the keys it holds, without the prefix;
    • doesn't list another cache's keys;
    • lists all 25 keys across many SCAN pages (scan count 2);
    • lists nothing for an empty cache.
  • ListableCacheTest:
    • of(RedisCache) returns the cache itself;
    • of(...) lists the keys of a real Micronaut Caffeine cache (micronaut-cache-caffeine 4.3.1);
    • of(...) returns empty for a cache it can't enumerate.

Also exercised end to end from sched through includeBuild: sched's RedisCacheSerializationTest runs the production redis profile against a Redis container. It records, lists and reads back an entry through a real RedisCache with JacksonObjectSerializer, and sched's full test suite passes against this build.

Note: ./gradlew :micronaut-cache-redis:javadoc already fails on master ("malformed HTML" on the @author … <email> lines in RedisCache, CacheValueEncryptor, …). The new file follows the same convention; this PR doesn't change that.

Release

The title carries [release], so merging publishes micronaut-cache-redis 0.4.0. sched will then drop its temporary includeBuild('../libseqera') and consume the published artifact.

🤖 Generated with Claude Code

…che (0.4.0)

Micronaut's SyncCache cannot enumerate its keys, so a caller that needs to walk
a cache (e.g. a periodic sweep over a small registry) had to reach for the
backend directly. ListableCache adds that one capability behind a portable
entry point:

- ListableCache.keys() returns the keys a cache holds, in string form
- RedisCache implements it with the SCAN walk invalidateAll() already used,
  now shared by both; keys are returned without the <cacheName>: prefix and
  de-duplicated. Weakly consistent; on a multi-shard cluster-mode server SCAN
  only sees one node's keys (same limit as invalidateAll())
- ListableCache.of(SyncCache) returns the RedisCache itself, a view over the
  native cache for Micronaut's Caffeine cache, or empty otherwise, so the same
  caller code runs with or without Redis. Caffeine is a compileOnly dependency
  loaded only after a class-presence check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Paolo Di Tommaso <paolo.ditommaso@gmail.com>
@pditommaso

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Claude finished @pditommaso's task in 2m 43s —— View job


Review: ListableCache for micronaut-cache-redis 0.4.0

  • Read the PR diff (git diff origin/master...HEAD)
  • Review ListableCache / CaffeineKeys
  • Review RedisCache.keys() and the shared scanKeys() refactor
  • Review tests, build and release metadata
  • Post review

Verdict: no blocking issues. The change is additive (a new one-method interface plus a static factory; RedisCache gains an interface, no public member is removed or reshaped), the invalidateAll() refactor is behaviour-preserving, and the Redis/Caffeine split is done carefully. Four non-blocking notes below.

What's right

  • scanKeys() extraction is faithful. micronaut-cache-redis/src/main/java/io/seqera/cache/redis/RedisCache.java:307 keeps the same connection, the same ScanParams(match, count), the same do/while cursor termination and the same "skip empty batch" behaviour. The CROSSSLOT-safe pipelined single-key DELs from 0.3.1 moved verbatim into the callback, and passing Jedis alongside the batch is what lets the pipeline still run on the scanning connection. The int[] counter box is confined to one single-threaded call.
  • keys() hygiene: LinkedHashSet de-duplicates the repeats SCAN is allowed to return, the result is wrapped unmodifiable (RedisCache.java:300), decoding uses the same redisCacheConfiguration.getCharset() the key serializer writes with, and stripPrefix (RedisCache.java:324) degrades to the raw key rather than throwing or mangling if a custom serializer doesn't add the prefix. getName() is getCacheConfiguration().getCacheName(), i.e. exactly the prefix DefaultStringKeySerializer writes and getKeysPattern() matches — no off-by-one on ":".
  • The optional-Caffeine dance is correct, which is the part most likely to get this wrong. Class.forName(..., false, ...) doesn't initialise, LinkageError is caught alongside ClassNotFoundException, and all Caffeine-typed bytecode is confined to the nested View so the JVM's lazy constant-pool resolution never touches it when Caffeine is absent. A Redis-only consumer won't see a NoClassDefFoundError.
  • Docs, changelog, VERSION bump and the stale 1.0.0 install coordinate fix are all consistent with the repo's release conventions, and the limits (weak consistency, whole-keyspace SCAN cost, multi-shard cluster, custom key serializers) are documented in both the Javadoc and the README rather than left implicit.

Non-blocking notes

1. The Caffeine listing isn't round-trippable for non-String keys, while the Redis one is. In CaffeineKeys.java:57-58 the view maps native keys through String::valueOf. Micronaut's Caffeine DefaultSyncCache stores the caller's key object as-is, so for a non-String key (e.g. a @Cacheable-generated composite key) keys() returns its toString() and the README's follow-up cache.get(key, MyValue.class) will miss — the native key is the object, not the string. On Redis the same call does round-trip, because DefaultStringKeySerializer converts the key to a string on write, so feeding that string back re-derives the identical Redis key. Since portability across the two backends is the whole point of of(), that asymmetry is worth one sentence in the keys() Javadoc/README: the listing is only usable for read-back when the cache's keys are strings. Relatedly, String::valueOf collapses distinct keys with equal toString() (1 and "1"), so keys().size() can be smaller than the cache size. Fix this →

2. keys() materialises the whole key set. Fine for the stated use case (a small registry swept every 6 hours) and the README says as much, but if a consumer ever points this at a large cache it's one unbounded Set<String> in heap. A forEachKey(Consumer<String>) on the interface, or a stricter "intended for small caches" line in the Javadoc (the README has it, the Javadoc doesn't), would keep that from being a surprise later.

3. Cache names containing glob metacharacters. getKeysPattern() interpolates the cache name into SCAN MATCH, so a name with *, ?, [ or \ matches more than its own keys. Pre-existing — invalidateAll() has had it since before this PR — but keys() now inherits it, and it is the more dangerous direction for invalidateAll(). Worth a follow-up issue rather than anything here.

4. Test fixture nit. redis.caches.list-cache.invalidate-scan-count: 2 (RedisCacheTest.groovy:45) sets no expire-after-write, so that cache's keys are written without a TTL and outlive the spec in the shared container. Every new test calls invalidateAll() first, so it's correct today; adding expire-after-write: '1h' as the neighbouring caches do would keep the fixture self-cleaning if a future test forgets the reset. Also, ListableCacheTest implements RedisTestContainer for all three features though only the first needs Redis — harmless, just slower.

Verification

I could not run Gradle in this environment (the ./gradlew invocation was denied by the sandbox), so I reviewed statically and am relying on the PR's reported run — :micronaut-cache-redis:test, 46 tests, 0 failures — plus CI. The four new RedisCacheTest features cover prefix stripping, cross-cache isolation, multi-page SCAN (25 keys at scan count 2) and the empty cache, and ListableCacheTest covers all three of() branches including a real Micronaut Caffeine cache; that matches the surface added. The pre-existing javadoc failure on @author … <email> is correctly called out as out of scope.

One process note: I'm unable to submit a formal GitHub review or approve a PR for security reasons, so treat the above as review comments — a maintainer still needs to click approve. More detail in the FAQ.
• branch feat/micronaut-cache-redis-listable

pditommaso and others added 2 commits September 28, 2026 17:35
…back

Review of #134: Micronaut's Caffeine cache keeps the caller's key object, so a
non-string key is listed as its toString(), which does not read the entry back
(and equal toString() values collapse), while the Redis cache stores every key
in string form and round-trips. Say so in ListableCache.keys() and the README,
along with keys() building the whole set in memory (small caches only).

Give the list-cache test fixture a TTL like its neighbours, so its keys don't
outlive the spec in the shared container.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Paolo Di Tommaso <paolo.ditommaso@gmail.com>
…tainer

Review of #134: only the RedisCache case of ListableCache.of needs Redis, yet
the whole spec started a container. That case moves to RedisCacheTest, which
already runs one; ListableCacheTest keeps the Caffeine and non-listable cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Paolo Di Tommaso <paolo.ditommaso@gmail.com>
@pditommaso

Copy link
Copy Markdown
Contributor Author

Addressed the review in #134 (comment):

  1. Caffeine keys only read back when they are strings. Confirmed: Micronaut's DefaultSyncCache.put hands the raw key object to Caffeine. The keys() Javadoc and the README now say a listed key reads its entry back only when the cache's keys are strings. They also note that equal toString() values show up once. The Redis cache is unaffected, since it stores every key in string form. Commit 63e8d37.
  2. keys() builds the whole key set in memory. The Javadoc now says it's intended for small caches, in the same commit. I didn't add a forEachKey method: the one consumer is a registry of a few dozen entries.
  3. Glob characters in the cache name. Reproduced on Redis 7.0.4: a cache named user? listed users:alice and its invalidateAll() deleted that key, while tokens[1] hit tokens1: keys and missed its own. Fixed separately in [release] fix(micronaut-cache-redis): keep keys() and invalidateAll() inside the cache's own key namespace (0.4.1) #135, stacked on this PR and released as 0.4.1. It escapes the name in SCAN MATCH, and refuses : in a cache name, a prefix overlap that escaping can't resolve.
  4. Test fixture. list-cache now has an expire-after-write (63e8d37). The Redis case of ListableCache.of moved into RedisCacheTest, so ListableCacheTest no longer starts a Redis container (4a343f5).

./gradlew :micronaut-cache-redis:test: 46 tests, 0 failures on this branch; 54 tests, 0 failures on #135.

🤖 Generated with Claude Code

@pditommaso
pditommaso merged commit 9fe1db2 into master Sep 28, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant