Files
llm-wiki/raw/official-docs/cache-redisson-rlock-vs-setnx.md
T

122 lines
15 KiB
Markdown

---
title: Redisson RLock vs Redis SETNX — distributed lock for cache stampede
source_type: official-doc
url: https://redisson.org/glossary/distributed-lock-and-synchronizer.html
archive_url:
status: raw
confidence: high
tags: [ca-cache-consistency, redisson, redis, distributed-lock, stampede, rlock, setnx]
related_projects: [ca-skeleton-operational-contract]
related_branches: [feature-cache-consistency-contract]
created: 2026-05-22
last_reviewed: 2026-05-27
---
# Redisson RLock vs Redis SETNX — distributed lock for cache stampede
> Layer: `raw/official-docs/` — Redisson 공식 문서 + Redis 공식 + Kleppmann 비판의 verbatim 발췌.
> ca-tmpl 의 "multi-instance HPA 시 Redisson RLock" 채택 + SETNX/Redlock 배제 결정의 1차 근거.
## Parent / 활용 branch (필수)
| Branch | 이 자료가 정당화하는 결정 |
|---|---|
| [[raw/branch-notes/feature-cache-consistency-contract]] | Group G-C 의 stampede 방지 도구 선택 — multi-instance HPA 환경에서 SETNX 직접 구현 / Redlock 을 배제하고 Redisson RLock 을 채택한 근거 (watchdog 자동 갱신, reentrancy, `j.u.c.locks.Lock` 호환) + Kleppmann 비판으로 efficiency vs correctness lock 분리 |
## 컨텍스트
ca-tmpl 의 cache stampede 방지 결정 **"multi-instance HPA 시 Redisson RLock"** 의 근거. SETNX 직접 구현 / Redlock / RLock 의 trade-off 를 비교.
## 출처 / Source
- 원본 URL (주): https://redisson.org/glossary/distributed-lock-and-synchronizer.html (Redisson 공식 — Distributed Locks and Synchronizers)
- 보조 URL (Redis 공식 — Distributed Locks with Redis / Redlock):
- 이전 URL (2026-05-22 capture 시점): https://redis.io/docs/latest/develop/use-cases/distributed-locks/ — [2026-05-27 verified attempt] HTTP 404 (페이지 이전됨)
- 현재 URL: https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/ — [2026-05-27 verified attempt] WebFetch 성공, LOCK-C1 verbatim 일치 확인
- 참고: Martin Kleppmann, "How to do distributed locking" (Redlock 비판, https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html)
- 아카이브 URL: (미수집)
- 저자 / 조직: Redisson (open source project) / Redis Ltd. / Martin Kleppmann (개인)
- 발행일: rolling docs (Redisson / Redis)
- 마지막 확인일 (capture): 2026-05-22
- 마지막 재검증 시도: 2026-05-27
- **[2026-05-25 capture]**: user 가 2026-05-22 수집한 인용 원형 유지 (needs-confirmation 마커는 2026-05-25 부여된 상태).
- **재검증 결과 [2026-05-27 verified attempt]**:
- LOCK-C1, LOCK-C2 (Redis 공식): 1차 URL `https://redis.io/docs/latest/develop/use-cases/distributed-locks/` HTTP 404. 현재 공식 URL 은 `https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/` (경로가 `use-cases``clients/patterns` 로 이전). 신 URL WebFetch 성공.
- LOCK-C1: 신 URL 본문에서 `SET resource_name my_random_value NX PX 30000` 명령 + "`NX` option" + "expire of 30000 milliseconds (`PX` option)" + "value 'my_random_value'" 의 verbatim 일치 확인됨. user 수집본 wording 과 의미 동일하나 user 수집본은 다소 paraphrase ("The simplest way to use Redis to lock a resource is to create a key in an instance with ..." 는 실제 페이지의 "To acquire the lock, the way to go is the following:" 와 다름) — verbatim wrapper 는 다르되 핵심 명령 + 옵션 의미는 **공식 출처에서 verbatim 일치 확인**.
- LOCK-C2: 신 URL 본문에서 "The key is usually created with a limited time to live, using the Redis expires feature, so that eventually it will get released (property 2 in our list)." 발견 — user 수집본 wording ("A lock with a fixed time-to-live is required to avoid deadlocks ...") 과 의미 동일하나 verbatim 불일치. user 수집본은 paraphrase.
- → LOCK-C1 의 핵심 명령 (`SET ... NX PX 30000`) 은 공식 vendor doc 에서 verbatim 확인 → **Strength 상향 `needs-confirmation` → `official-vendor-doc`** (단 user wrapping 문장은 paraphrase 잔존).
- → LOCK-C2 는 공식 vendor doc 에 동등 의미 명시 존재 → **Strength 상향 `needs-confirmation` → `official-vendor-doc-paraphrase`** (verbatim wording 은 user 수집본 ≠ 공식, 의미는 일치).
- LOCK-C3 (Redisson RLock): 1차 URL `https://redisson.org/glossary/distributed-lock-and-synchronizer.html``redisson.pro` 도메인으로 301 redirect. WebFetch permission denied (redirect 호스트 호출 차단) → verbatim 재확인 **불가**. Strength **유지** `needs-confirmation`.
- LOCK-C4 (Kleppmann): 1차 URL `https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html` WebFetch permission denied → verbatim 재확인 **불가**. Strength **유지** (기존 `engineering-blog` 유지, 상향 없음).
- **재검증 한계**: Redisson Javadoc / Kleppmann 본문 재검증 보류. ca-tmpl `verified` 승급 전 별도 채널 (Redisson Javadoc 직접 다운로드 / archive.org Kleppmann 스냅샷) 확인 필요.
## 핵심 인용 / Key quotes (verbatim, user 수집본 [2026-05-25 capture] — [2026-05-27 verified attempt] 결과 인라인)
> [§Redis 공식 — Distributed Locks with Redis] [2026-05-27 verified attempt] `official-vendor-doc` (핵심 명령 verbatim 확인): "The simplest way to use Redis to lock a resource is to create a key in an instance with `SET resource_name my_random_value NX PX 30000`. This sets the key only if it does not already exist (NX option) with an expire of 30000 milliseconds (PX option)."
> — 공식 페이지 (신 URL `https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/`) 의 실제 wording 은 "To acquire the lock, the way to go is the following: `SET resource_name my_random_value NX PX 30000`. The command will set the key only if it does not already exist (`NX` option), with an expire of 30000 milliseconds (`PX` option). The key is set to a value 'my_random_value'." → 명령 / 옵션 / 의미 verbatim 일치, user wrapping 문장은 paraphrase.
> [§Redis 공식 — Distributed Locks with Redis] [2026-05-27 verified attempt] `official-vendor-doc-paraphrase` (의미 일치, wording 불일치): "A lock with a fixed time-to-live is required to avoid deadlocks when the client crashes after acquiring the lock but before releasing it."
> — 공식 페이지 실제 wording: "The key is usually created with a limited time to live, using the Redis expires feature, so that eventually it will get released (property 2 in our list)." → 의미 동일, verbatim 불일치.
> [§Redisson — Distributed Locks and Synchronizers] [2026-05-27 verified attempt] `needs-confirmation` 유지 (1차 URL 301 → redisson.pro, redirect 호스트 호출 차단으로 재확인 불가): "RLock implements `java.util.concurrent.locks.Lock` and adds `tryLock(waitTime, leaseTime, unit)` semantics. It uses a watchdog (default 30s) that automatically extends the lock TTL while the holding thread is alive, preventing premature expiry on long operations."
> [§Kleppmann — How to do distributed locking] [2026-05-27 verified attempt] `engineering-blog` 유지 (WebFetch permission denied 으로 재확인 불가): "Any algorithm that relies on lease timers for correctness is unsafe in the presence of GC pauses or network delays. For correctness use fencing tokens; for efficiency lock the Redis way is fine."
## Claims Extracted / 추출된 주장
| Claim ID | Claim (이 자료가 직접 말하는 것) | Evidence quote | Strength | Applies to | Does not prove |
|---|---|---|---|---|---|
| LOCK-C1 | Redis 의 가장 단순한 단일-인스턴스 분산 락 패턴: `SET resource_name my_random_value NX PX 30000` (NX = 없을 때만, PX = ms TTL) | [§Redis 공식 — 신 URL `https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/`] [2026-05-27 verified] verbatim 핵심 명령 확인: "To acquire the lock, the way to go is the following: `SET resource_name my_random_value NX PX 30000`. The command will set the key only if it does not already exist (`NX` option), with an expire of 30000 milliseconds (`PX` option)." | `official-vendor-doc` (Strength 상향 [2026-05-27]: `needs-confirmation``official-vendor-doc` — Redis 공식 verbatim 일치 확인. user wrapping 문장은 paraphrase 잔존) | 단일 Redis 인스턴스 환경, efficiency lock | 멀티 노드 환경 (Redlock) 에서도 동일한 단순함이 유지된다는 뜻은 아님 |
| LOCK-C2 | client crash 시 deadlock 회피를 위해 **fixed TTL** 가 필수 (lock 획득 후 release 전 crash 대비) | [§Redis 공식 — 신 URL] [2026-05-27 verified, paraphrase] 공식 wording: "The key is usually created with a limited time to live, using the Redis expires feature, so that eventually it will get released (property 2 in our list)." — 의미 동일, verbatim 불일치 | `official-vendor-doc-paraphrase` (Strength 상향 [2026-05-27]: `needs-confirmation``official-vendor-doc-paraphrase` — 공식 vendor doc 에 동등 의미 명시, verbatim wording 은 user 수집본과 불일치) | Redis 기반 분산 락 일반 | TTL 만 있으면 correctness 가 보장된다는 뜻은 아님 (Kleppmann 비판 참고, LOCK-C4) |
| LOCK-C3 | Redisson `RLock``j.u.c.locks.Lock` 인터페이스를 구현 + `tryLock(waitTime, leaseTime, unit)` 시맨틱 + **watchdog (기본 30s) 으로 holding thread 가 살아있는 동안 lock TTL 자동 연장** → 긴 작업 시 premature expiry 방지 | [§Redisson] [2026-05-27 verified attempt] 1차 URL 301 → redisson.pro, redirect 호스트 호출 차단으로 verbatim 재확인 불가: "RLock implements `java.util.concurrent.locks.Lock` and adds `tryLock(waitTime, leaseTime, unit)` semantics. It uses a watchdog (default 30s)..." | `needs-confirmation` (유지 — Strength 상향 없음) | Redisson client 사용 시 | watchdog 이 모든 GC pause / network partition 시나리오를 흡수한다는 뜻은 아님 (Kleppmann 의 fencing token 비판 별도, LOCK-C4) |
| LOCK-C4 | **Kleppmann 비판**: lease timer 에 correctness 를 의존하는 알고리즘은 GC pause / network delay 상황에서 unsafe — correctness 가 필요하면 **fencing token**, efficiency 목적이라면 Redis 방식도 충분 | [§Kleppmann] [2026-05-27 verified attempt] WebFetch permission denied → verbatim 재확인 불가: "Any algorithm that relies on lease timers for correctness is unsafe in the presence of GC pauses or network delays. For correctness use fencing tokens; for efficiency lock the Redis way is fine." | `engineering-blog` (유지 — Strength 상향 없음) | distributed lock 의 efficiency vs correctness 구분 | Redlock 이 모든 시나리오에서 부적합하다는 뜻은 아님 — efficiency lock 용도는 여전히 유효 (Kleppmann 본인 명시) |
## Usage Boundaries / 적용 경계
- **이 자료가 직접 증명하는 것** ([2026-05-27 verified attempt] 결과 반영):
- `LOCK-C1`: Redis SET NX PX 분산 락 패턴의 기본 동작 — Redis 공식 (신 URL `https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/`) 에서 핵심 명령 verbatim 일치 확인 → `official-vendor-doc`
- `LOCK-C2`: TTL 의 deadlock 회피 역할 — Redis 공식에 동등 의미 명시 (wording 은 paraphrase) → `official-vendor-doc-paraphrase`
- `LOCK-C3`: Redisson RLock 의 `j.u.c.locks.Lock` 호환 + watchdog 자동 갱신 — 1차 URL 301 redirect (redisson.org → redisson.pro) + redirect 호스트 호출 차단으로 재확인 불가 → `needs-confirmation` 유지
- `LOCK-C4`: Kleppmann 의 efficiency vs correctness lock 분리 권고 — WebFetch permission denied 으로 재확인 불가 → `engineering-blog` 유지 (본 자료에서 가장 강한 출처는 LOCK-C1 의 Redis 공식으로 변경됨)
- **이 자료가 증명하지 않는 것**:
- Redisson RLock 이 모든 use case 에서 SETNX 보다 우월하다는 일반 claim (도구 선택은 운영 복잡도 / 의존성 vs 자동화 trade-off)
- Redlock 이 항상 over-engineering 이라는 평가 (Kleppmann 본인이 efficiency lock 으로는 OK 명시)
- SETNX 직접 구현이 모든 watchdog 시나리오에서 fail 한다는 보장 (운영자가 별도 갱신 스레드 구현 가능)
- watchdog 의 기본 30s 가 모든 워크로드에서 적정하다는 보장 (긴 batch / heavy GC 환경은 별도 튜닝 필요)
- Redisson 의존성 추가가 Lettuce/Jedis 와 충돌 없이 공존 가능하다는 보장 (운영 검증 필요)
- **내 프로젝트에 적용하려면 추가 확인이 필요한 것**:
- **재검증 한계로 인한 SSOT 확인 의무 (잔여)**: LOCK-C1/C2 는 [2026-05-27 verified attempt] 로 Redis 공식 신 URL verbatim 확인 완료. LOCK-C3 (Redisson RLock watchdog / leaseTime 시맨틱) 와 LOCK-C4 (Kleppmann) 는 여전히 redirect / permission 차단으로 재확인 불가 → ca-tmpl 의 `verified` / `published-ready` 승급 전 Redisson Javadoc + Kleppmann archive.org 스냅샷으로 직접 verbatim 격상 필요.
- ca-tmpl 의 "stampede 방지 = efficiency lock" 분류가 모든 cache 시나리오 (예: token bucket, rate limit) 에 적용되는지 (correctness lock 으로 격상해야 하는 endpoint 식별)
- spring-boot-starter-redisson 과 spring-boot-starter-data-redis (Lettuce) 의 connection pool 공존 운영 비용
## 메모 / Notes (내 프로젝트 해석)
> 본 섹션은 자료 직접 인용 아님. ca-tmpl 결정 컨텍스트 해석.
- SETNX 단독:
- 장점: 매우 단순. Lua script 로 atomic release (check-and-del) 가능.
- 단점:
- 직접 구현 시 **자동 갱신 (watchdog) 없음** → 처리 시간이 lease 를 넘으면 lock 해제 후 다른 thread 도 진입 (이중 stampede).
- reentrancy 없음 — 같은 thread 가 재진입 시 별도 코드.
- lock 해제 시 owner 검증 직접 구현해야 함 (key 의 random value 비교 Lua script).
- Redisson RLock:
- 장점: `java.util.concurrent.locks.Lock` 인터페이스 호환, reentrancy, **watchdog 자동 갱신**, fair lock / multi-lock / read-write lock 지원.
- 단점: Redisson client 추가 의존성. spring-boot-starter-redisson 이 별도. Lettuce/Jedis 와 connection pool 이 별도라 운영 복잡.
- Redlock (multi-node):
- 장점: 단일 Redis 장애에 강함.
- 단점: Kleppmann 비판 (LOCK-C4) — clock drift, GC pause 로 correctness 보장 안 됨. cache stampede 같은 efficiency lock 에는 over-engineering.
- ca-tmpl 결정 정당성:
- **stampede 방지는 efficiency lock** 이지 correctness lock 이 아님. RLock 단일 Redis 로 충분. 결제처럼 correctness 가 필요하면 RLock 도 부적합 — DB unique constraint 나 fencing token 사용.
- 시사점: ca-tmpl 의 "single-instance Caffeine local + multi-instance Redisson RLock" 분기는 **lock 책임 범위에 맞춘 도구 선택**. Redlock 은 의도적으로 배제.
## Related / 관련
- 같은 주제 다른 raw:
- [[raw/company-tech-blogs/cache-woowahan-after-commit-invalidation]] (cache invalidation timing 사례)
- 적용 ca-tmpl branch-note:
- [[raw/branch-notes/feature-cache-consistency-contract]]
- canonical contract 섹션:
- [[raw/project-notes/ca-skeleton-operational-contract]] (cache consistency 관련 섹션)
- 대안 그룹: **Group G-C — Cache consistency** (stampede 도구 비교: a) Caffeine local / b) Redisson RLock [ca-tmpl multi-instance] / c) SETNX 직접 구현 / d) Redlock multi-node) — 본 source 는 **b 채택 + c/d 배제 근거**.
- 인용한 wiki 요약: (미작성)