Files
clean-architecture-backend-…/src/adapter/outbound/cache-redis/README.md
T
donghyeon-kaandClaude Opus 5.5 27f23add08 review-followup Wave 3: 설정 prefix app.* 통일(P20), Wave 3 종료
- 결정 16: `ca-skeleton.*`·`backend.graphql` 등 → `app.*`(APP_* env 키 이름 유지), selector 키 상수 하나(`CapabilitySelectors`),
  바인딩만 되던 `streaming-idle` 삭제
- `StrictSettingsBinder`가 env 오타까지 거부 — 모든 capability(graphql·websocket·mongo는 edge 제약으로 파일만 strict),
  httpclient 리플렉션 `HttpClientEnvironmentKeys` 삭제
- persistence-jpa가 `APP_DATASOURCE_PASSWORD` secret 요구를 기여(bootstrap이 JPA 스위치를 읽지 않음), Redis ACL fixture에서 pub/sub 권한 제거
- 결함 수정: SMTP 설정 env 이름 충돌(P20-new-1), `bindExcept`가 system env까지 filter(P20-new-2), graphql 빈 deployment-mode 메시지(P20-new-6)
- 통합: P30과 충돌 11건(P30의 명시적 bean 구조 유지), P30 코드의 옛 키를 app.*로, persistence-jpa 포맷
- 현황표: 소유자 결정 36(persistence-jpa 설정은 플랫폼 키만 app.persistence-jpa.*로, 공유 기능 트리 예외), 재개 문서에 일시 정지 상태

Wave 3 종료 검증: check · ci verifyDependencyLocks --warning-mode=fail(714 task) · mainCheck · architectureCheck
verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys configContractCheck · :app-bootstrap:integrationTest
:sample-portfolio:integrationTest :sample-portfolio:systemTest · integrationCheck · -p build-logic test ·
-p optional-platforms ci · :app-bootstrap:qualificationBootJar releaseCheck 통과

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 17:01:54 +09:00

12 KiB

Redis semantic adapters

This module is the semantic Redis capability adapter, not a general Redis SDK.

The Redis implementation is deliberately split into three Gradle leaves:

  • :adapter:outbound:redis-runtime (dev.caskeleton.adapter.outbound.cache.redis.runtime) — shipped connection/topology/settings substrate: RedisRuntimeSettings, the lane owner, and the eight SemanticRedisCommands this module sends. It knows nothing of the typed SDK.
  • :adapter:outbound:cache-redis — shipped application-facing cache, rate-limit, lease and idempotency adapters.
  • :adapter:outbound:redis-sdk — optional typed/general-purpose SDK. It is not on the default application runtime graph.

The default application therefore does not acquire the optional SDK's command policy merely by selecting a semantic Redis capability. Semantic adapters call the runtime's SemanticRedisCommands directly and own their own correctness rules.

Using it as a capability module — what it provides, the one line, the env keys

The web-only default composition does not ship this module: app-bootstrap/build.gradle lists it as a commented runtimeOnly line. A service selects it by uncommenting that one line, and deleting the line removes everything below:

runtimeOnly project(':adapter:outbound:cache-redis')   // brings :adapter:outbound:redis-runtime

Provides, all registered by this module itself:

  • the port implementations the role selectors ask for — CacheRegionPort (cache), EdgeRateLimitPort (rate limit), DistributedLeasePort (lease), IdempotencyStorePort (idempotency; the application builds the executor over it);
  • RedisCapabilityConfig (AutoConfiguration.imports, after RedisRuntimeAutoConfiguration). With APP_REDIS_ENABLED=false neither it nor redis-runtime's RedisRuntimeAutoConfiguration contributes a bean — no settings, client, connection, thread or health contributor. The module pulls no Spring Data Redis, so there is no Boot Redis auto-configuration to exclude;
  • the readiness contribution RedisReadinessGroupPostProcessor (this module's spring.factories): redisRequired joins the readiness group only when a correctness role selects Redis. Which roles those are is this module's RedisCorrectnessRoleSelectors, registered in the same file as the runtime's RedisCorrectnessRequirement — the runtime asks, it does not list selectors;
  • the shipped settings config/module-defaults/cache-redis.yml — app.redis.enabled, app.rate-limit.*, and the Redis parts of app.capabilities.* (cache, lease, rate-limit, the Redis idempotency store's tuning). The support leaf's ModuleDefaultsEnvironmentPostProcessor loads it below every application setting.

The application provides SecretSourcePort and Clock.

Env keys (src/.env.example, registry docs/registries/env-keys.yaml):

Purpose Keys
Switch APP_REDIS_ENABLED (default true; false turns the present module off)
Connection APP_REDIS_MODE, APP_REDIS_NODES, APP_REDIS_DATABASE, APP_REDIS_SENTINEL_*, APP_REDIS_TLS_*, APP_REDIS_AUTHENTICATION_* (credential references)
Namespace APP_REDIS_NAMESPACE_ENVIRONMENT, APP_REDIS_NAMESPACE_SERVICE, APP_REDIS_NAMESPACE_DOMAIN
Roles APP_CACHE_CANONICAL_DEFAULT_PROVIDER, APP_RATE_LIMIT_PROVIDER, APP_LEASE_PROVIDER, APP_IDEMPOTENCY_PROVIDER=redis
Role tuning APP_CACHE_REDIS_*, APP_RATE_LIMIT_*, APP_LEASE_REDIS_*, APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT
Prod secrets (per selected role) APP_CACHE_REDIS_PASSWORD, APP_CACHE_REDIS_KEY_HMAC_SECRET, APP_RATE_LIMIT_REDIS_PASSWORD, APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET, APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET, APP_LEASE_REDIS_KEY_HMAC_SECRET

Activation and composition

Redis is on when this module is present. It has one off switch:

app.redis.enabled=false / APP_REDIS_ENABLED=false (default true).

A semantic role does not activate Redis by itself: with the switch off this module contributes no bean at all, whatever a role selector says. Redis idempotency refuses app.capabilities.idempotency.key-version other than 1 at startup (no dual-read yet).

Current role selectors are:

  • cache: app.capabilities.cache.bindings.default=redis
  • rate limit: app.capabilities.rate-limit.provider=redis
  • lease: app.capabilities.lease.provider=redis
  • idempotency: app.capabilities.idempotency.provider=redis

Only selected capabilities contribute their application port bean.

All capabilities render below the single namespace in app.redis.namespace.*. Per-capability namespace settings are deprecated because they made ACL fencing inconsistent.

Runtime ownership

:adapter:outbound:redis-runtime owns:

  • topology selection (standalone / sentinel / cluster),
  • role-aware credentials,
  • connection lifecycle and bounded lane leasing,
  • the low-level command gateway,
  • health,
  • TLS and connection/client timeouts.

RedisRuntimeOwner stops admission before shutdown, drains outstanding leases within a bounded budget, closes connections, then closes the client.

Connection lane limits and command queue limits are different contracts. In particular:

  • app.redis.capacity.maximum-in-flight-commands bounds the per-connection command queue.
  • app.redis.capacity.maximum-script-connections bounds physical SCRIPT lane connections (default 8).
  • app.redis.lifecycle.acquire-timeout (default 2s) is how long a borrow waits for a returned connection when its lane is full.

The second limit exists so a burst of semantic Lua calls cannot turn a command-capacity number such as 64 into 64 physical Redis sockets. It bounds connections, not callers: a lease holds a connection for one script round trip, so the ninth concurrent caller waits for one to come back instead of being refused. Only a borrow still waiting when the acquire timeout runs out is refused, and that refusal is a RedisCommandRejectedException whose metadata is not ambiguous — no command was ever sent.

Script ACL startup probe

Rate limiting, distributed leases and Redis idempotency execute Lua programs. If any of those roles select Redis, the composition root runs a startup probe on the SCRIPT lane:

  1. SCRIPT LOAD a program that calls the commands the semantic scripts depend on — TIME, then HSET/PEXPIRE/HGET/DEL on its own probe key, which it deletes;
  2. execute it through EVALSHA;
  3. require the expected reply (the value it wrote reads back).

Redis checks a script's inner commands against the ACL only when they run, so a probe that ran nothing proved EVALSHA and nothing else: an account granted by category (@read/@write) lacks TIME and failed every rate-limit and idempotency request after a clean start. A deployment whose effective Redis account lacks script permissions fails during startup rather than at the first request. Cache-only deployments do not run this probe.

At runtime, redisRequired (redis-runtime) probes the SCRIPT lane too when a script role is selected, so a broken advanced-account credential makes the pod unready instead of leaving the regular-lane PING to report UP.

Cache semantics

RedisCacheRegionAdapter implements the application cache port.

Important contracts:

  • value entries have soft and hard expiry;
  • negative entries use the shorter negative TTL;
  • Redis physical TTL is the hard expiry;
  • cache outages degrade to the application's typed unavailable/degraded outcomes;
  • identifiers are rendered through a keyed digest before entering the keyspace.

Conditional replacement

ONLY_IF_OBSERVED is an atomic server-side compare-and-replace.

The lookup returns an opaque SHA-1 observation token over the stored bytes. SHA-1 here is not a security primitive; it is used only because Redis Lua exposes redis.sha1hex, allowing the script to perform:

GET current -> compare observation -> SET replacement PX ttl

inside one Redis execution. A stale source load therefore cannot overwrite a value written between observation and replacement.

Region invalidation

Region invalidation increments a generation key; it never scans/deletes the keyspace.

Each adapter instance caches the observed generation only for the positive soft TTL. After that bounded interval it rechecks the server generation. This keeps ordinary cache hits from paying an extra Redis round trip while ensuring an invalidation issued by another process eventually becomes visible to every instance.

Rate-limit semantics

The rate-limit adapter supports the configured fixed-window, sliding-counter and token-bucket policies through registered Lua scripts.

Time is taken from Redis TIME, not the caller JVM clock. Multiple application nodes therefore make the same distributed decision even if their local clocks differ.

Script TTLs are computed as integer milliseconds in Java and passed as exact Lua arguments. cleanup-grace is part of the physical state TTL. There is no exposed maximum-clock-regression knob because Redis is the time authority for this state.

Rate-limit failures remain fail-closed according to the application contract.

Idempotency semantics

The Redis idempotency adapter stores owner-safe claim state and executes claim/transition/release programs atomically. RedisIdempotencyConfig contributes only the IdempotencyStorePort; the IdempotencyExecutor and its lifecycle policy (lease, replay TTL, retention, codec id, policy revision) come from app-bootstrap IdempotencySettings. This leaf reads only key-version and command-timeout under app.capabilities.idempotency.

Redis TIME determines lease deadlines. A failure after a command may have executed is returned as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean unavailable result that would invite duplicate execution.

Lease semantics

The distributed lease adapter uses owner/operation-safe Lua programs for acquire, inspect, renew and release.

Unknown mutation outcomes remain indeterminate. Local validity is shortened by the configured drift budget; a successful renew is the only event that extends it.

Failure visibility

Semantic adapters intentionally translate Redis failures into typed application outcomes, but those translations are not silent.

RedisSemanticFailureLogger records only:

  • capability,
  • semantic operation,
  • exception class.

It never logs Redis keys, values, command arguments, exception messages or credentials. The first occurrence of a capability/operation/failure-type combination is WARN; repeats are DEBUG to avoid turning a Redis outage into a log-flood outage.

Optional typed SDK

:adapter:outbound:redis-sdk contains the broader typed command surface, command policy, raw/admin and extension machinery. It is a separate library leaf that service code takes with implementation; see src/adapter/outbound/redis-sdk/README.md. This leaf does not depend on it, in production or in tests.

Its policy file and optional startup/library probes apply only when that SDK is deliberately added to a composition. Do not infer SDK command-policy enforcement from the presence of a semantic cache or rate-limit adapter.

Verification

Useful focused checks:

./gradlew :adapter:outbound:cache-redis:check
./gradlew :adapter:outbound:redis-runtime:check
./gradlew :adapter:outbound:cache-redis:test --tests '*RedisSemanticScriptAclProbeTest'
./gradlew :app-bootstrap:verifyEnvKeys
./gradlew architectureCheck

Live Redis/topology qualification remains separate from fast unit tests. A release claim for a specific Redis topology or ACL layout requires the corresponding live qualification lane; the in-memory gateway is for deterministic contract tests, not evidence that an external Redis deployment accepts the same network/TLS/ACL configuration.