Skip to content

Configuration Reference ​

How settings combine ​

Each cache's policy is merged field by field from six layers. A higher layer wins over a lower one; a field a layer doesn't set passes through:

Layer (low to high)KeysWhat it does
1. Type defaultDefaultPolicies.CACHE, VERSIONED_CACHE, STORE, VERSIONED_STORE, SET_STOREEach type has its own: a Store never inherits a derived cache's 1 h ttl (type defaults)
2. Global defaultscocache.defaults.cache.*, cocache.defaults.store.*Below the declaration: fills only the fields the declaration didn't write
3. Declaration@CoCache / @CaffeineCache, or the spec you buildThe library's or application's intent
4. CustomizersCacheSpecCustomizer beans, in Spring orderMay change policy fields and fields that don't decide the type, never the data source (customizers)
5. Global overridescocache.overrides.cache.*, cocache.overrides.store.*Above the declaration, tighten only: staleness bounds take the minimum, the ordered modes (read-failure, fill-in-transaction, invalidate-fills-on-rollback) take the stricter value; nothing else is allowed (what each layer may set)
6. One cachecocache.caches.[name].*Sets any field that applies to the cache, plus unknown-read, key-prefix, read-only and unlock

After the merge, a library's constraints run, then the validation chain. The cache sections apply to the derived types (Cache, VersionedCache), the store sections to the authoritative types (Store, VersionedStore, SetStore):

yaml
cocache:
  defaults:
    cache:
      local-max-age: 2m        # every derived cache that doesn't declare its own
    store:
      local-max-age: 10s       # every authoritative cache that doesn't declare its own
  overrides:
    cache:
      ttl: 30m                 # incident: no derived value lives longer than 30 minutes
  caches:
    "[UserCache]":
      load-max-concurrent: 32

Defaults sit below the declaration because the declaration knows the data: a library that declares readFailure = THROW or a short ttl keeps it whatever a global default says. Overrides sit above it so operators can bound staleness everywhere without a rebuild, but they can only tighten, so they never weaken what a declaration chose.

The layers reach every cache created through CoCacheFactory: @CoCache interfaces, spec beans, and libraries that use the starter's factory bean. A cache created directly with CacheRuntime.create is unlayered: no layer reaches it, and the start log and endpoint say so.

A key in a global layer that doesn't apply to a cache's type, isn't allowed in that layer, or is locked is skipped for that cache instead of failing startup: the start log has a WARN line for it and the endpoint lists it under skippedConfiguration. A value a global layer does set must still be valid for each cache it reaches: cocache.defaults.store.tombstone-ttl: forever fails every VersionedStore that doesn't set its own, because its tombstones need a finite lifetime.

Which fields a declaration writes ​

cocache.defaults fills only the fields the declaration leaves unwritten, so it matters what counts as written:

  • Annotation: every @CoCache attribute that isn't CoCache.UNSET, and unknownRead = ABSENT (the default THROW doesn't count). An @CaffeineCache that sets maximumSize writes local-maximum-size, even when it sets the default 10000.
  • Spec: every field assigned in policy { … } (Java: updatePolicy(…)), and unknownRead when assigned. Writing a sentinel counts: ttl = forever() is written, so defaults.cache.ttl doesn't apply. Assigning a nested policy (lease = LeasePolicy(…), load = LoadPolicy(…), local = LocalPolicy(…)) writes only the fields whose value it changes: lease = LeasePolicy(ttl = Duration.ofSeconds(30)) writes lease-ttl, and lease-wait stays open to cocache.defaults. A nested policy therefore can't write a value equal to the current one, such as LoadPolicy(maxConcurrent = unlimited()) over the default: declare an unlimited load concurrency with maxConcurrent = unlimited() (Java: maxConcurrent(Concurrency.UNLIMITED)), and an L2 size equal to the current one with localMaximumSize = 10_000 (Java: localMaximumSize(10_000L)).
  • A whole policy: policy = somePolicy (Java: policy(CachePolicy)) writes every field. cocache.defaults then sets none of its policy fields (the two transaction modes still apply); each skipped key is listed with the reason the declaration sets the whole policy, so defaults don't apply.

Edit the type default with policy { … } unless you mean to fix every field.

What each layer may set ​

FieldCategorydefaultsoverridescaches.[name]
ttl on a Cachestaleness boundsetsminimum; also caps per-call lifetimes (below)sets
local-max-age, degraded-local-max-age, absent-ttlstaleness boundsetsminimumsets
read-failuremode, throw stricter than degradesetsstricter of the twosets
fill-in-transactionmode, private stricter than registered-keys stricter than allowsetsstricter of the twosets
invalidate-fills-on-rollbackmode, true stricter than falsesetsstricter of the twosets
invalidate-failuremode without an ordersetsnot allowedsets
lease-wait, load-timeout, load-acquire-timeout, read-timeoutwait boundsetsnot allowedsets
ttl on a VersionedCache, tombstone-ttllifetime of the version fencesetsnot allowedsets
ttl on a Store, VersionedStore or SetStorelifetime is the data's meaningnot allowednot allowedsets
ttl-jitter, refresh-window, lease-ttl, load-max-concurrent, local-maximum-sizeothersetsnot allowedsets
unknown-readmodenot allowednot allowedsets
key-prefix, unlocknot policynot allowed (use cocache.key-prefix)not allowedsets
read-onlynot policynot allowednot allowedsets

Why overrides are this narrow: a smaller minimum tightens only a staleness bound. A shorter wait bound sends more instances around the lease to load for themselves, which multiplies load on a source that is already slow. A versioned type's ttl and tombstone-ttl also bound how long a redelivered older event stays refused, so shortening them lets old events back in. Setting a mode outright could weaken a stricter one below it, so only the modes with an order take part: read-failure and the two transaction modes.

overrides.cache.ttl also caps per-call lifetimes: the results of ttlOf, and the ttl passed to put(key, value, ttl) and putAll(entries, ttl). A longer one is clamped to the override. Each clamp counts in cocache.ttl.clamped, and the first one on each cache logs a WARN. The cap applies even when the cache's own ttl is already shorter than the override. A cocache.caches.[name].ttl raises the cap for that cache to its own value when that is longer, and ttl: forever there removes the cap, so a per-cache ttl is never cut by its own per-call cap.

Top-level properties ​

PropertyTypeDefaultMeaning
cocache.enabledbooleantruefalse turns off all CoCache auto-configuration, including the endpoint, health indicator, and metrics
cocache.backendredis | memoryredisredis: built from spring.data.redis.*. memory: in-process, single instance, for development and tests. A CoherenceBackend bean of your own replaces either.
cocache.key-prefixstringunset (the declaration's, cocache: by default)First part of every storage key. Outside the layering (below).
cocache.defaults.cache.*, cocache.defaults.store.*policy—Global defaults for derived and authoritative caches, below the declaration (policy properties)
cocache.overrides.cache.*, cocache.overrides.store.*policy—Global overrides that only tighten (what each layer may set)
cocache.caches.[name].*policy—Policy properties for one cache, plus unknown-read, key-prefix, read-only and unlock (one cache)
cocache.caches-validationfail | warnfailWhat happens to a cocache.caches entry whose name matches no cache, that sets a key CoCache doesn't know, or that sets a key that doesn't apply to its cache, and to a key CoCache doesn't know under cocache.defaults or cocache.overrides (validation)
cocache.redis.*——Redis backend settings
cocache.spring-cache.require-syncbooleanfalsetrue: startup fails if a @Cacheable on a CoCache cache lacks sync = true. false: a warning is logged. See Spring Cache.
cocache.spring-cache.degrade-on-errorbooleanfalsetrue: Spring's cache interceptor uses DegradingCacheErrorHandler, which logs read and write failures on CoCache caches instead of rethrowing them, so a non-sync @Cacheable runs its method while Redis is down. Failed invalidations, and failures on other caches, still go to the previous handler. See Spring Cache.
cocache.refresh-executorbean namebuilt-inThe Executor bean that runs refresh-ahead loads. See Executors.
cocache.executorbean namebuilt-inThe Executor bean that runs the async and suspending views: their continuations, shared loads, and synchronous loaders called through them. See Executors.
management.health.cocache.enabledbooleantrueRegisters the cocache health indicator (below)
cocache.observation.enabledbooleantrueWraps source loads in a Micrometer Observation when an ObservationRegistry bean exists. See tracing.
cocache.metrics.local-hitsbooleanfalseCounts L2 hits (cocache.hits{level=l2}, endpoint key localHits) for every cache. Off by default: it adds an atomic increment to every L2 hit. See metrics.

Policy properties ​

These keys work under cocache.defaults.cache., cocache.defaults.store., cocache.overrides.cache., cocache.overrides.store. and cocache.caches.[name]., as far as each layer allows and the type has the field.

KeyValueType defaultAnnotationMeaning
ttlduration or forever1h; authoritative types: forever@CoCache.ttlLifetime of a value in Redis
ttl-jitterduration1m@CoCache.ttlJitterRandom ± spread on each value's lifetime, capped at ttl / 2. 0s: off.
absent-ttlduration1m; authoritative types: 10s@CoCache.absentTtlLifetime of a negative entry
local-max-ageduration5m; authoritative types: 30s@CoCache.localMaxAgeMaximum age of an L2 copy: the staleness bound when an invalidation message is lost
degraded-local-max-ageduration10s—Maximum age of an L2 copy that couldn't be written to Redis
tombstone-ttlduration or foreverthe value's lifetime; VersionedStore: 1d—Lifetime of a versioned tombstone and of an eviction marker. It must cover your redelivery window. A VersionedStore needs a finite one.
refresh-windowduration or offoff@CoCache.refreshWindowRefresh-ahead window. off (or 0s) also removes a window the declaration enables. See validation.
lease-ttlduration10s—How long a lease lives if its holder never fills it. Keep it above the loader's p99.
lease-waitduration200ms—How long a miss waits for another instance's load before loading itself
load-max-concurrentinteger or unlimitedunlimited—Maximum concurrent source loads per cache per instance
load-acquire-timeoutduration1s—How long a load waits for a permit before throwing SourceLoadRejectedException
load-timeoutduration30s—Upper bound for a load. An AsyncCacheLoader load that takes longer fails with SourceLoadTimeoutException and releases the lease. Readers waiting for another caller's load fail the same way once the load has been in flight that long, and later readers start a new load instead of waiting behind it. A synchronous loader can't be stopped from outside, so give it its own timeout. See Async API.
read-timeoutdurationcocache.redis.command-timeout—Time limit for each Redis read of the cache (get, getAll, getIfChanged), capped at command-timeout. A read that runs out is a failed Redis read: with a source it follows read-failure, without one it is Lookup.Unknown. For caches that can't fall back to a source but mustn't wait a full command-timeout for a stalled Redis.
local-maximum-sizeinteger10000@CaffeineCache.maximumSizeMaximum L2 entries per instance
invalidate-failureretry | throwretry—A failed Cache.invalidate: queue for background retry, or throw CacheWriteException. Deleting a derived copy is always safe, so the default retries, externally sourced caches included. The authoritative types' deletes always throw and are never retried. See When Redis is down during a write.
read-failuredegrade | throwdegrade—A failed Redis read that has a source (the declared loader or a per-call one): load from the source, or answer Lookup.Unknown, so get throws CacheReadException
fill-in-transactionregistered-keys | private | allowregistered-keys—Needs spring-tx. Which loads inside a read-write transaction stay private (no lease, no write to Redis or L2, not shared): keys already registered for invalidation in the transaction, every load, or none. See Spring Cache.
invalidate-fills-on-rollbackbooleantrue—Needs spring-tx. Keys that a synchronous read loaded inside a read-write transaction and wrote to Redis or L2 are invalidated when the transaction rolls back, its commit outcome is unknown, or it rolls back to a savepoint. With this false and fill-in-transaction: allow, the cache's loads ignore transactions.
unknown-readthrow | absentthrow@CoCache.unknownReadcocache.caches.[name] only. A failed Redis read without a source: throw makes get throw CacheReadException; absent reads as not found and caches nothing. See unknown reads.
key-prefixstringcocache.key-prefix@CoCache.keyPrefixcocache.caches.[name] only. This cache's storage-key prefix (below).
read-onlybooleanfalse@CoCache.readOnlycocache.caches.[name] only, and only for Store, VersionedStore and SetStore. This instance only reads the cache: writes throw UnsupportedOperationException, and on Redis the reads need only read permission on the keys (read-only instances). false makes a cache declared read-only read-write on this instance. On a Cache or VersionedCache it follows caches-validation; under cocache.defaults and cocache.overrides it is skipped.
unlocklist of keys——cocache.caches.[name] only. Fields a library locked that this entry overrides on purpose.

How a cache treats content it can't read isn't configurable: a read with a source reclaims it and reloads, and a read without one fails (unreadable payloads).

Keeping Data Fresh explains how to choose these values.

Which keys apply to which type ​

KeyCache with a loaderCache, externally sourcedVersionedCacheStoreVersionedStoreSetStore
ttl, ttl-jitter, absent-ttl, local-max-age, read-timeout, local-maximum-size✓✓✓✓✓✓
degraded-local-max-age, lease-ttl, lease-wait, load-max-concurrent, load-acquire-timeout, load-timeout, invalidate-failure, read-failure, fill-in-transaction, invalidate-fills-on-rollback✓✓✓———
refresh-window✓—✓———
tombstone-ttl——✓—✓—
unknown-read—✓—✓✓—

An externally sourced Cache has no source to refresh from, but its reads with a per-call loader (get(key, loader), Spring Cache sync = true) load, so the lease, load, read-failure and transaction keys apply to them. The authoritative types have no source at all. A SetStore always throws on a failed read, so it has no unknown-read.

Durations and sentinels ​

Every duration in CoCache's configuration needs a unit, including cocache.redis.*: 500ms, 5s, 2m, 1h, 1d, or ISO-8601 such as PT2M. A number without one fails startup, naming the key:

cocache.defaults.cache.ttl: "60" needs a unit, e.g. 60s, 5m, PT2M.
cocache.redis.command-timeout: "1500" needs a unit, e.g. 1500ms, 5m, PT2M.

"Never" and "off" have their own words, so no number has a hidden meaning:

SentinelKeysMeaning
foreverttl, tombstone-ttlNever expires. In a minimum, any finite lifetime wins over it.
off (or 0s)refresh-windowNo refresh-ahead. In YAML, quote it ("off"): YAML reads a bare off as false, which fails startup.
unlimitedload-max-concurrentNo limit. 0 fails.
  • Apart from refresh-window: 0s, only ttl-jitter, lease-wait and load-acquire-timeout may be 0s; every other duration must be positive. None may be negative, and none may exceed 100 years. The 100-year limit is checked when a cache is created, so it fails only the caches the value reaches.
  • load-max-concurrent and local-maximum-size must be positive integers.
  • Values are parsed when the properties bind, so a malformed one fails startup even if no cache uses it.
  • Annotations stay in seconds: @CoCache(ttl = 600) is 10 minutes. The attributes are numbers checked by the compiler, and UNSET and FOREVER are their sentinels.

One cache ​

yaml
cocache:
  caches:
    "[UserCache]":
      ttl: 10m
      load-max-concurrent: 32
      read-failure: throw
    "[RevokedTokens]":
      unknown-read: absent      # Redis down: treat as "not revoked"
      read-timeout: 200ms
  • Cache names match case-insensitively, so the environment-variable form works: COCACHE_CACHES_USERCACHE_TTL=10m.
  • Quote and bracket names in YAML ("[UserCache]") to keep them exactly as written.
  • An entry is the last layer: it sets a field whatever the declaration, customizers and overrides said, except a locked one.
  • A name that matches no cache, or a key that doesn't apply to the cache, fails startup by default (validation).

Key prefix ​

Storage keys are {keyPrefix}{namespace}:{encodedKey} (see Declaring Caches). Setting the prefix once separates applications that share a Redis:

yaml
cocache:
  key-prefix: "${spring.application.name}:"   # quoted: an unquoted YAML value can't end with ":"
  caches:
    "[SharedIndexCache]":
      key-prefix: "shared:"

cocache.key-prefix is not a policy field and doesn't take part in the layering: configuration wins over the declaration and customizers, even over a keyPrefix written in @CoCache. cocache.caches.[name].key-prefix wins over cocache.key-prefix. A library that locks KEY_PREFIX keeps its own prefix: cocache.key-prefix is skipped for that cache, and a per-cache key-prefix fails unless the entry lists key-prefix in unlock.

Every instance of an application must use the same prefix, and changing it is a cold start. Applications that share a cache must also give it the same prefix: declare it once with its prefix locked, so one application's cocache.key-prefix can't move it. The invalidation channel {keyPrefix}inv:{namespace} includes the prefix, so applications with different prefixes don't receive each other's messages. The prefix may be empty: keys and channels then share no prefix, and the Redis ACL lists each namespace (Redis ACL). cocache.defaults.cache.key-prefix and the other global sections don't set a prefix: they are skipped, pointing to cocache.key-prefix.

Locking fields (for library authors) ​

A library whose correctness depends on a field, such as a revocation list that must fail closed and keep its storage keys, creates its caches through CoCacheFactory and locks those fields. Configuration can then no longer weaken them by accident:

kotlin
@Bean
fun revokedTokens(factory: CoCacheFactory, mapper: ObjectMapper): Store<String, Instant> =
    factory.create(storeSpec<String, Instant>("revoked-tokens") {
        codec = jacksonCodec<Instant>(mapper)
        unknownRead = UnknownReadMode.ABSENT                 // Redis down: treat as "not revoked"
        policy {
            ttl = Duration.ofHours(1)
            readTimeout = Duration.ofMillis(200)
        }
    }) {
        lock(PolicyField.UNKNOWN_READ, PolicyField.READ_TIMEOUT)
        lockLayout(LayoutField.KEY_PREFIX, LayoutField.NAMESPACE)
        constrain(PolicyField.TTL) { it.finiteOr(Duration.ofHours(1)) }   // entries always expire
        verify { spec -> require(spec is StoreSpec<*, *>) }
    }
In the blockEffect
lock(vararg PolicyField)The field reports LOCKED (locked by …). Global layers skip it for this cache (locked by … in the start log and skippedConfiguration). A cocache.caches.[name] entry that sets it fails startup unless it lists the field in unlock. A customizer that changes it throws.
lockLayout(vararg LayoutField)The same for the storage layout: NAMESPACE, KEY_PREFIX, KEY_ENCODER, CODEC, KEY_FILTER, TTL_OF, SOURCE. A locked KEY_PREFIX ignores cocache.key-prefix.
constrain(field) { value -> … }Runs after the merge and before validation, on the effective value. The value can be a sentinel (Ttl.Forever, RefreshWindow.Off, Concurrency.Unlimited), so write it.finiteOr(…), not a null check, when the intent is "always expires". A changed value reports LOCKED (constrained by …).
pin(field, value)Locks the field and fixes its effective value to value in one step (a sentinel works too: pin(PolicyField.TTL, Ttl.Forever)). The pinned value takes effect before any layer, so every check against a global layer sees it rather than the declared value it replaced, and it runs again after every constraint; it reports LOCKED (pinned by …). A cocache.caches.[name] entry that sets the field, or lists it in unlock, fails startup: there is no break glass for a pinned field.
verify { spec -> … }Checks the effective spec; a failure fails the creation

The lock owner shown in logs and errors defaults to the calling class; set by in the block to your library's name. From Java, build the locks and pass them; PolicyFields has one constant per field: factory.create(spec, Locks.builder("my-lib").lock(PolicyFields.READ_TIMEOUT).build()).

When the library needs one exact value, pin replaces the pair of a spec value and lock, and no layer can change it:

kotlin
factory.create(storeSpec<String, Instant>("revoked-tokens") { codec = jacksonCodec<Instant>(mapper) }) {
    by = "my-lib"
    pin(PolicyField.UNKNOWN_READ, UnknownReadMode.ABSENT)            // Redis down: always "not revoked"
    constrain(PolicyField.TTL) { it.finiteOr(Duration.ofHours(1)) }
}

In Java: Locks.builder("my-lib").pin(PolicyFields.UNKNOWN_READ, UnknownReadMode.ABSENT).build().

Break glass. During an incident, an operator can override a locked field on purpose:

yaml
cocache:
  caches:
    "[revoked-tokens]":
      read-timeout: 1s
      unlock: [read-timeout]

The start log warns, and the endpoint reports the field as UNLOCKED. unlock takes configuration keys, including key-prefix. It can't override a pinned field: listing one fails startup.

A cache created directly with CacheRuntime.create can't be locked, because no layer reaches it. Libraries should create caches through CoCacheFactory and lock what they need, rather than bypass the factory.

Executors ​

CoCache runs background, async and suspending work on two executors:

WorkPropertyBuilt-in executor
Refresh-ahead loadscocache.refresh-executorA bounded daemon pool (1–4 threads, 1024 queued tasks). A full queue skips the refresh and counts it in cocache.refresh.rejections.
Every step of the async and suspending views after a Redis reply or a loader's future completes (decoding, L2 fills, the next Redis command, calling loadAsync, completing your future); shared loads; synchronous loaders called through those views; the method body of Spring Cache's retrieve(key, loader)cocache.executorOne virtual thread per task, owned by the runtime, named cocache-worker-N

Each property takes the name of an Executor bean. CoCache looks the bean up by name only, never by type. A name that matches no bean, or a bean that isn't an Executor, fails startup with a message naming the property. The container owns that executor: closing the CacheRuntime doesn't shut it down, and the container destroys it after the runtime.

Spring Boot's own applicationTaskExecutor works for both when it uses virtual threads:

yaml
spring:
  threads:
    virtual:
      enabled: true          # applicationTaskExecutor uses virtual threads
cocache:
  refresh-executor: applicationTaskExecutor
  executor: applicationTaskExecutor

cocache.executor must tolerate blocking tasks

It runs blocking work (synchronous loaders, Spring method bodies) next to the continuations of every async and suspending call. Don't give it a queue or only a few threads: blocked loaders would hold every thread while the continuations they wait for queue behind them, and a loader can wait on another load. Use virtual threads or a platform pool that doesn't queue. On JDK 21–23, a loader that blocks inside synchronized pins 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. The blocking API never uses this executor: its loaders run on the calling thread. Tracing doesn't use it either: an observed async load is observed on a virtual thread of its own.

Spring Cache retrieve uses the async view, waits on no thread, and needs no executor of its own. See Spring Cache.

Redis ​

The Redis backend is built from Spring Boot's spring.data.redis.* connection details, with CoCache's own Lettuce client.

TopologySupported
StandaloneYes
SentinelYes. Sentinel nodes use spring.data.redis.sentinel.username / password; data nodes use spring.data.redis.username / password.
ClusterYes. Scripts are routed by key, and the topology refreshes adaptively.
Static master-replicaNo. Startup fails.

TLS follows the Spring Boot SSL bundle (spring.data.redis.ssl.bundle). A rediss:// URL enables TLS with the JDK defaults. CoCache always uses the master, because its read script also writes leases.

PropertyTypeDefaultMeaning
cocache.redis.channel-modepubsub | shardedpubsubpubsub: PUBLISH / SUBSCRIBE, atomic with the Redis change. sharded: SPUBLISH / SSUBSCRIBE (Redis 7+), sent right after the change. All instances must use the same mode; the two don't hear each other.
cocache.redis.command-timeoutduration2sMaximum wait for one command or script. read-timeout can only shorten it. Closing the runtime waits up to twice the backend's command timeout (this value, unless a RedisBackendOptionsCustomizer changes it), at least 5 s, for commands in flight.
cocache.redis.heartbeatduration5sPING interval on the subscription connection and on the command connections. A failed ping on the subscription connection clears L2 and reconnects; the command connections follow command-heartbeat-failures.
cocache.redis.command-heartbeat-failuresinteger3Failed pings in a row after which a command connection (on Cluster, the connection to one master) is dropped and Lettuce reconnects it. One success resets the count. 0 only reports the failure in the health details and never reconnects. Negative values fail startup. Commands in flight on a dropped connection fail with an unknown outcome, which is why one slow ping isn't enough.
cocache.redis.invalidate-batch-sizeinteger512Maximum keys per script of a batch write, invalidations and putAll alike, after grouping by slot in Redis Cluster
cocache.redis.client-namestringunsetCLIENT SETNAME for CoCache's connections
cocache.redis.store-eviction-checkwarn | fail | offwarnUnder volatile-*, what to do about an authoritative cache with a finite ttl (eviction check)
cocache.redis.assume-maxmemory-policystringunsetThe policy the eviction check uses when it can't read INFO memory (the Redis user lacks +info, or the service blocks it), such as noeviction or volatile-lru. Must be noeviction, allkeys-* or volatile-*. Ignored when the policy can be read.
cocache.redis.store-eviction-check-intervaldurationunsetRe-reads maxmemory-policy at this interval, such as 10m, and checks the authoritative caches created so far (eviction check). Unset: checked only at startup and when an authoritative cache is created.

Durations here need a unit as everywhere else (durations).

Eviction check ​

A Store, VersionedStore or SetStore keeps its only copy in Redis, and an evicted key can't be rebuilt. When the application has any of them (created, or declared and still lazy), the starter reads every primary's maxmemory-policy from INFO memory at startup. The authoritative caches' ttl comes from the same layers their creation uses. A read that times out or loses its connection is retried, up to 5 attempts (at most 5 command-timeouts plus 5.5 seconds), so one slow answer while many instances start at once doesn't fail startup; Redis refusing INFO is not retried. The same applies when the starter creates an authoritative cache after startup.

maxmemory-policyResult
noevictionStarts
allkeys-* on any primaryStartup fails, whatever store-eviction-check says: any key can be evicted
Can't be read, and assume-maxmemory-policy isn't setStartup fails, and the message gives the reason, with the last failure as its cause: a refused INFO asks you to grant +info; a timeout or connection failure says so. Either way you can set assume-maxmemory-policy instead
volatile-*, and an authoritative cache has a finite ttl, or has written entries with their own ttlstore-eviction-check: warn logs a warning, fail stops startup, off accepts it. Such keys can be evicted before they expire.
volatile-*, and every authoritative cache has ttl: forever and writes no entry with its own ttlStarts: keys without an expiry are never evicted under volatile-*

A VersionedStore tombstone always expires, but evicting one only lets a late older version in early, so tombstones don't count.

An entry can expire even when its cache's ttl is forever: a write that gives its own ttl (put(key, value, ttl), putAll(entries, ttl), putIfMatch(…, ttl), putIfNewer(…, ttl), SetStore.put(key, set, ttl)) or a spec's ttlOf stores a key with an expiry, such as a revocation list's entries. The configuration doesn't show these, so each instance learns of them as it goes: from the first time it writes such an entry, or reads one back from Redis with an expiry (whichever instance wrote it), that cache counts as having a finite ttl there. The health detail counts it at once, without reading Redis again, and a new risk logs a warning. Startup can't see these entries, so fail can't stop startup for them, and an instance that never writes or reads one (or reads only through getIfChanged, which returns no expiry) keeps reporting safe. An authoritative cache that writes its own ttl belongs on noeviction. Only a runtime on the Redis backend is checked, including one you declare yourself and a Redis backend wrapped in another, such as HookedBackend. See maxmemory-policy.

The check doesn't stop at startup:

  • Caches created later. An authoritative cache created after startup through the starter's CoCacheFactory bean (a lazily initialized bean, or a library creating caches at runtime) is checked when it is created, with the same rules: what would fail startup fails that creation instead, and the rest logs a warning. One created another way, directly with CacheRuntime.create or through a library's own CoCacheFactory(runtime), is checked once it exists, so any risk only logs a warning.
  • Policy changes. With cocache.redis.store-eviction-check-interval set, the starter re-reads every primary's policy at that interval, checks the authoritative caches created so far, and logs a warning when it finds a risk that differs from the last verdict.
  • Health. The storeEviction health detail shows the current verdict: the last one, plus any authoritative cache that has since written entries with their own ttl, judged against the policies read last. It never reads Redis and never turns the indicator DOWN.

Without the starter, a library applies the same rule with StoreEvictionRisk.check(runtime) from cocache-redis (libraries).

Operations covers sizing and deployment choices.

Actuator and health ​

With spring-boot-starter-actuator on the classpath:

FeatureSwitchNotes
cocache endpointmanagement.endpoints.web.exposure.include=cocache; access via management.endpoint.cocache.accessLists caches with their effective policy and counters, inspects and invalidates single keys, and broadcasts an invalidation for one key without touching Redis
Per-key deletes of the only copymanagement.endpoint.cocache.allow-store-delete (default false): Store, SetStore; management.endpoint.cocache.allow-purge (default false): VersionedStore, and ?purge=true on a VersionedCacheWithout the switch these return 403 and change nothing (Observability)
cocache health indicatormanagement.health.cocache.enabled (default true)DOWN only while the Redis invalidation heartbeat fails
Micrometer meters cocache.*Micrometer on the classpathTagged by cache

See Observability for the endpoint paths and meter names.

Effective values and sources ​

Every layered cache reports where each of its fields came from:

  • Start log. One INFO line per cache lists the fields whose value doesn't come from the type default, each with its source, for example Cache[UserCache] - policy: ttl=PT10M (caches), local-max-age=PT2M (defaults). Each skipped entry, clamped field and unlocked field gets a WARN line.
  • Endpoint. GET /actuator/cocache/{name} lists every field that applies to the cache under policy, with its effective value and source, and every skipped entry under skippedConfiguration, with its key, layer and reason. See the cache report.
SourceMeaning
TYPE_DEFAULTThe type default
DEFAULTScocache.defaults.cache.* or cocache.defaults.store.*
DECLARATIONThe annotation or spec
CUSTOMIZERA CacheSpecCustomizer (the detail names it)
OVERRIDESTightened by cocache.overrides.* (the detail gives the value before)
CACHEScocache.caches.[name].*
CLAMPEDChanged by the validation chain after a global layer caused a conflict
LOCKEDLocked by a library (locked by …), or changed by its constraint (constrained by …)
UNLOCKEDSet by cocache.caches.[name] over a lock, listed in unlock

Sentinels read forever, off and unlimited, modes are lowercase, and durations use ISO-8601 (PT10M). An unset read-timeout reads command-timeout. With spring-tx on the classpath, and unless the application declares a FillObserver bean of its own, a Cache or VersionedCache also lists invalidate-fills-on-rollback and fill-in-transaction after its policy fields. They aren't policy fields and have no declaration layer, but the global and per-cache layers merge them the same way. An application FillObserver bean replaces the starter's, and then neither key has any effect. An unlayered cache has an empty policy and uses the type defaults of both transaction modes.

Startup validation ​

CoCache fails startup instead of running with a configuration it can't honor.

Values. A duration without a unit, a misspelled sentinel, a zero where only a positive value makes sense, or a negative value fails as soon as the properties bind, naming the full key (durations).

cocache.caches entries. Two rules work side by side. cocache.caches-validation decides the first; nothing changes the second:

Entrycaches-validation: fail (default)caches-validation: warn
A name that matches no cache, checked once all singletons exist (almost always a typo; the message lists the declared caches)Startup failsWARN
A key CoCache doesn't know, such as ttl-forever or max-concurrent (for load-max-concurrent), checked before any cache is created. Relaxed forms that bind, such as localMaxAge, are known.Startup failsWARN; the key is ignored
A key that doesn't apply to the cache's type, or an unlock entry that isn't a fieldCreating the cache failsWARN; the key is ignored
A name that matches a cache created directly with CacheRuntime.create (unlayered)WARN, also under spring.main.lazy-initialization, and the entry is listed under the endpoint's ignoredConfigurationSame

Global layers. A key CoCache doesn't know under cocache.defaults or cocache.overrides follows caches-validation too, checked before any cache is created: fail stops startup, warn logs it and ignores the key. Most often it is left over from 6.x, such as cocache.defaults.ttl (8.x fields sit under cocache.defaults.cache or cocache.defaults.store) or cocache.defaults.key-prefix (now cocache.key-prefix); the message names where each layer's keys go (upgrade). Other keys under cocache, such as cocache.redis.*, are bound by Spring Boot's usual rules: an unknown one is ignored.

The third rule only warns because such a cache may be created after startup, and an override written during an incident shouldn't stop the application. The name check runs once, when all singletons exist, so it doesn't see a cache that a library creates later, at runtime or in a lazily initialized bean. Such a library publishes the names it may create with a CacheNameContributor bean. The interface lives in cocache-spring, so a library can publish it without depending on the starter:

kotlin
import me.ahoo.cocache.spring.CacheNameContributor

@Bean
fun cacheNames(): CacheNameContributor = CacheNameContributor { listOf("revoked-tokens", "permissions") }

The check reads every contributor when it runs, a lazily initialized one included, and counts the contributed names (case-insensitively) as declared, so entries for them pass without caches-validation: warn. Only those names are relaxed: any other unknown name still follows caches-validation. Contributing a name creates no cache and changes no configuration; the entry applies when the library creates the cache.

Locks. A cocache.caches.[name] entry that sets a locked field without listing it in unlock fails startup, whatever caches-validation says. So does a customizer that changes a locked field or layout, or any data source.

Policies. After every layer, every policy must hold together: refresh-window must be less than ttl − ttl-jitter (the effective jitter) and less than local-max-age, or a fresh copy would start inside the window. The validation chain decides who is at fault:

  • When a global layer (cocache.defaults or cocache.overrides) set one of the fields involved (refresh-window, local-max-age, ttl, ttl-jitter) and cocache.caches.[name] set none of them, the window is turned off for that cache. The start log warns, and the endpoint reports refresh-window as CLAMPED. An operator who shortens local-max-age everywhere doesn't stop the application. The exception is a window that a library pinned, locked or constrained (source LOCKED): turning it off would override the library, so creating the cache fails with an IllegalArgumentException that names the window and how it's held, and says to change this cache's cocache.caches.[name] or the library's lock. A library lock on another field involved, such as local-max-age, doesn't count: a window that comes from a global layer is still turned off.
  • Otherwise startup fails: when only the declaration caused the conflict, or when cocache.caches.[name] set one of the fields involved. For example, cocache.defaults.cache.ttl: 10m with cocache.caches.[UserCache].refresh-window: 20m fails: the per-cache entry asked for that window.

The chain looks only at the result of every layer, so a cocache.caches.[name] entry that removes the conflict lets the cache start with its window, even one a library locked: a longer local-max-age, or unlock: [refresh-window] with refresh-window: "off" for a window that is locked, not pinned.

refresh-window: "off" removes a window the declaration enables, so a property can turn refresh-ahead off for one cache.

Declaring Caches lists the declaration checks.

Beyond properties ​

Some settings exist only in code, because they are functions or objects rather than values:

SettingWhere
ttlOf, keyEncoder, keyFilter, codec, loaderSpec or customizer (a customizer can't change the source)
local.initialCapacity, local.expireAfterAccess@CaffeineCache, spec, or customizer
Locks and constraintsCoCacheFactory.create(spec) { … } (locks)
ClockA CacheClock bean (for example ManualClock in tests) is used by the runtime and the in-memory backend
Retry policy, node id, close timeoutA CacheRuntimeBuilderCustomizer bean (customizers)
Redis backend options in code, such as shared Lettuce ClientResourcesA RedisBackendOptionsCustomizer bean (customizers)
Redis clientYour own CoherenceBackend bean, such as RedisBackend.of(client, options)

Both the CacheRuntime and the CoherenceBackend beans are replaced when you declare your own; to change a few settings, use a customizer instead. A runtime of your own gets nothing the starter wires into its own: cocache.executor, cocache.refresh-executor, cocache.metrics.local-hits, the close timeout derived from cocache.redis.command-timeout, a CacheClock bean, the LoadObserver behind tracing, and, with spring-tx, the FillObserver behind the transaction modes. Pass on what you use. The startup checks use the backend your runtime was built with, so the backend doesn't have to be a bean, and a runtime on Redis still gets the eviction check:

kotlin
@Bean(destroyMethod = "close")
fun cocacheRuntime(
    backend: CoherenceBackend,
    loadObservers: ObjectProvider<LoadObserver>,
    fillObservers: ObjectProvider<FillObserver>,
): CacheRuntime {
    val builder = CacheRuntime.builder()
        .backend(backend)
        .retryPolicy(RetryPolicy(maxAttempts = 16, capacity = 50_000))
    loadObservers.ifUnique?.let { builder.loadObserver(it) } // tracing
    fillObservers.ifUnique?.let { builder.fillObserver(it) } // transaction modes (spring-tx)
    return builder.build()
}

Code that needs the backend your caches run on, such as a library's own eviction monitor, should read it from the runtime: CacheRuntime.backend, or CoCacheFactory.runtime.backend. Don't inject a CoherenceBackend bean for it. When you declare a runtime but no backend bean, the starter still builds a backend bean from spring.data.redis.*, and that may be a different Redis from the one your runtime uses.

RetryPolicy fieldDefault
maxAttempts8
initialBackoff100ms (doubles each attempt)
maxBackoff10s
capacity10000 pending invalidations

Customizing the runtime and the backend ​

To change a setting of the starter's runtime or Redis backend, declare a customizer bean rather than replacing cocacheRuntime or cocacheBackend. A replaced bean loses everything the starter wires into it: the clock, the observers, the executors and the close timeout.

kotlin
@Bean
fun retryCustomizer(): CacheRuntimeBuilderCustomizer =
    CacheRuntimeBuilderCustomizer { it.retryPolicy(RetryPolicy(maxAttempts = 10)) }

@Bean
fun sharedResources(resources: ClientResources): RedisBackendOptionsCustomizer =
    RedisBackendOptionsCustomizer { it.copy(clientResources = resources) }
CustomizerRunsReceives
CacheRuntimeBuilderCustomizerLast, just before build(): after the starter has set the backend, the CacheClock bean, the LoadObserver and FillObserver, cocache.executor, cocache.refresh-executor, cocache.metrics.local-hits and the close timeoutThe CacheRuntime.Builder. What it sets wins over the starter's wiring.
RedisBackendOptionsCustomizerAfter cocache.redis.* and the Spring Boot SSL bundle are applied, before the Redis backend is built (cocache.backend=redis)The RedisBackendOptions so far. The options are immutable: it returns new ones (copy), which the next customizer receives.

Several customizers of one kind run in Spring order (@Order or Ordered). The close timeout follows the command timeout the backend ends up with, so a backend customizer that raises commandTimeout raises the close timeout too. Customizers apply only to the starter's own beans: when you declare your own CacheRuntime or CoherenceBackend, the matching customizers aren't called.

Released under the Apache License 2.0.