Changelog
v8.2.0 (Current)
Module Group: me.ahoo.cocache · Minor release: a startup eviction check that survives one slow answer, seven fixes found by review, a build against Spring Boot 4.2.0, and a fix that Redis Cluster users on Spring Boot 4.2 need. It adds one public method (RedisBackend.readMaxmemoryPolicies()) and removes nothing; the wire format and channels are unchanged, so 8.2.0 instances can share Redis with 8.1.x and 8.0.x instances and be upgraded one at a time. Two fixes change behaviour you may notice: content that decodes to null now fails a read without a source instead of reading as absent (details), and an unlocked refresh window is now kept when a per-cache entry removes the conflict that defaults caused (details).
Fix: one slow answer no longer fails the startup eviction check
- With an authoritative cache, the starter reads Redis's
maxmemory-policyat startup. That read was made once, withincommand-timeout, and a timeout failed startup with a message that only suggested granting+info, without a cause. This happened when many JVMs started on one host at once and the client could not process the answer in time, though Redis was healthy. A read that times out, loses its connection or meets a transient reply (LOADING,BUSY,TRYAGAIN,MASTERDOWN,CLUSTERDOWN) is now retried, up to 5 attempts with pauses of 0.5, 1, 2 and 2 seconds; a refusedINFOis not retried. The check still fails closed: a policy that can't be read after the retries fails startup, as before. The message now says what happened, a timeout as a timeout and a refusedINFOas a permission problem, and the last failure is its cause. The same applies when the starter creates an authoritative cache after startup; the periodic re-check still reads once. (#1009) - New public API:
RedisBackend.readMaxmemoryPolicies(), which throws the reason instead of returningnulllikemaxmemoryPolicies().
Fix: a Store rejects versioned content even when its digest is right
- A
Storeread a value that carried a version segment and a correct digest segment as a normal value:get,getAll,lookup,lookupAllandlookupRemotereturned it and filled the local copy, andinspectshowedVALUE, whilegetIfChangedrejected the same entry. Such a value belongs to aVersionedStoreorVersionedCachesharing the namespace. Every read now fails withCacheReadExceptionand keeps the entry, andinspectshowsUNREADABLE, as for a versioned value without a digest. AVersionedStorestill reads it. (#1001)
Fix: a payload that decodes to null is unreadable, not absent
- When a codec decoded a stored value to
null(Jackson does for a JSONnull), aStorereported the existing entry as absent:getreturnednull,lookupreturnedAbsentand kept it in the local copy, andgetIfChangedreturnedPresent(null), whileputIfMatch(key, null, …)conflicted with the stored digest. AVersionedStoreread it as a tombstone, and aSetStoreput anullmember in the set. Such content now counts as content that can't be decoded: a read without a source fails withCacheReadExceptionand keeps the entry, and a cache with a loader reclaims and reloads it. (#997)
Fix: malformed invalidation frames reset the channel
InvalidationFrame.decodeaccepted two kinds of malformed frames instead of rejecting them: a key that isn't valid UTF-8 was decoded with replacement characters, so the invalidation hit a different key; and a count or length that overflows anInt(such as80 80 80 80 10, which is 2^32) was truncated, so a frame could pass as an empty probe frame. Either way the channel didn't reset and old local copies stayed untillocal-max-age. Both now throwIllegalArgumentException, and the channel resets its subscribers, as for any frame it can't read. CoCache's own encoder never writes such frames; a legal U+FFFD in a key still decodes. (#995)
Fix: a CacheManager alias no longer bypasses the Spring Cache startup check
- The startup check skips cache operations that name another
cacheManager. An operation that named a Spring alias ofcocacheCacheManagerwas skipped too, though it reaches the same manager: a@Cacheablewithoutsync = truepassedrequire-sync=true, and an operation on aStorefailed only at its first call with "Cannot find cache". Aliases ofcocacheCacheManagerare now checked like the name itself. (#999)
Fix: AOT agrees with the runtime when an alias replaces a scoped codec
- When a same-level Spring alias redirected the name of a scoped-proxy
Codecto another bean, the runtime correctly ignored the replaced proxy's hidden target, but the build-time check still read the old proxy definition and counted the target as a candidate.CoCacheAotProcessorthen assumed a custom codec and left out the Jackson binding hints for the value type, so a native image could miss reflection metadata that the JVM path needs. The build-time check now resolves the alias first, asgetBeandoes, and never creates the target. (#998)
Fix: a per-cache entry can repair a refresh-window conflict that defaults caused
- The starter checked the refresh window once right after
cocache.defaults, before customizers and beforecocache.caches.[name]. When a library locked or pinned a window that conflicted with a globallocal-max-age, creating the cache failed there, althoughcaches.[name].local-max-age(orunlock: [refresh-window]withrefresh-window: "off") made the final configuration valid, and the message even suggested changingcaches.[name]. A window that wasn't locked was turned off at that point, even when a later layer removed the conflict. The check now runs only on the result of every layer; the earlier step turns the window off only temporarily, to build the policy customizers receive. Invalid final configurations still fail as before. (#996)
Fix: a loader that reenters its own key fails fast even after its load was taken over
- A synchronous loader that reads its own key again fails fast instead of deadlocking. But when its load ran past
load.timeoutand another thread took it over and finished, the key had no registered load any more, and the check, which ran only against a registered load, didn't run: the old loader's read became a new leader and called the source again. The calling thread's own loading keys are now checked before it registers, forgetandgetAll, whether or not the load was taken over. (#1000)
Fix: Redis Cluster on Spring Boot 4.2 (Lettuce 7.8)
- Lettuce 7.8.0, which Spring Boot 4.2 manages, rejects a command at once when its Cluster node connection is still being established, if the client rejects commands while disconnected, as CoCache's does. Lettuce opens node connections lazily, so the first command to every primary failed with
Currently not connected. Commands are rejected.: creating the first read-write cache failed, and inshardedmode so did subscribing. CoCache 8.1.0 and earlier are affected on Spring Boot 4.2 with Redis Cluster; standalone and Sentinel are not. The backend now opens a node connection to every primary when it's created (waiting at mostcommand-timeout), takes them by host and port, the connection Lettuce routes commands through, and ashardedsubscription first obtains its primary's connection. The command-connection heartbeat now pings those same connections; it used to ping a separate per-node-id connection that commands never used. (#1023)
Changed: built against Spring Boot 4.2.0
- CoCache 8.2.0 is built and tested against Spring Boot 4.2.0 (8.1.0: 4.1.2). It still runs on Spring Boot 4.0 and 4.1: it is compiled against kotlinx-coroutines 1.10.2, the version those lines manage, and CI also runs its tests on Spring Boot 4.0. CoCache doesn't depend on Spring Cloud, so it doesn't constrain an application's Spring Cloud version (2026.0.0 included). (#1022)
v8.1.0
Module Group: me.ahoo.cocache · Minor release that adds read-only stores. It adds public API and removes nothing; the wire format and channels are unchanged, so 8.1.0 instances can share Redis with 8.0.x instances and be upgraded one at a time. For instances that write, one behaviour changes: the atomic-broadcast probe now runs when the first read-write store is created.
Added: read-only stores
- A
Store,VersionedStoreorSetStorecan be declared read-only on the instances that only read it:readOnlyin the spec (readOnly()on the builder),@CoCache(readOnly = true), orcocache.caches.[name].read-only. Reads and invalidations work as before; every write throwsUnsupportedOperationExceptionbefore it changes anything. On Redis, the reads go out asEVALSHA_RO/EVAL_RO(Redis 7.0+), so the instance's Redis user needs only read permission on the keys (%R~), and the ACL guarantees that it can't overwrite the only copy. Creating such a cache checks the read permissions instead of the publish permission, and names what is missing. See read-only instances and the Redis user. CoherenceBackend.readOnlyStore(keyspace), a new SPI method with a default that returnsnull(not supported). The Redis and in-memory backends implement it, andHookedBackendforwards it.CacheAdmin.readOnlyreports the declaration.- A
CacheorVersionedCachecan't be read-only: it writes Redis when it reads (load leases, refresh tokens, fills).
Changed: the atomic-broadcast probe runs at the first read-write store
- In
pubsubmode,RedisBackendchecked at construction whether a script may publish to a channel in another slot. It now checks when it creates its first read-write store, once per backend, so an instance with only read-only caches never runs it, and its read-only Redis user leaves no denial inACL LOG. - What moves for writers: a timeout during the probe now fails the creation of the first read-write cache, not the construction of the backend, and the next creation probes again. Under the starter both happen at startup.
RedisBackend.atomicBroadcastreadsfalseuntil that first read-write store exists; it never probes or blocks when read, and the newRedisBackend.atomicBroadcastIfProbedisnulluntil the probe ran. The health detailatomicBroadcastshowsnot-probedmeanwhile.
Changed: a refused subscription names the channel pattern
- When the ACL denies
SUBSCRIBEto a cache's invalidation channel, creating the cache now fails with anIllegalStateExceptionthat names the channel pattern to allow, for example[&cocache:inv:*], instead of Redis's bareNOPERMreply.
v8.0.1
Module Group: me.ahoo.cocache · Patch release with two fixes found by the review of 8.0.0. No API, wire format or channel changes, so 8.0.1 instances can share Redis with 8.0.0 instances and be upgraded one at a time.
Fix: transactions over two independent backends
- A transaction that used the same key prefix, namespace and key on two independent backends treated them as one piece of data. On rollback only the first backend's fill was invalidated, and the second kept the uncommitted value until its
ttl. On commit, anevicton one backend dropped the deferredputon the other. The two are now told apart, and each is invalidated and written on its own. Two runtimes on the same backend still count as one piece of data: a later invalidation still supersedes an earlierput. (#977) - Two backend objects connected to the same Redis count as two pieces of data: a rollback invalidates each once, but an invalidation through one does not supersede a deferred
putthrough the other. Share one backend object in such a setup.
Fix: a timed-out Redis command is abandoned before the caller sees the timeout
- When a command timed out on the backend's own timer (a client passed to
RedisBackend.of, a Redis Cluster client, or a readtimeoutshorter thancommand-timeout), the caller was told about the timeout just before the command was abandoned. A script that was not yet written to Redis could still be written in that window, after the caller had seenCommand timed out. The command is now abandoned first, for single commands and batches. A command that Redis already received can still run: its result stays unknown, as before. (#974)
v8.0.0
Module Group: me.ahoo.cocache · The first stable release of 8.x, a major release with breaking changes (RFC 0005). Its code is that of 8.0.0-rc.2, on which CoSec and Wow ran their test suites. 8.x doesn't run next to 6.x on one Redis: stop 6.x, then start 8.x (Upgrading from 6.x). Fixes for 6.x continue on the 6.x branch.
The compatibility promise starts here. Within 8.x, the public API of the published modules (the user API and SPI included), the published TCK, the starter's annotations and configuration keys, metric names, endpoint paths and the Redis wire format change only compatibly (CONTRIBUTING lists what the promise covers). A new part of the wire format that readers must understand ships in two releases: readers first, writers once every instance reads it.
Upgrading from 6.x
There is no migration tool: stop every 6.x instance, delete the keys of caches without a source, then start 8.x, and caches with a source reload from it. Upgrading from 6.x maps 6.x types, configuration keys, Redis ACLs and the backend SPI to 8.0. The changes themselves are recorded below by pre-release: 8.0.0-alpha.1 brought the 8.0 design and lists every change from 6.x, and each later pre-release lists what changed after the one before it, breaking changes first.
Upgrading from a pre-release
- From 8.0.0-rc.2: nothing to change. The code is the same, so keys written by rc.2 stay valid.
- From an earlier pre-release: delete every CoCache key first, as between pre-releases: keys an earlier pre-release wrote may not be readable. Then read the notes of each later pre-release, breaking changes first: rc.2 moves
CacheNameContributortococache-spring, and rc.1 has four.
The pre-releases
8.0.0 went through eight pre-releases, from alpha.1 (2026-11-04) to rc.2 (2026-11-08). Their notes follow unchanged, newest first.
v8.0.0-rc.2 (Pre-release)
Module Group: me.ahoo.cocache · Second release candidate of 8.0.0. It carries the fixes from CoSec's and Wow's trials of rc.1 and for the issues filed since. There is one breaking change, listed first: CacheNameContributor moved to cocache-spring. Like every pre-release, it carries no compatibility promise until GA; see v8.0.0-alpha.1 for the upgrade notes and the full list of 8.0 changes.
Breaking changes
CacheNameContributormoved from the starter (me.ahoo.cocache.spring.boot) tococache-spring(me.ahoo.cocache.spring.CacheNameContributor). A library that creates caches at runtime usually depends oncocache-corebut not on the starter, so it couldn't publish the contributor without pulling Spring Boot in. Change the import, and any string that names the class, such as@ConditionalOnClass(name = "me.ahoo.cocache.spring.boot.CacheNameContributor"): a stale name doesn't fail, the condition silently stops matching and the contributor isn't registered. The starter reads the bean as before, and its message for an undeclared cache now names the interface by its full name. (#964)
Fixed
- The eviction check counted an authoritative cache as never expiring whenever its policy
ttlwasforever, even when it wrote entries with their own lifetime:put(key, value, ttl),putAll(entries, ttl),putIfMatch(…, ttl),VersionedStore.putIfNewer(…, ttl),SetStore.put(key, set, ttl), or a spec'sttlOf. Those keys carry a Redis expiry, sovolatile-*can evict them before they expire, yet the check reportedvolatile-*as safe, even withstore-eviction-check: fail. A revocation list written this way could lose an entry early, and the revoked token would be valid again. The engine now records the first such lifetime each instance sees, from its own writes or from reading such an entry back from Redis, so an instance that only reads learns of it too (CacheAdmin.observedEntryTtl), andStoreEvictionRiskcounts that cache as expiring. The starter's health detail picks it up without reading Redis again and logs a warning for a new risk. Startup can't see these writes, so an authoritative cache that writes its own ttl belongs onnoeviction. (#965) - Spring Boot starter: when an alias in the same context pointed a scoped proxy's name
xat another bean (possible only with bean definition overriding allowed), the replaced proxy's hidden targetscopedTarget.xstill counted as a by-type candidate. A cache that matches its loader or codec by type then saw two candidates and failed to start, although Spring's own by-type injection skips that target. The hidden target is no longer a candidate; a bean whose name merely starts withscopedTarget.is still used under that name. (#899) - An interface cache or join view whose interface redeclared
equals,hashCodeortoString(for example Kotlin'soverride fun toString(): String) was rejected at creation as declaring an unsupported abstract method, although the JDK proxy dispatches these calls asObjectmethods. Redeclarations withObject's signatures are now accepted and keep the proxy's identity semantics; any other abstract method is still rejected before the cache is registered. (#902) - Spring Boot starter: a refresh window pinned by a library (
Locks.pin) was checked against a global layer with the value the declaration had before the pin replaced it. With a declared window of 30s pinned to 10s oroff,cocache.defaults.cache.local-max-age: 20sfailed cache creation, and the message named the replaced 30s as the pinned value. Pinned values now take effect before any layer is applied, so every check sees them; a pinned window that really conflicts with a global layer still fails, naming its own value. (#967) - Spring Boot starter: messages about a
cocache.caches.[name]entry wrote its path without brackets,cocache.caches.user.ttl, which isn't a valid key for a cache whose name contains dots. They now writecocache.caches.[user].ttl, the form the docs use, and the key can be copied as is. A rejected override of a pinned field now shows the pinned value as it is configured (throw), not as an enum name (THROW). (#966)
v8.0.0-rc.1 (Pre-release)
Module Group: me.ahoo.cocache · First release candidate of 8.0.0. It carries the pre-GA architecture review: four module reviews plus what the downstream trials of CoSec and Wow asked for. Since alpha.6 there are four breaking API changes, listed first; the engine is split into smaller collaborators without behavior change, and the performance budgets of RFC 0005 §7 still hold against 6.10. Like every pre-release, it carries no compatibility promise until GA; see v8.0.0-alpha.1 for the upgrade notes and the full list of 8.0 changes.
Breaking changes
- SPI:
SetL1Store.addMembers/removeMembers(andFutureSetL1Store) return the sealedL1SetWrite(WrittenorUnreadable(format)) instead ofInt?. A Java future completing withnullnow fails instead of meaning "written". (#912) CachePolicyhas no public constructor and nobuilder()without a base. Build a whole policy from a type default withDefaultPolicies.STORE.toBuilder()orCachePolicy.builder(DefaultPolicies.STORE), so an authoritative cache can no longer inherit a derived cache's 1 httlby accident (storeSpec { policy = CachePolicy(localMaxAge = …) }used to do that silently). (#913)putIfNewer,invalidateIfNeweranddeleteIfNeweraccept anullttl, meaning the policy's lifetime (ttlOffirst; the tombstone lifetime for tombstones), so callers with an optional lifetime need no branches. Callers compile unchanged; only a hand-written implementation of these interfaces changes its signatures. (#922)StoreandVersionedStore(and their async and suspending views) gainlookupRemote(key): one read of the only copy in Redis, without L2, a lease or coalescing, answeringLookup.Known(PresentorAbsent) and throwing on a Redis failure regardless ofunknownRead.Lookup.Knownis a new sealed supertype ofPresentandAbsent. Callers compile unchanged; only a hand-written implementation of these interfaces needs the new method (reading a Store). (#955)
Added
HookedBackend.failReads(cocache-test) fails only reads (single-key, batch and conditional), so an application test can check how reads degrade while writes keep working.- The async views gain
suspending()and the suspending views gainsync()(default methods with covariant return types), so each view reaches the other two directly:asyncStore.suspending()instead ofasyncStore.sync().suspending(). (#917) CacheFailures.isTransient(error)tells whether a failure is temporary: source-load timeout, rejection or cancellation, or an L1 read or write failure that isn't unreadable content. Callers no longer catch each exception type (retry or degrade). (#919)- Spring Boot starter: new
CacheNameContributor. A library that creates caches at runtime publishes the names it may create, sococache.caches.[name]entries for them no longer fail startup as undeclared caches. Contributors are read once all singletons exist, lazy ones included, and only the contributed names are relaxed (startup validation). (#921) - Typed sentinel setters
ttl(Ttl),tombstoneTtl(Ttl),refreshWindow(RefreshWindow)andmaxConcurrent(Concurrency), the constantsTtl.FOREVER,RefreshWindow.OFFandConcurrency.UNLIMITED, andPolicyFields(one Java constant per policy field). In Java,ttl(null),tombstoneTtl(null),refreshWindow(null)andmaxConcurrent(null)are now ambiguous: use the constants. (#927) Locks.Builder.pin(field, value)(also in theCoCacheFactory.create(spec) { … }DSL) locks a field and fixes its value in one step. It's reported aspinned by <owner>, andcocache.caches.[name]can't override it, not even withunlock(locking fields). (#936)- Redis backend: the command connections now have a heartbeat as well. Each is pinged every
heartbeat, and aftercocache.redis.command-heartbeat-failures(default 3) consecutive failures it is dropped and Lettuce reconnects it, so a half-open command connection no longer times out every command until the kernel notices.RedisBackend.commandConnectionHealthyand thecommandConnectionhealth detail report it; the health status is unchanged (command timeouts). (#925) - Redis backend: abandoned token releases are counted (
RedisBackend.abandonedTokenReleases, metercocache.redis.releases.abandoned), and their warnings are aggregated to at most one every 10 seconds plus a summary, so a command-timeout storm no longer floods the log. (#937) - Spring Boot starter: new
CacheRuntimeBuilderCustomizerandRedisBackendOptionsCustomizer. They adjust the runtime builder and the Redis backend options after the starter's own wiring, in@Orderorder, so you no longer have to replacecocacheRuntimeorcocacheBackend(which drops the clock, observers, executors and close timeout the starter wires) (customizers). (#923) - SPI: new default method
CoherenceBackend.unwrap(type)returns the backend itself or, for a wrapper such asHookedBackend, the wrapped backend. Checks that need a concrete backend (like the Redis eviction check) no longer skip a wrapped one (extending). (#946)
Changed
- A key CoCache doesn't define under
cocache.defaultsorcocache.overridesnow followscocache.caches-validation, as one undercocache.caches.[name]already did (#846):fail, the default, stops startup andwarnlogs it. Most such keys are left over from 6.x, such ascocache.defaults.ttl(8.x fields sit undercocache.defaults.cacheorcocache.defaults.store) orcocache.defaults.key-prefix(nowcocache.key-prefix), and Spring Boot used to ignore them silently. A silently ignoredkey-prefixput applications that shared one Redis under different prefixes onto the same keys and channels. The message says where each layer's keys go. Other keys undercocache, such ascocache.redis.*, are unaffected (startup validation). - The messages of
CacheReadExceptionandCacheWriteExceptionend with a summary of the cause, its class and message, so a one-line log names the reason. For example:Cache[x] - putIfNewer failed on the remote store (not executed): ForeignFormatException: …. Before, the reason was only in the cause. - When an unknown key under
cocache.cacheslooks like a cache name with dots that is missing its brackets, such ascocache.caches.wow.shop.order.ttl, the startup message suggests the bracketed formcocache.caches.[wow.shop.order].ttl. KeyFilter.notExistnow receives the encoded key (theKeyEncoderoutput, without{keyPrefix}{namespace}:) instead of the full storage key, the same keyCacheAdmin,ExternalInvalidatorand invalidation listeners use, so a filter keeps answering after an operator changeskey-prefix. A filter built from storage keys must be rebuilt from encoded keys.CacheAdmin's per-key operations, the actuator endpoint andExternalInvalidatorreject a key that starts with the cache's{keyPrefix}{namespace}:(a pasted full Redis key) withIllegalArgumentException; before, the call addressed a key no cache reads and appeared to succeed. (#915)- A runtime without an explicit clock adopts the clock an
InMemoryBackendwas built with (InMemoryBackend.clock), so tests pass aManualClockonce.ManualClock.advancerejects sub-millisecond durations instead of silently dropping them. (#924) - Redis backend: a scalar write is now a single
SET … PXand set members are written in chunks with multi-fieldHSET/HDEL, so writes make fewer Redis calls inside their scripts. The wire format is unchanged; script SHAs change, andEVALSHAfalls back toEVALduring a rolling upgrade. (#938) - Redis backend: a batch of commands (
getAll,putAll, batched invalidation and fills) now shares one deadline instead of scheduling a timer task and allocating a future per command. Timeouts behave as before. (#939) - Spring Boot starter: the
cocacheMeterBindingPostProcessorbean is removed.CoCacheMeterBinderalready binds every cache when it is created, lazily initialized cache beans included, so metrics are unchanged. (#940) - Spring Boot starter: a constant
@JoinCacheable.joinKeyExpression(a template without#{...}) now fails startup withIllegalArgumentException, like a constant@CoCache.keyExpression, instead ofIllegalStateException. (#942) - Spring: the second constructor parameter of
CoCacheSpringCacheManager(create a declared cache on first lookup) is ajava.util.function.Consumer<String>rather than a Kotlin function type, so Java callers don't returnUnit.INSTANCE. (#951) - Redis backend: a single-key write whose command fails before it is written is now reported as not executed (
CacheWriteException.outcomeUnknown = false), like a failed group of a batch write. (#944) - The Redis eviction check for authoritative caches (
Store,VersionedStore,SetStore) now also runs when such a cache is created after startup: through the starter'sCoCacheFactorya fatal risk fails that creation, and any other creation gets a warning. It can re-readmaxmemory-policyperiodically (cocache.redis.store-eviction-check-interval), shows its last verdict for all authoritative caches in the health details, and is reusable without Spring asStoreEvictionRisk.check(runtime)incocache-redis. The check, the Redis health details, the abandoned-releases meter and the close timeout all see through wrapped backends such asHookedBackend(eviction check). (#947) - A runtime without an explicit clock also adopts the clock of a wrapped
InMemoryBackend(such asHookedBackend(InMemoryBackend(clock))), found throughCoherenceBackend.unwrap. (#952) - Spring Boot starter: the Spring Cache wiring (
cocacheCacheManager,cocacheDegradingCacheErrorHandler,cocacheSpringCacheSyncCheck) moved to its own auto-configuration,CoCacheSpringCacheAutoConfiguration. Bean names are unchanged; exclude that class to switch off only CoCache's Spring Cache integration (other cache managers). (#954)
Fixed
- Native images:
GET /actuator/cocachereturned 500 (KotlinReflectionInternalError: Unresolved class: class kotlin.collections.EmptyList) whenever a report held an empty list, because jackson-module-kotlin introspects Kotlin's empty-collection singletons and the native image had no reflection hints for them. The starter now registersEmptyList,EmptySetandEmptyMap, which also covers cache values with empty collections encoded byJacksonCodec. (#960) - Closing a
CacheRuntimefrom code that runs inside one of its own coroutines but not on a thread its dispatcher handed out waited for itself untilcloseTimeout(5 s by default), then logged "CacheRuntime closed with N coroutines still running". This happened when aLoadObserverclosed the runtime while observing an async or suspending load, and when a data source closed it before the call's first suspension, which runs on the caller's thread. These threads now carry the runtime's own mark, as dispatched tasks already did (#872), soclosedoes not wait for itself; closing a different runtime from them still waits for that runtime to drain. (#892) invalidationsReceived(cocache.invalidations.received) counted a message from another instance before applying it. Code that waited for the count to rise and then read the cache, as the TCK suites do, could still see the evicted copy, so cross-node TCK cases failed now and then (seen on Valkey). The message now takes effect first: when the count rises, the local copies of its keys are already evicted.InMemoryBackend.writeForeignaccepted anykey, though it needs the full storage key (keyspace.storageKey(encodedKey)). Given the encoded key, which is what a downstream test naturally holds, it wrote into a slot no cache reads, so the following assertions passed for the wrong reason. A key that doesn't start with the keyspace's storage prefix is now rejected withIllegalArgumentException.- When the backend threw an
Errorwhile a cache was being created, for example aTODO()in an unimplemented SPI method or anExceptionInInitializerError,CacheRuntime.createdidn't roll the registration back. The cache name and keyspace stayed taken and the engine stayed open, so retrying the same name failed with "already exists". Creation now rolls back on any throwable and rethrows it unchanged. - A refresh that didn't get the refresh token treated an
Errorthrown by the codec while re-reading Redis as unreadable content and fell back to a full load; the error now propagates, as on every other read path. An asyncSetStoreread in flight when the runtime closed, whose Redis read then failed, completed withCacheReadException; it now fails with the original exception, as scalar caches already did. A cache without a loader that declaresrefresh-windowno longer allocates on every local hit inside the window. (#911) - Redis Cluster in
pubsubmode: a failed heartbeat now forces the subscription connection to reconnect, as on a single node, instead of only warning and waiting for TCP keepalive (meanwhile every heartbeat cleared L2). Inshardedmode the heartbeat pings every subscribed node concurrently, so several bad nodes no longer delay detection by one command timeout each. (#914) - Spring Boot starter: under
spring.main.lazy-initialization, the warning forcocache.caches.[name]on an unlayered cache works again, and aCacheused only through@Cacheableis created on the first call instead of failing with "Cannot find cache" (CoCacheSpringCacheManagertakes an optionalcreateDeclaredfunction for this). Spring AOT detects the Jackson fallback by the same rule as the runtime when a child context's alias shadows a parentCodec, so the native image gets its binding hints. (#918) - The per-call lifetime ceiling (
CachePolicy.ttlCeiling, set bycocache.overrides.cache.ttl) applied by code path rather than by type. AVersionedCacheclamped lifetimes fromttlOfon loads, and aStoreclamped them onput. It now applies toCacheonly, as documented. AStore,VersionedStore,SetStoreorVersionedCachespec whose policy carries attlCeilingnow fails withIllegalArgumentExceptioninstead of applying it in some paths. (#929) - Spring AOT: the starter registers the Lettuce method that the Redis Cluster force-reconnect calls by reflection, so a native image also reconnects a failed classic Pub/Sub connection instead of only warning. (#950)
- Spring Boot starter: when a global layer conflicts with a refresh window that a library pinned, locked or constrained, cache creation now fails with an explanation instead of silently turning the window off (startup validation). (#953)
v8.0.0-alpha.6 (Pre-release)
Module Group: me.ahoo.cocache · Sixth pre-release of 8.0.0, with the fixes from the third round of the GA invariant audit. Like every pre-release, it carries no compatibility promise; see v8.0.0-alpha.1 for the upgrade notes and the full list of 8.0 changes. One behaviour change: JacksonCodec now encodes with the declared type, so with a declared type that is not polymorphic, properties that only a subclass has are no longer written (#873).
Fixed: Spring Boot configuration and startup
- When a child application context defined a bean with the same name as a scoped-proxy loader, codec or
JoinKeyExtractor(@Scope(proxyMode = …)) in a parent context, the parent's internalscopedTarget.<name>bean was still matched by type. Startup then failed with "Multiple CacheLoader beans … [loader, scopedTarget.loader]", or, when the child bean had another type, the hidden parent target was injected as the data source, bypassing its scope. A same-name child bean now hides the parent's proxy together with its target. (#865) - In a child application context, an alias that points a name at a bean in a parent context was ignored by the starter's name checks. A join cache whose
firstCacheNameorjoinCacheNamewas that alias silently joined the parent's spec cache with that cache name instead of the alias target, and a loader name that such an alias redirected to a bean of another type was still matched by type, so startup failed with a false "Multiple CacheLoader beans". A child's alias now hides a parent's bean of the same name, as it does forgetBean. (#887) - In a child application context,
@JoinCacheable.firstCacheNameandjoinCacheNamecould name a spec cache declared in a parent context only by its bean name; its cache name failed startup with "does not match any cache". Names now resolve through parent contexts by cache name or bean name, and a child bean still hides a parent's bean of the same name. (#875) - Another
@ConfigurationPropertiesclass bound to thecocacheprefix (for example one that reads onlycocache.enabled) replaced the record of unknown keys, so a valid key such ascocache.caches.user.ttlfailed startup as unknown. Only the binding of CoCache's own properties is checked now. (#867) - An application that supplied its own
CacheRuntimewithout also exposing its backend as aCoherenceBackendbean failed startup incocacheStoreEvictionCheck("No qualifying bean of type CoherenceBackend"). The eviction check now uses the runtime's own backend, so a custom runtime on Redis is still checked. (#874) - With two
ObjectMapperbeans and no@Primary, startup failed withNoUniqueBeanDefinitionExceptioneven when no cache needed the Jackson codec (every interface cache names a codec or matches aCodecbean, or the application declares only specs). TheObjectMapperis now looked up only when an interface cache falls back to Jackson, and that cache then fails with a message naming it and the candidates. (#883)
Fixed: interface caches, join views and codecs
CoCacheFactory.create(type, spec)with asealedinterface created and registered the cache and notified the creation listeners, and only then failed because a JDK proxy can't implement a sealed interface; a retry with a valid interface then failed with "Cache[users] already exists.". Sealed interfaces, and any other interface a JDK proxy can't implement, are now rejected before anything is created. (#879)JoinView.gettreated a missingSetStoreset as present, becauseSetStore.getreturns an empty set for a missing key: a missing first key returnedJoinValue([], null, null)instead ofnull, and a missing joined set gavesecondValue = [], whilegetAllleft both out. Single and batch reads now agree, and an empty set stored as a value in a scalar cache is still present. (#870)JacksonCodecencoded a value by its runtime type and decoded it by the declared type, so a polymorphic element type in a generic container (List<Animal>orMap<String, Animal>with@JsonTypeInfo) lost its type id: aStore.putsucceeded and the next read threwCacheReadException. It now encodes with the declared type as well. With a declared type that is not polymorphic, properties that only a subclass has are no longer written; decoding never read them back. (#873)
Fixed: transactions
- A load that a creation listener started while a cache was being created, before its
fill-in-transactionandinvalidate-fills-on-rollbackmodes took effect, could read one mode before they took effect and the other after. Withprivateandinvalidate-fills-on-rollback: false, the load's fill was then shared but not invalidated on rollback, and the rolled-back value stayed in Redis untilttl. A call now reads both modes once and uses them for its whole run. (#868) - When a
CacheErrorHandlercompensated for a failed eviction during commit through the transaction-aware cache it was handed (anevictor aputof another key), aputof that key registered earlier in the transaction ran afterwards and wrote its older value back. An operation issued while the transaction's cache operations run now supersedes the same key's pending writes. (#878)
Fixed: reads, loads and local copies
- A value read from Redis got a local copy whose lifetime was counted from when decoding finished, not from when Redis was read. A slow
Codec.decode, or the decoding of earlier keys in the samegetAll, therefore let the local copy outlive the value in Redis, and new reads kept returning it after it had expired there. The local copy's lifetime now starts before the read (and before a fill is sent), for every cache type,SetStoreincluded. (#877) - A
getAllwhose keys included one that can't be encoded losslessly as UTF-8 (an unpaired surrogate) threwIllegalArgumentException, but an earlier key of the batch that was insiderefresh-windowhad already started a refresh-ahead from the source. The whole batch is now checked before any refresh, whatever the key order. (#866) - A batch read whose
Codec.decodethrew anError(such asAssertionError) for a key found in Redis kept the leases it had taken for the batch's missing keys, so later reads of those keys loaded from the source but bypassed Redis until the leases expired (10 s by default). Every lease the batch took is now released before the original error is rethrown. (#886) - When a
LoadObserverread another cache while recording a failure, anAsyncCacheLoaderfuture of the outer load failing withInterruptedExceptionwas again taken for an interrupt of the leading caller, and the other sync readers of the key each called the source again; the alpha.5 fix covered only loads without nesting. Each sync load now keeps its own record. (#864) - When the method behind
@Cacheable(sync = true)(or theCallablepassed to the Spring cache'sget(key, valueLoader)) was interrupted, the callers waiting on the same key got the interrupted caller's failure instead of running the method themselves. They now load on their own, and the interrupted caller sees the same exception as before. (#871)
Fixed: observation and shutdown
- A suspending load under a propagated parent observation (a
ThreadContextElementthat opens the parent's scope) ran the loader with the parent as the current observation instead of the newcocache.load, for a declaredAsyncCacheLoaderand for a call-level suspending loader alike. The loader now starts undercocache.load; the caller's other context elements, such as MDC, are kept. (#876) CacheRuntime.close()called in an async result's callback that ran after the runtime's executor had rejected a task waited the wholecloseTimeout(5 s by default) for itself. It now returns without waiting, as it does when the executor accepts the task. (#872)
v8.0.0-alpha.5 (Pre-release)
Module Group: me.ahoo.cocache · Fifth pre-release of 8.0.0, with the fixes from the second round of the GA invariant audit. Like every pre-release, it carries no compatibility promise; see v8.0.0-alpha.1 for the upgrade notes and the full list of 8.0 changes.
Fixed: configuration and startup
- The unknown-key check under
cocache.caches.[name]added in alpha.4 bound the properties a second time with Spring Boot's default converters, so a value that only an application's@ConfigurationPropertiesBindingconverter accepts (such as a custom alias forread-failure) failed startup. The check now runs inside the regular binding ofCoCachePropertiesand uses the same converters. - A rejected creation through
CoCacheFactory(for example a duplicate name) had already rewritten the existing cache'sfill-in-transactionandinvalidate-fills-on-rollbackmodes, so rolled-back data could stay cached. The modes now take effect only when the cache they were computed for is created. - A cache interface ignored a
CacheLoader,AsyncCacheLoader,CodecorJoinKeyExtractordeclared in a parent application context when matching by type. ACachethen failed startup with "no data source", and a cache without a codec silently fell back to Jackson instead of the parent'sCodec<V>. Matching by type now includes ancestor contexts; a child bean with the same name still hides the parent's, and a match in each context is ambiguous. - A loader, codec or
JoinKeyExtractordeclared as a scoped proxy (@Scope(proxyMode = …)) and matched by type was injected as its target, so its scope no longer applied (a prototype loader kept one instance). The proxy is now injected. Naming a scopedJoinKeyExtractorwithjoinKeyExtractor = "…"no longer fails startup with "is not aJoinKeyExtractor<V1, K2>". - A spec bean declared as a
FactoryBeanwith full generics (fun recordsSpec(): FactoryBean<StoreSpec<String, String>>) failed startup with "must declare its generic types".KandVnow come from the factory's product type, without creating the factory. @CaffeineCache(maximumSize = 10000), an explicit value equal to the default, wasn't recorded as written, sococache.defaults.*.local-maximum-sizereplaced it. AnymaximumSizeother thanUNSETnow counts as written.CachePolicy.BuilderhaslocalMaximumSize(Java:localMaximumSize(Long)), which always counts as written.- A cache interface that inherits its type arguments through a generic intermediate interface (
interface UserStore : BaseStore<User>,BaseStore<V> : Store<String, V>) decoded values read from Redis asLinkedHashMapwith the default Jackson codec, so reads threwClassCastException; members ofList<User>and set elements were affected too. The codec, and the AOT binding hints, now use the inherited types.
Fixed: creating and closing caches
CacheRuntime.createracingclose()could finish after close returned, adding a cache and leaving its invalidation subscription open. A cache is now handed to the runtime only once its subscription is confirmed and while the runtime is open; otherwise the creating call closes what it built and fails withCacheRuntime is closed.- A cache whose subscription was still pending was already visible to
cacheNames,cache,adminandmetrics, so the Micrometer binder could bind an engine that then rolled back; after a same-name retry the meters kept reading the discarded engine. A cache is now visible only once it has been created. - Two caches whose storage prefixes
{keyPrefix}{namespace}:were equal or one started the other (for exampleapp:+usersandapp:users:+v2) could both be created, overwrote each other's keys in Redis and missed each other's invalidations. Creating the second in the sameCacheRuntimenow fails, naming the first. Caches of different runtimes or applications sharing one Redis are not checked: give them prefixes that don't start one another. - An async or suspending call issued after
CacheRuntime.close()still ran: aputchanged Redis and other instances read the new value, while the caller gotIllegalStateException("CacheRuntime closed."). Such a call now fails without running. - A refresh-ahead queued on a caller-provided
refreshExecutorbeforeCacheRuntime.close()but started after it still loaded from the source and wrote the new value to Redis. Such a refresh is now skipped.
Fixed: transactions
- A value loaded in a transaction for the empty business key
""(or a key a customKeyEncoderencodes as"") is now invalidated on rollback and on a rollback to a savepoint. Before, the invalidation was rejected as an empty encoded key and the uncommitted value stayed cached untilttl. AVersionedCachekeeps its version fence. (#823) - A value that another synchronization's
savepointRollbackcallback loads, before Spring rolls the database back to the savepoint, no longer survives the outer commit. A transaction that rolled back to a savepoint now also invalidates what it loaded when it commits, and keys it had loaded by then load privately for the rest of the transaction underregistered-keys. (#814) - An eviction or
put(key, null)that another synchronization makes inafterCommit, after CoCache's own has run, now hands its failure to theCacheErrorHandlerinstead of throwing it into the committed transaction and skipping the laterafterCommitcallbacks. (#838)
Fixed: interface caches
- An interface cache could narrow a fixed return type, such as
override fun getAll(keys: Collection<String>): SortedMap<String, String>in aStore(or the result of asuspendmethod), and creating it succeeded; the first call then failed withClassCastException, because the cache returns aLinkedHashMap. Creating the cache now fails, before anything is registered. Narrowing the value type (getreturningUserinstead ofV) still works. (#843) - A join cache interface could declare an abstract method whose parameters the target can't take, such as
getAll(keys: String), and only the first call failed withClassCastException. Creating the proxy now fails, like for interface caches. (#833) - A default method declared in a package-private interface, either the interface you declare or a package-private base of a public one, failed on every call with
IllegalAccessException(wrapped inUndeclaredThrowableException). It now runs, in interface caches, their async and suspending views, and join caches. In a named module, open the package to CoCache, or creating the cache fails. (#827)
Fixed: Redis commands and invalidation channels
- When Redis answered a script's
EVALSHAwithNOSCRIPTbefore Lettuce handed the command back, a command timeout no longer lets the queued fallbackEVALrun afterwards. A timed-out write that was not yet sent is now always dropped, instead of possibly overwriting a newer value later. - A batch load whose L1 fills were partly rejected before they were sent was reported as not executed as a whole, so on a
VersionedCachea fill that did advance the version skipped its local fence and an earlier reader on the same instance could leave the old version in L2. A batch with mixed outcomes is now outcome unknown, and every versioned fill in it is fenced. - A
SetStorehash with an explicit empty!mfield could be read while writes rejected it as a higher format. Reads now treat it as a higher format as well: they fail withCacheReadExceptionand keep the content. - Creating a cache on a thread whose interrupt flag was set could fail with
InterruptedExceptionwhile waiting for Redis to confirm the subscription, and cleared the flag. The wait now ignores interrupts: the cache is created and the flag is kept. - An invalidation listener whose
onResetthrew when it joined an existing channel madesubscribefail but stayed registered, receiving invalidations with no way to unsubscribe. The failure is now logged andsubscribereturns a closable handle, on the Redis and in-memory backends.
Fixed: loads, refreshes and writes
- When a
FillScope.filledhook (transactional fill recording) threw, a read kept the Redis leases it had taken, so other reads of those keys waited up tolease-waitand bypassed Redis until the lease expired (10 s by default). The read still fails with the hook's exception, and now releases every lease first, for a single key and for every key of agetAll, and fills neither layer. - A sync loader that read its own key again after running longer than
load-timeoutstarted a second load of that key instead of failing withIllegalStateException, so a recursive loader could load without bound. Reentry now fails fast whether or not the load has expired, and other threads still take over an expired load. - When an
AsyncCacheLoader's future failed withInterruptedException(the source was interrupted on its own thread), sync readers of the same key treated it as an interrupt of the leading caller, and each of them called the source again. They now share the failure like any other source failure: every caller gets the same exception, with no interrupt flag set, from one source call. An interrupt of the calling thread itself, including one insideloadAsyncbefore it returns its future, still lets the other readers load on their own. - Two concurrent writes of the same key whose outcome was unknown could shorten the window in which the instance applies its own late invalidation (
localMaxAgeafter the later failure), when the write that read the clock first registered last. A late write inside the later window was then filtered, and the instance kept serving its old local copy untillocalMaxAge. The window now always ends at the latest deadline registered for the key. - A
SetStore.putAllthat mixes non-empty and empty sets reportedoutcomeUnknown = falsewhen its delete was rejected after the replacements had reached Redis, and on a backend without atomic broadcast other instances kept their old copies of the replaced keys. It now reportsoutcomeUnknown = trueand broadcasts the whole batch. - When a
VersionedCacherefresh was refused because the source returned an older version (or anullwithout a version), the local copy it kept got the lifetime Redis reported before the load, so after a slow load it outlived the value in Redis. It now expires with that value, and a copy that expired in Redis during the load isn't put back in L2. get(key, loader)on the sync, async and suspending views of aCachedidn't start refresh-ahead when it hit a local copy insiderefresh-window. It now schedules the refresh through the declared loader, likeget; the per-call loader still only serves misses.- A
Cacheread that found content written in an older format (or not by CoCache) could, if aputof the same bytes landed before the read reclaimed the key, reclaim that new value and write its own reload over it; other instances then read the stale reload untilttl. The reclaim fingerprint now also covers the content kind (value, negative entry or set) and the format the read reported, so the new value stays. SPI:ContentFingerprint.of(envelope)is replaced byContentFingerprint.of(envelope, format);InMemoryBackend.writeForeignand theEngineSpec.writeForeignhook write lower-format content for tests. (#834)
Fixed: keys and diagnostics
- A key whose encoded form contains an unpaired UTF-16 surrogate (for example
"bad-\uD800") was accepted, but Redis keys and invalidation frames are UTF-8, which turns it into?. The key then shared its Redis key with another key, and other instances evicted that other key instead, keeping their stale copy untillocalMaxAge. Such a key now fails withIllegalArgumentExceptionbefore it reaches Redis, on reads, writes,CacheAdminandExternalInvalidator; emoji, CJK and other well-formed keys are unaffected (keys). CacheAdmin.inspectand thecocacheendpoint showed a versioned tombstone that this instance loaded itself (Versioned(null, v)from the loader) as a localVALUEholding the internalVersionedwrapper. It is nowABSENTwith no value, likegetand the remote copy.
For backend and test authors
ContentFingerprint.of(envelope, format)replacesof(envelope): the fingerprint that conditional reclaim compares now starts with the content's class (scalar, negative entry, set) and the format the read reported, and a backend'sreclaimmust compute the same over the current content. The client and its scripts ship together, so mixed versions stay consistent (extending).InMemoryBackend.writeForeignstores content of an older format for tests, andCachePolicy.Builder.localMaximumSize(Java:localMaximumSize(Long)) always counts as written, likemaxConcurrent.
v8.0.0-alpha.4 (Pre-release)
Module Group: me.ahoo.cocache · Fourth pre-release of 8.0.0. Like every pre-release, it carries no compatibility promise; see v8.0.0-alpha.1 for the upgrade notes and the full list of 8.0 changes.
Changed: unknown per-cache keys fail startup
- A key under
cocache.caches.[name]that CoCache doesn't define, usually a typo such asttl-foreverormax-concurrent(forload-max-concurrent), now fails startup. Spring Boot used to ignore it, so the override silently had no effect.cocache.caches-validation: warnlogs a warning instead. Relaxed forms that bind, such aslocalMaxAge, still work, and unknown keys incocache.defaultsandcocache.overridesare still ignored (startup validation).
Fixed: consistency under faults
- On a backend without atomic broadcast (
shardedchannel mode, or when the atomic-broadcast probe fails), a write whose separate invalidation publish was rejected, for example while disconnected, was reported as not executed (outcomeUnknown = false).Cache.putthen skipped its compensating invalidation, and other instances kept their old L2 copies untillocalMaxAge. Such a write is now outcome unknown:putschedules the compensating invalidation andinvalidateretries. - The suspending view of a
Cachedidn't apply the per-call TTL ceiling (cocache.overrides.cache.ttl) toput(key, value, ttl)andputAll(entries, ttl). It now clamps them and counts them incocache.ttl.clamped, like the sync and async views. - On an externally sourced
Cache,getAllwithout a loader capped the local copy of a key held under another instance's lease, in a newer format, or with a pending invalidation atlocalMaxAge. Likeget, it now caps it atdegradedLocalMaxAgeand counts it incocache.degraded.fills. - With the Redis backend, removing the last member of a set left the key behind as an empty hash when the set carried metadata besides
!f(an explicit!m = "0", or any reserved!field). Without a TTL it never expired. The set is now deleted once no member remains.
Fixed: content written by another cache type
- A
Storeread a value written by aVersionedCacheorVersionedStoreon the same namespace (a version segment and no digest) as its own, although its conditional reads refuse it. It now fails like a value without a digest:CacheReadException, the copy in Redis kept. SetStorereads of unreadable content didn't all fail the same way. A newer format threwForeignFormatException, a scalar on a set key threwIllegalStateExceptionand an undecodable element threw the codec's exception, and the last two weren't counted. Each now throwsCacheReadExceptionwith aForeignFormatExceptioncause and counts incocache.unknown.formats, like aStore.cocache.reclaimscounted undecodable values written by aStore(with a digest segment) that a derived cache read, although such values are never reclaimed. They are now counted only incocache.type.mismatch.- A
VersionedCachelogged a WARN on everyevictrefused because the key holds a value written by aStore. It now warns once per cache and logs later refusals at DEBUG, like reads of such values;cocache.type.mismatchstill counts each one.
Fixed: configuration
maxConcurrent = unlimited()could not be declared. Its documented form,load = LoadPolicy(maxConcurrent = unlimited()), equals the default, so a nested assignment didn't record it as written andcocache.defaults.*.load-max-concurrentreplaced it.CachePolicy.Buildernow hasmaxConcurrent(Java:maxConcurrent(Int?)), which always counts as written:policy { maxConcurrent = unlimited() }.refresh-window: offwritten without quotes in YAML failed startup with"false" is not a duration, because YAML reads a bareoffasfalse. It now turns refresh-ahead off.cocache.defaults.store.tombstone-ttl: foreverfailed the creation of everyVersionedStorethat didn't set its own, whose tombstones need a finite lifetime. It is now skipped for aVersionedStore, like any other global-layer entry that can't apply: logged as aWARNand listed under the endpoint'sskippedConfigurationwith the reasona VersionedStore needs a finite tombstone-ttl. AVersionedCachestill takescocache.defaults.cache.tombstone-ttl: forever, andcocache.caches.[name].tombstone-ttl: foreveron aVersionedStorestill fails startup.
TCK: faults in evict
HookedBackendnow passesevictKeepingVersionthroughfailWrites,rejectWrites,beforeInvalidateandafterInvalidate, soVersionedSpeccan inject faults intoevict.
v8.0.0-alpha.3 (Pre-release)
Module Group: me.ahoo.cocache · Third pre-release of 8.0.0. Like every pre-release, it carries no compatibility promise; see v8.0.0-alpha.1 for the upgrade notes and the full list of 8.0 changes.
Performance: declared suspending interfaces
- An L2 hit through a declared suspending interface (
interface UserCache : SuspendingCache<String, User>) costs about 2 ns more than a hit onsuspending()directly, down from about 10 ns: roughly twice the throughput of alpha.2. The proxy calls the view's reads (get,getAll,lookup,lookupAll,getVersioned) through method handles, so the view's hit path no longer counts against the caller's JIT inlining budget. Behavior is unchanged: a hit returns without suspending, and exceptions arrive unwrapped.
New: a cache's keyspace in CacheAdmin and the endpoint
CacheAdmin.keyspacereturns the cache's key prefix and namespace, so operators and integrations can build storage keys ({keyPrefix}{namespace}:{encodedKey}) and ACL patterns without repeating the configuration. The endpoint's cache report (GET /actuator/cocacheandGET /actuator/cocache/{name}) adds them askeyPrefixandnamespace(Observability).
Docs: upgrade guide corrections
- At the cutover, delete the old keys of every
VersionedCachetoo: a versioned write (putIfNewer,invalidateIfNewer,evict) refuses a 6.x value withCacheWriteExceptioninstead of overwriting it (the cutover). - A namespace with several
:segments moves everything up to the last:intokeyPrefix, and each key prefix this produces needs its own&{keyPrefix}inv:*channel pattern (Redis ACL). - Internal keys live under
{keyPrefix}!, except the atomic-broadcast probe's fixed keycocache:!probe:{a}.
v8.0.0-alpha.2 (Pre-release)
Module Group: me.ahoo.cocache · Second pre-release of 8.0.0. Like every pre-release, it carries no compatibility promise; see v8.0.0-alpha.1 for the upgrade notes and the full list of 8.0 changes.
New: declare a cache as its async or suspending view
- A
@CoCacheinterface, or the type passed toCoCacheFactory.create(type, spec), can extend an async or suspending view instead of a synchronous type:interface UserCache : SuspendingCache<String, User>. All ten views can be declared (AsyncCache…AsyncSetStore,SuspendingCache…SuspendingSetStore). Each declares the same kind of cache as its synchronous type, so aSuspendingStoreinterface takes astoreSpec(interface caches, coroutines, async). - The proxy hands each call to the cache's
async()orsuspending()view, passing a suspending call's continuation through: an L2 hit returns without suspending, re-entry fails fast, and exceptions arrive unwrapped, including a checked exception thrown before a suspending call suspends. - The starter registers these interfaces as beans of the interface type, with native-image hints. Spring Cache keeps using the cache by name, so
@Cacheableon a cache declared as aSuspendingCacheuses theCachebehind it.
| Before | Now | What to know |
|---|---|---|
CoCacheFactory.create(type: Class<C>, spec) with C : ReadableCache<*, *> | C : Any | Source-compatible. Code compiled against 8.0.0-alpha.1 must be recompiled: the erased return type changed. |
@EnableCoCache(caches: Array<KClass<out ReadableCache<*, *>>>) | Array<KClass<*>> | Source-compatible. A type that is not one of the fifteen declarable types still fails when its cache is created. |
v8.0.0-alpha.1 (Pre-release)
Module Group: me.ahoo.cocache · First pre-release of 8.0.0, a major release with breaking changes (RFC 0005). 8.x doesn't run next to 6.x on one Redis: stop 6.x, then start 8.x (Upgrading from 6.x). Fixes for 6.x continue on the 6.x branch.
Pre-release: no compatibility promise. Until 8.0.0, any pre-release may change the API, the SPI and TCK, configuration keys, metric names, endpoint paths and the Redis wire format. When you upgrade from one pre-release to the next, delete every CoCache key: caches with a source reload them, and caches without a source start empty. Don't use pre-releases for data you can't rebuild.
Upgrading from 6.x
8.x doesn't run next to 6.x on one Redis, and there is no migration tool: stop every 6.x instance, delete the keys of caches without a source, then start 8.x, and caches with a source reload from it. Upgrading from 6.x has the procedure and maps 6.x types, configuration keys, Redis ACLs and the backend SPI to 8.0. The sections below list every change.
The user API is split by role
8.0 replaces the one Cache interface, with or without a loader, and SetCache with one type per role (RFC 0005 §4.1). A derived type holds a copy that its source can rebuild; an authoritative type holds the only copy, in Redis, and has no loader. Each type has only the operations that are safe for its role, and every method is abstract: no method throws UnsupportedOperationException because the cache was declared one way and not the other. See Choosing a type.
| 6.x | 8.x | What changes |
|---|---|---|
Cache<K, V> with a loader | Cache<K, V>, cacheSpec { loader(…) } | getIfChanged, putIfMatch, putIfNewer, invalidateIfNewer and getVersioned are gone from it. |
Cache<K, V> without a loader, filled by Spring Cache or another system | Cache<K, V> with externallySourced(), or @CoCache(source = EXTERNAL) | A CacheSpec needs exactly one of loader, asyncLoader and externallySourced(); creating one with none fails. Its values carry no writer id or digest, and a failed invalidate is retried in the background, as for a cache with a loader. |
Cache<K, V> without a loader, Redis holds the only copy | Store<K, V>, storeSpec | delete and deleteIfMatch replace invalidate: they are synchronous, throw on failure and are never retried. getIfChanged and putIfMatch live here. Reads take no lease. The store must provide conditional(). |
Cache<K, V> with versioned and a versioned loader | VersionedCache<K, V>, versionedCacheSpec | getVersioned, putIfNewer, invalidateIfNewer, evict (keeps the version, state E) and purge (drops it). There is no put or plain invalidate. |
Cache<K, V> with versioned and no loader | VersionedStore<K, V>, versionedStoreSpec | deleteIfNewer replaces invalidateIfNewer; purge drops the version. Tombstones expire after tombstoneTtl (1 day by default). |
SetCache<K, E>, SetCacheSpec | SetStore<K, E>, SetStoreSpec, setStoreSpec | No invalidate: use clear(key). |
AsyncCache, AsyncSetCache | AsyncCache, AsyncVersionedCache, AsyncStore, AsyncVersionedStore, AsyncSetStore (all AsyncReadableCache) | The async views follow the same split, and so do the suspending views. |
cocache-coroutines: SuspendingCache, the suspending() extensions, suspendingLoader | suspending() is a member of every type, and SuspendingCache and its siblings are in cocache-api. suspendingLoader and suspendingVersionedLoader are in me.ahoo.cocache.core | The cocache-coroutines module and its BOM entry are removed. Drop the dependency and the me.ahoo.cocache.coroutines imports. |
JoinCache over any two caches | JoinView (read only) over any readable caches; JoinCache only over two derived Caches | JoinCache is a JoinView with the two invalidations. |
CacheRuntime.create(CacheSpec) returns Cache | One create per spec type, returning that type; create(spec: Spec) dispatches; cache(name) returns ReadableCache | Creation checks the capabilities the type needs: Store needs conditional(), VersionedCache and VersionedStore need versioned(), SetStore needs sets(). |
Reads and failures:
Lookuphas a third case,Unknown(error): L1 failed and there was no source to fall back to, or the read has a source andread-failureisthrow. It comes only from L1 faults, never from content.Lookup.valueOrThrow()throws itsCacheReadException. See Reading: present, absent, or unknown.unknownRead(THROWby default, orABSENT) onCacheSpec,StoreSpecandVersionedStoreSpecdecides what a read without a loader returns onUnknown;ABSENTreads absent and caches nothing in either layer.SetStorealways throws. ACacheSpecmay setABSENTonly together withexternallySourced().readFailurenow applies only to reads with a loader, whereDEGRADEremains the default;readFailure = DEGRADEon a read without a loader no longer turns a failure into absent.getAllwith some keysUnknowncompletes the other keys first, then throwsCacheReadExceptionwithunknownKeysand thepartialResultof the others. The newlookupAllreturns aLookupper key instead.CacheWriteException.outcomeUnknownsays whether the write may have reached Redis. It isfalseonly when the write was not sent or the store refused it without changing Redis. SPI: a store reports a command rejected before it was sent asL1RejectedException(new), as the Redis backend does while disconnected.- An unversioned
nullfrom a versioned loader over versioned content in Redis is refused: the fill writes nothing,cocache.fill.unversioned.absentcounts it, and the cache logs a warning once. - New meters:
cocache.reads.unknown(CacheMetrics.readsUnknown) andcocache.fill.unversioned.absent(CacheMetrics.unversionedAbsentRefusals). The endpoint's local stateUNRESOLVEDis nowUNFILLED.
Defaults and wire format:
- Authoritative types (
Store,VersionedStore,SetStore) start from their own policy:ttlnever expires,localMaxAge30 s,absentTtl10 s (default policy). Only the declaration andcocache.caches.[name].ttlset theirttl(three-layer configuration). StoreandVersionedStorewrite the writer id,Storealso writes the digest, and only these two types verify it. ACache, externally sourced or not, writes neither. A derived cache that reads a value with a digest counts a type mismatch, andevictrefuses one.- SPI:
ConditionalL1Store.deleteIfMatch(key, expected, frame)(abstract;FutureConditionalL1StoreandForwardingConditionalL1Storetoo) deletes a value whose stored digest equalsexpectedand publishes the frame.ConditionalDeleteis its result in the API. - Spring: an
@CoCacheinterface is created as the type it extends; one that extends none of the five fails at startup. ACacheinterface with no matching loader bean fails at startup unless it declaressource = EXTERNAL; in 6.x it silently had no loader.loaderorsource = EXTERNALon an authoritative type fails. Spring Cache andTransactionalInvalidatortake only derivedCaches.cocache.redis.set-cache-eviction-checkis nowcocache.redis.store-eviction-checkand also coversStoreandVersionedStore.CoCacheProperties.setPolicyForis removed (three-layer configuration). - TCK:
CacheAccesscreates each type (cache,versionedCache,store,versionedStore,setStore).EngineSpeccoversCacheandStore,VersionedSpeccoversVersionedCacheandVersionedStore, andSetEngineSpeccoversSetStore.HookedBackend.rejectWritesrejects writes withL1RejectedExceptionbefore they are sent.
Libraries create caches through CoCacheFactory
CoCacheFactory(cocache-core) is the entry point for creating caches (RFC 0005 §4.8). It hascreate(spec)for each spec type andcreate(type, spec)for an interface, which must be an interface extending the type the spec declares. The starter publishes aCoCacheFactorybean and creates its own interface and spec-bean caches through it. A library that injects it gets the same customizers andcocache.*properties, the endpoint and meters. See CoCacheFactory.- A cache created directly with
CacheRuntime.createis unlayered: customizers andcocache.*properties don't apply to it. Its start log line ends withunlayered: …and the endpoint reportslayered: false. Acocache.caches.[name]entry for it logs a warning and is listed under the endpoint'signoredConfiguration. CacheAdminhasapiType(the cache's API type),layeredandpolicyReport. The endpoint's cache report addstype,layered,ignoredConfiguration,policyandskippedConfiguration(three-layer configuration).CacheRuntime.addCreationListenercalls aCacheCreationListenerafter each later cache is created. The starter uses it to bind meters for every cache, including ones created directly after startup.
Three-layer configuration
A cache's policy is now merged field by field from three configuration layers around the declaration (RFC 0005 §4.8). See How settings combine.
- Layers, low to high: the type default (
DefaultPolicies),cocache.defaults.cache.*/cocache.defaults.store.*, the declaration,CacheSpecCustomizerbeans,cocache.overrides.cache.*/cocache.overrides.store.*,cocache.caches.[name].*. Thecachesections apply toCacheandVersionedCache, thestoresections toStore,VersionedStoreandSetStore. - Defaults sit below the declaration: they fill only the fields the declaration didn't write. A field counts as written when an annotation attribute is set, when
policy { … }assigns it (ttl = forever()included; a nestedlease,loadorlocalwrites only the fields whose value it changes), or when the spec assigns a wholepolicy, which writes every field.Spec.declaredFieldslists them. - Overrides only tighten:
local-max-age,degraded-local-max-age,absent-ttland aCache'sttltake the minimum, andread-failure,fill-in-transactionandinvalidate-fills-on-rollbacktake the stricter mode.overrides.cache.ttlalso caps per-call lifetimes (ttlOf,put(key, value, ttl),putAll(entries, ttl)), counted in the new metercocache.ttl.clamped(CacheMetrics.ttlClamped, endpoint keyttlClamped); a longercocache.caches.[name].ttlraises that cap for its cache, andforeverremoves it. Any other key inoverridesis skipped. - Applicability. Global layers skip, per cache, the keys that don't apply to its type, that the layer doesn't allow, or that a library locked: a
WARNline at creation and an entry in the endpoint's newskippedConfiguration. Acocache.caches.[name]key that doesn't apply fails startup, as an unknown cache name does;cocache.caches-validation: warn(defaultfail) only warns for both. An entry that names an unlayered cache still only warns. See which keys apply and validation. - Values. Every duration needs a unit,
cocache.redis.*included:500ms,5s,2m,PT2M. Sentinels are explicit:forever(ttl,tombstone-ttl),offor0s(refresh-window),unlimited(load-max-concurrent). Values are parsed at binding, and a malformed one fails startup naming the key, for examplecocache.defaults.cache.ttl: "60" needs a unit, e.g. 60s, 5m, PT2M.Annotations stay in seconds. - New keys:
read-timeout(CachePolicy.readTimeout),tombstone-ttl, and, undercocache.caches.[name]only,unknown-readandunlock.cocache.key-prefixsets the prefix for every cache outside the layering;cocache.caches.[name].key-prefixstill wins over it. - Locks for libraries.
CoCacheFactory.create(spec) { lock(…); lockLayout(…); constrain(field) { … }; verify { … } }(Java:create(spec, Locks.builder("my-lib")….build())) fixes policy fields and the storage layout. Locked fields reportLOCKED(locked by …), global layers skip them,cocache.caches.[name]fails on them unless itsunlocklists them (the field is then reportedUNLOCKED, with a warning), and a customizer that changes one throws. A lockedKEY_PREFIXignorescocache.key-prefix. See Locking fields. - Validation chain. When a global layer makes
refresh-windowno shorter thanlocal-max-ageorttlminus jitter, andcocache.caches.[name]set none of these fields, the window is turned off for that cache (CLAMPED, with a warning). A conflict caused by the declaration alone, or one that involves a field set bycocache.caches.[name], fails startup. - Reports. Each layered cache logs one
INFOline with the fields that don't come from the type default and their sources.GET /actuator/cocache/{name}addspolicy(every field's effective value and source:TYPE_DEFAULT,DEFAULTS,DECLARATION,CUSTOMIZER,OVERRIDES,CACHES,CLAMPED,LOCKED,UNLOCKED) andskippedConfiguration.CacheAdmin.policyReportreturns the samePolicyReport,nullfor an unlayered cache. See Effective values and sources. - Eviction check. With an authoritative cache,
allkeys-*always fails startup, and so does amaxmemory-policythat can't be read withoutcocache.redis.assume-maxmemory-policy.cocache.redis.store-eviction-check(warn,fail,off) now governs onlyvolatile-*with an authoritative cache whosettlis finite, andfailfails there. See the eviction check. - API (
cocache-core):DefaultPolicies;PolicyFieldwith one object per configurable field; the sentinel typesTtl(Forever,Finite,finiteOr,min),RefreshWindow(Off,Of) andConcurrency(Unlimited,Max);Locks,LayoutField,PolicyReportandLayered;CachePolicy.ttlCeiling; and the builder helpersforever(),off()andunlimited().
What to change when you upgrade:
| Before | 8.x | What to know |
|---|---|---|
cocache.defaults.<field>, such as cocache.defaults.ttl | cocache.defaults.cache.<field> (Cache, VersionedCache) or cocache.defaults.store.<field> (Store, VersionedStore, SetStore) | The meaning changed. cocache.defaults.<field> overrode the declaration, annotations included; the new keys sit below it and fill only fields the declaration didn't write. To keep forcing a value over every declaration, use cocache.overrides.cache.<field> (staleness bounds, read-failure and the two transaction modes only) or cocache.caches.[name].<field>. Spring Boot ignores the old key without a warning. |
ttl-forever: true | ttl: forever | Spring Boot ignores ttl-forever without a warning, so a cache that relied on it gets the type default: 1 h for a derived cache. |
cocache.defaults.key-prefix | cocache.key-prefix | Configuration still wins over the declaration, unless a library locks KEY_PREFIX. Spring Boot ignores the old key without a warning, so the caches fall back to the declared prefix (cocache: by default): a cold start for derived caches, and empty authoritative caches. |
A number without a unit: seconds under cocache.defaults and cocache.caches (ttl: 600), milliseconds under cocache.redis (command-timeout: 2000) | ttl: 10m, command-timeout: 2s | A number without a unit now fails startup, naming the key. |
refresh-window: 0, ttl-jitter: 0 | refresh-window: "off" (or 0s), ttl-jitter: 0s | Quote off: YAML reads a bare off as false |
load-max-concurrent: 0 (unlimited) | load-max-concurrent: unlimited | 0 fails startup. |
LoadPolicy(maxConcurrent = 0) | LoadPolicy(maxConcurrent = null), or unlimited() inside policy { … } | maxConcurrent is an Int?, and 0 throws IllegalArgumentException. |
CachePolicy.DEFAULT, StoreSpec.DEFAULT_POLICY, VersionedStoreSpec.DEFAULT_POLICY, SetStoreSpec.DEFAULT_POLICY | DefaultPolicies.CACHE, VERSIONED_CACHE, STORE, VERSIONED_STORE, SET_STORE | CachePolicy.builder() starts from DefaultPolicies.CACHE. |
policy = … on a spec to change a few fields | policy { … } / updatePolicy(…) | A whole policy counts as writing every field, so cocache.defaults no longer applies to that cache. |
| — | CacheLayers.apply(spec, locks), returning Layered (spec, report) | New. CacheLayers.NONE keeps only the declaration and runs the constraints. |
CoCacheProperties.policyFor, setPolicyFor, versionedPolicyFor, keyPrefixFor, PolicyProperties.applyTo | Removed | The starter's CacheAssembler merges the layers. CoCacheProperties.defaults and overrides are Layer(cache, store), and policy and cocache.redis durations bind as strings. |
An undeclared name under cocache.caches always failed startup | Fails by default; cocache.caches-validation: warn only warns | A per-cache key that doesn't apply to the cache's type fails the same way. |
Eviction check: allkeys-* and an unreadable policy failed only with store-eviction-check: fail; volatile-* with a finite ttl only warned, even with fail | allkeys-* and an unreadable policy without assume-maxmemory-policy always fail; store-eviction-check decides only volatile-* with a finite ttl, and fail fails there | off no longer skips the allkeys-* check. |
Breaking changes
Configuration is merged from three layers around the declaration:
cocache.defaults.<field>is nowcocache.defaults.cache.<field>orcocache.defaults.store.<field>and sits below the declaration,cocache.overrides.*only tightens, every duration needs a unit, and several keys and constants are renamed. See three-layer configuration.Interface proxies come only from
CoCacheFactory.create(type, spec):CacheProxies.createis internal, andCacheAssemblerno longer creates caches (it is the starter'sCacheLayers). See Libraries create caches throughCoCacheFactory.The user API is split into
Cache,VersionedCache,Store,VersionedStoreandSetStore, andcocache-coroutinesis removed: see the user API is split by role.A per-call loader on a suspending view (
suspending().get(key) { … }) no longer runs on the caller's dispatcher orDispatchers.Default: it runs inside the load, on CoCache's executor from its first suspension, andload-timeoutcancels it. See suspending views run on the cache core.The baseline is JDK 21 (was JDK 17).
Storage keys keep the 6.x shape
{keyPrefix}{namespace}:{encodedKey}. The invalidation channel is{keyPrefix}inv:{namespace}(6.x:cocache:inv:{namespace}, without the prefix), so applications with the same namespace and different prefixes no longer receive each other's invalidations. Inpubsubmode the startup probe usescocache:!probe:{a}andcocache:!probe:{b}(6.x:cocache:probe:{a}, which is also a key of namespaceprobe). Internal keys live under{keyPrefix}!, which no namespace can produce, and{keyPrefix}!meta:{namespace}is reserved. See storage keys.A namespace must match
[A-Za-z0-9._-]+. One with:(or any other character outside the set) fails at creation withIllegalArgumentException, and the message shows how to move the prefix intokeyPrefix:namespace = "app:user"becomeskeyPrefix = "cocache:app:"andnamespace = "user". This makes the 6.x overlap between namespacesaanda:bimpossible.Caches are registered by prefix and namespace. Two caches with the same namespace and different prefixes can now be created in one runtime. The duplicate error reads
Namespace[x] with keyPrefix[p] is already used by another cache.Redis ACL: the channel pattern is
&{keyPrefix}inv:*(&cocache:inv:*by default) and, inpubsubmode,&cocache:!probe:*(6.x:&cocache:probe:*); with a key prefix other thancocache:, the probe key also needs~cocache:!probe:*. With an emptykeyPrefix, keys and channels share no prefix: list each namespace (~{namespace}:*,&inv:{namespace}), plus~!*and, for the probe,~cocache:!probe:* &cocache:!probe:*. A denied probe falls back to non-atomic broadcast with aWARNinstead of failing startup. See Redis ACL.Creating a cache on Redis publishes one frame with no keys to the cache's channel, in the write script when broadcast is atomic. If the ACL denies that channel, creation fails with
IllegalStateExceptionnaming the pattern to allow, instead of every write failing at its broadcast after it has changed Redis. Transient errors still fail as before, and a denial never downgrades the backend to non-atomic broadcast.ExternalInvalidatorprobes the same way the first time it uses a namespace.An invalidation frame that a channel can't read (unknown version, truncated, trailing bytes) now resets every cache on that channel, clearing its L2. 6.x logged a warning and dropped it, which lost an invalidation. Frame version
2is reserved for a future namespace reset (InvalidationFrame.NAMESPACE_RESET_VERSION). A frame with no keys does nothing and isn't counted incocache.invalidations.received.SPI: a
Keyspace(keyPrefix, namespace)value type identifies a cache's keys and channel.CoherenceBackend.store,InvalidationChannel.subscribe/publishandFutureInvalidationChannel.subscribe/publishtake aKeyspaceinstead of a namespace string. A backend names the channel from both parts, resets listeners on a frame it can't decode, and delivers frames with no keys.Spec.keyspaceexposes a cache's keyspace, on every spec type.LoadPolicy.asyncTimeoutis nowLoadPolicy.timeout, and the propertyload-async-timeoutis nowload-timeout(default30s). It bounds more than async loads: readers waiting for another caller's load fail withSourceLoadTimeoutExceptiononce that load has been in flight that long, and later readers start a new load instead of waiting behind a stuck synchronous loader. In 6.x, a synchronous reader waited indefinitely.cocache.load.timeoutscounts both kinds of timeout.cocache-coredepends onkotlinx-coroutines-coreat runtime. The blocking, async and suspending APIs of every type run on one coroutine implementation of the protocol. With assertions enabled (-ea, the default in test runs), kotlinx adds a coroutine suffix such as@coroutine#3to thread names while a read runs, including inside a blocking loader.The runtime no longer starts a
cocache-timerthread. Lease waits and load-permit waits are coroutine suspensions.The async and suspending views run on one executor:
cocache.executorreplacescocache.async-executorandcocache.blocking-executor,CacheRuntime.Builder.executor(…)replacesasyncExecutor(…)andblockingExecutor(…), andCacheRuntime.executorreplacesCacheRuntime.blockingExecutor. Every continuation is dispatched to it, so it must tolerate blocking tasks. See one executor.LoadObserver.observeAsyncis removed:observealso sees async and suspending loads, called on an observation thread of CoCache's own. See one executor.cocache-redisno longer contains the CoCache 5.x migrator:CoCache5Migrator,CoCache5Migration,CoCache5Format,CoCache5KeyMapper,CoCache5MigrationOptions,CoCache5MigrationReport,CoCache5CacheReportandCoCache5MigrationException(packageme.ahoo.cocache.redis.migration) are removed. 8.x never needs to read 5.x data, so it doesn't carry the converter. Migrate 5.x data whose only copy is Redis with CoCache 6.x (6.5+) first; see Migrating withCoCache5Migrator.Load permits (
load.max-concurrent) are handed out in arrival order to sync and async callers alike. In 6.x, a blocking caller competed for a released permit directly and could take it before async callers already waiting.An async read in flight when its
CacheRuntimecloses fails withIllegalStateException("CacheRuntime closed."). An async write in flight still finishes its Redis change, broadcast and local invalidation first, then completes with that exception if it succeeded, or with its own failure.A blocking call (
get,getAll,put,invalidate, …) no longer blocks its thread on each Redis command. It sends commands the way the async API does and parks inrunBlockinguntil they finish. As a result, interrupting the calling thread no longer abandons a Redis command. An interrupted caller can wait up to one morecommand-timeout(default2s). In 6.x the wait failed at once withRedisException("Interrupted while waiting for Redis."): a write threw it wrapped inCacheWriteException, and a read treated it as a Redis failure (by default, loading from the source). A command in flight finishes or times out first. A read then releases any lease it took and doesn't call the loader, and the call throwsInterruptedException. A call that completes before the interrupt takes effect, such as an L1 hit or aputwhose command was in flight, returns as usual. Either way the interrupt flag stays set. A command abandoned on a timeout is still never sent later.Wire format 2. Every value 8.x writes is format 2, leases, negative entries and sets included (wire format, RFC 0005 §4.7). Byte 3 of the 36-byte header, reserved in 6.x, holds flags, and segments follow the header: a version (8 bytes, flag bit 0) and an extension area of TLVs (flag bit 7). A versioned value keeps its version in that segment instead of the token slot, and the
VERSION_MARKof 6.8 is gone. A set's!ffield is"2", and a!mfield, when present and not"0", makes the set unreadable. Values of aCache, leases and negative entries are 36 bytes of header as before, and a versioned value adds its 8-byte version segment; each value aStoreorVersionedStorewrites carries a 28-byte writer id.8.x doesn't read 6.x data. Format 1, the format of 6.x, is content the cache can't read, like content CoCache didn't write: a cache with a loader reclaims it and reloads from the source, and a cache without one fails the read. 8.x and 6.x instances can't share a cache. Format-2 content with a must-understand flag (bits 2–6) or a state this version doesn't know is a higher format, which the store reports as format 3: a cache with a loader loads around it, and nothing reclaims or overwrites it. A read grants a lease or a refresh token only on format-2 content without such a flag, a fill or release reads only the 36-byte header (
GETRANGE), and a version segment never holdsVersioned.NO_VERSION.Redis ACL: the scripts now call
GETRANGE,STRLENandHMGETand no longer callHGETorHEXISTS. Add+getrange +strlen +hmgetto an existing user before you upgrade. See Redis ACL.foreign-formatis removed:CachePolicy.foreignFormat,CachePolicy.Builder.foreignFormat,ForeignFormatMode, and the propertiescocache.defaults.foreign-formatandcocache.caches.[name].foreign-format. A read with a loader reclaims content the cache can't read and reloads it; a read without one fails withCacheReadException. In 6.x,reclaimon a cache without a loader deleted the only copy (RFC 0005 §4.7, §12 decision 6). Spring Boot ignores the property like any key it doesn't know.Conditional writes (
putIfMatch,deleteIfMatch), versioned writes (putIfNewer,invalidateIfNewer,deleteIfNewer) andSetStore.add/removealways refuse content the cache can't read. They throwCacheWriteExceptionwith aForeignFormatExceptioncause and leave the key alone, andgetIfChangedthrowsCacheReadExceptionthe same way. In 6.x,foreign-format: reclaimmade them treat content CoCache didn't write (format 0) as absent:putIfMatch(key, null, …)andputIfNeweroverwrote it,getIfChangedreturnedAbsent, andaddreplaced the whole key with the new members.SPI: content the store can't read is never overwritten. Conditional and versioned writes have no
foreignAsAbsentparameter and returnUnreadablefor such content, and the set-member writesSetL1Store.addMembers/removeMembersrefuse it atomically and return its format (see the suspending L1 SPI below). The overwriting set-member writes of 6.x and the Redis scriptsADD_MEMBERSandREMOVE_MEMBERSare gone.SPI: the L1 SPI is suspending (RFC 0005 §4.3).
CoherenceBackend.storereturns anL1Store, whose operations aresuspendfunctions. Conditional reads and writes, versioned writes and set-member writes moved to capability surfaces returned byconditional(),versioned()andsets(), which returnnullwhen the store doesn't support them.CoherenceBackend.versionedWritesis removed;versioned()replaces it.InvalidationChannel.publishissuspend;subscribestays blocking. Java backends implementFutureL1StoreandFutureInvalidationChannel, whose methods returnCompletableFuture, and returnFutureL1Store.adapt(…)andFutureInvalidationChannel.adapt(…). Decorators extendForwardingL1Store. A future the implementation cancels counts as an L1 failure, not as a cancellation of the caller.L1Storehas noclose: connections belong to the backend, and the runtime no longer closes stores. The engine never cancels an L1 call, so an implementation may wait with a cancellableawait(). A backend that only implements the blockingRemoteStoreno longer works, because the engine no longer runs such a store on the blocking executor.RemoteStore,AsyncRemoteStoreandAsyncInvalidationChannelare removed.CacheRuntime.createchecks the L1 capabilities a cache needs. AStoreneedsconditional(), aVersionedCacheorVersionedStoreneedsversioned()and aSetStoreneedssets(); when one is missing, creation fails withUnsupportedOperationExceptionand registers nothing. The log line for each created cache names its type and lists what its namespace's store provides, for examplecreated as Store … L1 capabilities[conditional, versioned, sets]. In 6.x,getIfChangedfell back to a plain read on such a store.SPI: the L1 result types are renamed:
RemoteReadis nowL1Read,RemoteConditionalRead/RemoteConditionalWriteareL1ConditionalRead/L1ConditionalWrite, andRemoteVersionedWriteisL1VersionedWrite.SPI:
Envelope.Scalarhas awriter: Token?(defaultnull), a write id the engine sets on every scalar write of aStoreorVersionedStore. A store saves it with every operation that writes a scalar (put,putAll,fill,fillAll,putIfMatch,putIfNewer) and returns it unchanged fromreadandreadAll; it takes part in equality, not in the digest.VersionedL1Store.putIfNewerrefusesVersioned.NO_VERSIONwithIllegalArgumentException. The engine reads only content in exactlyCoherenceBackend.formatand treats any lower format like format0, as content it can't read (6.x did so only for0); a higher format is loaded around as before.InMemoryBackend.FORMATis2.ForeignFormatExceptiontakes the node's format: its constructor is(cacheName, storageKey, format, nodeFormat, cause), andneweris computed from the two. The two 6.x constructors are removed. ASetStorethat reads a set in a newer format throws this exception, still anIllegalStateException, instead of a plainIllegalStateException.SPI:
L1Store.fillreturns anL1Fillinstead of aBoolean:Filled(advanced)when it wrote,Rejected(currentVersion)when it didn't.fillAllreturns one per fill. A token mismatch isRejected(currentVersion = null); the version rule is described below.reclaimcompares an SPI-ownedContentFingerprint(the SHA-1 of the content, computed by the script) instead of aDigest.SPI:
L1Store.read,readAllandConditionalL1Store.readIfChangedtake atimeout: Duration?for that call.nullmeans the store's own command timeout. A value must be positive and is capped at the command timeout, and the store bounds the call by the shorter of the two.FutureL1Store, its capability surfaces,adaptand theForwarding*classes take the same parameter. The engine passes the cache'sCachePolicy.readTimeout(see below).SPI contract: after any failure of a command that takes or returns a token (
read,readAll,fill,fillAll,release,reclaim), the store releases that token asynchronously, unless the command was rejected before it was sent. ARELEASEwith a token that no longer matches does nothing, so a late or repeated release is harmless. A store never reports a failure asCancellationException: on the JVM that is coroutine cancellation, and the engine would treat it as the caller cancelling.Digest segment. A value written by a
Storecarries the SHA-256 of its payload in its header (flag bit 1, 32 bytes), next to its writer id: such a value takes 60 bytes more than a value of aCache(wire format, RFC 0005 §4.7). CoCache computes it on the client and checks it whenever it receives the payload: aStorethat reads a value whose payload doesn't match its digest, or a value that has no digest, fails the read withCacheReadException(ForeignFormatExceptioncause) and leaves the key alone. A value with a digest never gets a refresh token and is never reclaimed. ACacheorVersionedCachethat reads one counts it in the newcocache.type.mismatchmeter (CacheMetrics.typeMismatches) and logs once: aStoreshares the namespace.Digestis the SHA-256 of the payload and names its algorithm:Digest(algorithm, bytes)withDigest.SHA_256,Digest(bytes),Digest.ofPayload(bytes),bytes, andtoString()printingSHA-256:<hex>.Digest.sha1is removed, and digests stored by 6.x (SHA-1) never match.Conditional reads and writes (
getIfChanged,putIfMatch,deleteIfMatch) work only on values aStorewrote. A value without a digest (written by aCache), a versioned value, a tombstone and an evicted versioned key are content they can't read:getIfChangedthrowsCacheReadExceptionandputIfMatchthrowsCacheWriteException, both with aForeignFormatExceptioncause.putIfMatch(key, null, value)on a key without a value still writes. Their scripts read only the header (GETRANGEandSTRLEN) and compare the stored digest, so an unchangedgetIfChangedcosts Redis the same whatever the value's size; Lua no longer reads the value or computes SHA-1. WhengetIfChangedreturns a value, CoCache recomputes its digest and throws on a mismatch.Versioned caches refresh ahead. A versioned value gets a refresh token, and
cocache.defaults.cache.refresh-windowapplies to aVersionedCachewhose declaration doesn't writerefreshWindow; aVersionedCacheSpecwithrefreshWindowis valid. A refresh writes back only a version at least as new as the one in Redis: when the loader returns an older version, the instance keeps its copy and tries again after a back-off. SetrefreshWindow = off()(orcocache.caches.[name].refresh-window: off) on a versioned cache whose writer pushes every version.A versioned cache's local copy never moves back to an older version. When a refresh loses its token to another reader, or its write-back fails, and the loader returns an older version than the copy, the instance keeps the copy and retries after a back-off; the dropped fill counts in
cocache.stale.discards.A versioned write-back (fill) that fails with an unknown outcome counts as a write: the instance bumps its stamps and drops its local copy (and publishes the invalidation when broadcast isn't atomic), because a timed-out or drained
FILLcan still advance the version later, after readers on that instance have already read the old one. Its late broadcast also drops copies on that instance on backends that broadcast atomically (own messages after an unknown outcome).Fills follow the version in Redis. A fill under a refresh token or lease on versioned content is refused when its version is older (or absent), and the token is cleared in the same script; an equal version renews the value without an invalidation message; a newer version writes and broadcasts, and the loading instance treats it as a write: it drops its local copy instead of filling L2 with it.
The endpoint's per-key
DELETE(CacheAdmin.invalidateEncoded) on aVersionedCachekeeps the version: the key becomes an eviction marker (stateE, 44 bytes, the tombstone's lifetime) that still refuses older versions. The next read takes a lease on it; if the loader is behind, its result is returned and kept in L2 fordegraded-local-max-agebut not written to Redis (cocache.fill.rejections). A failure throws instead of being retried in the background. Seeevictandpurge.The endpoint's per-key
DELETErefuses to delete the only copy unless a switch allows it:StoreandSetStoreneedmanagement.endpoint.cocache.allow-store-delete=true,VersionedStoreneedsmanagement.endpoint.cocache.allow-purge=true. Without it the request returns403and changes nothing. See deleting the only copy needs a switch.A
Cache.putorputAllwhose outcome is unknown no longer throws under the defaultinvalidate-failure: retry: it queues a compensating invalidation. See compensated puts.Fix:
putIfNewerandinvalidateIfNewerpublish the invalidation when Redis already holds the given version, without writing, on every backend; before, only the non-atomic path did. A load that filled that version onto a lease broadcast nothing, so another instance could keep an older copy untillocal-max-ageeven after the writer's ownputIfNewerreturnedStale. An older version still publishes nothing.SPI:
Envelope.Scalarhas adigest: Digest?(defaultnull) that the engine sets with the writer id. A store saves it as the digest segment on every operation that writes a scalar and returns it unchanged fromread,readAllandreadIfChanged, without checking or recomputing it.readIfChangedandputIfMatchcompare the stored digest and refuse a value without one and versioned content.L1Fillnow carries the version rule:Filled(advanced = true)when the fill raised a version or replaced an eviction marker and the store broadcast it (a frame for the key whose origin is the fill token's node),Rejected(currentVersion)when the rule refused it.VersionedL1StoreandFutureVersionedL1StoreaddevictKeepingVersion(key, ttl, frame), returning the newL1Eviction(Evicted,Authoritative,Unreadable(format)).L1ConditionalRead.Changedhas value equality.Spring: with
spring-txon the classpath, the starter'scocacheCacheManageris CoCache'sTransactionAwareSpringCacheManager, and its caches areTransactionAwareSpringCache. It replaces Spring'sTransactionAwareCacheManagerProxyandTransactionAwareCacheDecorator, so code that checks for or unwraps those types no longer finds them. Inside a transaction@CacheEvictnow also invalidates on rollback, a later eviction of a key replaces an earlier@CachePutof it, and failures after the commit go to theCacheErrorHandlerinstead of being thrown. Without Spring Boot, wrapCoCacheSpringCacheManagerinTransactionAwareSpringCacheManagerinstead ofTransactionAwareCacheManagerProxy. See Spring: CoCache's own transaction decorator.Spring:
TransactionalInvalidatorkeeps one registration per transaction instead of one per instance. Invalidations of the same cache through several instances, and throughevictIfPresent, merge into oneinvalidateAllafter the commit, and their failures are thrown together (the first, with the rest as suppressed).Spring:
CoCacheSpringCacheManager(runtime, executor)andCoCacheSpringCacheManager.DEFAULT_EXECUTORare removed; useCoCacheSpringCacheManager(runtime).CoCacheSpringCache(cache, admin, executor)stays: its executor runs the method body ofretrieve(key, loader). The propertycocache.spring-cache.retrieve-executoris removed as well: Spring Boot no longer binds it, and setting it no longer logs a warning.SourceLoadCancelledExceptionmoved fromme.ahoo.cocache.coroutinestome.ahoo.cocache.core, and it now covers every loader. ACacheLoaderthat throws its ownCancellationException, or anAsyncCacheLoaderwhose future completes with one (awithTimeoutinside it, an HTTP client that cancelled the request), fails withSourceLoadCancelledExceptionfor every caller that shares the load. The original exception is itscause. In 6.x those callers got theCancellationExceptionitself, so an async caller's future looked cancelled.The starter no longer checks for the properties removed in 6.0 (
cocache.redis.strict-failure,cocache.redis.eviction-channel,cocache.redis.missing-guard-sentinel,cocache.metrics.client-side-hits,cocache.load.*,cocache.next.*). They no longer fail startup withCoCache 6.0 removed these properties: like any unknown key, Spring Boot ignores them. Their entries in the configuration metadata are gone too.The runtime's default executor is always one virtual thread per task. The fallback for JDKs without virtual threads, a daemon pool of up to 512
cocache-blocking-*threads, is gone, and the starter no longer registers a native-image reflection hint forExecutors.The wiki no longer carries the 5.x upgrade guide (
guide/migration-6); the 6.x branch keeps it. Thecocache-migrateagent skill is removed, and 8.x ships no upgrade skill.SPI:
InvalidationListener.onInvalidatedreceives encoded keys, the part of the storage key after{keyPrefix}{namespace}:(whatKeyEncoderproduces andExternalInvalidatortakes), not storage keys. A channel converts a frame's keys with the newKeyspace.encodedKeys(…), which also drops keys outside the keyspace, and calls the listeners of a keyspace one after another in the order they subscribed, so a listener added after the cache was created runs after the cache has dropped its local copies. Code that subscribes to a channel itself and strips"$namespace:"from the keys must use them as they are now, or every notification is silently ignored. TheBackendProtocolSpeccaselistenersReceiveEncodedKeysInSubscriptionOrderchecks both rules.Spring:
CoCacheSpringCache.retrieve(key), which Spring calls for a@Cacheablemethod that returnsCompletableFuture,MonoorFlux, fails withCacheReadExceptionwhen Redis can't answer (Lookup.Unknown), likeget(key), instead of reporting a miss. Spring hands the failure to theCacheErrorHandleron all three kinds of method;unknownRead = ABSENTstill reads it as a miss. See When Redis fails.Spring: a cache operation (
@Cacheable,@CachePutor@CacheEvict, with or withoutsync) that names a CoCache cache that isn't aCache(Store,VersionedStore,SetStore,VersionedCache) fails startup. Before, it failed at its first call with "Cannot find cache". See the startup check.Spring: loads inside a read-write Spring transaction are watched by default (see the next section). A rolled-back transaction now invalidates what it loaded, and a key evicted in a transaction loads privately in it: set
cocache.defaults.cache.invalidate-fills-on-rollback: falseandcocache.defaults.cache.fill-in-transaction: allowto keep 6.x behavior.
New: loads inside a Spring transaction
See Spring Cache: loads inside a transaction.
- A synchronous read with a source (
@Cacheable(sync = true),get,lookup,getAll,get(key, loader)) inside a read-write transaction can load a row that the transaction wrote but never commits. CoCache now records every key such a load writes to Redis or L2, including a fill that only reached this instance's L2 because Redis failed, and invalidates them when the transaction rolls back, when its commit outcome is unknown, or when aNESTEDtransaction rolls back to its savepoint (invalidate-fills-on-rollback, on by default). In 6.x the row stayed in Redis untilttlunless the key had been evicted in the transaction. fill-in-transaction(defaultregistered-keys): once a key is registered for invalidation in the transaction, loading it again there is private, with no lease, no write to Redis or L2, and no sharing with other callers. Registering also drops this instance's copy at once.privatemakes every load in a write transaction private,allowturns this off. Private loads count in the newcocache.fills.gatedmeter (CacheMetrics.fillsGated).- When a caller inside such a transaction leads a load, concurrent callers on the same instance no longer take its result: they load for themselves.
- Both settings are per cache and layer like the policy fields:
cocache.defaults.cache.*,cocache.overrides.cache.*(the stricter value wins:privateoverregistered-keysoverallow,trueoverfalse) andcocache.caches.[name].*, forCacheandVersionedCache. The endpoint'spolicylists them with their sources. A cache with both off ignores transactions, as if no hook were installed. An unlayered cache uses the defaults of both. - Read-only transactions, async and suspending calls, refresh-ahead and reactive transactions aren't watched. The transaction is read once, on the calling thread, when the read misses L2.
- Keys registered with the transaction match by namespace and encoded key, so a
TransactionalInvalidatorcall through an interface cache's proxy also replaces a@CachePutof the same key made through Spring Cache. cocache-coreadds the hook:FillObserver,FillScopeandFillKey, set withCacheRuntime.Builder.fillObserver(…)(defaultFillObserver.NONE). The engine callsFillObserver.enter(cacheName), which defaults toenter().cocache-springimplements it asTransactionalFillObserver(Predicate<String>, Function<String, FillInTransaction>), both looked up by cache name. The starter registers it ascocacheFillObserverwhenspring-txis present, readingTransactionalFillModes.
New: per-cache read timeout and broadcast-only invalidation
CachePolicy.readTimeout(CachePolicy.Builder.readTimeout(…), unset by default) bounds every Redis read of the cache (get,getAll,getIfChanged). The store caps it at its command timeout. A read that runs out is a failed Redis read: a read with a loader followsread-failure, a read without one isUnknown(unknownReaddecides),getIfChangedthrows, and any lease the read was granted is released. Use it on a cache that can't fall back to a loader but must not wait a fullcommand-timeoutfor a stalled Redis, such as a revocation list. Its configuration key isread-timeout(three-layer configuration).EngineSpechas an optionalpause()hook whose casereadTimeoutBoundsEveryL1Readchecks it.ExternalInvalidator.broadcast(namespace, encodedKeys)publishes the invalidation message without touching Redis: every instance drops its local copy and reloads from Redis. Use it when Redis already holds the right value.POST /actuator/cocache/{name}/{key}does the same for one key from the endpoint (CacheAdmin.broadcastEncoded): it needs no switch on any type, only write access to the endpoint (broadcasting an invalidation).invalidatedeletes the key, which on the namespace of a cache without a loader deletes the only copy.- Creating a cache with an empty
keyPrefixlogs a warning: its keys and channel share no prefix, so ACLs and prefix-based operations must name each namespace.
Behavior change: suspending views run on the cache core
The suspending views no longer wrap the async views; they call the cache core directly (RFC 0005 §4.4).
- An L2 hit returns without suspending, switching dispatchers or allocating a future.
- A miss, a write or a conditional read runs on CoCache's executor from its first suspension, and the caller resumes from a CoCache thread, never from a Redis client thread. A caller on
Dispatchers.Unconfined(Spring WebFlux handlers) therefore no longer risks continuing on Lettuce's event loop. - The caller's context elements (
ThreadContextElements such as a tracing context orMDCContext, the coroutine name) reach the shared load, without the caller'sJoband dispatcher. A spec-levelAsyncCacheLoadernow sees them too. - A per-call loader runs inside the load: it starts on the caller's thread and continues on CoCache's executor (before: on the caller's dispatcher, or
Dispatchers.Defaultwithout one or on arunBlockingevent loop).load-timeoutcancels it, and so does closing the runtime. Wrap blocking calls inwithContext(Dispatchers.IO). - The suspending methods throw the original exception instance, also in coroutine debug mode.
Behavior change: one executor for the async and suspending views
The async and the blocking executor are merged into one (RFC 0005 §4.4, §5).
cocache.executorreplacescocache.async-executorandcocache.blocking-executor. It names anExecutorbean and follows the rules ofcocache.refresh-executor: it is resolved by name only, startup fails when the bean is missing or isn't anExecutor, the container owns it (CacheRuntime.close()doesn't shut it down), and it is destroyed after the runtime. Spring Boot'sapplicationTaskExecutorcan still be named:cocache.executor=applicationTaskExecutor. Without Spring,CacheRuntime.Builder.executor(…)(Kotlin DSL:executor = …) replacesasyncExecutor(…)andblockingExecutor(…), andCacheRuntime.executorreplacesCacheRuntime.blockingExecutor.- Unset, the runtime starts one virtual thread per task, named
cocache-worker-N. Before, it was aForkJoinPool(cocache-async-*) for continuations and unnamed virtual threads for blocking loaders. - It runs every step of the async and suspending views: every resume after a Redis command or a loader's future completes is a new task on it, never a continuation in place on the thread that completed the step (a Lettuce I/O thread, the loader's own thread). The shortcut that ran a continuation in place when the step completed on the executor is gone. It also runs shared loads, synchronous loaders called through the async and suspending views, and the method body of Spring Cache's
retrieve(key, loader)(@Cacheable(sync = true)on an async or reactive method). The blocking API never uses it. - It must therefore tolerate blocking tasks: don't give it a queue or only a few threads. On JDK 21–23, a loader that blocks inside
synchronizedpins the carrier thread of its virtual thread (JEP 491 fixes this in JDK 24), so prefer JDK 24 or later, or a platform thread pool. See Executors. LoadObserver.observeAsyncis removed;LoadObserverhas onlyobserve. For an async or suspending load, CoCache callsobserveon a virtual thread of its own, one per observed load (cocache-observe-N), never on the caller's thread and not oncocache.executor. That thread waits while the whole load runs, so the observation covers the load until the loader's future completes, and an engine timeout is recorded as outcometimeout. The load starts on that thread, so the synchronous part ofloadAsyncsees the observer's thread-local state, such as Micrometer's currentObservation, and trace context can propagate. An observer that implements onlyobservenow sees async loads too; before, it saw none.MicrometerLoadObserverhas no async override any more, and its tags are unchanged:cocache.loadwithcache,operation,outcome(success,error,timeout) andkey.count.
Behavior change: closing the runtime waits for in-flight Redis steps
CacheRuntime.close()now waits up tocloseTimeoutbefore it shuts down its executors: 5 seconds by default (CacheRuntime.Builder.closeTimeout). The Spring Boot starter sets it to twicecocache.redis.command-timeout, and at least 5 seconds, so a command timeout above 5 seconds no longer letsclose()return while a command is still in flight. In that time, async calls in flight finish the Redis steps they can't skip: releasing a lease, the broadcast after a write on a backend without atomic broadcast, and commands already sent. Close the backend after the runtime. The Spring Boot starter already does that, because the runtime bean depends on the backend. Before,close()returned at once, and a backend closed right after it could fail those steps. Other nodes then kept their stale local copy untillocal-max-age, and the lease stayed untillease-ttl. Synchronous calls run on their callers' threads and aren't waited for.
Behavior change: outcome-unknown puts are compensated
- A
Cache.putorputAllwhose outcome is unknown (a timeout, a connection dropped mid-reply) no longer throws wheninvalidate-failureisretry, the default for a derived cache. Its value may be in Redis now or later, so CoCache queues an invalidation of those keys on the same retry queue as a failedinvalidate, and the keys converge to "reload from the source" (RFC 0005 §4.6). While it is pending, misses on that instance skip Redis. If the late put lands after the compensating delete, its value stays until its TTL. - A put that definitely didn't run (
CacheWriteException.outcomeUnknown = false) still throws and queues nothing. Withinvalidate-failure: throw, every failed put throws. AStoreorSetStorewrite is never compensated. - The warning reads
Cache[…] - put […] failed, retrying the invalidation.(invalidate […] failed, retrying the invalidation.for a failedinvalidate).
New: @CoCache(unknownRead)
@CoCache(unknownRead = CoCache.UnknownRead.ABSENT)sets the spec'sunknownReadon an interface declaration: a read without a loader returnsnullwhen Redis fails, instead of throwing (Unknown). It applies toStore,VersionedStoreandCachewithsource = EXTERNAL; on any other interfaceABSENTfails startup.
Behavior change: deleting the only copy needs a switch
DELETE /actuator/cocache/{name}/{key}on aStoreorSetStoreneedsmanagement.endpoint.cocache.allow-store-delete=true, and on aVersionedStore(a purge)management.endpoint.cocache.allow-purge=true. Both default tofalse; without the switch the request returns403, names the switch, and changes nothing. Invalidating aCachekey and evicting aVersionedCachekey need no switch (Observability).DELETE /actuator/cocache/{name}/{key}?purge=truepurges aVersionedCacheorVersionedStorekey, dropping its version; it needsallow-purge. Other types return400.- The per-key
DELETEreport has a new fielddeletion(INVALIDATE,EVICT,DELETE,PURGEorCLEAR), andCacheAdminhaskeyDeletionandpurgeEncoded(encodedKey).
Behavior change: readers behind an interrupted load load for themselves
- When several readers wait on the same load and the thread running it is interrupted (or its coroutine is cancelled), that thread still gets the original exception. The waiting readers no longer fail with it: each retries once and, if it joins another interrupted load, loads by itself. Batch reads do the same for the affected keys. In 6.x, every waiting reader failed with the interrupted thread's exception.
- A load counts as interrupted only when the thread running it is interrupted or its coroutine is cancelled. Any other failure is shared with the waiting readers, as in 6.x. That includes the loader's own
CancellationException(seeSourceLoadCancelledExceptionabove) and anInterruptedExceptionfrom a thread other than the caller's.
Performance: compiled key templates
@CoCache(keyExpression)and@JoinCacheable(joinKeyExpression)templates are evaluated in SpEL's compiled mode (SpelCompilerMode.MIXED), since they run on every call. A template is interpreted until it has been evaluated a number of times, then compiled to bytecode. One that can't compile (projection or selection, for example) stays interpreted, and compiled code that fails, for example because the key's class changed, falls back to interpreting. Results are the same as before. Native images always interpret.
Performance: L2 hits no longer build the Redis key
- The local (L2) copy is keyed by the encoded key instead of the full Redis key (
{keyPrefix}{namespace}:{key}), so a read served by L2 no longer concatenates and hashes a new string. On the hit-path benchmark, an L2 hit on one cache runs at about 2.6× the previous throughput (sync, async and interface proxy alike), and alternating between three differently configured caches is 68% faster on one thread and 8% faster on eight. L1 hits are unchanged. Keys and invalidation messages in Redis are unchanged.
Fix: closing the runtime no longer abandons an async read's Redis command
- When a
CacheRuntimeclosed while an async read waited for Redis, the read stopped waiting at once and sent a release without waiting for it. A backend that doesn't apply commands in the order they were sent (or a Redis Cluster redirect) could apply the release first, and the lease the read then took stayed untillease-ttl; misses on that key from other instances waitedlease-waitmeanwhile. The read now waits for its command, releases what it took, then fails withIllegalStateException("CacheRuntime closed.")as before. This also covers a lease taken by a lease-wait reread when aLoadObserveris configured.
Fix: no stale local copy after a write returns
- A load that read Redis just before a concurrent write could still put the old value into the local (L2) copy after the write returned, briefly, until its own recheck removed it. A read on the same instance right after the write could see the old value. The local copy is now checked and written in one step under the key's lock, so once a write returns, no older value can appear in that instance's local copy.
Fix: a late write's own broadcast drops the writer's stale copy
- A write whose outcome is unknown (a
put,putAll,invalidate, set write or versioned write that timed out or lost its connection, but not one rejected before it was sent) may still run later and broadcast its invalidation. The writing instance skipped that message because it came from itself, so a stale copy it had loaded between the failure and the late write stayed in its L2 untillocal-max-age. Now, forlocal-max-ageafter the failure, the instance handles its own messages for those keys like another instance's: it drops its copy. These messages don't count incocache.invalidations.received. A versioned write-back (fill) with an unknown outcome is covered the same way (RFC 0005 §4.6). - Only on backends that broadcast atomically (the Redis default). With
channel-mode: sharded, or when the atomic-broadcast probe failed, a late command carries no broadcast, andlocal-max-ageremains the bound.
Fix: SetStore batch reads read Redis in one batch
getAllandlookupAllon aSetStore(synchronous, async and suspending views) read every key that missed L2 with onereadAll, merged with in-flight reads of the same keys, instead of one Redis read per key (RFC 0005 §9). A key whose content can't be read still fails the call, after the other keys are filled.
New: cocache.refresh.skipped
- A counter of refresh-ahead runs that were due but didn't happen: another instance held the refresh token, so this one only re-read Redis and backed off; or a copy got no refresh point although the cache refreshes ahead, because its remaining lifetime was no longer than
refresh-windowor refreshing it would only read the same content.CacheMetrics.refreshSkipped; see refresh meters.
Fix: a failed reload in a batch read no longer strands the rest of the batch
getAllloads and fills the whole batch first, then reclaims corrupt keys one by one. If a corrupt key's reload fails, the other keys are still written back to Redis (or their leases released), and the batch then fails with the first error. In 6.x, the blocking path reclaimed corrupt keys first and stopped at the first failure, leaving the other keys' leases until they expired, so other instances waitedlease.waiton those keys.
Fix: Spring transactions no longer lose an invalidation
Also fixed on the 6.x branch. See Spring Cache transactions.
@CacheEvict(beforeInvocation = true)inside a transaction. Spring callsevictIfPresentfor it, and itsTransactionAwareCacheDecoratorpasses that call straight through, so the key was invalidated only before the commit. A read on another instance between the eviction and the commit could load the committed old row back into Redis, and nothing invalidated it afterwards, so every instance read the old value untilttl.evictIfPresentstill invalidates at once, as Spring requires, and inside a transaction it now also registers the key withTransactionalInvalidator, so the commit, a rollback, or a rollback to a savepoint invalidates it again. Without a transaction, or withoutspring-tx, nothing changes.- Rollback to a savepoint (
NESTED). When a nested transaction rolls back to its savepoint, Spring doesn't callafterCompletionon the outer transaction's synchronizations, and the outer commit later reports a commit. An uncommitted row that a read inside the nested part had put into Redis stayed visible to every instance, and to the outer transaction itself, until the outer transaction ended.TransactionalInvalidatornow handlessavepointRollback(Spring 6.2+): it invalidates every key registered so far in the transaction, keeps them registered, and invalidates them again when the transaction ends. A failure there is logged, not thrown: Spring callssavepointRollbackbefore it rolls the database back to the savepoint, and an exception would skip that rollback. - On the
6.xbranch, a@CachePutinside a nested transaction that rolls back to its savepoint still writes its value when the outer transaction commits. 8.0 drops it; see the next section.
Spring: CoCache's own transaction decorator
See Spring Cache transactions.
@CacheEvictinvalidates on rollback too. Spring's decorator ran it only after the commit. A@Cacheable(sync = true)read in the same transaction could load the uncommitted row into Redis, and after a rollback that row stayed untilttl. The 6.9.0 changelog listed this as not covered. The key is now registered with the transaction and invalidated after the commit and after a rollback.- A later eviction wins. At the commit, the registered invalidations run first, then the deferred
@CachePutwrites that weren't followed by an invalidation of the same key. A@CachePutand then a@CacheEvictof one key end with the key evicted. - Savepoints. When a
NESTEDtransaction or a programmatic savepoint rolls back, writes registered after the savepoint are dropped. Before, a@CachePutinside a rolled-back nested transaction was still written at the outer commit. - Failures after the commit go to the
CacheErrorHandler(the cache interceptor's, as outside a transaction) instead of being thrown to a caller whose data is already committed and who would retry. If the handler rethrows, as Spring's default does, the exception is logged atERRORand not thrown. Spring then also runs the other synchronizations'afterCommit, which a thrown exception skipped. @CacheEvict(allEntries = true)still clears only this instance's L2, and now logs aWARNthe first time on each cache. Clearing a cache cluster-wide comes with the namespace reset in a later 8.x.- At startup, the starter logs a
WARNwhen the cache advice and the transaction advice have the same order. Both default toLOWEST_PRECEDENCE, so which one is outermost depends on registration order. Declare@EnableTransactionManagement(order = Ordered.LOWEST_PRECEDENCE - 1)to put the transaction outermost. See Transaction advice outermost.
Spring: an optional degrading CacheErrorHandler
cocache.spring-cache.degrade-on-error: truegives Spring's cache interceptor aDegradingCacheErrorHandler. For CoCache caches only, read and write failures are logged and not rethrown, so a non-sync@Cacheableruns its method while Redis is down, assync = truealready did. Failed invalidations and clears, and failures on other caches, still go to the handler configured before, which becomes its delegate. See When Redis fails.
Redis: the store is natively suspending
RedisBackend.storereturns a native suspending store. It sends Lettuce's async commands and waits without holding a thread;readAllandfillAllsend every command first and wait for all of them together. The invalidation channel'spublishsuspends the same way. Commands, scripts and the wire format are unchanged.- Lettuce cancellations are Redis failures. A command Lettuce cancels when it resets or closes a connection now fails as
RedisException, with the cancellation as its cause. In 6.x it reached the core as aCancellationException, which the core took for the caller's own cancellation: a read didn't fall back to the source, and readers waiting on it loaded for themselves. - Leases come back sooner after a dropped connection. A read, reclaim, fill or release that fails for any reason except a rejection before it was sent now releases its token. A release rejected while the connection is down is resent with backoff (100 ms doubling to 2 s) until it runs, the token expires or the backend closes. In 6.x only a timeout or an interrupt released the token, so a lease taken by a read that was in flight when the connection dropped stayed until
lease-ttl, and misses on that key across the cluster waitedlease-waitfirst. - Fix: a batch read that fails on a dropped connection releases the other leases. Lettuce fails every command in flight with one shared exception. In 6.x,
getAllthen threwIllegalArgumentException: Self-suppression not permittedinstead of the Redis error and left the leases the other reads in the batch had taken untillease-ttl. Batch writes (putAll,invalidate) had the sameIllegalArgumentException. Now the Redis error is thrown and the leases are released. - Reading a reply (parsing the header, copying the value or the set members) happens on the caller's thread for the blocking API and on the runtime's executor for the async API, no longer on a Lettuce I/O thread.
- A batch write (
putAll,invalidate) that spans several groups sends all of them at once, so a failing batch waits about onecommand-timeoutinstead of one per group.
TCK
- Breaking: every suite (
BackendProtocolSpec,EngineSpec,SetEngineSpec,MultiNodeSpec,FaultSpec,VersionedSpec) has an abstractexpectedCapabilities: Set<L1Capability>(CONDITIONAL,VERSIONED,SETS) with no default, so a subclass that doesn't declare it no longer compiles. Each suite's newstoreProvidesExactlyTheDeclaredCapabilitiesfails when the store provides a capability you didn't declare or lacks one you did, or whenconditional(),versioned()orsets()returns a different object on another call. Cases that need a capability are skipped only when it isn't declared:SetEngineSpecandVersionedSpecskip every case withoutSETSorVERSIONED.EngineSpec.supportsConditionalWritesis removed; leaveCONDITIONALout instead.L1Capabilityexists only in the TCK: the store's accessors remain the only way to state a capability. See Declaring capabilities. FaultSpec.cancelledCommandsAreL1FaultsNotCancellationschecks commands the client under your store cancels (a future yourFutureL1Storecancels, a Lettuce connection reset): the read falls back to the loader and serves the readers waiting on it,putfails withCacheWriteException, no caller sees aCancellationException, and the cancelled read's lease is gone once L1 is back. It runs when you override the newcommandCancellation()hook, which returns aCommandCancellation(hold,cancel,close); the defaultnullskips it. CoCache runs it on the in-memory backend throughFutureL1Store.adaptand on standalone Redis.HookedBackend.putscounts single-key puts.- CoCache runs the whole TCK on its in-memory backend through
FutureL1Store.adapt, the path a Java backend takes, and on a store with no optional capability. On Redis, the async view reruns each engine suite once, on classic Pub/Sub, since both views now call the same store. - Breaking: the TCK drops
AsyncEngineSpec,AsyncSetEngineSpec,AsyncMultiNodeSpec,AsyncFaultSpec, andAsyncVersionedSpec. ExtendEngineSpec,SetEngineSpec,MultiNodeSpec,FaultSpec, orVersionedSpecinstead; to also run a suite through the async view, overrideaccess = CacheAccess.ASYNC. The async-only cases (cancellation, completion threads, waits that hold no threads, timeouts, reentrancy) test the core, not a backend, and now live in CoCache's own tests. - Breaking:
BackendProtocolSpectakes the suspending shape. Its cases callL1Storedirectly throughSuspending.await(new in the TCK; it uses only the Kotlin standard library), and the set-member cases needsets().AsyncBackendProtocolSpecis removed; a Java backend runsBackendProtocolSpecon the store thatFutureL1Store.adaptreturns.HookedBackendwraps the store inForwardingL1Storeand theForwarding*surfaces and keeps only the capability surfaces the wrapped store has. Its hooks run in the calling coroutine after the wrapped store returns, andioExecutordelivers the result of every call.HookedBackend.versionedWritesis gone with the SPI property. - Breaking: the TCK follows the SPI changes above:
L1Fill,ContentFingerprint, thetimeoutparameter and theL1*result names.HookedBackend.afterFillreceives theL1Fillresult instead of aBoolean. - Breaking: the TCK follows the digest segment and state
E. The newBackendProtocolSpec.segmentsRoundTripThroughEveryScalarWritechecks that a store keepsEnvelope.Scalar.writeranddigest, andversionwhen it declaresVERSIONED, throughput,putAll,fill,fillAll,putIfMatchandputIfNewer, and returns them fromreadandreadAll; other new cases check that a value with a digest gets no refresh token and is never reclaimed, that conditional reads and writes compare the stored digest and refuse a value without one, and that a lease onEis taken over after its lease lifetime.VersionedSpec.versionedContentIsNeverRefreshedOrReclaimedis nowversionedContentIsRefreshedButNeverReclaimed, and new cases cover the fill's version rules, every script onE,evictKeepingVersion, refresh-ahead on versioned caches and the per-key eviction.EngineSpecchecks that only aStorewrites a digest, that its reads fail on a tampered or missing digest, that aCachecounts a type mismatch, and that conditional reads verify the value they return;writeRemoteSilentlytakes an optionaldigest, andwriteAuthoritativeSilentlywrites a value with one. BackendProtocolSpechas apause()hook, and its new casereadTimeoutBoundsTheCallAndReleasesItsLeasechecks that, while L1 stalls, a read with a shorttimeoutfails as an L1 failure in about that time, and that the lease it asked for is released afterwards. The case is skipped whenpause()returnsnull, the default.InMemoryBackendhasstall()and acommandTimeoutconstructor parameter for it: while stalled, operations wait up to their time limit, and one that times out never runs.FaultSpec.lateOutcomeUnknownPutEvictsTheWritersOwnStaleCopycovers the own-message fix on backends that broadcast atomically and is skipped on the others.HookedBackend.deferPutsfails single-key puts with an unknown outcome and holds them;applyDeferredPuts()then runs them, broadcast included.SetEngineSpec.getAllReadsTheMissesInOneBatchchecks that aSetStorebatch read sends onereadAllfor the keys that missed L2 and no single-key reads, so a backend'sreadAllmust read set keys the same wayreaddoes.Concurrency.currentThreadName()returns the thread name without the kotlinx coroutine suffix.HookedBackend.issuer()and the specs use it, so hooks that orchestrate races by thread name work whether or not assertions are enabled.EngineSpec.corruptKeyFailingItsReloadStillCompletesTheRestOfTheBatchcovers the batch fix above, andEngineSpec.getAllAfterOwnInvalidateNeverSharesALoadStartedBeforecovers read-your-writes for batch reads.Concurrency.Forked.parkedis true while the thread waits (WAITINGorTIMED_WAITING). A blocking follower now waits insiderunBlocking, which parks with a timeout, so the specs no longer expectWAITINGonly.BackendProtocolSpecwrites set members with the check-and-write operations (SetL1Store.addMembers/removeMembers). The newmemberWritesRefuseUnreadableContentAndKeepItchecks that a member write on a scalar value returns its format and changes nothing; it replacesremoveMembersOnScalarIsNoOp, andmembersAreAddedAtomicallyOverAnyNonSetStateis nowmembersAreAddedAtomicallyOverLeases.EngineSpecandSetEngineSpecdrop thereclaimcases on caches without a loader.EngineSpec.conditionalOperationsFailOnUnreadableContentcovers conditional reads and writes and checks that they never reclaim. Withforeign-formatremoved,EngineSpecdropsforeignContentWithoutLoaderIsReclaimedWhenConfiguredandforeignContentFailsWithLoaderWhenConfigured.SetEngineSpec.unrecognizedContentFailsByDefaultandSetEngineSpec.memberWritesOverUnreadableContentFailByDefaultlose theirByDefaultsuffix.BackendProtocolSpec.putIfNewerRejectsNoVersionchecks thatputIfNewerrefusesVersioned.NO_VERSIONand changes nothing.EngineSpec.onlyStoresWriteAWriterIdAndADigestandVersionedSpec.onlyVersionedStoresWriteAWriterIdcheck that only aStoreorVersionedStorewrites one.
v6.10.0
Module Group: me.ahoo.cocache · Minor release, because it adds a configuration property and CacheRuntime.policy, and the last 6.x feature release: later 6.x releases only fix defects. Fixes the remaining 6.x items from the 6.8.0 architecture review and isolates failing invalidation listeners. No API is removed. The Redis wire format and the invalidation channel are unchanged, so 6.10.0 instances can share Redis with any 6.x instance and be upgraded one at a time.
Behavior change: the SetCache eviction check no longer skips silently
- The startup check reads
maxmemory-policyfromINFO memoryinstead ofCONFIG GET. Managed services that blockCONFIGusually allowINFO. With aSetCache, the Redis user needs+info; the ACL starting point now includes it. - If the policy still can't be read, the check no longer skips silently. It uses the new
cocache.redis.assume-maxmemory-policywhen set. Otherwise it logs a warning, or stops startup withcocache.redis.set-cache-eviction-check: fail. To keepfailmode on a Redis that deniesINFO, grant+infoor setassume-maxmemory-policyto the policy of your deployment. - It checks every declared
SetCache, including lazy beans that aren't created at startup (for example withspring.main.lazy-initialization=true). Theirttlcomes from the same annotation, customizers and properties as at creation. The check doesn't create them. - Under
volatile-*it warns about eachSetCachewith a finitettl, which Redis can evict before it expires. This is only a warning, also infailmode. - See maxmemory-policy.
Behavior change: endpoint DELETE on an unknown cache returns 404
DELETE /actuator/cocache/{name}andDELETE /actuator/cocache/{name}/{key}return404for an unknown cache name instead of204, so a misspelled name no longer looks like success. Known caches still return204and200.CoCacheEndpoint.clearLocalreturnsBoolean(whether the cache exists) instead ofUnit. Over JMX the operation returns that value.
Fix: a failing invalidation listener no longer starves the others
- An invalidation listener that throws an
Error, or a checked exception thrown from Kotlin, no longer keeps the listeners after it from receiving that message. In 6.9.1 and earlier the Redis channel caught onlyRuntimeExceptionaround each listener. It now catches everyThrowable, logs it and goes on, and rethrows only aVirtualMachineError. Resets were already isolated. - The in-memory backend (
InMemoryBackend, for tests) isolates listeners the same way. A listener's exception no longer reaches the caller whoseputorinvalidatepublished the message.
Fix: an interrupted waiter stops waiting
- A synchronous call that joins another caller's load of the same key (
get,getAll) now responds to interruption. It throwsInterruptedExceptionwith its interrupt flag still set, and only that caller stops waiting: the load continues, and the other waiters still get its result. In 6.9.1 and earlier the waiter ignored interruption until the load finished, soFuture.cancel(true), aTimeLimiterorExecutorService.shutdownNowcouldn't stop it. - A call through a
@CoCacheinterface receives thatInterruptedExceptionwrapped inUndeclaredThrowableException, as the JDK does for any checked exception an interface method doesn't declare (see below).
Fix: L2 copies ignore wall-clock steps
- The default clock reads the wall clock once at startup and then advances by
System.nanoTime(). In 6.9.1 and earlier it re-read the wall clock every 100 ms, so stepping the clock back by an hour (an NTP correction, a manual change) kept L2 copies alive for an extra hour, and stepping it forward expired them early. The hit path still does one volatile read.
Fix: a failed cache creation can be retried
- When creating a cache failed in
backend.storeor while constructing the engine, its namespace stayed taken, so retrying the same cache failed withNamespace[…] is already used by another cache.The namespace is now released, and a store that was already created is closed.
Docs
Subscription.close()doesn't wait for callbacks already being delivered, so such a callback can arrive afterclose()returns. It only guarantees that messages and resets arriving after it are not delivered. See Extending CoCache.- Deployment now spells out what non-atomic broadcast (
shardedmode, or after the probe fell back) means when the publish fails after the write succeeded. @CoCacheinterface proxies pass exceptions through unwrapped, except where the JDK requires otherwise: a checked exception the interface method doesn't declare, such as anIOExceptionthrown by a Kotlin loader, arrives wrapped inUndeclaredThrowableException, with the original as itscause. Caches injected from a spec are the engine itself and are unaffected. See Architecture.
API
CacheRuntime.policy(name)returns the effectiveCachePolicyof a created cache.- New property
cocache.redis.assume-maxmemory-policy(see Configuration).
v6.9.1
Module Group: me.ahoo.cocache · Patch release that completes two Redis fixes from 6.9.0 on paths they missed, found by the second review round of RFC 0005 (appendix B). No API, wire format or channel changes, so 6.9.1 instances can share Redis with any 6.x instance and be upgraded one at a time.
Fix: interrupted Redis calls
- Interrupted scripts. A script whose caller is interrupted while waiting for Redis is handled like a timeout: it is never written to Redis afterwards, and the call fails with
RedisException("Interrupted while waiting for Redis.")with the interrupt flag still set. In 6.9.0 an interruptedputcould still run later, in Redis Cluster while it waited for a node connection, and overwrite a newer value. Interrupts come fromFuture.cancel(true), Resilience4jTimeLimiter, orExecutorService.shutdownNow. Once the flag is set, every later wait on that thread fails at once in the same way, such as the remaining keys of agetAll. - Leases after an interrupted read. A read whose wait is interrupted releases, in the background and best effort, the lease or refresh token it may have been granted, as a timed-out read already did. For
getAll, this covers every key that hadn't returned yet. In 6.9.0 each such key kept its lease forlease-ttl, and other instances waitedlease-waiton every miss of it.
Fix: leases after a failed fill
- A fill (the write-back of a loaded value) that times out or whose wait is interrupted releases its lease in the background, best effort. In 6.9.0 a fill dropped before it was sent kept its lease for
lease-ttl. If the fill already ran, the release finds no matching token and changes nothing. A fill rejected while disconnected still leaves its lease tolease-ttl. - A batch fill (
getAll) stops at its first failure and gives up the rest: it releases their leases instead of waiting for each, so a failing batch still waits at most onecommand-timeout. - A lease release that times out or is interrupted is sent again, since it may have been dropped before it was sent.
v6.9.0
Module Group: me.ahoo.cocache · Minor release with two default changes for caches without a loader, where Redis holds the only copy, and fixes from an architecture review of 6.8.0: transactional invalidation, refresh-ahead, Redis command timeouts and subscriptions, and a broadcast fix for conditional and versioned writes. No API is removed. CachePolicy.invalidateFailure and CachePolicy.readFailure become nullable; their JVM signatures are unchanged, so compiled callers keep running. The Redis wire format and the invalidation channel are unchanged, so 6.9.0 instances can share Redis with any 6.x instance and be upgraded one at a time.
Behavior change: reads without a loader fail when Redis fails
read-failure(CachePolicy.readFailure) is now unset by default and decided per read:degradewith a loader, as before, andthrowwithout one. An explicitdegradeorthrowstill applies.- So by default a read without a loader (a
Cachewith no loader, read throughget,lookuporgetAll) now throwsCacheReadExceptionwhen the Redis read fails, and caches nothing in L2. Such a read has no source to degrade to: skipping Redis can only answer "absent". This matchesgetIfChangedandSetCache. - A cache without a loader that treats "unreadable" as a safe answer, such as a revocation list where a Redis failure means "not revoked", sets
read-failure: degradeexplicitly. The read then returnsnull(absent fromgetAll,Absentfromlookup) and counts incocache.remote.failures, but writes nothing to L1 or L2, so every read during the failure goes to Redis again. - In 6.8.0 and earlier the read returned
nulland kept thatnullin L2 as a negative entry fordegraded-local-max-age(10 s); an explicitdegradedoesn't bring that copy back. During the outage callers saw a present key as absent, and for those 10 s after recoveryget(key)still returnednullandget(key, loader)returnednullwithout calling its loader. get(key, loader)has a source and still degrades. If it joins a read without a loader that fails, it loads with its own loader instead of sharing the failure.- The other reads that skip Redis without a loader (lease wait timeout, pending invalidation,
foreign-format: reclaimon a newer format, failed reclaim) still returnnullbut no longer cache it as a negative entry, soget(key, loader)isn't blocked by it. - Spring Cache: a non-sync
@Cacheablereads without a loader, so a Redis read failure reaches Spring'sCacheErrorHandler(see Spring Cache).
Behavior change: invalidate-failure defaults to throw without a loader
invalidate-failure(CachePolicy.invalidateFailure) is now unset by default and decided per cache:retrywith a loader, as before, andthrowwithout one. An explicitretryorthrowstill applies.- Without a loader a delayed retry loses updates. Instance A's
invalidatefails and is queued for retry; instance B then writes the key withput; about 100 ms later A's retry deletes B's value. With a loader, deleting is always safe because the next read reloads. - Spring Cache caches usually have no loader, so a failed
@CacheEvictnow throwsCacheWriteException(through Spring'sCacheErrorHandler) instead of retrying. The annotated method is the source there and a delete is safe: setinvalidate-failure: retryon those caches to keep the 6.8 behavior. CachePolicy.invalidateFailureandCachePolicy.Builder.invalidateFailureare nowInvalidateFailureMode?, andreadFailureis nowReadFailureMode?. Kotlin code that reads the property sees a nullable type. Binaries compiled against 6.8 or earlier, including the 6.4 constructor, get the new default.
Fix: replayed conditional and versioned writes broadcast without atomic broadcast
- Without atomic broadcast (the
shardedchannel mode, or when the startup probe falls back), aputIfNewerorputIfMatchcould be written to Redis while its separate publish failed. The caller gotCacheWriteExceptionand replayed it as documented, but the replay returnedStale(version)orConflict(own digest)and published nothing, so other instances kept their stale L2 copy untillocal-max-age. - The engine now also publishes when
putIfNewer/invalidateIfNewerreturnsStalewith the version it was given, and whenputIfMatchconflicts with the digest of its own value. An extra invalidation only drops copies. An older version and other conflicts still publish nothing. Atomic broadcast is unchanged.
Fix: transactional invalidation
These fixes apply to TransactionalInvalidator. See Transactions.
- Rollback. A rollback, or a commit whose outcome is unknown, now also invalidates the keys registered in the transaction. A load inside the transaction runs on the caller's thread, so it can read the transaction's uncommitted rows and write them to Redis under its lease. In 6.8.0 a rollback left that value in Redis for its
ttl. - Late registrations. An invalidation registered from another synchronization's
afterCommit, or after this one already ran, is no longer lost. It runs inafterCompletion, or at once. The same holds when an earlier synchronization'safterCommitthrows. - Failures. One failing cache no longer stops the others. Every registered cache is invalidated, then the first exception is thrown and the rest are added to it as suppressed. Exceptions in
afterCompletion(rollback, fallback) are logged by Spring, not thrown to the caller. - Not covered.
@CacheEvictand@CachePutgo through Spring'sTransactionAwareCacheDecorator, which acts only after commit, so they still don't run on rollback. Reactive transactions (R2DBC,@Transactionalsuspend functions) aren't visible to this class and invalidate at once, before commit; invalidate after the transaction ends instead.
Fix: refresh-ahead
- Backoff without the token. An instance that doesn't get the refresh token backs off before reading Redis again: by the smaller of
max(lease-wait, 100 ms)and half the value's remaining lifetime. Before, it re-read Redis on every hit while another instance reloaded, and for up tolease-ttlif that instance crashed. Redis reads per instance and key during a refresh no longer grow with the hit rate. The instance still picks up the new value before the old one expires. - Short lifetimes. A value whose remaining lifetime is no longer than
refresh-windowis no longer refreshed ahead. It expires and reloads on the next miss. This covers lifetimes set byttlOforput(key, value, ttl). In 6.8.0 every hit on such a value reloaded from the source.
Fix: Redis timeouts and subscriptions
- Timed-out scripts. A script that timed out is never written to Redis afterwards. Before, a command Lettuce had not sent yet could still run after the caller saw the timeout, and overwrite a newer value: in Redis Cluster, a command waiting for a node connection; with
RedisBackend.ofand a client that buffers while disconnected, a buffered command. A command already sent still runs on Redis and its reply is dropped, as before. WithRedisBackend.of, keepDisconnectedBehavior.REJECT_COMMANDS: without it, commands wait the fullcommand-timeoutinstead of failing fast. - Leases after a read timeout. A read that times out releases, in the background and best effort, the lease or refresh token it may have been granted. Other instances no longer wait
lease-waiton every miss of that key forlease-ttl. shardedchannel mode. A channel whose subscription was lost and isn't confirmed again yet resets its subscribers on every heartbeat, not only once. Staleness stays within the heartbeat plus the resubscribe time.- Concurrent subscribe and unsubscribe. Subscribing and unsubscribing the same channel at the same time (several runtimes sharing one backend) no longer leaves a subscriber without invalidations.
- Format byte. The format byte of a Redis value is read as unsigned. This only matters for format numbers of 128 and above.
TCK
EngineSpec,FaultSpecandVersionedSpec(and their async versions) gain cases for these behaviors, includingread-failure: degradewithout a loader.VersionedSpec.refusedVersionsChangeNothingAndDoNotBroadcastnow expects equal versions to broadcast on backends without atomic broadcast.EngineSpecgains two refresh-ahead cases: an instance without the token backs off, and values that don't outliverefresh-windowaren't refreshed.MultiNodeSpec.refreshAheadLoadsOncePerKeyAcrossNodesadvances the clock past the backoff before it checks the other instances.
v6.8.0
Module Group: me.ahoo.cocache · Minor release, additive only: Cache, AsyncCache and SuspendingCache gain version-ordered writes as default methods (they throw UnsupportedOperationException in implementations that don't override them), CacheSpec can declare a cache versioned, and the cocache-api SPI gains CoherenceBackend.versionedWrites and RemoteStore.putIfNewer / AsyncRemoteStore.putIfNewerAsync with defaults. Existing callers, custom Cache / SuspendingCache implementations, and custom backends keep compiling and running unchanged. The Redis key layout, header layout, format version and invalidation channel are unchanged. 6.0 to 6.7 instances read versioned values (below), so 6.8.0 instances can share Redis with any 6.x instance and be upgraded one at a time.
Versioned writes
For writers that know each value's version, such as an event-sourced aggregate with one writer and increasing versions whose events can be redelivered. See Versioned writes.
- Declare a cache versioned with
versioned = true, or with aversionedLoader/versionedAsyncLoaderreturningVersioned(value, version)(suspendingVersionedLoaderincocache-coroutines). Creating one fails at once on a backend withoutversionedWrites. The Redis and in-memory backends support it. putIfNewer(key, value, version[, ttl])writes only ifversionis greater than the version in Redis, in one Lua script. An equal version is an idempotent no-op and an older one is refused; both returnStale(current)and change, broadcast and re-expire nothing. A successful write is aput: it fences out loads in flight, including one holding the lease that read a higher version.invalidateIfNewer(key, version[, ttl])writes a tombstone: a negative entry with a version that blocks older redelivery for the value's lifetime.- A versioned loader's miss-fill stores the version, so later writes compare against it. A loader returning
Versioned(null, n)(deleted at versionn) writes the same tombstone asinvalidateIfNewer(key, n);null(never existed) stays a plain negative entry.getVersioned(key)reads through and returns the value with its version, ornullfor an absent key or a tombstone. - Ordering holds while the entry lives: after a value or tombstone expires, any version can be written again. Size
ttlto your redelivery horizon. - A versioned cache doesn't support
refresh-window.cocache.defaults.refresh-windowskips it. - New meter
cocache.versioned.stale(Observability).
Wire format
A versioned value or tombstone is a format-1 String with the usual 36-byte header and payload. Only the token slot holds something new: a 16-byte mark, the 8-byte version, and an issue time of +inf. Older instances read the payload as before, their read script (unchanged in 6.8) never grants a refresh token on such a value, and their fill and release never match it. Their writes (put, invalidate, putIfMatch) replace it with content without a version, so ordering holds only once every writer of a versioned cache runs 6.8. See Wire format.
SPI
CoherenceBackend.versionedWrites(defaultfalse),RemoteStore.putIfNewer/AsyncRemoteStore.putIfNewerAsync(defaults refuse withUnsupportedOperationException: a read-then-put default would let a late version overwrite a newer one),RemoteVersionedWrite,Fill.version(a new constructor; the 6.7 constructor,copyandcomponentNare unchanged), andEnvelope.Scalar.version. A backend that supports versions overrides both methods atomically, storesEnvelope.Scalar.versiononfill,putandputAlland returns it on reads. See Extending.- The TCK gains
VersionedSpecandAsyncVersionedSpecfor backends withversionedWrites.
v6.7.0
Module Group: me.ahoo.cocache · Minor release, additive only: Cache, AsyncCache and SuspendingCache gain conditional reads and writes as default methods (they throw UnsupportedOperationException in implementations that don't override them), and the cocache-api SPI gains RemoteStore.readIfChanged / putIfMatch and their AsyncRemoteStore counterparts with default implementations. Existing callers, custom Cache / SuspendingCache implementations, and custom backends keep compiling and running unchanged. The Redis wire format and the invalidation channel are unchanged (the new scripts only read the existing format), so 6.7.0 instances can share Redis with any 6.x instance and be upgraded one at a time.
Conditional reads and writes
For caches whose only copy is Redis and whose values are updated by read-modify-write. See Conditional writes.
putIfMatch(key, expected, value[, ttl])writes only if Redis still holds the value with digestexpected(null: only if Redis holds no value). Compare and write are one Lua script, and the invalidation is broadcast only when the value is written. It returnsWritten(digest)orConflict(current). A successful write follows the same TTL and fencing rules asput.getIfChanged(key, known)reads Redis, never L2, and returnsUnchangedwithout transferring the value when its digest still equalsknown. Otherwise it returnsPresent(value, digest)orAbsent. It saves wire bytes, not Redis CPU: the script reads and hashes the value on every call, about 20 ms for an 8 MB value on Redis 7.4 (about 13 ms of it is the read a plain L1 read also pays). The digest isn't stored at write time, because that needs a wire-format change.- The digest is the SHA-1 of the value's encoded bytes, the same digest
reclaimalready used for scalar values. - Read and write classify unreadable content the same way. Values written by a newer CoCache and sets always throw with a
ForeignFormatExceptioncause and are left untouched;reclaimnever treats them as absent. Content CoCache 6 didn't write followsforeign-format:fail(the default) throws,reclaimcounts it as no value. A value the codec can't decode makesgetIfChangedthrow, andputIfMatchonly ever conflicts on it.getIfChangedthrowsCacheReadExceptionwhen Redis fails, regardless ofread-failure. - New meters
cocache.conditional.conflictsandcocache.conditional.unchanged(Observability).
SPI
RemoteStore.readIfChanged/putIfMatch,AsyncRemoteStore.readIfChangedAsync/putIfMatchAsync, and the result typesRemoteConditionalRead/RemoteConditionalWrite. ThereadIfChangeddefaults read and compare on the client: correct, but they always transfer the value. TheputIfMatchdefaults throwUnsupportedOperationException(the async one fails with it): a read-then-put default would lose updates under concurrency. A backend supports conditional writes only by overriding both with one atomic operation, as the Redis and in-memory backends do. See Extending.- The TCK (
EngineSpec) covers both operations. A backend that doesn't implementputIfMatchsetssupportsConditionalWrites = falseto skip those cases. Otherwise they must pass, including a concurrent case that forces every writer to race on one digest.
v6.6.0
Module Group: me.ahoo.cocache · Minor release: the cocache-api SPI gains RemoteStore.addMembersIfReadable / removeMembersIfReadable and their AsyncRemoteStore counterparts, all with default implementations, so existing backends keep compiling and running. Two behavior changes tighten fail-closed handling for caches without a loader: SetCache writes fail on content they can't read, and reads without a loader fail on values written by a newer version (below). The Redis wire format and the invalidation channel are unchanged, so 6.6.0 instances can share Redis with any 6.x instance and be upgraded one at a time.
Behavior change: SetCache writes fail on content they can't read
SetCache.addandremovenow followforeign-formatlike reads do. Withfail, the default for aSetCache, adding or removing members on a key that holds content the cache can't read throwsCacheWriteExceptionwith aForeignFormatExceptioncause. Such content is an unmigrated 5.x native set, string or hash, a hash without the 6.x format field, a 6.x scalar value, or a set written by a newer CoCache version. The check and the write are one atomic step: the key keeps its content and TTL, nothing is broadcast, and the write counts incocache.unknown.formatsandcocache.write.failures.- In 6.5.0 and earlier, one
addon an unmigrated native set replaced all its members, and the key then looked migrated, soCoCache5Migratorskipped it and the old members were lost for good.removesilently did nothing and reported success. Setforeign-format: reclaimon the cache to keep that behavior. - Whole-value writes (
put,putAll, on aCacheor aSetCache) still replace any content, because the caller supplies the whole value. The replaced 5.x content isn't backed up by the migrator, which skips the key afterwards. See Caches whose only copy is Redis.
Behavior change: newer-format values fail without a loader
- A read without a loader that hits a value written by a newer CoCache version (during a mixed-version rollout) now fails like unreadable content under
foreign-format: fail: it throwsCacheReadExceptionwith aForeignFormatExceptioncause (newer = true), keeps the key, doesn't fill L2, and counts incocache.unknown.formats. It used to read the value as absent, which silently drops data when Redis is the only copy.foreign-format: reclaimkeeps the old behavior. Reads with a loader are unchanged: they load from the source and leave the newer value alone.
SPI
RemoteStore.addMembersIfReadable/removeMembersIfReadableand theirAsyncRemoteStorecounterparts: likeaddMembers/removeMembers, but they leave content that isn't a set of the store's protocol untouched and return its format. The defaults read first and then write, which isn't atomic and can't recognize a newer format. Backends should override them with one atomic check-and-write, as the Redis and in-memory backends do. See Extending.ForeignFormatExceptionhas a newnewerproperty and constructor parameter. The 6.5.0 constructor is kept.
v6.5.0
Module Group: me.ahoo.cocache · Minor release. Additive API in cocache-core and cocache-redis, and one changed default for reads without a loader (below). The Redis wire format and the invalidation channel are unchanged, so 6.x instances can share Redis and be upgraded one at a time.
Migrating caches whose only copy is Redis
CoCache5Migrator (cocache-redis) converts CoCache 5.x data to the 6.x format, for caches with no loader where Redis is the store of record, and for 5.x SetElementsCaches. It covers every 5.x value format: JSON or plain strings, native sets (to a SetCache or a Cache<K, Set<String>>), hashes, and negative entries, and keeps each key's remaining TTL. It can be run again, reports read, written, skipped and failed keys per cache, stops at the first key it can't decode, and supports a read-only dryRun. In-place migration backs up each 5.x value first, and rollback restores the backups. See Caches whose only copy is Redis.
CoCache5Migrator.standalone(uri).use { migrator ->
migrator.migrate(CoCache5Migration.scalar(policySpec, CoCache5Format.string()).sourcePrefix("app:policy:").build())
}Behavior change: reads without a loader fail on content they can't read
- New policy
foreignFormat(failorreclaim; propertyforeign-format) decides what a read does when the key holds content the cache can't read: a value 6.x didn't write (format 0, for example left by 5.x, or a native set or hash), or a value its codec can't decode. - Default for reads without a loader (
SetCache, andCachewithout a loader) is nowfail: the read throwsCacheReadExceptionwith aForeignFormatExceptioncause, leaves Redis and L2 unchanged, and counts incocache.unknown.formats, also withread-failure: degrade. Up to 6.4 such a read reclaimed the key, which deletes the only copy, and returnednull. ASetCachereturned an empty set. Both looked like a real "not found" to the caller. - Reads with a loader, including
get(key, loader), keep reclaiming and reloading (reclaim). Setforeign-format: reclaimon a cache to restore the old behavior.cocache.defaults.foreign-formatdoesn't apply toSetCache. - Who sees a change: only applications that have unreadable content under a cache without a loader. Before 6.5 that content was silently discarded on the first read.
v6.4.1
Module Group: me.ahoo.cocache · Patch release. No API or configuration change. The Redis wire format and the invalidation channel are unchanged, so 6.4.1 instances can share Redis with any 6.x instance and be upgraded one at a time.
Async Redis command timeouts
- Async Redis commands no longer schedule their timeout on the JDK's single-threaded delay scheduler (
CompletableFuture.orTimeout) (RFC 0004 §14). Clients that CoCache creates now time every command with Lettuce's own command timeout (TimeoutOptions, fixed atcocache.redis.command-timeout), which replaces Lettuce's default 60-second timeout at no extra cost. On a standalone Redis this is the only timer. In a Cluster, Lettuce starts timing a command only when it's written to a node connection, so a command that waits for a node connection to open keeps its own timer, now on Lettuce's Netty timer wheel. A client passed toRedisBackend.ofkeeps its own options, and CoCache times its async commands on the same wheel. - Timeouts fail with the same
RedisException("Command timed out after …")as before, on the synchronous and async paths. On the async path, theEVALretry afterNOSCRIPTis a new command with its own timeout.
Behavior changes:
- An async timeout is now precise to one tick of the timer wheel (100 ms by default), so it can fire up to one tick after
command-timeout. It used to be precise to the millisecond. - On clients that CoCache creates, Lettuce's command timeout drops from 60 seconds to
command-timeout(2 seconds by default), and Lettuce 7's relaxed timeouts during server maintenance are turned off. This also bounds the commands that Lettuce sends itself: the re-subscribe after a reconnect, andCLUSTER NODES/INFOduring a Cluster topology refresh. A re-subscribe that times out still runs on the server, and the heartbeat forces a reconnect if the connection is really gone. A topology refresh that times out is retried by the next adaptive trigger. In a very large or busy Cluster, raisecommand-timeoutifCLUSTER NODEStakes longer than that. The connection handshake isn't affected. - On clients that CoCache creates, the cause of a timeout can now be Lettuce's
RedisCommandTimeoutExceptioninstead ofTimeoutException. The outer exception type and message are unchanged.
Fewer thread hops on the async view
- An async continuation now runs in place when the step before it completed inside a task that the same async executor is already running, instead of being submitted to the executor again (investigation). An L1 hit through the async view now makes one executor hop instead of four, and a miss at most three instead of seven. Results that complete on a Lettuce I/O thread, a timer thread, the blocking executor or a loader's own thread are still handed to the async executor, so no continuation runs on an I/O thread. Nesting is capped at 16 levels, after which the continuation is dispatched again.
- On the default
ForkJoinPool, each extra hop could wake an idle worker. Compared with 6.4.0 (median of paired runs), an async L1 hit is 5.5% faster with 1 thread and 8% faster with 8 threads, and an async miss is at least about 8% faster with 8 threads (only 2 valid paired runs). Writes and L2 hits are unchanged.
Fixes
- The heartbeat stopped for good on Lettuce 6.8 (Spring Boot 4.0). Since 6.0.0, on the Lettuce version that Spring Boot 4.0 manages, the forced reconnect after a failed heartbeat threw
NoClassDefFoundError(it used Lettuce 7'sDelegatinginterface). The error escaped the heartbeat task, so the subscription connection was never checked again and the node could no longer heal itself after a half-open connection. Forcing a reconnect no longer uses that interface. The heartbeat task now also logs any error, includingErrors, and carries on with the next heartbeat. The wholecocache-redistest suite passes on Lettuce 6.8.2 and 7.5.2. - No false reentry after inline continuations. While a thread loads a key, either as the leader of a synchronous call or inside a data source, other keys' async continuations that complete on that thread are no longer run in place. This covers a data source that completes another key's load, and a synchronous leader that hands its load permit to another key's async waiter. Before this fix, a callback of that other key that read the key being loaded failed with
IllegalStateException("Recursive call on the same key"). It came from a change made after 6.4.0, so no released version was affected.
v6.4.0
Module Group: me.ahoo.cocache · Minor release, additive. No API change in existing modules, and the Redis wire format and the invalidation channel are unchanged, so 6.x instances can share Redis and be upgraded one at a time.
Kotlin coroutines
The new optional module cocache-coroutines adds a suspending view over the async API (RFC 0004 §7). See Kotlin Coroutines.
val users = userCache.suspending()
val user = users.get("42") // suspends instead of blocking; an L2 hit doesn't suspend
cacheSpec<String, User>("user") {
suspendingLoader { id -> userRepository.findById(id) }
}Cache.suspending()/SetCache.suspending()returnSuspendingCache/SuspendingSetCache, with the same methods as the synchronous API. They share the same L2, fences, in-flight loads and leases.SuspendingCacheLoaderis a suspending data source. Set it withsuspendingLoader(context)(defaultDispatchers.Default), or convert it withasAsyncCacheLoader(). A per-call loader,get(key) { … }, runs in the caller's coroutine context without itsJob.- Cancelling a waiting coroutine doesn't cancel a shared load. Exceptions are the original ones. A loader that reads the key it is loading, from the same cache, fails at once with
IllegalStateException, even after it suspends. - A load that ends in cancellation fails with
SourceLoadCancelledException(aRuntimeException) for every caller that shares it: synchronous, async or suspending. This covers aCancellationExceptionfrom the loader itself (for example awithTimeoutinside it) and a cancelledJobin the spec'scontext. Spec-level loads run under oneSupervisorJob, so one failure doesn't cancel later loads. - Java sees the extensions on the facade classes
SuspendingCachesandSuspendingCacheLoaders. - The module depends on
kotlinx-coroutines-core1.10.2. No other module needs coroutines at runtime. Thecocache-dependenciesplatform declares a 1.10.2 version constraint, the same version Spring Boot 4.1 manages. The starter registers native-image hints for the suspending views when the module is on the classpath. - The synchronous and async hit paths are unchanged.
Gradle Setup
implementation("me.ahoo.cocache:cocache-coroutines:6.4.0")v6.3.1
Module Group: me.ahoo.cocache · Patch release. No API or configuration change. The Redis wire format and the invalidation channel are unchanged, so 6.3.1 instances can share Redis with any 6.x instance and be upgraded one at a time.
Fixes
- A rejecting async executor no longer drops a write's broadcast. Only applies when the backend broadcasts invalidations as a separate command (
channel-mode: sharded, or when the atomic-broadcast probe failed at startup). If thecocache.async-executoryou configured rejected the task that sends the broadcast after an asyncput,putAll,invalidateor set write, the broadcast was skipped and the write's outcome was replaced withRejectedExecutionException. Other instances could then serve their old local copy for up tolocalMaxAge, a successful write counted as a write failure, and a successfulinvalidatescheduled a needless retry. The broadcast now goes out on the completing thread when the executor rejects it, and the write keeps its own result or exception. If the executor also rejects completing the future returned to you, that future still fails withRejectedExecutionException, as before. The default executor (ForkJoinPool) doesn't reject tasks, so the default setup was not affected. - Broadcast after a command timeout: documented, not changed. When a synchronous
putAllorinvalidatetimes out, the broadcast sent after the failure can reach other instances before the timed-out command runs in Redis. We evaluated waiting for the command to finish and kept the current behavior: after a timeout there is no way to know whether or when the command runs, and any bounded wait narrows the window without closing it. Stale copies in this window are still bounded bylocalMaxAge. See architecture.md §4.2.
v6.3.0
Module Group: me.ahoo.cocache · Minor release. 6.2 was not released on its own: the work planned for 6.2 ships in 6.3.0. The Redis wire format and the invalidation channel are unchanged, so 6.0, 6.1 and 6.3 instances can share Redis and be upgraded one at a time.
Async API
Every cache now has an asynchronous view on the same engine (RFC 0004). See the Async API guide.
val async = userCache.async() // same L2, fences, in-flight loads and leases
async.get("42").thenAccept { user -> ... }
async.put("42", user).thenCompose { async.get("42") }Cache.async()/SetCache.async()returnAsyncCache/AsyncSetCache. The methods have the same names and semantics as the synchronous API and returnCompletableFuture. An L2 hit returns an already-completed future.AsyncCacheLoader(loadAsync,loadAllAsync) loads from non-blocking sources. Set it asasyncLoaderin a spec;@CoCacheinterfaces find it by type or byloader = "…". Either kind of loader works with both APIs.- No thread is parked: waits for another instance's lease and for load permits are scheduled, and futures complete on the async executor, never on the Lettuce I/O thread. Futures fail with the original exception, cancelling one doesn't cancel the shared load, and async methods never throw synchronously.
- New settings:
cocache.async-executorandcocache.blocking-executor, each naming anExecutorbean;load-async-timeout(default 30 seconds) per cache, with the newSourceLoadTimeoutExceptionand thecocache.load.timeoutsmetric;cocache.observation.enabled(defaulttrue) for load-path tracing. With Spring Boot Actuator and a Micrometer tracing bridge on the classpath, tracing is on by default; set it tofalseto turn it off.
- The Redis backend implements the new optional SPI
AsyncRemoteStore/AsyncInvalidationChannelnatively. Third-party backends keep working unchanged, because the engine runs their synchronous methods on the blocking executor. - Spring Cache:
retrieveuses the async view, so async and reactive@Cacheable(sync = true)methods load without holding a thread. - Performance: the synchronous hit path is unchanged (JMH within noise of the code before the async work, at 1 and 8 threads). An async L2 hit runs at about 90% of a synchronous one. With 32 requests in flight, one thread completes about 12 times as many Redis reads or writes as a blocking thread.
Batch writes with putAll
putAll(entries) and putAll(entries, ttl) write several keys as one write: one script per Redis slot group, one broadcast per group, and the same stale-write-back protection as put. See Keeping Data Fresh.
Load-path tracing
With an ObservationRegistry bean, the starter registers a MicrometerLoadObserver. It wraps every source load and every wait for another instance's lease in a cocache.load observation, with tags cache, operation and outcome. Hits create no observation. The new LoadObserver SPI lets you plug in your own. See Observability.
Faster SetCache reads
The SetCache read script fetches members with HKEYS and the format version with HGET, instead of HGETALL with every member's empty value. The stored layout is unchanged. In server-side throughput, reads are 1.33, 1.55 and 1.76 times as fast at 10, 100 and 1000 members. ACL errors raised inside the read script now reach the caller instead of being read as unrecognized content.
L2 hit counter
cocache.metrics.local-hits=true (without Spring: CacheRuntime.builder().recordLocalHits(true)) counts reads answered by L2 as cocache.hits{level=l2} and the endpoint key localHits, so reads split exactly into L2 hits, misses and filtered reads. It is off by default because it adds an atomic increment to every L2 hit: with it on, L2 hit throughput drops by about 3–9% in JMH (1 and 8 threads, depending on the call site). With it off, throughput matches 6.1. The 5.x property cocache.metrics.client-side-hits now points to it. See Observability.
Fixes
- With non-atomic broadcast (
channel-mode: sharded, or when the atomic-broadcast probe fails), a write that failed but partly took effect is now broadcast too. Before, aputAllthat failed in one slot group, or aputapplied in Redis whose reply was lost, left other instances reading the old local copy untillocal-max-age. SynchronousputAllandinvalidateAllon Redis now wait for every slot group before they throw. - A read that saw a local copy inside the refresh window just as the previous refresh finished could start a second refresh of the same key on the same instance. That second refresh only cost an extra Redis read, and it no longer happens.
- Executors named by bean (
cocache.refresh-executor, and the newcocache.async-executor/cocache.blocking-executor) could be destroyed before the CoCache runtime when the application shut down, so work submitted while the runtime closed was rejected. This was present since 6.1. The runtime now closes first.
Compatibility kit and CI
- New TCK suites:
MultiNodeSpec(three runtimes, every invalidation interleaving, one load and one refresh per key cluster-wide),FaultSpec(L1 faults, retries, writes that took effect but reported an error, no replay after a reconnect), and async variants of every suite (AsyncBackendProtocolSpec,AsyncEngineSpec,AsyncSetEngineSpec,AsyncMultiNodeSpec,AsyncFaultSpec). - The Redis backend and the starter are tested on Valkey 8 in CI.
- A
SetCacheread benchmark (setRead) confirmed the Hash encoding.
Upgrade notes
cocache.spring-cache.retrieve-executor,CoCacheSpringCacheManager(runtime, executor)andCoCacheSpringCacheManager.DEFAULT_EXECUTORare deprecated: the executor is ignored, and the property logs a warning at startup. They are removed in 7.0.CoCacheSpringCache(cache, admin, executor)is not deprecated: its executor runs the method body.- Async and reactive
@Cacheable(sync = true)methods behave differently in two ways:- The method body runs on
cocache.blocking-executor: virtual threads on JDK 21+. On JDK 17 it's a pool of up to 512 threads that rejects new loads when full (RejectedExecutionException). When full, the old retrieve executor ran them on the calling thread instead. - The load is bounded by
load-async-timeout(default 30 seconds): past it the call fails withSourceLoadTimeoutException, while the method body keeps running.
- The method body runs on
Cache.async()is a default method that throwsUnsupportedOperationException. ACacheyou implement yourself, for example a test double, needs to override it only if callers use the async view.- A custom
LoadObserversees async loads only if it overridesobserveAsync. - Kotlin callers must recompile against 6.3, or they fail with
NoSuchMethodError.LoadPolicygainedasyncTimeout, which changescopyand the synthetic constructor behind Kotlin default arguments, so this applies to Kotlin code that callscopyor omitsLoadPolicyarguments. The constructors andcopyofCoCachePropertiesandPolicyPropertieschanged too, for code that builds the starter's properties itself. Java callers are unaffected. - Redis ACL: a user with a minimal ACL needs
+hkeys +hgetbefore the upgrade, orSetCachereads fail with an ACL error. Keep+hgetall: conditional reclaim and 6.0/6.1 instances still use it. See ACL. - TCK:
HookedBackend.closesDelegate(defaultfalse, as before) and each suite'sclosesBackendlet the suites close a backend created per case. Turn it on if your backend opens connections or threads.BackendProtocolSpecandAsyncBackendProtocolSpecalways close the backend they create and have no such switch. Hooks that pick out a caller should useHookedBackend.issuer(), because async calls complete on other threads.
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:6.3.0")v6.1.0
Module Group: me.ahoo.cocache · Minor release. The Redis wire format and the invalidation channel are unchanged, so 6.0 and 6.1 instances can share Redis and be upgraded one at a time.
Spring AOT and GraalVM native images
Applications that use the starter now build with Spring AOT and run as GraalVM native images. CoCache registers the hints it needs at build time:
- JDK proxies for
@CoCacheand@JoinCacheableinterfaces, and reflection on those interfaces (default methods included); - the key type's
toString()for the default key encoder; - the SpEL root types of
keyExpressionandjoinKeyExpression; - Jackson binding for the value type when the default codec applies.
Cache beans are created by factory methods that AOT can generate code for. A custom Codec or types that only your own code reflects on still need your hints. See Native images.
Configurable executors
cocache:
refresh-executor: applicationTaskExecutor # refresh-ahead loads
spring-cache:
retrieve-executor: applicationTaskExecutor # Spring Cache async retrieveBoth name an Executor bean, resolved by name. An unknown name or a bean that isn't an Executor fails startup. CoCache never shuts down an executor you supply. Prefer a virtual-thread executor for retrieve: a pool that queues tasks behind ones waiting on them can deadlock nested async @Cacheable(sync = true) calls. See Configuration.
SetCache eviction check
With any SetCache, CoCache reads every primary's maxmemory-policy at startup. allkeys-* can evict the set's only copy, so it logs a warning by default. cocache.redis.set-cache-eviction-check selects warn, fail or off. The check is skipped when CONFIG isn't available (managed Redis, ACL). RedisBackend.maxmemoryPolicies() exposes the lookup for applications without Spring.
Agent skills and docs
- The agent skills are split by outcome:
cocache-develop,cocache-migrateandcocache-extend, each withclaude plugin evalcases and a validator in CI. - The documentation site has an animated home page that shows the read and write paths, and a new logo.
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:6.1.0")v6.0.0
Module Group: me.ahoo.cocache · Major release. CoCache is rebuilt on the coherence protocol in RFC 0003. No rolling upgrade: the Redis value layout and the invalidation channel changed, so 5.x and 6.0 instances cannot share Redis. Follow the migration guide and switch every instance at once.
What changes for you
- Stale write-backs are closed. Loads write Redis only while they hold a lease token, and every L2 fill is checked against an invalidation stamp. The 5.x "known inherent window" no longer exists: races inside the protocol leave no stale value in Redis.
- Faster hit path. An L2 hit is 54–59% faster than 5.4, an interface proxy hit 28–64% faster, and
put/invalidateabout twice as fast (JMH, RFC 0003 §7.1). - One loader per key across the cluster, refresh-ahead with one refresh per key cluster-wide, and batch
getAllthat reads L2, then Redis in one round trip, then the source in oneloadAll. - Failure modes you can choose:
read-failure: degrade | throw,invalidate-failure: retry | throw, a bounded invalidation retry queue, and a load bulkhead (load-max-concurrent). - Redis backend on native Lettuce (
cocache-redis, no Spring dependency): standalone, Sentinel and Cluster, TLS through Spring Boot SSL bundles orrediss://, Pub/Sub or Sharded Pub/Sub (cocache.redis.channel-mode). - Spring:
@EnableCoCachewith@CoCacheinterfaces orCacheSpecbeans,CacheSpecCustomizer, layeredcocache.defaults.*/cocache.caches.[name].*properties with full IDE metadata, theCoCacheSpringCacheManager(use@Cacheable(sync = true)for coherent loads), andTransactionalInvalidator(invalidate after commit). - Observability: the
cocacheactuator endpoint andcocache.*Micrometer meters tagged bycache.
Developer experience
JoinCache: a read-only view that joins two caches with two batch reads, declared with@JoinCacheableand registered with@EnableCoCache(joinCaches = […]). See JoinCache.- No Redis for local development and tests:
cocache.backend: memoryruns every cache on the in-process backend (single process only). ACacheClockbean such asManualClocklets tests advance time. - Per-key troubleshooting:
GET /actuator/cocache/{name}/{key}shows the L2 copy and the L1 state of one key without loading it;DELETEon the same path invalidates it cluster-wide. See Operations. - Health indicator
cocache: DOWN when the Redis heartbeat fails; pending invalidations are listed in the details. - Spring Cache check: a WARN for each
@Cacheableon a CoCache cache withoutsync = true(the non-sync path isn't lease-protected);cocache.spring-cache.require-sync=truefails startup instead. - Global key prefix:
cocache.defaults.key-prefix(and per cachecocache.caches.[name].key-prefix), for example${spring.application.name}:when several apps share one Redis. - Key type check: the default
toString()key encoder rejects key types that don't overridetoString(), which would otherwise never hit. ExternalInvalidator: invalidate from CDC consumers or batch jobs with the same protocol, without creating a cache.@JvmOverloadsonLeasePolicy,LoadPolicy,LocalPolicy,RetryPolicyandRedisBackendOptions, andupdatePolicy(Consumer)on spec builders, for Java.
Migration at a glance
| 5.x | 6.0 |
|---|---|
me.ahoo.cache.* | me.ahoo.cocache.*; @EnableCoCache is in me.ahoo.cocache.spring.boot |
cocache-spring-redis, cocache-spring-cache | cocache-redis, cocache-spring (plus cocache-codec-jackson) |
ttlAmplitude, missingTtl, clientSideTtl, refreshAhead | ttlJitter, absentTtl, localMaxAge, refreshWindow |
{name}.CacheSource bean | a CacheLoader<K, V> bean matched by type, or @CoCache(loader = …) |
{name}.ClientSideCache and other bean suffixes | CacheSpecCustomizer, cocache.caches.[name].* |
getCache / set(key, ttlAt, value) / evict | get / lookup / put(key, value, ttl) / invalidate |
SetElementsCache | SetCache |
cocache.redis.strict-failure=true | cocache.defaults.read-failure=throw |
cocache.redis.eviction-channel=sharded | cocache.redis.channel-mode=sharded |
cocache.load.* | cocache.defaults.load-max-concurrent / load-acquire-timeout |
actuator cocacheClient | removed; use cocache |
JoinCache (me.ahoo.cache.api.join) | me.ahoo.cocache.api.join.JoinCache: a read-only view of two caches, registered with @EnableCoCache(joinCaches = […]); evict → invalidate, no set (see JoinCache) |
| Jedis, pluggable L2, explicit negative-entry writes | removed |
Removed 5.x property keys fail startup with a message that names the replacement, if there is one. Some renames change meaning (for example, L2 is now always bounded by localMaxAge, 5 minutes by default): see Behavior changes.
Dependencies
| Dependency | Version |
|---|---|
| JDK (minimum) | 17 (tested on 17 and 25) |
| Spring Boot | 4.1.1 |
| Kotlin | 2.4.21 (artifacts target Kotlin API and language level 2.2) |
| Lettuce | 7.5.2.RELEASE |
| Caffeine | 3.2.4 |
| Jackson | 3.1.5 (tools.jackson) |
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:6.0.0")v5.4.0
Module Group: me.ahoo.cocache · Minor release, additive. The default eviction channel and the Redis wire format are unchanged, so 5.3.x and 5.4 instances can share Redis. The new channel is off by default.
Sharded Pub/Sub eviction channel
cocache:
redis:
eviction-channel: sharded # default: pubsubIn Redis Cluster, a plain PUBLISH reaches every node. SPUBLISH/SSUBSCRIBE (Redis 7+) stays within the shard that owns the channel's slot, so the cost doesn't grow with the cluster.
- It requires Lettuce.
ShardedRedisCacheEvictedEventBususes Lettuce directly, because Spring Data Redis doesn't support Sharded Pub/Sub yet. - Channel names and messages are unchanged. Resubscribing after a reconnect still clears L2.
- The two channels don't interoperate, so switch every instance at once.
- Failed publishes on either channel count in
cocache.eviction.publish.failures(new interfaceEvictionPublishStats).
Evicting from outside CoCache
The operations guide now documents the eviction protocol: the storage key, the channel, and the key@@publisherId message. It includes redis-cli and CDC-consumer examples. A writer that bypasses CoCache runs DEL on the storage key, then PUBLISH.
Redis Cluster tests
A new CI job, "Test (Redis Cluster)", also runs the Redis, Spring Cache, and starter tests on a 3-master, 3-replica cluster. Start the same cluster locally with .github/scripts/start-redis-cluster.sh.
TCK
The two concurrent cases in SetElementsCacheSpec now assert the L1 contents (the authoritative copy) immediately, and poll the per-instance reads with a timeout. Before this change they could fail intermittently where eviction events are slower, such as on Redis Cluster.
Design documents
- RFC 0001: L1 write-back leases for 6.0, which close the cross-instance stale write-back window.
- RFC 0002: the RESP3 client tracking spike result (not adopted for 6.0).
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:5.4.0")v5.3.0
Module Group: me.ahoo.cocache · Minor release, additive (every new interface method has a default). Redis wire format and eviction messages are unchanged, so 5.2.x and 5.3 instances can share Redis. New behaviors are off by default.
Batch reads: getAll / getCaches / loadCacheValues
Reading N keys no longer costs N Redis round trips and N source loads:
val users: Map<String, User> = userCache.getAll(ids)- CoCache reads L2 first, then the remaining keys from Redis in one pipeline, then loads the rest with one
CacheSource.loadCacheValues(keys)call. Keys missing from that result become negative entries. Reading 100 keys from L1 drops from about 13.6 ms to about 1 ms (JMH). - Every fill and write-back is stamp-guarded per key, as in single-key reads.
CacheSource.loadCacheValuescallsloadCacheValueper key by default. Override it with one query, such asfindAllById.SimpleJoinCachejoins with two batch reads.- New API, all with default implementations:
CacheGetter.getCaches/getAll,CacheStore.getCaches,CacheSource.loadCacheValues, andCodecExecutor.executeAndDecodeAll.
Refresh ahead: @CoCache.refreshAhead
@CoCache(ttl = 600, refreshAhead = 60)
interface UserCache : Cache<String, User>When a value has at most refreshAhead seconds left, reads still return it, and one background refresh per key per instance reloads it. Hot keys no longer stall on expiry. Expired values are never served, and negative entries are not refreshed. The default 0 turns it off. Meter: cocache.refreshes.
Source load limit
cocache:
load:
max-concurrent: 32
acquire-timeout: 1sWhile Redis is down, every L2 miss goes to the source. With a limit set, each cache runs at most max-concurrent source loads at once. A load beyond the limit waits acquire-timeout, then fails with SourceLoadRejectedException. Meter: cocache.load.rejections. Unlimited by default.
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:5.3.0")v5.2.0
Module Group: me.ahoo.cocache · Minor release, additive. Redis wire format and eviction messages are unchanged, so 5.1.x and 5.2 instances can share Redis.
Bounded L2 staleness: @CoCache.clientSideTtl
Eviction events travel over Redis Pub/Sub, which delivers at most once. When an event is lost, other instances keep serving their L2 copy until the value's ttl (3600 s by default).
@CoCache(clientSideTtl = 30)
interface UserCache : Cache<String, User>- An L2 copy lives at most
clientSideTtlseconds, then refills from Redis. L1 keeps the full TTL. - The default
0means unlimited, the same as 5.1. - The cap is computed only when writing L2, so the hit path costs nothing extra. Each L2 expiry costs one Redis round trip.
- When set, an L2 hit reports the L2 copy's expiry from
getTtlAt.
Micrometer metrics
With Micrometer on the classpath (spring-boot-starter-actuator brings it), the starter binds cocache.* meters tagged by cache: hits{level=l2|l1}, misses, loads (timer), load.failures, filtered, stale.discards, evictions.received, resets, l2.size, plus the untagged eviction.publish.failures. See Operations.
- The orchestration layer accumulates the counts in
LongAdders. Read them directly fromCoherentCache.stats. - The L2 hit counter (
hits{level=l2}) is off by default. Turn it on withcocache.metrics.client-side-hits=true. Counting on the hottest path costs 8–15% of L2 hit throughput (JMH, 1–8 threads). No other meter touches the hit path. RedisCacheEvictedEventBus.publishFailureCountcounts failed publishes.
CosId dependency removed
cocache-core used CosId only to build the clientId. It now uses the JDK instead.
cosid-coreis no longer a transitive dependency. Projects that use CosId directly must declare it.CosIdHostAddressSupplierAutoConfigurationis removed, so a CosIdHostAddressSupplierbean no longer feeds the clientId's host. The random suffix makes the id unique; the host is only for readability.
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:5.2.0")v5.1.1
Module Group: me.ahoo.cocache · Patch release, backward compatible with 5.1.0. Redis wire format and eviction messages are unchanged.
- Client ids are unique across instances.
HostClientIdGeneratorused{counter}:{pid}@{host}as the clientId, but host + pid is not unique: two containers on the same machine with host networking share an IP and can both run as pid 1. Subscribers ignore eviction events whose publisherId equals their own clientId, so such instances dropped each other's evictions and served stale L2 copies until TTL. The clientId is now{counter}:{pid}:{random suffix}@{host}, and theClientIdGeneratorcontract now requires ids to be unique across instances. - Dependencies: CosId 3.4.1, fluent-assert 1.2.1.
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:5.1.1")v5.1.0
Module Group: me.ahoo.cocache · Minor release, additive. Redis wire format and eviction messages are unchanged, so 5.0.x and 5.1 instances can share Redis.
Atomic element updates for Set-valued caches
Concurrent "read the whole set → modify → write the whole set" updates lose writes across instances. A cache interface can now also declare SetElementsCache<K, E>, and each update becomes one atomic L1 operation:
@CoCache(ttl = TtlAt.FOREVER)
interface PolicyIndexCache : Cache<String, Set<String>>, SetElementsCache<String, String>
policyIndexCache.addElements(key, listOf(policyId))
policyIndexCache.removeElements(key, listOf(policyId))- Wiring: the distributed cache must implement the new
SetElementsStoreSPI. For Redis, useRedisSetDistributedCache(redisTemplate)(native Redis Set, same layout asSetToSetCodecExecutor).InMemoryDistributedCachesupports it as well. If a proxy declaresSetElementsCacheover a store that can't support it, creating the proxy fails with a message that names the fix. - Semantics: L1 is the authoritative copy, and these operations never call the
CacheSource. Adding to a negative cache replaces it, so the sentinel never ends up in the set. After every update, the key's expiry follows the cache'sTtlPolicy(TtlAt.FOREVER→ no expiry, even when the key previously held the 60 s negative cache). Removing from an absent key or a negative cache does nothing. Removing the last element deletes the key. - Coherence: invalidation stamp → atomic L1 update (one Lua round trip) → L2 evict → eviction event. Read-your-writes and in-flight-load protection match
setCache. - Failures always surface: element updates are explicit writes, so an L1 failure always throws, even with
strictFailure = false. The update may still have been applied, for example when the response timed out, so the local copy is evicted and the eviction is published anyway. Both operations are idempotent, so callers can retry. - Write-back safety: on stores that implement
SetElementsStore, a source load's write-back is now conditional: it writes only when the key is absent or holds a negative cache. Its undo is now compare-and-delete. Before this, a load that started before anaddElements(for example, writing the negative cache) could overwrite or delete the added elements. BecauseInMemoryDistributedCacheimplements the SPI, it uses the conditional write-back for every value type. TtlPolicy.valueTtlAt()exposes the jittered value expiry.RedisDistributedCacheis nowopen.
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:5.1.0")v5.0.1
Module Group: me.ahoo.cocache · Patch release, backward compatible with 5.0.0. Redis wire format unchanged.
- Corrupted payloads are no longer deleted on read. A payload that fails to decode is still a miss. The coherent cache's reload now overwrites it through the stamp-guarded write-back. Previously the read issued an unconditional
DEL, which could remove a valid value that another instance had just written. cocache-spring-boot-starterdrops theactuator-support/cloud-supportGradle capabilities. Actuator is nowcompileOnly, and the endpoints still activate only when the application addsspring-boot-starter-actuator. The POM no longer lists actuator as an optional dependency, and nothing changes for Maven or Gradle consumers who don't request those capabilities.- Build: ready for Gradle 10 (no deprecated APIs in the build scripts) and Kotlin's
-jvm-default=enable, with the same binary output as-Xjvm-default=all-compatibility. The test suite also runs on JDK 25. - Docs site: fixed three sequence diagrams that failed to render, and patched all Dependabot alerts in the docs toolchain.
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:5.0.1")v5.0.0
Module Group: me.ahoo.cocache
5.0 rebuilds the coherence core around three first-principles goals — bounded staleness, no lost invalidations, and a cheap hit path. It is a breaking release with no compatibility bridges. Redis storage layout and the eviction message format are unchanged, so 4.x and 5.0 instances can share Redis during a rolling upgrade.
Correctness Fixes
- L1 miss is never a negative cache — Redis reads are one atomic round trip (a Lua script returns TTL + value). An absent key, a key deleted mid-read, or a corrupted payload is a miss that reloads from the source. Previously a concurrent eviction between the
TTLandGETcalls was decoded as a negative cache and pinned into L2 until the old TTL (forever by default). - Local writes invalidate in-flight loads —
evict/setCacheon the same instance now discard a concurrent source load's stale write-back (previously only remote events did). L1 → L2 fills are guarded the same way. - Original exceptions from cache proxies — proxies unwrap
InvocationTargetException; callers no longer receiveUndeclaredThrowableException. - Bounded staleness by default — default
ttlis 3600 s (was forever); the negative cache has its ownmissingTtl(default 60 s, was the value TTL); default L2 is a bounded Caffeine cache (10 000 entries); every (re)subscription of the eviction channel clears L2 so lost pub/sub messages cannot leave L2 stale. - Read-your-writes — a
getafter the same thread'sevict/setCachenever returns the result of a load that started before that invalidation; it reloads once. - Spring Cache —
get(key, valueLoader)loads once per key (@Cacheable(sync = true)semantics);retrieveruns on a dedicated executor instead of the common ForkJoin pool. - Stateful components are never shared —
ClientSideCache,DistributedCacheandKeyConverterbeans resolve by name only; previously a bean matched by generic type could be shared by every cache with the same value type. - JoinCache.evict(key) no longer loads — it evicts only the first cache.
Architecture
cocache-apiowns all SPI:CacheStore→ClientSideCache/DistributedCache,CacheEvictedEventBus/CacheEvictedSubscriber/CacheEvictedEvent,KeyConverter,KeyFilter,CacheSource.CacheValueis sealed:PresentValue(value, ttlAt)|MissingValue(ttlAt).- Storage tiers are pure stores; TTL policy (
TtlPolicy) lives in the orchestration layer. DefaultCoherentCachecoalesces loads per key withSingleFlight(no striped-lock collisions) and guards write-backs withInvalidationStamps.- One
CacheInvocationHandlerserves CoCache and JoinCache proxies.
Performance
JMH, 4.3.0 vs 5.0.0, same machine and Redis (ops/s):
| Benchmark | 4.3.0 · 1 thread | 5.0.0 · 1 thread | 4.3.0 · 8 threads | 5.0.0 · 8 threads |
|---|---|---|---|---|
| L2 hit | 31.1M | 32.6M | 217.5M | 235.9M |
| L1 read | 3,188 | 6,144 | 5,438 | 10,758 |
| Miss + load | 1,487 | 3,082 | 2,467 | 5,173 |
| Set | 2,779 | 2,804 | 4,714 | 4,694 |
L1 reads and miss-loads are about 2× faster, because one Lua round trip replaces TTL + GET. L2 hits still scale with threads: plain bounded Caffeine checks expiry on read against the cached CacheClock. The benchmark ships as RedisCacheBenchmark (./gradlew :cocache-spring-redis:jmh).
Migration from 4.x
| 4.x | 5.0 |
|---|---|
me.ahoo.cache.DefaultCacheValue(value, ttlAt) / .forever(v) / .missingGuard(...) | CacheValue.of(value, ttlAt) / CacheValue.forever(v) / CacheValue.missing(ttlAt) |
cacheValue.isMissingGuard | cacheValue.isMissing (or is MissingValue) |
ComputedTtlAt.at(ttl), ComputedTtlAt.FOREVER, CacheSecondClock.INSTANCE.currentTime() | TtlAt.at(ttl), TtlAt.FOREVER, TtlAt.currentTime() |
ClientSideCache / DistributedCache extended Cache (cache[key] = v) | They are CacheStores: getCache / setCache / evict |
me.ahoo.cache.distributed.DistributedCache, me.ahoo.cache.consistency.CacheEvicted*, me.ahoo.cache.converter.KeyConverter, me.ahoo.cache.KeyFilter | me.ahoo.cache.api.distributed.DistributedCache, me.ahoo.cache.api.consistency.CacheEvicted*, me.ahoo.cache.api.converter.KeyConverter, me.ahoo.cache.api.filter.KeyFilter |
@GuavaCache, GuavaClientSideCache, GuavaCacheEvictedEventBus | @CaffeineCache, CaffeineClientSideCache.build(...), LocalCacheEvictedEventBus |
MockDistributedCache | InMemoryDistributedCache |
CoherentCache.clientSideCache / .distributedCache / ... | CoherentCache.configuration.clientSideCache / ... |
Custom CacheEvictedSubscriber | Implement onReset() (clear local copies) |
Custom CodecExecutor | executeAndDecode(key) reads value and TTL itself; extend StringCodecExecutor / HashCodecExecutor or AbstractCodecExecutor |
ClientSideCache<User> bean picked by type | Name it UserCache.ClientSideCache |
TtlConfiguration, TtlConfigurationAware, ComputedCache | Removed — TTL comes from @CoCache (TtlPolicy) |
@CoCache without ttl meant "forever" | Now 3600 s — set ttl = TtlAt.FOREVER explicitly to keep the old behavior |
JoinCache.evict(key) evicted both caches | Evicts the first cache only; use evict(firstKey, joinKey) for both |
A CacheSource reading the same key from the same cache re-entered the lock | Fails fast with IllegalStateException (it previously over-evicted) |
Dependencies
| Dependency | Version |
|---|---|
| Spring Boot | 4.1.1 |
| CosId | 3.2.1 |
| Guava | 33.7.2-jre |
| Kotlin | 2.4.21 |
| JUnit | 6.1.3 |
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:5.0.0")<dependency>
<groupId>me.ahoo.cocache</groupId>
<artifactId>cocache-spring-boot-starter</artifactId>
<version>5.0.0</version>
</dependency>v4.3.0
Module Group: me.ahoo.cocache
Highlights
- Cache Breakdown Protection Hardened — Replaced the per-key lock map (which had a lock-object recycling race allowing duplicate source loads) with Guava
Stripedlocks inDefaultCoherentCache(#519). - Clock Thread Startup Race Fixed —
CacheSecondClocktimer thread startup no longer races with field initialization; eliminates the "frozen clock → caches never expire" failure mode (#519). - Stale Write-Back Race Fixed — A per-key invalidation generation counter makes in-flight loads detect eviction events that arrive during loading: stale results are discarded (or compensating-evicted) instead of being pinned into both cache tiers until TTL (#519).
- Lifecycle Management —
CoherentCachenow extendsAutoCloseablewith an idempotentclose()(unregister from event bus + close distributed cache); Spring destroys caches automatically at shutdown (#519). - Corrupted Payload Self-Healing — Undecodable Redis values are deleted and treated as a cache miss (source reload) instead of throwing on every read (#520).
- Null Value Normalization —
nullvalues are consistently written as negative-cache sentinels across all codecs (previously: empty-string corruption, NPEs, or codec-dependent semantics) (#520). - Redis Failure Degradation — By default, Redis read failures now degrade to cache-miss semantics (source reload, business calls unaffected) and write/evict failures only log a warning. Set
cocache.redis.strict-failure=trueto restore the strict throwing behavior (#520). - Atomic Hash/Set Writes — Structural codec writes use single-key Lua scripts (
DEL+HSET/SADD+EXPIRE), eliminating concurrent-write field-union corruption. Empty Map/Set writes now silently evict the key instead of throwing (#520). - Configurable Missing-Guard Sentinel — New property
cocache.redis.missing-guard-sentinelmitigates collisions between business data and the"_nil_"sentinel (#520).
Breaking Changes & Behavior Notes
- API removal (the only breaking change):
AbstractCodecExecutor.setPipelined/serializemembers were removed — affects only third-party codecs directly extending this abstract class. CodecExecutor.executeAndDecodereturn type is now nullable (CacheValue<V>?) — covariant-compatible for implementers; direct callers must handlenullon recompile.- Redis failures degrade by default (previously threw); JSON codec
nullvalues become negative-cache sentinels instead of"null"-literal round-trips. - Spring containers now auto-close caches at shutdown;
FactoryBean.getObject()returns a memoized instance (eliminates duplicate event-bus subscriptions). strict-failure/missing-guard-sentinelapply only to auto-configured (fallback-created) caches; customDistributedCachebeans are unaffected.- Wire formats (storage structure, eviction messages) are unchanged — rolling upgrades are fully compatible.
Dependencies
| Dependency | Version |
|---|---|
| Spring Boot | 4.1.0 |
| CosId | 3.2.0 |
| Guava | 33.6.0-jre |
| Kotlin | 2.4.10 |
| JUnit | 6.1.3 |
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:4.3.0")<dependency>
<groupId>me.ahoo.cocache</groupId>
<artifactId>cocache-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>v4.2.0
Module Group: me.ahoo.cocache
Dependencies
| Dependency | Version |
|---|---|
| Spring Boot | 4.1.0 |
| CosId | 3.2.0 |
| Guava | 33.6.0-jre |
| Kotlin | 2.4.0 |
| JUnit | 6.1.1 |
Gradle Setup
implementation("me.ahoo.cocache:cocache-spring-boot-starter:4.2.0")<dependency>
<groupId>me.ahoo.cocache</groupId>
<artifactId>cocache-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>Historical Releases
For the full release history, see GitHub Releases.