문제: 설계서·계획서·납품 패키지·증거·학습 문서와 ADR이 기록이라는 표시 없이 지금 문서처럼 읽힌다. 상태 칸이 설계서 72개 중 40개, 계획서는 거의 없고, 있어도 Approved·확정·Accepted.처럼 값이 제각각이며 영어다. 고른 방법: docs/design, docs/history, docs/adr, docs/notification/adr의 .md 246개 맨 위에 같은 모양의 머리 블록을 단다. 칸은 상태·작성일· 요약(한국어 한 문장)·현재 정본, 대체됐으면 대체됨이다. 블록은 표시 줄 두 개로 감싸서 빼면 원문 바이트가 그대로 돌아온다(246개 모두 대조함). - 종류는 폴더가 정하고 둘째 줄에 적는다(plans/evidence는 증거). - 상태는 원래 상태 줄을 고정 어휘로 바꾼 값이다. 상태 줄이 없는 설계서와 체크 상자가 다 표시되지 않은 계획서는 「확인 안 함」. capability-status.md 제거 표로 지운 것이 확인된 설계서 다섯은 「폐기」, 2026-07-20 하네스 설계·계획과 production capability platform 설계는 「대체됨」이다. - 현재 정본은 구조 정리로 옮겨질 수 있는 src/messaging·src/grpc 대신 docs/ 쪽 문서나 옮기지 않는 leaf README를 가리킨다. docs/README.md에 「문서 수명과 언어」「기록 문서의 머리 블록」「문서와 코드를 같은 변경에서 고친다」를 더하고, 파생 서비스 안내에 머리 블록 충돌 가능성을 적었다. 버린 대안: H1 제목 아래에 블록을 두는 안은 보기에는 낫지만 빼는 규칙이 파일마다 달라져 원문 복원이 기계적이지 않다. 「종류」 칸을 따로 두는 안은 폴더와 같은 정보를 두 번 쓰게 한다. 위험·한계: 「확인 안 함」 설계서 38개, 계획서 51개는 지금 유효한지 아무도 판정하지 않았다. 요약은 제목·목표 줄을 보고 쓴 것이라 본문을 끝까지 읽지 않았다. 납품 패키지 셋의 MANIFEST.sha256는 이제 맞지 않는다 (납품 당시 바이트의 해시이고, 블록을 빼면 다시 맞는다). 리뷰 폴더에는 아직 머리 블록을 달지 않았다. 검증: 머리 블록을 뺀 내용과 HEAD 원본 246개 일치, check-work-docs.py rc=0, --links docs·README.md·CLAUDE.md·AGENTS.md 깨진 링크 0.
52 KiB
기록 · 설계서 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다.
- 상태: 채택
- 작성일: 2026-08-07
- 요약: Redis 자료구조와 명령을 위험도에 따라 Typed API와 통제된 Raw Gateway로 나눠 제공하는 설계다.
- 현재 정본:
docs/redis/support-matrix.md
Redis Wrapper 및 Typed API 설계서
- 상태: 구현 기준선 확정
- 작성일: 2026-08-07
- 대상: Spring 기반 Backend Skeleton의 공통 Redis SDK
- 입력 근거:
붙여넣은 마크다운(1)(7).md— Redis Open Source, Lettuce, Spring Data Redis 공식 문서 및 운영 사례를 정리한 심층 리서치 - 문서 목적: 구현 중 추가 설계 판단이나 반복 질문 없이 모듈 구조, 공개 API, 명령 노출 정책, 장애 의미론, 운영 통제, 테스트 및 완료 조건을 확정한다.
1. 요약
이 설계는 Redis 자료구조와 명령을 폭넓게 즉시 사용할 수 있도록 제공하되, 모든 명령을 동일한 권한과 형태로 노출하지 않는다.
최종 노출 모델은 다음 네 단계다.
- Typed API: 자료구조별 R1 명령과 bounded operation을 기본 제공한다.
- Advanced Typed API: R2 고비용·Blocking·다중 키 명령은 명시적 permit와
OperationBudget을 요구한다. - Approved Raw Gateway: Typed API에 아직 포함되지 않은 R1·R2 명령을 사전 등록된 command descriptor로만 실행한다.
- Admin Plane: R3 운영·관리 명령은 별도 모듈·계정·연결·배포 경로로 분리한다. R4 파괴적 명령은 SDK에서 실행하지 못한다.
핵심 원칙은 다음과 같다.
자료구조와 명령 지원 폭은 넓히되, namespace·직렬화·TTL·timeout·Cluster slot·위험 등급·관측성·ACL을 우회할 수 있는 범용 문자열 실행 API는 제공하지 않는다.
2. 범위
2.1 포함 범위
- Redis Open Source classic 자료구조
- String
- Hash
- List
- Set
- Sorted Set
- Bitmap
- Bitfield
- HyperLogLog
- Geospatial
- Stream
- Pub/Sub 및 Sharded Pub/Sub
- Key·TTL
- Pipeline과 명시적 Batch
WATCH/MULTI/EXEC- 등록형 Lua Script와 Redis Function
- Standalone, Sentinel, Cluster
- 동기 API와 Reactive API
- 명령 위험 등급 R1~R4
- ACL, namespace, 직렬화, version gate, timeout, retry, 오류 변환, metric, trace, audit
- Raw Command Gateway
- Redis 8 확장 기능의 독립 모듈
- JSON
- Search 및 Vector Query
- Time Series
- Probabilistic 자료구조
- 계약·통합·동시성·장애·성능·보안 테스트
2.2 제외 범위
- 비즈니스 정책
- 도메인별 TTL
- 사용자 등급별 요청 제한
- 주문·결제·채팅 등의 업무 흐름
- Redis를 업무의 유일한 강한 정합성 저장소로 가정하는 기능
- 임의 문자열 기반
execute(String, byte[]...) - R4 파괴적 명령 실행
- Redis Cluster에서 cross-slot 다중 키 연산의 자동 분산 실행
- Pipeline을 transaction으로 표현하는 API
- Redis transaction을 관계형 데이터베이스 rollback 모델로 표현하는 API
- Pub/Sub을 durable messaging으로 표현하는 API
- 자동 blind retry로 결과 불명 write를 재실행하는 기능
3. 입력 자료의 제약과 처리 원칙
첨부된 Markdown은 309개 명령·기능 항목이 포함된 Excel 워크북을 참조하지만, 현재 작업 공간에는 Markdown만 존재한다. 따라서 다음 원칙을 적용한다.
- 이 설계서는 Markdown에 명시된 지원 기준, 위험 등급, API 방향, 운영 정책, 테스트 및 구현 순서를 그대로 기준선으로 사용한다.
- 309행의 정확한 초기 분류는 구현 과정에서 Redis 공식
COMMAND DOCS,COMMAND INFO,COMMAND GETKEYSANDFLAGS결과로 재생성한다. - 공식 metadata로 결정할 수 없는 조직 정책은
redis-command-policy.yml오버레이에 명시한다. - 향후 Excel 워크북이 제공되면 오버레이 import 도구로 병합하되, 코드에 수작업으로 중복 입력하지 않는다.
4. 설계 결정
| ID | 결정 | 근거와 결과 |
|---|---|---|
| D-01 | 기본 API는 자료구조별 Typed API로 한다. | 타입 안전성, namespace, codec, TTL, 위험 통제를 일관되게 강제한다. |
| D-02 | Typed API에 없는 기능은 승인형 Raw Gateway로 제공한다. | 최대 지원 폭을 확보하되 정책 우회는 차단한다. |
| D-03 | deprecated 명령명은 공개 API에 남기지 않는다. | SETEX, SETNX, 역방향 range 등은 최신 의미의 메서드와 옵션으로 통합한다. |
| D-04 | R1은 기본, R2는 permit+budget, R3는 admin plane, R4는 차단한다. | 성능과 운영 위험을 권한·구성·ACL에 반영한다. |
| D-05 | 공개 프로그래밍 모델은 동기와 Reactive 두 축이다. | Lettuce native async는 내부 구현 또는 명시적 고급 API로만 사용한다. |
| D-06 | 기능 최소 버전은 Redis 7.2다. | 주 인증은 7.4·8.2, 최신 호환성은 8.10으로 검증한다. |
| D-07 | Standalone·Sentinel은 완전 지원, Cluster는 slot 제약을 공개 계약에 반영한 조건부 완전 지원이다. | 다중 키는 same-slot을 사전 검증하고 DB 0만 허용한다. |
| D-08 | classic Redis와 Redis 8 확장 기능을 모듈로 분리한다. | Redis 7, managed Redis, Redis 8 통합 배포 간 호환성을 보존한다. |
| D-09 | 일반·Blocking·Transaction·Pub/Sub·Admin 연결을 분리한다. | shared connection 오염과 장애 전파를 방지한다. |
| D-10 | timeout 후 write는 ambiguousExecution을 구분한다. |
자동 retry 여부를 호출자가 정확히 판단할 수 있게 한다. |
| D-11 | command catalog와 지원 매트릭스는 서버 metadata와 정책 파일로 생성한다. | 새 명령, deprecated, ACL category, key spec 변화를 CI에서 탐지한다. |
| D-12 | 모든 collection read와 batch는 bounded API로 설계한다. | Big Key, 응답 폭증, JVM heap pressure를 구조적으로 제한한다. |
5. 지원 기준
5.1 Redis 버전
| 프로파일 | 용도 | 지원 정책 |
|---|---|---|
| Redis 7.2 | 기능 최소선 | 기본 API가 반드시 동작해야 한다. |
| Redis 7.4 | 주 인증 | Hash field TTL 기능을 version-gated module로 인증한다. |
| Redis 8.2 | 주 인증 | Redis 8 LTS 및 향상된 Stream 기능을 인증한다. |
| Redis 8.10 | 최신 호환성 | 기존 API와 command policy가 깨지지 않는지 검증한다. |
| Redis 6.2 | 제한적 유지 | 신규 기능은 제공하지 않고 마이그레이션 호환성만 별도 job에서 확인한다. |
| Redis 7.2 미만 | 기본 비지원 | 신규 프로젝트 대상에서 제외한다. |
5.2 클라이언트와 프레임워크
- 공개 Spring 통합: Spring Data Redis 4.1 계열
- 드라이버: Lettuce 7.6 계열
- 테스트: JUnit 5, Testcontainers, Toxiproxy
- Reactive 계약: Reactor
Mono와Flux - Java 기준선: Java 21
- 빌드: Gradle Kotlin DSL 멀티모듈
Java·Gradle 기준선은 현재 저장소가 제공되지 않은 상태에서 이 문서를 실행 가능한 기준으로 만들기 위한 구현 가정이다. 실제 저장소가 더 높은 기준선을 사용하면 상향 적용하되 API 계약은 변경하지 않는다.
5.3 배포 모드
| 기능 | Standalone | Sentinel | Cluster |
|---|---|---|---|
| 단일 키 read/write | 지원 | 지원 | 지원 |
| 다중 키 명령 | 지원 | 지원 | same-slot만 지원 |
| Pipeline | 지원 | 지원 | node별 분할 |
| Transaction | 지원 | 지원 | same-slot만 지원 |
| Lua/Function | 지원 | 지원 | 선언 key same-slot |
| Blocking | 전용 연결 | 전용 연결·failover 처리 | slot별 전용 연결 |
| Pub/Sub | 지원 | 재구독 손실 의미 노출 | Sharded Pub/Sub 우선 |
| Replica read | 선택 | stale 정책 필수 | stale 정책 필수 |
| DB index | 설정 가능 | 설정 가능 | 0만 허용 |
| SCAN | instance 범위 | 현재 primary 범위 | node별 scan aggregation |
6. 전체 아키텍처
flowchart TB
APP[Application Modules]
subgraph Public API
SYNC[redis-core-api\nSync Typed API]
REACTIVE[redis-core-api\nReactive Typed API]
ADV[Advanced Typed API\nR2 Permit + Budget]
RAW[redis-raw-gateway\nApproved Commands]
end
subgraph Policy and Runtime
CAT[Command Catalog\nVersion/Risk/Key Spec]
GUARD[Policy Guard\nNamespace/Slot/Size/ACL]
CODEC[Codec Registry\nSchema Envelope]
EXEC[Command Executor\nTimeout/Error/Retry/Telemetry]
end
subgraph Connections
REG[Regular Connection]
BLOCK[Blocking Pool]
TX[Transaction Connection]
PUB[Pub/Sub Connection]
ADMIN[Admin Connection]
end
subgraph Redis Deployment
STD[Standalone]
SEN[Sentinel]
CLU[Cluster]
end
APP --> SYNC
APP --> REACTIVE
APP --> ADV
APP --> RAW
SYNC --> GUARD
REACTIVE --> GUARD
ADV --> GUARD
RAW --> GUARD
GUARD --> CAT
GUARD --> CODEC
GUARD --> EXEC
EXEC --> REG
EXEC --> BLOCK
EXEC --> TX
EXEC --> PUB
EXEC --> ADMIN
REG --> STD
REG --> SEN
REG --> CLU
BLOCK --> STD
BLOCK --> SEN
BLOCK --> CLU
TX --> STD
TX --> SEN
TX --> CLU
PUB --> STD
PUB --> SEN
PUB --> CLU
6.1 실행 흐름
- 호출자는 자료구조별 Typed API 또는 승인형 Raw Gateway를 호출한다.
- API는
CommandRequest를 생성한다. CommandPolicyGuard가 서버 capability, 위험 등급, permit, namespace, key slot, request/reply 예산을 검증한다.RedisCodecRegistry가 key·field·value를 직렬화한다.RedisCommandExecutor가 명령 유형에 맞는 연결을 선택한다.- timeout, retry, exception translation, metric, trace, audit가 실행 경로 전체를 감싼다.
- 결과는 드라이버 타입이 아닌 안정된 SDK 타입으로 반환한다.
7. 모듈 구조
backend-skeleton/
├── modules/redis/
│ ├── redis-core-api/
│ ├── redis-core-lettuce/
│ ├── redis-cluster/
│ ├── redis-programmability/
│ ├── redis-raw-gateway/
│ ├── redis-admin-plane/
│ ├── redis-spring-boot-starter/
│ ├── redis-testkit/
│ └── extensions/
│ ├── redis-json/
│ ├── redis-search/
│ ├── redis-timeseries/
│ └── redis-probabilistic/
├── infra/redis/
│ ├── standalone/
│ ├── sentinel/
│ ├── cluster/
│ └── acl/
└── docs/redis/
| 모듈 | 책임 | 의존 규칙 |
|---|---|---|
redis-core-api |
공개 타입, 동기·Reactive 자료구조 API, 오류 모델 | Spring Data·Lettuce에 의존하지 않는다. Reactor만 reactive package에 사용한다. |
redis-core-lettuce |
Spring Data Redis·Lettuce 구현, policy guard, codec, executor | redis-core-api에만 공개적으로 의존한다. |
redis-cluster |
CRC16 slot 계산, hash tag, same-slot, topology·redirect 관측 | Cluster 기능을 사용하지 않는 서비스에서 제외 가능하다. |
redis-programmability |
Transaction, 등록 Lua, Redis Function | 임의 script source를 받지 않는다. |
redis-raw-gateway |
allowlist 기반 R1·R2 Raw 실행 | core policy와 catalog를 우회하지 않는다. |
redis-admin-plane |
R3 진단·운영 조회 | 별도 계정·연결·배포 경로를 요구한다. |
redis-spring-boot-starter |
properties, auto-configuration, capability probe, bean 조건 | application module이 직접 Lettuce를 구성하지 않게 한다. |
redis-testkit |
Testcontainers topology, contract suite, fault injection | production module에서 의존하지 않는다. |
extensions/* |
Redis 8 또는 Stack 확장 기능 | classic core와 독립적으로 capability probe를 수행한다. |
8. 공개 API 기본 모델
8.1 Key 모델
package io.backend.skeleton.redis.api.key;
public record RedisNamespace(
String environment,
String service,
String domain
) {
public RedisNamespace {
RedisKeyRules.requireToken("environment", environment);
RedisKeyRules.requireToken("service", service);
RedisKeyRules.requireToken("domain", domain);
}
}
public record RedisKeyName(String entity, String identifier) {
public RedisKeyName {
RedisKeyRules.requireToken("entity", entity);
RedisKeyRules.requireIdentifier(identifier);
}
}
public record RedisSlotTag(String value) {
public RedisSlotTag {
RedisKeyRules.requireIdentifier(value);
}
}
public record QualifiedRedisKey(
RedisNamespace namespace,
RedisKeyName name,
Optional<RedisSlotTag> slotTag
) {}
렌더링 규칙은 다음과 같다.
일반 key: {environment}:{service}:{domain}:{entity}:{identifier}
slot key: {environment}:{service}:{domain}:{{slotTag}}:{entity}:{identifier}
제약:
- UTF-8 기준 최대 512 bytes
- 이메일, 전화번호, access token, refresh token 원문 금지
- 동적 전체 raw key 문자열 입력 금지
- slot tag는
RedisSlotTag를 통해서만 생성 - 저카디널리티 tag로 전체 tenant를 한 slot에 고정하는 사용을 금지
8.2 자료구조별 Typed Key
public sealed interface RedisTypedKey permits
ValueKey, HashKey, ListKey, SetKey, SortedSetKey,
BitmapKey, HyperLogLogKey, GeoKey, StreamKey {
QualifiedRedisKey key();
}
public record ValueKey<V>(QualifiedRedisKey key, RedisCodec<V> valueCodec)
implements RedisTypedKey {}
public record HashKey<F, V>(
QualifiedRedisKey key,
RedisCodec<F> fieldCodec,
RedisCodec<V> valueCodec
) implements RedisTypedKey {}
List, Set, Sorted Set, Bitmap, HyperLogLog, Geo, Stream도 동일한 원칙으로 자료구조별 key 타입을 제공한다. 서로 다른 자료구조 key는 컴파일 단계에서 같은 operations에 전달할 수 없다.
8.3 Expiration
public sealed interface Expiration permits Expiration.Persistent, Expiration.After, Expiration.At {
record Persistent(PersistentKeyPermit permit) implements Expiration {}
record After(Duration duration) implements Expiration {}
record At(Instant instant) implements Expiration {}
}
public enum ExpirationUpdatePolicy {
KEEP_EXISTING,
REPLACE,
ONLY_IF_NO_EXPIRY,
ONLY_IF_HAS_EXPIRY
}
- Cache, session, lock, idempotency, rate-limit API에서는
Persistent를 받지 않는다. SET과 TTL은 한 command 또는 등록 script로 원자화한다.- 정확한 만료가 필요한 기능에는 TTL jitter를 적용하지 않는다.
8.4 Permit 발급과 검증
Permit는 편의용 boolean flag가 아니라 R2·다중 키·영구 key 사용을 명시적으로 승인했다는 capability token이다. 다만 같은 JVM 안의 Java 타입만으로 보안 경계를 만들 수는 없으므로 최종 강제 수단은 Redis ACL과 bean 노출 정책이다. SDK 내부에서는 위조 permit가 guardrail을 우회하지 못하도록 발급자와 검증자를 분리한다.
public interface AdvancedOperationPermit {
String policyName();
}
public interface MultiKeyPermit {
String policyName();
}
public interface PersistentKeyPermit {
String policyName();
}
public interface RedisPolicyAuthority {
AdvancedOperationPermit issueAdvanced(String policyName);
MultiKeyPermit issueMultiKey(String policyName);
PersistentKeyPermit issuePersistentKey(String policyName);
}
public interface RedisPermitVerifier {
void verify(AdvancedOperationPermit permit, String requiredPolicy);
void verify(MultiKeyPermit permit, String requiredPolicy);
void verify(PersistentKeyPermit permit, String requiredPolicy);
}
- permit 구현체는 starter 내부 package-private 클래스로 둔다.
- authority는 활성화된 정책 이름만 발급하며, 발급자 식별자와 서명을 permit 내부에 보관한다.
- verifier는 구현 타입, 발급자, 서명, 정책 이름을 모두 검사한다.
- 애플리케이션이 permit 인터페이스를 임의 구현해도 verifier를 통과하지 못한다.
- permit는 Redis ACL 권한을 확대하지 않는다. 해당 계정에 명령 권한이 없으면 실행은 실패한다.
- permit와 verifier bean은
backend.redis.advanced.enabled=true일 때만 등록한다.
8.5 OperationBudget
public record OperationBudget(
int maxElements,
long maxRequestBytes,
long maxReplyBytes,
Duration timeout
) {
public OperationBudget {
if (maxElements < 1 || maxRequestBytes < 1 || maxReplyBytes < 1 || timeout.isZero() || timeout.isNegative()) {
throw new IllegalArgumentException("Operation budget must be positive");
}
}
}
R2 API는 반드시 AdvancedOperationPermit와 OperationBudget을 요구한다.
8.6 동기·Reactive 진입점
public interface RedisOperations {
RedisValueOperations values();
RedisHashOperations hashes();
RedisListOperations lists();
RedisSetOperations sets();
RedisSortedSetOperations sortedSets();
RedisBitmapOperations bitmaps();
RedisBitFieldOperations bitFields();
RedisHyperLogLogOperations hyperLogLogs();
RedisGeoOperations geo();
RedisStreamOperations streams();
RedisKeyOperations keys();
RedisBatchOperations batches();
}
public interface ReactiveRedisOperations {
ReactiveRedisValueOperations values();
ReactiveRedisHashOperations hashes();
ReactiveRedisListOperations lists();
ReactiveRedisSetOperations sets();
ReactiveRedisSortedSetOperations sortedSets();
ReactiveRedisBitmapOperations bitmaps();
ReactiveRedisBitFieldOperations bitFields();
ReactiveRedisHyperLogLogOperations hyperLogLogs();
ReactiveRedisGeoOperations geo();
ReactiveRedisStreamOperations streams();
ReactiveRedisKeyOperations keys();
ReactiveRedisBatchOperations batches();
}
동기와 Reactive API는 의미·이름·옵션 모델을 동일하게 유지한다. 반환 타입만 Optional/List/...와 Mono/Flux로 다르다.
9. 명령 노출 정책
9.1 위험 등급
| 등급 | 의미 | 공개 정책 |
|---|---|---|
| R1 | bounded, 단일 키, 일반적인 빠른 명령 | 기본 Typed API |
| R2 | O(N), 무제한 반환 가능, Blocking, 다중 키, 큰 payload | Advanced Typed API 또는 승인형 Raw Gateway |
| R3 | 서버·클라이언트·ACL·토폴로지 운영 명령 | redis-admin-plane만 |
| R4 | 데이터 삭제, 서버 중단, replication/module 변경 등 파괴적 명령 | SDK 전체 차단 |
9.2 명령 지원 상태
public enum CommandSupport {
TYPED,
ADVANCED_TYPED,
RAW_ONLY,
ADMIN_ONLY,
VERSION_GATED,
BLOCKED
}
9.3 Command descriptor
public record RedisCommandDescriptor(
String command,
Optional<String> subcommand,
RedisVersion minimumVersion,
RedisRiskLevel riskLevel,
CommandSupport support,
CommandAccess access,
boolean blocking,
boolean readOnly,
boolean retrySafe,
boolean mayBeAmbiguous,
KeySpec keySpec,
TimeoutProfile timeoutProfile
) {}
9.4 정책 SSOT
modules/redis/redis-core-lettuce/src/main/resources/redis-command-policy.yml을 조직 정책 SSOT로 둔다.
commands:
GET:
minimum-version: "7.2"
risk: R1
support: TYPED
access: APPLICATION
blocking: false
read-only: true
retry-safe: true
timeout-profile: FAST
HGETALL:
minimum-version: "7.2"
risk: R2
support: ADVANCED_TYPED
access: APPLICATION_ADVANCED
blocking: false
read-only: true
retry-safe: true
timeout-profile: COLLECTION
KEYS:
minimum-version: "7.2"
risk: R4
support: BLOCKED
access: NONE
blocking: false
read-only: true
retry-safe: false
timeout-profile: ADMIN
빌드 task는 공식 metadata와 이 파일을 비교한다.
- 신규 command 또는 subcommand 탐지
- deprecated 변경 탐지
- ACL category 변경 탐지
- key specification 변경 탐지
- movable key 탐지
- 위험 명령의 자동 허용 방지
10. 자료구조별 Typed API
10.1 String
public interface RedisValueOperations {
<V> Optional<V> get(ValueKey<V> key);
<V> List<Optional<V>> multiGet(List<ValueKey<V>> keys, MultiKeyPermit permit);
<V> void set(ValueKey<V> key, V value, Expiration expiration);
<V> boolean setIfAbsent(ValueKey<V> key, V value, Expiration expiration);
<V> boolean setIfPresent(ValueKey<V> key, V value, Expiration expiration);
<V> Optional<V> getAndSet(ValueKey<V> key, V value, Expiration expiration);
<V> Optional<V> getAndDelete(ValueKey<V> key);
<V> Optional<V> getAndExpire(ValueKey<V> key, Expiration expiration);
long increment(ValueKey<Long> key, long delta, Expiration expiration);
double increment(ValueKey<Double> key, double delta, Expiration expiration);
long append(ValueKey<String> key, String suffix, OperationBudget budget);
long length(ValueKey<?> key);
byte[] getRange(ValueKey<byte[]> key, long start, long end, OperationBudget budget);
long setRange(ValueKey<byte[]> key, long offset, byte[] value, OperationBudget budget);
}
정책:
SETNX,SETEX,PSETEX는 별도 메서드로 노출하지 않는다.MGET/MSET/MSETNX는 same-slot 또는 node grouping 정책을 명시하며, 원자성이 필요한 경우 same-slot만 허용한다.LCS는 R2 Advanced API로 둔다.INCR와 최초 TTL 설정은 script fallback 또는 version-gatedINCREX로 한 번에 실행한다.
10.2 Hash
public interface RedisHashOperations {
<F, V> Optional<V> get(HashKey<F, V> key, F field);
<F, V> Map<F, Optional<V>> multiGet(HashKey<F, V> key, Collection<F> fields);
<F, V> void put(HashKey<F, V> key, F field, V value);
<F, V> void putAll(HashKey<F, V> key, Map<F, V> values);
<F, V> boolean putIfAbsent(HashKey<F, V> key, F field, V value);
<F, V> long delete(HashKey<F, V> key, Collection<F> fields);
<F, V> boolean exists(HashKey<F, V> key, F field);
<F> long increment(HashKey<F, Long> key, F field, long delta);
<F> double increment(HashKey<F, Double> key, F field, double delta);
<F, V> long size(HashKey<F, V> key);
<F, V> ScanPage<Map.Entry<F, V>> scan(HashKey<F, V> key, ScanRequest request);
<F, V> Map<F, V> entries(HashKey<F, V> key, AdvancedOperationPermit permit, OperationBudget budget);
}
Version-gated module:
public interface RedisHashFieldExpirationOperations {
<F, V> Map<F, ExpirationResult> expireFields(HashKey<F, V> key, Collection<F> fields, Duration ttl);
<F, V> Map<F, Optional<Duration>> ttl(HashKey<F, V> key, Collection<F> fields);
<F, V> Map<F, ExpirationResult> persistFields(HashKey<F, V> key, Collection<F> fields, PersistentKeyPermit permit);
}
entries()는 R2이며 budget 없이 호출할 수 없다.- field TTL API는 Redis 7.4 이상에서만 bean이 등록된다.
HGETEX/HSETEX기반 복합 연산은 Redis 8.0 profile에서만 활성화한다.
10.3 List
public interface RedisListOperations {
<V> long pushLeft(ListKey<V> key, Collection<V> values);
<V> long pushRight(ListKey<V> key, Collection<V> values);
<V> long pushLeftIfPresent(ListKey<V> key, V value);
<V> long pushRightIfPresent(ListKey<V> key, V value);
<V> Optional<V> popLeft(ListKey<V> key);
<V> Optional<V> popRight(ListKey<V> key);
<V> List<V> popLeft(ListKey<V> key, int count);
<V> List<V> popRight(ListKey<V> key, int count);
<V> Optional<V> index(ListKey<V> key, long index);
<V> void set(ListKey<V> key, long index, V value);
<V> long remove(ListKey<V> key, long count, V value);
<V> void trim(ListKey<V> key, long start, long end);
<V> List<V> range(ListKey<V> key, long start, long end, OperationBudget budget);
<V> Optional<V> move(ListKey<V> source, ListKey<V> destination, ListSide from, ListSide to, MultiKeyPermit permit);
}
public interface RedisBlockingListOperations {
<V> Optional<KeyedValue<V>> pop(Collection<ListKey<V>> keys, ListSide side, Duration block);
<V> Optional<V> move(ListKey<V> source, ListKey<V> destination, ListSide from, ListSide to, Duration block, MultiKeyPermit permit);
}
- Blocking API는 별도 bean과 전용 pool을 사용한다.
- 무한 block은 금지한다.
LRANGE 0 -1은 budget이 충분하고 실제 length가 제한 이내일 때만 허용한다.
10.4 Set
public interface RedisSetOperations {
<V> long add(SetKey<V> key, Collection<V> values);
<V> long remove(SetKey<V> key, Collection<V> values);
<V> boolean isMember(SetKey<V> key, V value);
<V> Map<V, Boolean> multiIsMember(SetKey<V> key, Collection<V> values);
<V> long size(SetKey<V> key);
<V> Optional<V> pop(SetKey<V> key);
<V> List<V> pop(SetKey<V> key, int count);
<V> List<V> randomMembers(SetKey<V> key, int count, boolean distinct);
<V> ScanPage<V> scan(SetKey<V> key, ScanRequest request);
<V> boolean move(SetKey<V> source, SetKey<V> destination, V value, MultiKeyPermit permit);
<V> Set<V> difference(Collection<SetKey<V>> keys, AdvancedOperationPermit permit, OperationBudget budget);
<V> Set<V> intersection(Collection<SetKey<V>> keys, AdvancedOperationPermit permit, OperationBudget budget);
<V> Set<V> union(Collection<SetKey<V>> keys, AdvancedOperationPermit permit, OperationBudget budget);
}
SMEMBERS대응 전체 반환은 제공하지 않는다.scan또는 budget이 있는 set operation을 사용한다.- 다중 키 연산은 same-slot을 사전 검증한다.
- store variants는 Advanced API로 제공한다.
10.5 Sorted Set
public interface RedisSortedSetOperations {
<V> boolean add(SortedSetKey<V> key, V value, double score, SortedSetAddOptions options);
<V> long addAll(SortedSetKey<V> key, Collection<ScoredValue<V>> values, SortedSetAddOptions options);
<V> double incrementScore(SortedSetKey<V> key, V value, double delta);
<V> long remove(SortedSetKey<V> key, Collection<V> values);
<V> OptionalDouble score(SortedSetKey<V> key, V value);
<V> Map<V, OptionalDouble> scores(SortedSetKey<V> key, Collection<V> values);
<V> OptionalLong rank(SortedSetKey<V> key, V value, SortDirection direction);
<V> long size(SortedSetKey<V> key);
<V> long countByScore(SortedSetKey<V> key, ScoreRange range);
<V> List<ScoredValue<V>> rangeByRank(SortedSetKey<V> key, RankRange range, SortDirection direction, OperationBudget budget);
<V> List<ScoredValue<V>> rangeByScore(SortedSetKey<V> key, ScoreRange range, PageRequest page, SortDirection direction, OperationBudget budget);
<V> List<V> rangeByLex(SortedSetKey<V> key, LexRange range, PageRequest page, SortDirection direction, OperationBudget budget);
<V> List<ScoredValue<V>> popMin(SortedSetKey<V> key, int count);
<V> List<ScoredValue<V>> popMax(SortedSetKey<V> key, int count);
<V> ScanPage<ScoredValue<V>> scan(SortedSetKey<V> key, ScanRequest request);
}
Union, intersection, difference, store, blocking pop은 Advanced/Blocking API로 분리한다.
10.6 Bitmap 및 Bitfield
public interface RedisBitmapOperations {
boolean get(BitmapKey key, long offset);
boolean set(BitmapKey key, long offset, boolean value);
long count(BitmapKey key, Optional<LongRange> byteRange);
OptionalLong position(BitmapKey key, boolean value, Optional<LongRange> byteRange);
long bitOperation(BitmapOperation operation, BitmapKey destination, Collection<BitmapKey> sources, MultiKeyPermit permit, OperationBudget budget);
}
public interface RedisBitFieldOperations {
List<BitFieldResult> execute(BitmapKey key, List<BitFieldSubcommand> commands, BitFieldOverflow overflow, OperationBudget budget);
}
- 최대 offset은 설정값으로 제한한다.
BITOP은 same-slot과 reply budget을 검증한다.- Bitfield overflow mode는 호출 시 명시한다.
10.7 HyperLogLog
public interface RedisHyperLogLogOperations {
<V> boolean add(HyperLogLogKey<V> key, Collection<V> values);
long count(Collection<? extends HyperLogLogKey<?>> keys, MultiKeyPermit permit);
void merge(HyperLogLogKey<?> destination, Collection<? extends HyperLogLogKey<?>> sources, MultiKeyPermit permit);
}
반환값은 근사치이며 정확 cardinality 용도로 사용하지 않는다는 계약을 API 문서에 고정한다.
10.8 Geospatial
public interface RedisGeoOperations {
<V> long add(GeoKey<V> key, Collection<GeoLocation<V>> locations);
<V> Optional<Distance> distance(GeoKey<V> key, V from, V to, DistanceUnit unit);
<V> Map<V, Optional<GeoPoint>> positions(GeoKey<V> key, Collection<V> members);
<V> List<GeoSearchResult<V>> search(GeoKey<V> key, GeoSearchRequest request, OperationBudget budget);
<V> long searchStore(GeoKey<V> source, GeoKey<V> destination, GeoSearchRequest request, MultiKeyPermit permit, OperationBudget budget);
}
deprecated radius 계열은 공개하지 않고 GEOSEARCH 의미로 통합한다.
10.9 Stream
public interface RedisStreamOperations {
<V> StreamId append(StreamKey<V> key, V value, StreamAppendOptions options);
<V> long delete(StreamKey<V> key, Collection<StreamId> ids);
<V> long trim(StreamKey<V> key, StreamTrimPolicy policy);
<V> List<StreamRecord<V>> range(StreamKey<V> key, StreamRange range, int count);
<V> List<StreamRecord<V>> reverseRange(StreamKey<V> key, StreamRange range, int count);
<V> List<StreamRecord<V>> read(StreamKey<V> key, StreamReadOffset offset, int count);
<V> List<StreamRecord<V>> readGroup(StreamKey<V> key, StreamGroup group, StreamConsumer consumer, StreamReadOffset offset, int count);
<V> long acknowledge(StreamKey<V> key, StreamGroup group, Collection<StreamId> ids);
<V> PendingSummary pendingSummary(StreamKey<V> key, StreamGroup group);
<V> List<PendingRecord> pending(StreamKey<V> key, StreamGroup group, PendingQuery query);
<V> ClaimResult<V> autoClaim(StreamKey<V> key, StreamGroup group, StreamConsumer consumer, Duration minIdle, StreamId start, int count);
<V> void createGroup(StreamKey<V> key, StreamGroup group, StreamReadOffset offset, boolean createStream);
<V> void destroyGroup(StreamKey<V> key, StreamGroup group);
<V> void createConsumer(StreamKey<V> key, StreamGroup group, StreamConsumer consumer);
<V> void deleteConsumer(StreamKey<V> key, StreamGroup group, StreamConsumer consumer);
}
public interface RedisBlockingStreamOperations {
<V> List<StreamRecord<V>> read(StreamKey<V> key, StreamReadOffset offset, int count, Duration block);
<V> List<StreamRecord<V>> readGroup(StreamKey<V> key, StreamGroup group, StreamConsumer consumer, StreamReadOffset offset, int count, Duration block);
}
정책:
StreamAppendOptions는MAXLEN또는MINID를 반드시 요구한다.- Consumer group 사용 시 pending age와 count metric을 제공한다.
- 중복 전달 가능성을 계약에 명시한다.
- Redis 8.2의
XACKDEL/XDELEX, 8.8의XNACK은 별도 capability bean으로 제공한다.
10.10 Pub/Sub
public interface RedisPubSubOperations {
<V> long publish(PubSubChannel<V> channel, V message);
<V> Subscription subscribe(Collection<PubSubChannel<V>> channels, RedisMessageHandler<V> handler);
<V> Subscription patternSubscribe(Collection<PubSubPattern<V>> patterns, RedisMessageHandler<V> handler);
}
public interface RedisShardedPubSubOperations {
<V> long publish(ShardedPubSubChannel<V> channel, V message);
<V> Subscription subscribe(Collection<ShardedPubSubChannel<V>> channels, RedisMessageHandler<V> handler);
}
- at-most-once 의미를 인터페이스 Javadoc과 문서에 명시한다.
- durable 업무 이벤트, 결제·주문·재처리 작업에는 사용하지 않는다.
- Cluster에서는 Sharded Pub/Sub을 기본 bean으로 우선한다.
10.11 Key·TTL
public interface RedisKeyOperations {
boolean exists(QualifiedRedisKey key);
long exists(Collection<QualifiedRedisKey> keys, MultiKeyPermit permit);
RedisDataType type(QualifiedRedisKey key);
boolean touch(QualifiedRedisKey key);
long delete(Collection<QualifiedRedisKey> keys, MultiKeyPermit permit);
long unlink(Collection<QualifiedRedisKey> keys, MultiKeyPermit permit);
ExpirationResult expire(QualifiedRedisKey key, Duration ttl, ExpirationCondition condition);
ExpirationResult expireAt(QualifiedRedisKey key, Instant instant, ExpirationCondition condition);
Optional<Duration> ttl(QualifiedRedisKey key);
boolean persist(QualifiedRedisKey key, PersistentKeyPermit permit);
boolean rename(QualifiedRedisKey source, QualifiedRedisKey destination, RenameMode mode, MultiKeyPermit permit);
ScanPage<QualifiedRedisKey> scan(ScanRequest request, AdvancedOperationPermit permit);
}
KEYS는 차단한다.SCAN도 전체 비용이 O(N)이므로 R2 permit, page size, rate limit을 요구한다.- 대형 key 삭제는
UNLINK를 우선하지만 batch와 rate limit을 적용한다.
11. Batch와 Pipeline
public interface RedisBatchOperations {
RedisBatchResult execute(RedisBatch batch, BatchOptions options);
}
public record BatchOptions(
int maxCommands,
long maxRequestBytes,
long maxReplyBytes,
int maxInFlightPerNode,
Duration timeout
) {}
public record RedisBatchResult(List<BatchItemResult<?>> items) {
public boolean hasPartialFailure() {
return items.stream().anyMatch(BatchItemResult::failed);
}
}
정책:
- Pipeline은 원자적이지 않다.
- input index와 result index를 보존한다.
- Cluster에서는 node별로 분할하고 결과를 원래 순서로 재조합한다.
- write batch는 자동 retry하지 않는다.
- 최대 command 수, request bytes, 예상 reply bytes, in-flight를 모두 제한한다.
- 기본값:
- 최대 500 commands
- request 4 MiB
- reply 16 MiB
- node별 in-flight 2
- timeout 2초
12. Transaction 및 서버 프로그래밍
12.1 Transaction
public interface RedisTransactionOperations {
<R> TransactionResult<R> watchAndExecute(
Collection<QualifiedRedisKey> watchedKeys,
RedisTransactionCallback<R> callback,
TransactionOptions options
);
}
- 전용 connection을 사용한다.
finally에서DISCARD또는 connection reset을 보장한다.- rollback이 없음을 공개 계약에 명시한다.
- Cluster에서는 watched key와 transaction key가 same-slot이어야 한다.
EXEC응답 유실은RedisAmbiguousExecutionException으로 반환한다.
12.2 등록 Lua Script
public record RegisteredRedisScript<R>(
String id,
String sha256,
int maxKeys,
Duration timeout,
long maxReplyBytes,
RedisResultDecoder<R> decoder
) {}
public interface RedisScriptOperations {
<R> R execute(RegisteredRedisScript<R> script, List<QualifiedRedisKey> keys, List<RedisArgument> arguments);
}
- 런타임 script source 문자열을 받지 않는다.
- key는 전부
KEYS인자로 선언한다. - Cluster same-slot을 사전 검증한다.
- loop bound, 실행시간, reply size를 리뷰한다.
NOSCRIPT는 등록 script에 한해 load 후 한 번 재실행한다.
12.3 Redis Function
Function library는 ID와 semantic version으로 관리한다. 배포 시 capability probe와 library checksum을 확인하며, 운영 중 동적 임의 function 등록은 지원하지 않는다.
13. Raw Command Gateway
13.1 공개 계약
public interface RedisRawGateway {
<R> R execute(
ApprovedRawCommand<R> command,
List<RedisArgument> arguments,
RawCommandPolicyToken policyToken
);
}
public record ApprovedRawCommand<R>(
String policyId,
RedisCommandDescriptor descriptor,
RedisResultDecoder<R> decoder
) {}
13.2 강제 통제
- command와 subcommand allowlist
- 최소 Redis version 확인
- 공식 key specification 또는
COMMAND GETKEYSANDFLAGS로 key 추출 - namespace 확인
- same-slot 확인
- R3·R4 거부
- argument 수·request bytes·reply bytes 제한
- timeout profile 적용
- 등록 decoder만 허용
- 호출자·policyId·command family·결과·latency audit
- key/value 원문 로그 금지
- Raw Gateway 전용 ACL user 사용 가능
일반 애플리케이션에는 execute(String, byte[]...) 형태를 제공하지 않는다.
14. Admin Plane
redis-admin-plane은 애플리케이션 request path와 분리한다.
14.1 제공 범위
- read-only 진단
INFOMEMORY USAGESLOWLOG GETLATENCY LATESTCLIENT LIST의 제한된 projectionCLUSTER INFO,CLUSTER SLOTS,CLUSTER SHARDSACL DRYRUNCOMMAND INFO
- 운영 도구가 사용하는 node-local scan 및 big-key 후보 수집
14.2 차단 범위
FLUSHDB,FLUSHALLSHUTDOWNDEBUG- module unload
- replication·topology 변경
- 광범위한
CONFIG SET - 일반 애플리케이션 계정으로 ACL 변경
관리 plane은 별도 ACL account, 별도 connection factory, 별도 deployment profile을 요구한다.
15. Connection 및 실행 모델
| 연결 종류 | 용도 | 공유 여부 |
|---|---|---|
| Regular | 일반 R1/R2 non-blocking 명령 | thread-safe shared 또는 제한 pool |
| Blocking | BLPOP, BZPOP*, XREAD BLOCK |
전용 pool |
| Transaction | WATCH/MULTI/EXEC |
호출당 전용 connection |
| Pub/Sub | subscribe lifecycle | subscription별 또는 제한 pool |
| Admin | R3 진단 | 별도 account·factory |
기본 pool 제한:
- Regular pending command queue: 1,000
- Blocking 최대 동시 연결: 32
- Transaction 최대 동시 연결: 16
- Pub/Sub subscription connection: 16
- queue 상한 초과 시 즉시
RedisCommandRejectedException
Lettuce offline queue는 무제한으로 사용하지 않는다. timeout되거나 이미 취소된 command는 reconnect 후 replay하지 않는다.
16. Timeout, Retry, 오류 의미론
16.1 Timeout profile
| Profile | 기본값 | 대상 |
|---|---|---|
| FAST | 500 ms | 단일 키 GET/SET, membership, score |
| COLLECTION | 2 s | bounded range, scan page, union/intersection |
| SCRIPT | 1 s | 등록 Lua/Function |
| BATCH | 2 s | pipeline/batch |
| ADMIN | 3 s | read-only 운영 조회 |
| BLOCKING | server block + 2 s | blocking API |
기본값은 skeleton guardrail이며 서비스 SLO에 따라 더 짧게 재정의할 수 있다. 더 길게 설정할 때는 configuration validation 경고를 낸다.
16.2 Retry matrix
| 상황 | 자동 retry |
|---|---|
| 전송 전 실패가 확인된 read | 최대 2회, jittered backoff |
| idempotent read | 최대 2회 |
MOVED, ASK |
cluster client 처리 |
resharding 중 TRYAGAIN |
최대 2회, 짧은 backoff |
| write 후 timeout | 금지 |
INCR, LPUSH, XADD 결과 불명 |
금지 |
transaction EXEC 결과 유실 |
금지 |
| script 결과 불명 | 금지 |
등록 script의 NOSCRIPT |
load 후 1회 |
16.3 예외 모델
public class RedisOperationException extends RuntimeException {
private final RedisFailureMetadata metadata;
}
public record RedisFailureMetadata(
String commandCategory,
CommandAccess access,
boolean readOperation,
boolean retryable,
boolean ambiguousExecution,
RedisVersion serverVersion,
RedisDeploymentMode deploymentMode,
OptionalInt slot,
Duration elapsed
) {}
하위 예외:
RedisTimeoutExceptionRedisConnectionExceptionRedisAccessDeniedExceptionRedisCrossSlotExceptionRedisRedirectionExceptionRedisBusyExceptionRedisNoScriptExceptionRedisSerializationExceptionRedisDataTypeMismatchExceptionRedisCommandRejectedExceptionRedisCapabilityUnavailableExceptionRedisAmbiguousExecutionException
key, value, credential, 전체 argument는 메시지에 포함하지 않는다.
17. 직렬화와 schema
17.1 기본 codec
- key: UTF-8 String
- counter: Redis integer/double native representation
- object: versioned JSON 기본
- 선택: CBOR, Protobuf
- Java native serialization: 금지
public interface RedisCodec<T> {
String id();
byte[] encode(T value);
T decode(byte[] bytes) throws RedisSerializationException;
}
public record RedisEnvelope(
String schema,
int version,
Instant createdAt,
byte[] payload
) {}
17.2 schema 변경
- 호환 reader를 먼저 배포한다.
- 필요 시 dual write 또는 read repair를 사용한다.
- migration은 rate-limited SCAN으로 실행한다.
- version별 read와 deserialize failure를 관측한다.
- 기존 TTL 만료 또는 migration 완료 후 old reader를 제거한다.
역직렬화 실패 처리:
- Cache: miss fallback + corruption metric
- Session·idempotency·workflow: data corruption 예외
- Raw Gateway: decoder failure로 명시
17.3 기본 크기 제한
- key: 512 bytes
- object value: 1 MiB
- Stream payload: 256 KiB
- Hash field value: 512 KiB
- Raw argument total: 4 MiB
- Raw reply: 16 MiB
초과 시 Redis 호출 전에 거부한다.
18. Cluster 설계
18.1 Slot-aware key codec
- CRC16 slot을 client side에서 계산한다.
- multi-key 요청은 서버 호출 전에 same-slot을 검증한다.
- hash tag는
RedisSlotTag를 통해서만 지정한다. - 모든 key가 동일 slot이어야 하는 API에는
MultiKeyPermit을 요구한다.
18.2 Redirect와 topology
관측 항목:
MOVEDASKTRYAGAIN- topology refresh
- slot cache refresh
- node connection failure
- replica promotion
18.3 제한
- DB 0 이외 설정은 startup failure
- cluster-wide SCAN은 node별 cursor를 가진
ClusterScanCursor로만 제공 - node-local command를 전체 cluster 결과로 오인하지 않도록 결과 타입에 node id를 포함
- cross-slot operation 자동 fan-out은 조회-only batch에서만 허용하고 원자성을 보장하지 않는다고 표시
19. Sentinel 및 failover
- primary·replica·Sentinel endpoint를 startup에 검증한다.
- promotion 구간의 결과를 다음 네 가지로 분류한다.
- confirmed success
- confirmed failure
- safe-to-retry failure
- ambiguous failure
- non-idempotent write는 자동 retry하지 않는다.
- reconnect queue는 상한을 가진다.
- failover 후 stale replica read 허용 여부는 별도
ReadConsistencyPolicy로 명시한다. WAIT는 durability 가능성을 높이는 선택 기능일 뿐 강한 일관성으로 표현하지 않는다.
20. ACL과 접근 제한
20.1 계정 분리
| 계정 | 권한 |
|---|---|
| application | R1 Typed API |
| application-advanced | 승인된 R2 command |
| raw-gateway | 등록된 R1·R2 command 및 namespace |
| admin-readonly | R3 read-only diagnostics |
| extension-* | JSON/Search/TimeSeries 등 사용 명령만 |
20.2 원칙
- allowlist 방식
- key pattern과 Pub/Sub channel pattern 제한
+@all -@dangerous사용 금지- Redis 업그레이드 시 ACL regression test
ACL DRYRUN과 실제 제한 계정 integration test를 모두 수행
예시:
on
>secret-from-runtime
~prod:order-service:*
&prod:order-events:*
+get +set +del +unlink
+hget +hset +hdel +hscan
+xadd +xreadgroup +xack +xautoclaim
21. 관측성
21.1 Metric
| 이름 | 핵심 tag |
|---|---|
backend.redis.command.duration |
family, outcome, mode, risk |
backend.redis.command.request.bytes |
family, mode |
backend.redis.command.reply.bytes |
family, mode |
backend.redis.connection.active |
connection-kind, node |
backend.redis.connection.pending |
connection-kind |
backend.redis.connection.reconnects |
mode, node |
backend.redis.cluster.redirects |
type |
backend.redis.retry.count |
reason, ambiguous |
backend.redis.batch.size |
mode, outcome |
backend.redis.stream.pending |
namespace, group |
backend.redis.policy.rejections |
reason, risk |
backend.redis.serialization.failures |
codec, schema |
실제 key, field, member, user ID는 tag에 넣지 않는다.
21.2 Trace
Span 이름: redis.command
속성:
- command family
- risk level
- read/write
- deployment mode
- connection kind
- slot 또는 node의 low-cardinality projection
- outcome
- retry count
- ambiguous execution
21.3 Log와 audit
- key와 value는 기본 마스킹
- 식별이 필요하면 HMAC fingerprint
- Raw/Admin 호출은 caller, policyId, command family, result, elapsed를 audit
- authentication material은 절대 기록하지 않는다.
22. Redis 8 확장 모듈
| 모듈 | 범위 | 활성화 조건 |
|---|---|---|
redis-json |
JSON get/set/path/array/object operations | capability probe 성공 |
redis-search |
index lifecycle, query, aggregation, vector query | Search capability와 schema 선언 |
redis-timeseries |
series create/add/range/aggregation/rules | Time Series capability |
redis-probabilistic |
Bloom, Cuckoo, CMS, Top-K, t-digest | capability별 bean |
원칙:
- classic core에 명령을 섞지 않는다.
- 시작 시
COMMAND INFO또는 capability probe를 수행한다. - 명시적으로 enable한 모듈의 capability가 없으면 startup failure다.
- Redis 8 통합 배포와 Redis 7 Stack 환경을 모두 테스트한다.
- 새 자료구조는 client 지원과 운영 안정성 검증 후 독립 API로 추가한다.
23. Spring Boot 설정
backend:
redis:
enabled: true
mode: standalone
nodes:
- localhost:6379
database: 0
ssl:
enabled: false
namespace:
environment: local
service: sample-service
domain: shared
timeout:
fast: 500ms
collection: 2s
script: 1s
batch: 2s
admin: 3s
limits:
max-key-bytes: 512
max-value-bytes: 1MiB
max-stream-payload-bytes: 256KiB
max-collection-elements: 1000
max-scan-count: 500
max-batch-commands: 500
max-batch-request-bytes: 4MiB
max-batch-reply-bytes: 16MiB
offline-queue-commands: 1000
blocking:
max-connections: 32
max-block: 30s
transaction:
max-connections: 16
raw:
enabled: false
admin:
enabled: false
Validation:
- Cluster에서
database != 0이면 startup failure - namespace token 형식 위반 시 startup failure
- Fast timeout이 5초를 넘으면 warning, 30초를 넘으면 startup failure
- 무한 blocking 금지
- Raw Gateway enable 시 allowlist와 별도 ACL credential 필수
- extension enable 시 capability 미지원이면 startup failure
24. 테스트 전략
24.1 토폴로지 매트릭스
| 실행 주기 | 환경 |
|---|---|
| PR | Standalone 7.4, Standalone 8.2 |
| Nightly | Standalone 7.2·7.4·8.2·8.10, Sentinel 7.4·8.2, Cluster 7.4·8.2 |
| Release | Nightly 전체 + Toxiproxy 장애 + Redis 8 extensions |
| Compatibility | Redis 6.2 제한 job |
24.2 계약 테스트
각 Typed API 구현체는 동일한 contract suite를 통과한다.
- 정상 결과
- 없는 key/field
- WRONGTYPE
- 잘못된 argument
- 크기 경계
- serialization 실패
- ACL 거부
- version 미지원
- CROSSSLOT
- timeout
24.3 동시성·원자성
INCRSET NXWATCHconflict- 등록 Lua conditional update
- rate limit window boundary
- idempotency script
- Stream duplicate delivery
24.4 장애
- connection refused
- DNS 실패
- connect/read timeout
- half-open TCP
- packet loss·latency
- 응답만 유실
- Sentinel promotion
- Cluster replica promotion
- resharding과
TRYAGAIN - 일부 node partition
24.5 성능과 guardrail
- p50/p95/p99/max
- Redis CPU·memory·output buffer
- JVM heap·allocation·GC
- request/reply bytes
- pipeline batch size와 in-flight
- big key delete/expire tail latency
- 대형 String, Hash, Set, ZSet, Stream, pipeline
24.6 보안
- 금지 command/subcommand
- Raw Gateway 우회
- Lua/Function 우회
- namespace 밖 key
- channel pattern 위반
- movable key extraction
- Redis 업그레이드 후 ACL category 변화
- R3/R4 deny
25. CI 품질 Gate
모든 release는 다음을 통과해야 한다.
- command metadata diff가 승인됨
- Typed API와 support matrix가 일치함
- sync/reactive API parity test 통과
- unit/contract/integration test 통과
- Sentinel·Cluster 장애 test 통과
- ACL regression test 통과
- forbidden API 검사 통과
- raw string command
- native Java serialization
- key/value metric tag
- 무한 blocking
- API binary compatibility 검사 통과
- 문서의 support matrix와 생성된 catalog가 일치함
- performance baseline의 허용 regression 이내
26. 배포 및 사용 방식
26.1 기본 서비스
dependencies {
implementation(project(":modules:redis:redis-spring-boot-starter"))
}
기본으로 노출:
- R1 Typed API
- Sync/Reactive
- Standalone/Sentinel
- 설정 시 Cluster
- metric, trace, health
26.2 Advanced API
backend.redis.advanced.enabled: true
- R2 bean 등록
AdvancedOperationPermit발급 bean 필요- ACL account에 승인된 R2 command만 추가
26.3 Raw Gateway
backend.redis.raw.enabled: true
backend.redis.raw.policy-resource: classpath:redis/raw-command-allowlist.yml
- 별도 credential 필수
- 임의 command string 불가
26.4 Admin Plane
일반 service process에는 포함하지 않는다. 운영 tool 또는 별도 profile에서만 실행한다.
27. 비지원 및 오해 방지 문구
문서와 Javadoc에 다음 내용을 명시한다.
- Redis Sentinel·Cluster의 승인 write가 failover 중 유실될 수 있다.
- timeout 후 write 결과는 알 수 없을 수 있다.
- Pipeline은 원자적이지 않다.
- Redis transaction은 rollback을 제공하지 않는다.
SCAN은 snapshot이 아니며 중복·변경 영향을 받을 수 있다.- Pub/Sub은 at-most-once이며 재연결 중 메시지가 유실된다.
- Stream consumer는 중복 전달을 처리해야 한다.
- HyperLogLog는 근사치다.
- Cluster multi-key는 same-slot이 필요하다.
- Raw Gateway는 안전성 보장이 아니라 제한된 확장 경로다.
28. 완료 정의
| 산출물 | 완료 조건 |
|---|---|
| command 지원 매트릭스 | target Redis metadata와 자동 비교되고 신규 command가 CI를 실패시킨다. |
| 자료구조별 Typed API | classic 자료구조 전체에 sync/reactive API가 있으며 contract test를 통과한다. |
| 위험 등급 정책 | R1~R4가 code, bean exposure, ACL, Raw Gateway에 반영된다. |
| version gate | 7.2·7.4·8.2·8.10 capability가 자동 판별된다. |
| topology | Standalone·Sentinel·Cluster test가 통과한다. |
| common policy | namespace, codec, TTL, timeout, retry, error, telemetry가 모든 경로에 적용된다. |
| Blocking 분리 | 일반 connection과 blocking/transaction/pubsub/admin 연결이 격리된다. |
| Raw Gateway | allowlist, key extraction, slot, size, version, audit가 강제된다. |
| Extensions | 독립 module과 capability probe가 존재한다. |
| 테스트 | 계약·동시성·장애·성능·ACL suite가 CI 또는 정기 job에 연결된다. |
| 운영 문서 | 사용 기준, 비보장, alert, upgrade, rollback 절차가 포함된다. |
29. 구현 순서
- Gradle 모듈과 공통 규칙
- command catalog와 policy schema
- core type, key, codec, exception, version capability
- Spring Data/Lettuce 연결과 auto-configuration
- policy-aware executor와 telemetry
- String, Hash, Set, Sorted Set, Key·TTL
- Batch·Pipeline
- List, Bitmap, Bitfield, HLL, Geo
- Stream과 Blocking connection
- Pub/Sub과 Sharded Pub/Sub
- Sentinel failover 의미론
- Cluster slot·redirect·topology
- Transaction, Lua, Function
- Raw Gateway
- Admin Plane
- Redis 8 확장 모듈
- CI matrix, chaos, performance, release documentation
이 순서는 정책 우회 경로인 Raw Gateway가 core guardrail보다 먼저 생기지 않도록 강제한다.