fix: 하네스 제거 및 keycloak 문서 보강

This commit is contained in:
DongHyeonka
2026-07-25 12:53:13 +09:00
parent 6c53ded9cb
commit d71669eb59
2329 changed files with 138239 additions and 172816 deletions
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/api-error-envelope-design.md
+151
View File
@@ -0,0 +1,151 @@
---
title: API Error Envelope 설계 (custom vs ProblemDetail vs rpc.Status)
source_type: llm-generated
status: draft
confidence: medium
tags: [api-design, error-handling, http]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# API Error Envelope 설계 (custom vs ProblemDetail vs rpc.Status)
> Layer: `wiki/concepts/` — 일반 개념. 특정 프로젝트의 결정/구현 사실은 `wiki/projects/`에서 다룬다.
## Summary
API error envelope은 실패 응답의 구조 계약이다. 표준 후보는 RFC 7807 ProblemDetail, Google `rpc.Status`, JSON:API errors, GraphQL errors가 있고, 그 외 대형 서비스의 custom envelope (Stripe / GitHub / 토스페이먼츠 등)이 사실상 진영별 컨벤션으로 자리잡았다. 설계 결정의 핵심 축은 (a) 성공/실패 응답의 대칭 여부, (b) `code` · `category` · `retryable` 같은 운영 메타데이터의 1급 필드 승격 여부, (c) 표준 lock-in과 client SDK 호환성의 trade-off다.
## Standard (공식 정의)
### RFC 7807 ProblemDetail (실패 전용 평면)
IETF 표준. `application/problem+json` media type. 필드: `type` (URI), `title`, `status`, `detail`, `instance`. 모든 필드 optional이고 확장은 top-level에 임의 필드 추가로 한다. RFC 9457로 obsolete되었지만 의미상 호환이며, Spring 6+는 `ProblemDetail` 클래스로 기본 지원한다. 성공 응답에는 적용되지 않고 실패 전용 평면 shape이다.
### Google `rpc.Status` (gRPC, typed details)
Google AIP-193. `code` (정수, `google.rpc.Code` enum), `message`, `details: Any[]`. `details``google.protobuf.Any`로 packing되며 표준 detail 타입(`ErrorInfo`, `LocalizedMessage`, `Help`, `RetryInfo`, `QuotaFailure`, `BadRequest`)을 포함한다. `RetryInfo`로 retryable + delay까지 표준화되어 있다. REST/gRPC 양쪽에 동일 모델로 매핑된다.
### JSON:API errors (배열)
JSON:API v1.1 spec. top-level에 `errors: []` array 필수. 각 error 객체는 `id`, `links`, `status`, `code`, `title`, `detail`, `source.pointer` (JSON Pointer), `meta` 중 하나 이상을 가진다. `source.pointer`로 form 필드 단위 오류를 가리킨다.
### GraphQL errors (HTTP 200 + errors field)
GraphQL Specification (October 2021) §7.1.2. 응답은 `data``errors`를 모두 가질 수 있고, error 객체는 `message` (required), `locations`, `path`, `extensions`를 가진다. transport는 보통 HTTP 200이고 4xx/5xx는 transport-level 실패에만 사용한다.
### 진영별 custom envelope (표준 아님)
- **Stripe**: `{ error.{ type, code, decline_code, message, param, doc_url, ... } }`. `type` enum이 사실상 category 역할.
- **GitHub**: `{ message, documentation_url, errors[].{ resource, field, code } }`. validation 항목별 풀이가 명시적.
- **토스페이먼츠**: `{ code, message }`. 가장 얇은 envelope. retryable/category는 `code` semantic으로 추론.
이 세 사례는 어떤 IETF/W3C 표준도 따르지 않으며, 각 회사 SDK가 envelope을 흡수하는 전제로 동작한다.
## 한계 / 주의점
### Custom envelope
- 외부 표준이 존재하지 않으므로 client SDK를 직접 작성하거나 envelope 처리 규칙을 client에게 명시적으로 전달해야 한다.
- 성공/실패 대칭, `retryable` 1급 같은 운영 친화 결정을 자유롭게 둘 수 있지만 그 비용은 "표준 client 라이브러리 0개"다.
### RFC 7807 ProblemDetail
- 실패 전용 평면 shape이므로 "성공도 envelope으로 감싸 `success: true/false`로 분기하고 싶다"는 요구와 구조적으로 충돌한다.
- `code` 필드가 표준에 없다 — `type` URI가 식별자다. 짧은 머신리더블 코드를 원하면 확장 필드를 강제해야 하고, 결국 "표준 위에 사실상 custom 레이어"가 된다.
- Spring 6+는 기본 활성이므로, custom envelope을 채택한다는 것은 의식적으로 표준 인프라를 비활성화하는 선택이다.
- `application/problem+json`을 content-negotiation으로 처리하는 client는 흔하지 않다 — 실질 호환성 이득은 명목 수준에 가깝다.
### Google `rpc.Status`
- 본질적으로 gRPC/protobuf 생태계 결합이다. HTTP REST 전용 서비스에 강제하면 `Any` 디코딩 부담이 client에 mismatch로 전가된다.
- 표준 detail 타입 카탈로그를 알아야 효용이 발휘되어 학습 곡선이 높다.
- 가벼운 CRUD API에는 과한 표현력이다.
### JSON:API errors
- `errors[]` array와 `source.pointer`는 항목 단위 오류 표현에 강하지만, `category`/`retryable`이 1급 필드가 아니라 `meta`로 빠진다.
- 부분 채택 시 표준성이 사라진다. 완전 채택 시 success response 리소스 객체 구조, sparse fieldsets 등 spec 전체에 lock-in된다.
### GraphQL errors
- HTTP 200 + `errors` field가 transport 규약이라 CDN / proxy / observability 도구의 4xx/5xx 기반 알람·캐시·라우팅과 부조화한다.
- partial success가 1급 개념이라 REST envelope과 패러다임 자체가 다르다 — REST 컨텍스트에서 직접 비교해 "GraphQL이 옳다/그르다"라고 말할 수 없다.
### 흔한 오해
- "Stripe / GitHub / 토스페이먼츠가 그렇게 하니까 industry standard다" — 표준이 아니라 진영별 컨벤션이다. SDK 없이 직접 다루는 client는 거의 없다는 전제 위에서 동작한다.
- "ProblemDetail은 잘못된 설계다" — 실패 전용 use case (예: 외부 노출 API, RFC 9457 client 생태계 활용)에서는 유효한 선택이다.
## Project Application
- [[wiki/projects/ca-tmpl/api-error-envelope-design]] — ca-tmpl 의사결정 기록 (`verified` — envelope record/handler 코드 구현 + `./gradlew check` 로컬 통과). 실제 구현 범위·검증 수준은 project 문서 참조.
- [[raw/project-notes/ca-skeleton-operational-contract]] — §3 Structured API Response Contract / §5 Exception Ownership Contract / §6 Operational Error Category / §29 Topic 4 (custom envelope 결정 라인업)
- [[raw/branch-notes/feature-operational-error-observability-foundation]] — envelope schema SSOT
- [[raw/branch-notes/feature-boundary-validation-mapping-contract]] — validation error → `error.details` 매핑
- [[raw/branch-notes/feature-business-rule-validation-contract]] — business invariant → category 매핑
위 branch-note들은 success / error 대칭, `error.code` · `error.category` · `error.retryable` · `error.details` 분리, `meta.requestId` / `meta.traceId` / `meta.correlationId` 1급 노출, raw exception / SQL / token / body의 응답 leak 금지를 계약으로 둔다.
## Claim-backed Knowledge
> 이 개념 문서의 핵심 설명은 raw source claim 으로 뒷받침되어야 한다.
> 공식 문서 claim, 회사 사례 claim, 내 프로젝트 decision 을 분리한다.
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| RFC 7807 ProblemDetail은 `application/problem+json` 기반 실패 전용 평면 shape이며 `type` URI가 식별자다 (`code` 필드 없음) | [[raw/official-docs/problem-detail-rfc-7807]], [[raw/official-docs/spring-problem-detail]] | `high` | 공식 표준 (IETF / Spring) — success/error 대칭·머신리더블 `code` 요구와 구조적으로 충돌 |
| Google `rpc.Status``RetryInfo` 등 typed detail로 retryable + delay까지 표준화 (REST/gRPC 공통 모델) | [[raw/official-docs/google-api-error-format]] | `high` | 공식 vendor 문서(AIP-193) — 단 protobuf/`Any` 결합이라 HTTP REST 전용에는 과한 표현력 |
| JSON:API는 `errors[]` + `source.pointer`(JSON Pointer)로 항목 단위 오류를 가리키지만 `category`/`retryable`이 1급 필드가 아니다 | [[raw/official-docs/json-api-errors-spec]] | `high` | 공식 표준 — 부분 채택 시 표준성 상실, 완전 채택 시 spec 전체 lock-in |
| Stripe/GitHub/토스페이먼츠 envelope은 IETF/W3C 표준이 아니라 진영별 컨벤션이며 각 사 SDK가 envelope을 흡수하는 전제로 동작한다 | [[raw/company-tech-blogs/stripe-error-format]], [[raw/company-tech-blogs/github-api-error-format]], [[raw/company-tech-blogs/toss-payments-error-format]] | `medium` | company-case-study — 공식 best practice로 일반화 금지. SDK 부재 client는 거의 없다는 전제 |
## 내가 설명할 수 있어야 하는 것
- API error envelope의 후보 표준(RFC 7807 / Google `rpc.Status` / JSON:API / GraphQL errors)의 공식 정의와 각자의 식별자 표현 방식은?
- 어떤 문제를 해결하는가 — client가 실패를 어떻게 분기·재시도·관측 가능하게 만드는 구조 계약인가?
- 어떤 상황에서는 custom envelope을 쓰면 안 되는가(표준 client 생태계 활용이 우선인 외부 노출 API 등)?
- 공식 표준이 말하지 않는 부분(success/error 대칭, `retryable`·`category` 1급화)은 무엇이고 그 비용("표준 client 라이브러리 0개")은 무엇인가?
- Stripe/GitHub/토스 사례를 industry standard처럼 일반화하면 안 되는 지점은?
- 내 프로젝트에서는 어떤 branch decision(custom envelope 채택 + ProblemDetail 거부)으로 연결됐는가?
- 이 개념을 코드/운영에서 검증하려면 무엇을 확인해야 하는가(envelope 직렬화, leak 금지, ProblemDetail 비활성 build-time 강제 등)?
## Interview Questions
- 왜 RFC 7807 ProblemDetail을 채택하지 않았는지? 표준을 우회한 비용은 무엇이고, 그 대신 무엇을 얻는지?
- `retryable`을 1급 필드로 둔 이유는? client는 `retryable: true`를 받았을 때 어떻게 다르게 동작해야 하는지?
- validation error를 `error.details`에 담을 때 GitHub `errors[].{resource, field, code}` 또는 JSON:API `source.pointer`와 비교하면 어떤 형식을 택했고, 왜 그렇게 택했는지?
- `error.code``error.category`를 분리한 이유는? client 분기는 어느 쪽으로 하라고 가이드하는지?
- 응답에 절대 leak하면 안 되는 항목은? exception class name, stack trace, SQL, token, raw body, upstream raw error body 각각이 왜 금지인지 설명할 수 있는지?
## Do Not Overclaim
- "내 envelope이 표준이다" / "ca-tmpl envelope이 IETF 표준 envelope이다"라고 말하면 안 된다. 어떤 표준도 success/error 대칭 + `retryable` 1급 + `category` 1급을 동시에 강제하지 않는다 — 자체 결정일 뿐이다.
- "ProblemDetail은 잘못된 설계다"라고 단정하면 안 된다. 실패 전용 평면이라는 그 자체가 결함이 아니며, 외부 표준 client 호환을 우선하는 use case에서는 합리적이다.
- "Stripe / GitHub / 토스가 다 custom이니까 표준은 의미 없다"라고 말하면 안 된다. 그들은 SDK가 envelope을 흡수하는 전제 위에 동작하며, 표준 미준수가 정당화되는 것이 아니라 trade-off가 다른 것뿐이다.
- Google `rpc.Status``RetryInfo.retry_delay`보다 `retryable: boolean`이 우월하다고 주장하면 안 된다 — 후자는 단순하지만 actionable한 delay 정보를 잃는다.
## Sources
### 공식 표준
- [[raw/official-docs/problem-detail-rfc-7807]] — RFC 7807 (Problem Details for HTTP APIs)
- [[raw/official-docs/spring-problem-detail]] — Spring Framework `ProblemDetail` (RFC 9457 기본 지원)
- [[raw/official-docs/google-api-error-format]] — Google AIP-193, `google.rpc.Status`
- [[raw/official-docs/json-api-errors-spec]] — JSON:API v1.1 Errors
- [[raw/official-docs/graphql-errors-spec]] — GraphQL Specification (October 2021) Errors
### 진영별 사례 (표준 아님)
- [[raw/company-tech-blogs/stripe-error-format]] — Stripe custom envelope
- [[raw/company-tech-blogs/github-api-error-format]] — GitHub REST API error format
- [[raw/company-tech-blogs/toss-payments-error-format]] — 토스페이먼츠 `{code, message}`
### Canonical (프로젝트 결정 사실)
- [[raw/project-notes/ca-skeleton-operational-contract]] §3 / §5 / §6 / §29 Topic 4
## Cluster / 묶음
<!-- GENERATED: derived-blogs:start -->
- [[wiki/blog/ca-tmpl-api-error-envelope-design-2026-07-02]]
<!-- GENERATED: derived-blogs:end -->
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/api-evolution-and-schema.md
+177
View File
@@ -0,0 +1,177 @@
---
title: API Evolution & Schema (compatibility + serialization + HTTP contract surface)
source_type: llm-generated
status: reviewed
confidence: medium
tags: [api-design, versioning, schema, deprecation, pagination, conditional-request, http-cache]
related_projects: [ca-skeleton]
last_reviewed: 2026-06-04
---
# API Evolution & Schema (compatibility + serialization)
> Layer: `wiki/concepts/` — 일반 개념. 특정 프로젝트의 결정/구현 사실은 `wiki/projects/`에서 다룬다.
## Summary
API evolution은 두 축으로 나뉜다. (1) **compatibility / deprecation** — 응답 필드 제거나 의미 변화를 막기 위해 breaking change를 분류하고 migration window 동안 deprecated marker와 Sunset 헤더로 client에게 신호를 보낸다. (2) **schema / serialization** — date·money·enum·null·unknown field의 의미를 framework default에 맡기지 않고 명시 계약으로 고정한다. 대표 결정 라인업은 `90d public + 30d internal migration window`, RFC 8594 `Sunset` 헤더, ISO-8601 offset datetime (UTC default), `BigDecimal` scale 2 + `HALF_UP`, **strict inbound / tolerant outbound** 정책이다.
## Standard (공식 정의)
### Compatibility / deprecation 표준 후보
- **RFC 8594 Sunset header (IETF)**: 응답 헤더로 자원이 응답 불가가 될 시점을 HTTP-date로 알린다. `Sunset` 단독은 *언제* 사라지는지 신호일 뿐이고, deprecation 자체는 별도 `Deprecation` 헤더(IETF draft)로 표시하는 것이 표준 의도다.
- **Microsoft REST API versioning policy**: `api-version` query/header를 정식 권고. major version 단위 breaking change 허용, minor/preview는 additive only. preview API는 별도 lifecycle.
- **GitHub REST API**: 2022년부터 `X-GitHub-Api-Version: YYYY-MM-DD` 날짜 헤더. 새 버전 release 후 **24개월 EOL** 정책, EOL된 버전 호출은 `410 Gone` 응답. preview API는 `Accept` 헤더 `application/vnd.github.<name>-preview+json`로 옵트인.
- **Stripe date-based versioning**: account마다 첫 호출 시 version pin. 이후 새 version이 나와도 client가 명시적으로 upgrade하지 않으면 **freeze forever** (Stripe가 영구적으로 구버전 응답을 유지). 외부 컨슈머 규모가 큰 결제 도메인 특화.
- **Google AIP-180 (Backwards compatibility)**: enum value 제거 / 의미 변경 / 응답 필드 제거 / 기본값 변경 / required request field 추가 모두 breaking으로 분류. additive (optional response field 추가)만 minor에 허용.
- **Twitter tier-based**: legacy / current / beta 트랙 병렬 운영.
- **Spring HATEOAS**: 응답에 `_links`로 다음 자원 URI를 동봉해 client가 version이 아닌 link relation에 결합하게 한다.
### Schema / serialization 표준 후보
- **ISO-8601**: date·time·datetime·duration의 wire 표현 표준. offset datetime(`2026-05-22T11:30:00+09:00` 또는 `Z`)이 timezone ambiguity 회피의 정석.
- **JSON Schema** (draft 2020-12): JSON payload의 shape 검증 spec. `additionalProperties: false`로 unknown field strict, `nullable` / `required` / `enum`으로 의미 분리.
- **OpenAPI 3.1**: JSON Schema 2020-12 정합. response shape SSOT 후보. `deprecated: true` 플래그를 schema/operation 양쪽에 둘 수 있어 deprecation marker 표준 위치가 된다.
- **Avro schema evolution**: backward / forward / full compatibility를 schema registry가 자동 검사. 필드 추가/삭제 시 default 의무, alias로 rename. event/outbox 환경에 우위.
- **Protobuf**: `reserved` 키워드로 field number와 name 재사용을 영구 차단. wire-format 기반 strict typing.
- **Jackson** (Java): `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`는 default `true`. 단, `FAIL_ON_NULL_FOR_PRIMITIVES`는 default `false`라 null/missing primitive가 묵시적으로 0이 된다. 출력측은 `SerializationFeature.WRITE_DATES_AS_TIMESTAMPS`(default `false``JavaTimeModule` 경유 ISO-8601 문자열, `true` 면 epoch/배열)와 `JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN`(default `false` → 큰 값이 지수 표기 `1.23E+10`)이 wire 형식을 좌우한다. 이 둘은 *프레임워크 기본값*이라 버전 업그레이드로 flip 될 수 있으므로 계약을 명시 핀하고 effective bean 동작 테스트로 회귀를 잡는 것이 안전하다.
- **Property naming strategy**: Jackson `PropertyNamingStrategies`(camelCase default / `SNAKE_CASE` / `KEBAB_CASE`)는 wire 의 field 이름 컨벤션을 결정한다. 한 번 정하면 client 가 그 이름에 결합하므로 *변경 자체가 breaking* — 전역 strategy 변경은 모든 응답 field rename 과 동치다.
- **Null vs absent (`@JsonInclude`)**: `JsonInclude.Include.NON_NULL`/`NON_ABSENT`/`NON_EMPTY` 는 null 또는 빈 값을 출력에서 *생략* 한다. 생략(absent)과 명시적 `null` 은 client 에게 다른 의미(부재 vs 값이 null) 일 수 있어, JSON Merge Patch 같은 부분 갱신 의미가 필요하면 `JsonNullable<T>` 로 3-상태(present-null / present-value / absent)를 구분한다.
- **Java BigDecimal**: 금액 계산 표준. `new BigDecimal(double)` 함정 (`0.1``0.1000000000000000055511151231257827021181583404541015625`), `setScale(2, RoundingMode.HALF_UP)` 패턴, JSON에서는 string 직렬화로 client 부동소수 손실 회피가 표준 권고.
- **Smithy**: AWS의 API modeling DSL. SDK 코드 생성 친화적, 단 외부 ecosystem에서는 OpenAPI보다 미성숙.
### HTTP contract surface 표준 (conditional request / cache / pagination)
versioning·schema 와 별개로, HTTP API surface 자체의 일반 계약 표준. (RFC 9110/9111 은 IETF official-standard, AIP 는 Google community guideline)
- **Conditional request (RFC 9110 §13)**: `ETag` 는 representation 의 opaque validator (weak `W/"..."` 또는 strong). write 는 `If-Match` 로 optimistic concurrency 검증 — condition 이 false 면 **412 Precondition Failed**. read 는 `If-None-Match` 로 cache validation — match 면 **304 Not Modified** (body 없음, client 저장본 사용). RFC 9110 은 `If-Match`*strong comparison* 을 MUST 로 요구한다.
- **HTTP caching (RFC 9111 §5.2)**: `Cache-Control` directive — `no-store` (저장 금지, 인증 API 안전 default), `private` (shared cache 저장 금지), `public` (Authorization 있어도 shared cache 허용), `max-age=N` (stale 판정 초). 협상/인증 응답은 `Vary` (RFC 9110 §12.5.5) 로 어떤 request 부분이 content 선택에 영향을 줬는지 명시해 proxy/CDN cache poisoning 을 막는다.
- **Pagination (Google AIP-158, JSON:API)**: offset (`page`/`size`) vs cursor (opaque token). AIP-158 은 page token 이 opaque + URL-safe MUST, server-side size cap SHOULD coerce, empty next-token = end-of-collection 을 규정. JSON:API 는 `links` object 안의 `first`/`last`/`prev`/`next` key 위치를 정의. 구체 숫자(size cap, TTL)는 표준이 아닌 구현 trade-off.
- **Transport error 의미 구분 (RFC 9110 §15)**: 413 Content Too Large, 406 Not Acceptable (응답 표현 협상 실패) vs 415 Unsupported Media Type (요청 본문 format), 405 Method Not Allowed (+ `Allow` header MUST). 같은 code 로 뭉개면 표준 의미가 손실된다.
- **Long-running operation (Google AIP-151 + RFC 9110)**: 비동기 처리는 **202 Accepted** + `Location` polling URL + Operation 객체(`done`/`response`/`error`). `Retry-After` 로 polling interval 권고.
## 한계 / 주의점
### Compatibility / deprecation 측
- **Stripe freeze-forever**: 무기한 구버전 유지 비용이 외부 결제 컨슈머 규모에서만 정당화된다. internal API에 그대로 차용하면 server 코드에 N개 버전 분기를 영구 운반하게 된다.
- **GitHub 24개월 EOL + `410 Gone`**: 길어 보이는 EOL window지만 catalog에 EOL 응답 코드(410)를 명시하지 않으면 client 입장에서 *어느 날 갑자기 410*과 다를 바 없다. EOL 응답 코드 자체를 contract에 박는 것이 필요하다.
- **Twitter tier-based (legacy/current/beta)**: 트랙별 행위 분기가 server-side 복잡도와 운영 비용을 곱한다. 단일 팀 / internal-first 환경에 과하다.
- **Spring HATEOAS (links over versions)**: 이론적으로 우아하지만 실제 client가 `_links`를 dynamic하게 따라가는 경우는 드물고, 학습 곡선과 client 구현 강제 비용이 크다.
- **Google AIP-180 `enum value 제거 = breaking`**: client switch/case 누락을 유발하므로 strict 분류가 맞지만, enum value 추가 또한 client 입장에서 unknown enum 처리 정책이 없으면 깨진다 — server-side enum addition을 "additive"로만 분류하는 단순화는 위험하다.
- **`Sunset` 단독 사용**: RFC 8594는 *언제 사라지는지*만 알린다. 같은 자원이 *이미 deprecated인지*는 `Deprecation` 헤더로 함께 보내야 정합이다. Sunset만 보내면 "사라질 날짜는 알지만 지금 권장 여부는 모름" 상태가 된다.
- **`Sunset` 헤더 단독 사용 금지 — `Deprecation` draft와 paired**: IETF httpapi WG 권고에 따르면 `Sunset` 헤더는 `Deprecation` 헤더(draft-ietf-httpapi-deprecation-header, RFC 9745 진행)와 paired로 송신해야 client tooling이 deprecation 상태를 감지할 수 있다. paired invariant는 "Sunset 시점 ≥ Deprecation 시점". 추가로 `Link: <url>; rel="deprecation"` / `rel="sunset"`을 함께 보내 사람-가독 가이드를 연결한다. ca-tmpl처럼 marker만 OpenAPI에 박고 응답 헤더 paired 송신을 누락하면 외부 client interceptor가 deprecation을 자동 인지하지 못한다.
### Schema / serialization 측
- **Avro / Protobuf strict typing**: schema registry가 backward/forward 자동 검사로 강력하나, 외부 REST API가 JSON인 환경에서는 outbox / event 한정 도입이 현실적이다.
- **Smithy**: AWS SDK 친화적이지만 외부 ecosystem(예: third-party tooling, doc generator) 성숙도가 OpenAPI 대비 낮다.
- **Jackson default**: `FAIL_ON_UNKNOWN_PROPERTIES=true`는 strict inbound와 정합하나, `FAIL_ON_NULL_FOR_PRIMITIVES=false`는 null/empty/missing 분리 정책과 **불일치**다 — 명시적으로 override하지 않으면 contract가 깨진 줄도 모르고 0이 흘러간다.
- **"Jackson은 unknown field tolerant가 default"라는 오해**: 보안/계약 측면에서 unknown inbound를 silently 허용하면 typo로 인한 데이터 손실 + payload smuggling 모두 위험. strict inbound가 안전 default.
- **JSON 환경의 Protobuf `reserved` 흉내**: Protobuf는 field number / name 재사용을 wire-format 수준에서 영구 차단한다(`reserved 3, 5;` / `reserved "foo";`). OpenAPI 3.1 / JSON Schema 2020-12에는 동등 시맨틱이 없다 — `deprecated: true`*비권장* 신호일 뿐 재사용 차단이 아니고, field가 사라지면 schema에서도 사라져 미래 재사용 방지 불가. 현실적 대안은 두 가지: (1) **OpenAPI `x-removed-fields` 같은 Specification Extension**으로 schema SSOT에 catalog를 통합하고 자체 lint로 재사용 검출, (2) **별도 markdown catalog**(예: `docs/removed-fields-catalog.md`)에 제거된 이름/번호/일자 기록 후 CI에서 OpenAPI diff와 cross-check. 둘 다 표준 검증 도구가 없어 자체 도구 작성이 따라온다. (needs-confirmation)
- **`new BigDecimal(double)` 함정**: 같은 `0.1``BigDecimal.valueOf(0.1)` (정확)과 `new BigDecimal(0.1)` (부동소수 잔차)으로 갈린다. 코드 review 규칙으로 차단하지 않으면 unit test 통과 + 운영에서 1원 차이 인시던트가 흔하다.
- **ISO-8601 offset 없는 datetime**: `2026-05-22T11:30:00`는 표준상 valid이지만 timezone이 누락된다. 서버 timezone에 따라 의미가 달라지므로 contract에서는 offset 필수로 강제해야 한다. 직렬화 형식을 `WRITE_DATES_AS_TIMESTAMPS=false`로만 핀해도 `JavaTimeModule`(`jackson-datatype-jsr310`)이 등록되지 않으면 `LocalDateTime``[2026,5,22,...]` 배열로 직렬화되므로, module 등록 + effective 직렬화 동작 테스트가 함께 필요하다.
- **naming strategy 변경 = 전역 breaking change**: snake_case ↔ camelCase 같은 `PropertyNamingStrategy` 전역 변경은 모든 응답 field 이름이 바뀌는 것과 같아 deprecation window 없이 적용하면 client 가 일제히 깨진다. naming 은 초기에 고정하고 이후 변경을 breaking change catalog 대상으로 다뤄야 한다.
- **`@JsonInclude(NON_NULL)` 의 의미 손실**: null 생략은 payload 를 줄이지만 "값이 null" 과 "field 부재" 를 구분 불가하게 만든다. 부분 갱신(PATCH/merge-patch) contract 에서는 이 구분이 의미를 가지므로 3-상태(`JsonNullable`/`Optional`) 표현을 별도로 둬야 하고, 무분별한 NON_NULL 전역 적용은 이 의미 분리를 무너뜨린다.
### 흔한 오해
- "Stripe 방식이 표준이다" — IETF/W3C 표준이 아니고 진영별 사례다. 외부 결제 컨슈머 규모를 가정한 trade-off의 결과다.
- "`Sunset` 헤더만 보내면 deprecation은 끝이다" — 잘못. `Deprecation` 헤더(현재 진행 중인지)와 `Sunset` 헤더(언제 사라지는지)는 함께 사용해야 정합이다.
- "Jackson은 unknown field tolerant가 안전한 default다" — 잘못. inbound strict가 보안/계약 안전 default이고, outbound는 schema에 없는 field가 노출되지 않도록 controlled해야 한다(소위 **strict inbound / tolerant outbound**가 아니라 "strict inbound / schema-controlled outbound"가 정확).
- "enum 값 추가는 무조건 additive다" — server-side 입장에서는 additive지만 client 입장에서는 unknown enum 처리 정책이 없으면 깨진다. client side에 unknown enum fallback이 contract로 명시되어야 비로소 additive다.
## Project Application
- [[wiki/projects/ca-tmpl/api-evolution-and-schema]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
- [[raw/project-notes/ca-skeleton-operational-contract]] §13 API Contract Surface / §16 Schema / Serialization Contract / §18 API Compatibility / Deprecation / §29 G-F (외부 근거 인덱스)
- [[raw/branch-notes/feature-api-compatibility-deprecation-contract]] — breaking change catalog(7행), 90d/30d migration window, OpenAPI `deprecated: true` marker, Sunset 헤더 채택
- [[raw/branch-notes/feature-schema-serialization-contract]] — ISO-8601 offset/UTC, BigDecimal scale 2 + HALF_UP, unknown field strict inbound, null/empty/missing 의미 분리
위 branch-note들이 (a) breaking change 7 분류 + migration window + deprecation marker 위치, (b) serialization producer 책임(date/time/money/enum/null/unknown)을 계약으로 둔다. canonical 승급 여부와 검증 등급은 해당 project 문서가 판정한다.
ca-tmpl 의 **HTTP contract surface (versioning/pagination/conditional/cache/OpenAPI)** 는 위 두 축과 달리 실제 코드로 구현·로컬 검증됐다 — 구현 사실과 검증 등급은 [[wiki/projects/ca-tmpl/api-evolution-and-schema]] 의 "API contract baseline 구현" 절 참조.
## Claim-backed Knowledge
> 각 Knowledge Point 는 이미 §Sources 에 인용된 자료로만 뒷받침된다. company-tech-blog 출처는 사례일 뿐 official best practice 로 격상하지 않는다.
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| `Sunset` 헤더는 자원이 응답 불가가 될 시점을 HTTP-date 로 알리며 `Deprecation` 헤더와 paired 송신해야 client tooling 이 deprecation 상태를 감지 | [[raw/official-docs/compat-rfc-8594-sunset-header]], [[raw/official-docs/sunset-deprecation-headers-paired-usage]] | high | `official-standard`(RFC 8594) + IETF httpapi draft. "Sunset 단독 충분" 금지. invariant: Sunset 시점 ≥ Deprecation 시점 |
| Google AIP-180 은 enum 제거/의미변경, 응답 필드 제거, 기본값 변경, required request field 추가를 breaking 으로 분류 | [[raw/official-docs/api-versioning-google-aip-180]] | high | `official-reference` (Google community guideline, IETF/W3C 표준 아님). additive 만 minor 허용 |
| Jackson `FAIL_ON_UNKNOWN_PROPERTIES` default `true` (strict inbound) 이나 `FAIL_ON_NULL_FOR_PRIMITIVES` default `false` (null/missing primitive → 묵시적 0) | [[raw/official-docs/schema-jackson-unknown-field-handling]] | high | `official-vendor-doc`. "Jackson default 가 안전" 금지 — 후자는 명시 override 필요 |
| `new BigDecimal(double)` 은 부동소수 잔차를 남기므로 `BigDecimal.valueOf` + `setScale(2, HALF_UP)` + JSON string 직렬화 권고 | [[raw/official-docs/schema-bigdecimal-money-serialization-java]] | high | `official-vendor-doc`. client 부동소수 손실 회피 |
| ISO-8601 offset datetime 이 timezone ambiguity 회피의 정석, offset 없는 표현은 서버 timezone 의존 | [[raw/official-docs/schema-jackson-unknown-field-handling]] | medium | wire 계약에서 offset 강제 근거 (ISO-8601 일반 상식 + Jackson 직렬화 자료) |
| OpenAPI 3.1 은 JSON Schema 2020-12 정합의 machine-readable HTTP API contract 이며 `deprecated: true` marker 를 schema/operation 양쪽에 둘 수 있음 | [[raw/official-docs/openapi-spec-3-1-0]] | high | `official-standard`(OAS/Linux Foundation). "marker 만으로 client 가 알아서 migrate" 금지 |
| Protobuf `reserved` 는 field number/name 재사용을 wire-format 수준에서 영구 차단하나 OpenAPI/JSON Schema 에는 동등 시맨틱이 없음 | [[raw/official-docs/schema-protobuf-vs-json-evolution]], [[raw/official-docs/protobuf-reserved-vs-json-openapi-extension]] | medium | `official-reference`. "JSON 에서 완벽 흉내" 금지 — `x-` extension + 자체 lint 필요, needs-confirmation |
| RFC 9110 conditional request: `ETag` validator + `If-Match`(write, strong comparison MUST)→412 + `If-None-Match`(read)→304; RFC 9111 cache directive(`no-store`/`private`/`public`/`max-age`) + `Vary` 로 cache poisoning 방지 | [[raw/official-docs/rfc9110-http-semantics]], [[raw/official-docs/rfc9111-http-caching]] | high | `official-standard`(IETF). ca-tmpl 의 weak/lenient `If-Match` 비교는 skeleton 단순화 — project 문서 참조 |
| Pagination: AIP-158 은 page token opaque+URL-safe MUST, server-side size cap SHOULD coerce, empty next-token = EoC. JSON:API 는 `links` 의 first/last/prev/next 위치 정의 | [[raw/official-docs/spring-data-pageable-defaults]] (offset/zero-indexed) | medium | `official-vendor-doc`(Spring). size cap 숫자/TTL 은 표준 아닌 구현 trade-off |
## 내가 설명할 수 있어야 하는 것
- **API evolution 의 세 영역 분리**: compatibility/deprecation vs schema/serialization vs HTTP contract surface (versioning/pagination/conditional/cache). 세 영역이 framework default 가 아니라 명시 계약이어야 하는 이유.
- **`Sunset` vs `Deprecation` 헤더의 역할 분리**와 paired 송신 이유, paired invariant.
- **breaking change 분류 기준** (enum 축소/제거, 응답 필드 제거, 기본값 변경, required request field 추가) 과 "internal API 니까 그냥 한다" 가 위험한 이유 (client deploy lag).
- **strict inbound / schema-controlled outbound** 의 정확한 의미와 Jackson 의 두 feature default 차이.
- **money 직렬화**에서 `double` 위험 / `BigDecimal.valueOf` / HALF_UP / JSON string 직렬화 근거.
- **conditional request** 가 DB optimistic lock 과 같은 충돌의 HTTP 표현이라는 점 (ETag → If-Match → 412, If-None-Match → 304), strong vs weak comparison 차이.
- **인증 API 의 안전한 cache default = `no-store`** + `Vary` 가 cache poisoning 을 막는 원리.
- **offset vs cursor pagination** trade-off, size cap 이 DoS 방어인 이유, page token opacity 의 의미.
- **transport error 의미 구분** (406 vs 415, 405 + `Allow`, 413/414) 을 같은 code 로 뭉개면 안 되는 이유.
## Interview Questions
- **90d public + 30d internal migration window**의 근거는? 더 짧게/길게 잡으면 어떤 비용이 생기는지? Stripe(freeze forever)나 GitHub(24mo EOL)와 비교했을 때 internal-first 환경에서 90d가 합리적인 이유는?
- **`Sunset` 헤더와 `Deprecation` 헤더의 차이**는? 둘 중 하나만 보내면 client 입장에서 어떤 정보가 빠지는지?
- **enum value 추가/제거가 breaking change**가 되는 이유는? client side에 unknown enum fallback이 있을 때와 없을 때 분류가 어떻게 달라지는지?
- **strict inbound / tolerant outbound**가 무슨 의미인지? Jackson `FAIL_ON_UNKNOWN_PROPERTIES``FAIL_ON_NULL_FOR_PRIMITIVES`는 default가 어떻게 잡혀 있고, 어느 쪽을 override해야 하는지?
- **money 직렬화에서 `BigDecimal` scale 2 + HALF_UP**을 택한 이유는? `double`이 위험한 이유, `new BigDecimal(double)` 함정, JSON string 직렬화로 client 부동소수 손실을 회피하는 이유를 설명할 수 있는지?
## Do Not Overclaim
- "Stripe 방식이 API versioning의 표준이다"라고 말하면 안 된다 — 진영별 사례이며 외부 결제 컨슈머 규모에 특화된 trade-off다.
- "`Sunset` 헤더만 보내면 deprecation 정책으로 충분하다"라고 말하면 안 된다 — `Deprecation` 헤더와 함께 사용해야 정합이다.
- "OpenAPI `deprecated: true`로 표시했으니 client가 알아서 migration한다"라고 단정하면 안 된다 — schema marker는 신호일 뿐이고 실제 cutover는 migration window + contract test + compatibility fixture가 함께 강제해야 한다.
- "Jackson default가 안전하다"고 단정하면 안 된다 — `FAIL_ON_UNKNOWN_PROPERTIES`는 strict default이지만 `FAIL_ON_NULL_FOR_PRIMITIVES`는 lenient라 null/missing primitive가 묵시적으로 0이 된다.
- "Avro / Protobuf로 가면 schema evolution이 자동 검사된다"라고 일반화하면 안 된다 — registry 인프라(예: Confluent Schema Registry)와 wire format 변경 비용이 따라온다. 외부 REST가 JSON인 환경에서는 outbox/event 한정 도입이 현실적이다.
- "narrow enum / 응답 필드 제거 / 필드 rename"을 "internal API니까 그냥 한다"라고 정당화하면 안 된다 — client가 deploy lag을 가지면 internal에서도 breaking이다.
## Sources
### 공식 표준 / 표준 후보
- [[raw/official-docs/compat-rfc-8594-sunset-header]] — IETF RFC 8594 (HTTP `Sunset` header)
- [[raw/official-docs/sunset-deprecation-headers-paired-usage]] — IETF RFC 8594 + Deprecation draft paired 사용 권고 (Sunset 단독 금지)
- [[raw/official-docs/api-versioning-google-aip-180]] — Google AIP-180 (Backwards compatibility 분류)
- [[raw/official-docs/schema-jackson-unknown-field-handling]] — Jackson DeserializationFeature default
- [[raw/official-docs/schema-bigdecimal-money-serialization-java]] — Java BigDecimal scale/HALF_UP + JSON string 직렬화
- [[raw/official-docs/schema-avro-evolution-rules]] — Avro backward/forward/full compatibility
- [[raw/official-docs/schema-protobuf-vs-json-evolution]] — Protobuf `reserved` field semantics
- [[raw/official-docs/protobuf-reserved-vs-json-openapi-extension]] — Protobuf `reserved` 시맨틱의 JSON/OpenAPI 환경 흉내 대안 비교 (G-F follow-up, needs-confirmation)
- [[raw/official-docs/rfc9110-http-semantics]] — IETF RFC 9110 (HTTP Semantics): conditional request(ETag/If-Match/If-None-Match/304/412), transport error(406/413/414/415/405+Allow), HEAD/OPTIONS, 202+Retry-After, Vary
- [[raw/official-docs/rfc9111-http-caching]] — IETF RFC 9111 (HTTP Caching): `no-store`/`private`/`public`/`max-age` directive
- [[raw/official-docs/openapi-spec-3-1-0]] — OpenAPI 3.1.0 (machine-readable HTTP API contract, JSON Schema 2020-12 정합)
- [[raw/official-docs/google-aip-185-resource-versioning]] — Google AIP-185 (major-only `/v1` path versioning)
- [[raw/official-docs/google-aip-158-pagination]] — Google AIP-158 (page token opacity + size cap + EoC)
- [[raw/official-docs/jsonapi-pagination-format]] — JSON:API pagination link key/위치
- [[raw/official-docs/google-aip-151-long-running-operations]] — Google AIP-151 (LRO Operation shape + polling)
- [[raw/official-docs/spring-data-pageable-defaults]] — Spring Data `Pageable` zero-indexed + size default + `DEFAULT_MAX_PAGE_SIZE` 2000
### 진영별 사례 (표준 아님)
- [[raw/company-tech-blogs/api-versioning-stripe-date-based]] — Stripe date-based versioning (account pin + freeze)
- [[raw/company-tech-blogs/api-versioning-github-rest-date-header]] — GitHub `X-GitHub-Api-Version` + 24mo EOL + `410 Gone`
### Canonical (프로젝트 결정 사실)
- [[raw/project-notes/ca-skeleton-operational-contract]] §13 / §16 / §18 API Compatibility / Deprecation / §29 G-F
- [[raw/branch-notes/feature-api-compatibility-deprecation-contract]]
- [[raw/branch-notes/feature-schema-serialization-contract]]
## Cluster / 묶음
<!-- GENERATED: derived-blogs:start -->
- [[wiki/blog/ca-tmpl-api-evolution-and-schema-2026-07-02]]
<!-- GENERATED: derived-blogs:end -->
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/archunit-scope-classpath-vs-package-filter.md
@@ -0,0 +1,81 @@
---
title: ArchUnit 분석 scope — import scope(어떤 클래스가 검사되는가) vs classpath 의존성(어떻게 검사하는가)
source_type: llm-generated
status: draft
confidence: medium
tags: [archunit, clean-architecture, testing, static-analysis, jvm]
related_projects: [ca-skeleton]
last_reviewed: 2026-06-04
---
# ArchUnit 분석 scope — import scope(어떤 클래스가 검사되는가) vs classpath 의존성(어떻게 검사하는가)
> Layer: `wiki/concepts/` — 일반 개념. 내 프로젝트 사실(`wiki/projects/`)은 `wiki-project-template` 사용.
## Summary
ArchUnit rule의 결과는 두 개의 독립적인 축에 의해 결정된다. (1) **import scope**`ClassFileImporter`/`@AnalyzeClasses`가 어떤 class를 분석 대상 집합(`JavaClasses`)으로 끌어왔는가. (2) **classpath 의존성** — 그 class를 분석할 때 ArchUnit이 JVM classpath(reflection)에 의존하는가, 아니면 bytecode만 읽는가. 첫 번째 축을 잘못 잡으면 검사하려던 class가 아예 집합에 없어 rule이 *vacuous하게* 통과한다(false-negative). 두 번째 축은 대부분의 default rule에서 무관하지만 strongly-typed annotation 접근 같은 일부 ergonomics에만 영향을 준다.
## Standard (공식 정의)
- **Import 진입점**: class import의 표준 진입점은 `new ClassFileImporter().importPackages("<base-package>")`이며, JUnit 통합에서는 `@AnalyzeClasses(packages = ...)`가 같은 역할을 한다. `importPackages(...)`는 varargs라 다중 package를 받을 수 있고, "단일 root package만 가능"하다는 의미가 아니다. 출처: [[raw/official-docs/archunit-user-guide]] (ARCHUNIT-UG-C2).
- **import은 classpath와 무관**: ArchUnit은 classpath/JAR/folder 어디서 import했는지와 무관하게 `JavaClasses`를 구성할 수 있다. 즉 import scope는 "어떤 `.class` 파일을 읽었는가"의 문제이지 "그 class가 현재 test의 classpath에 있는가"와 자동으로 같지 않다. 출처: [[raw/official-docs/archunit-conditional-on-property-3-layer-pattern]] (AUCP-C4).
- **rule 평가는 classpath에 의존하지 않음**: ArchUnit 자체의 rule API와 default rule + syntax 조합 평가는 classpath에 의존하지 않는다. 출처: [[raw/official-docs/archunit-conditional-on-property-3-layer-pattern]] (AUCP-C4).
- **classpath가 영향을 주는 곳**: classpath가 있으면 annotation을 `javaClass.getAnnotationOfType(CustomAnnotation.class).value()`처럼 strongly-typed로 접근할 수 있고, 없으면 `JavaAnnotation<?>` + `Object value = annotation.get("value")` 같은 untyped 접근을 써야 한다. 출처: [[raw/official-docs/archunit-conditional-on-property-3-layer-pattern]] (AUCP-C2, AUCP-C3).
- **rule 평가 흐름**: rule은 `ArchRule` 객체로 표현되고 `myRule.check(importedClasses)` 또는 `@ArchTest`로 평가된다. `@ArchTest`가 붙은 rule은 지정된 class를 자동 import(또는 재사용)해 평가한다. 출처: [[raw/official-docs/archunit-user-guide]] (ARCHUNIT-UG-C3, ARCHUNIT-UG-C6).
## 한계 / 주의점
- **package filter가 import scope를 보장하지 않는다**: rule의 `that().resideInAPackage("..application..")`*이미 import된 집합 안에서* 필터링할 뿐이다. 해당 package의 class가 import scope(`@AnalyzeClasses(packages=...)` 또는 test classpath)에 애초에 없으면, 위반 코드가 존재해도 매칭 대상이 0개가 되어 rule이 통과한다. 즉 "package glob을 썼으니 그 package를 다 본다"는 착각이 가장 흔한 실패 모드다.
- **두 가지 빈-집합 동작이 다르다**: (a) `that()` 결과가 비면 ArchUnit은 기본적으로 `failed to check any classes` 에러를 낸다 — 이때는 *눈에 보이는* 실패다. 빈 anchor module이 의도된 상태라면 `allowEmptyShould(true)`로 명시적으로 허용해야 한다. (b) 그러나 검사 대상 class가 *import scope 자체에 빠져* 있으면 ArchUnit은 그것을 "정상 평가했고 위반 0건"으로 인식해 `failed to check any classes` 에러조차 내지 않고 `BUILD SUCCESSFUL`로 통과한다 — 이 vacuous pass가 더 위험하다(에러 신호가 없으므로).
- **`allowEmptyShould(true)`는 양날의 검**: 빈 anchor를 합법화하지만, 동시에 import scope 누락으로 인한 vacuous pass도 똑같이 통과시켜 버린다. 따라서 빈-집합 허용 정책만으로는 rule이 *실제로* 위반을 잡는지 보증할 수 없다.
- **권장 보완**: (1) 검사 대상이 될 수 있는 module/package(예: sample·fixture)를 test의 import scope에 명시적으로 포함시킨다(예: Gradle `testImplementation project(':<sample>')`). (2) "위반을 데이터로 보는(violations-as-data)" negative fixture를 두고, 의도된 위반 class에 대해 `rule.evaluate(fixtureClasses).hasViolation() == true`를 별도 test로 assert해 rule이 진짜 catch하는지 commit으로 보증한다.
- **classpath 의존성과 import scope를 혼동하지 말 것**: "classpath에 없어서 못 잡았다"와 "import scope에 안 넣어서 못 잡았다"는 다른 문제다. 전자는 주로 annotation ergonomics(typed accessor)에만 영향을 주고, false-negative의 실제 원인은 거의 항상 후자(import scope 누락)다. 두 축을 섞어 진단하면 엉뚱한 곳을 고친다. (이 구분의 정밀한 경계는 ArchUnit 버전·import 옵션에 따라 달라질 수 있어 `needs-confirmation`)
## Project Application
이 개념과 관련된 내 프로젝트 사실·검증 등급은 아래 project 문서에서 판정한다(concept 문서는 등급을 직접 매기지 않는다).
- [[wiki/projects/ca-tmpl/clean-architecture-package-layout]] — ca-tmpl의 `CleanArchitectureTest``@AnalyzeClasses(packages = "dev.caskeleton", importOptions = DoNotIncludeTests.class)`로 import scope를 잡고, `allowEmptyShould(true)`로 빈 anchor를 허용하며, `ArchitectureViolationFixtureTest`(violations-as-data)로 각 rule의 catch 동작을 보증하는 실제 적용.
- [[wiki/concepts/clean-architecture-package-layout]] — 경계 강제(enforcement)의 두 축(build-graph 검사 vs source/bytecode import 검사) 일반 지식.
## Claim-backed Knowledge
> 이 개념 문서의 핵심 설명은 raw source claim으로 뒷받침되어야 한다. 공식 문서 claim과 내 프로젝트 트러블슈팅 사실을 분리한다.
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| import 진입점은 `ClassFileImporter().importPackages(...)`이며 varargs로 다중 package 가능(단일 root 강제 아님) | `raw/official-docs/archunit-user-guide.md#ARCHUNIT-UG-C2` | high | 공식 vendor doc |
| ArchUnit rule API/default rule 평가는 classpath(reflection)에 의존하지 않으며, classpath/JAR/folder 어디서 import했는지와 무관 | `raw/official-docs/archunit-conditional-on-property-3-layer-pattern.md#AUCP-C4` | high | 공식 vendor doc. "import scope ≠ classpath presence"의 근거 |
| annotation 접근 ergonomics만 classpath에 의존(있으면 typed `.value()`, 없으면 untyped `JavaAnnotation.get("value")`) | `raw/official-docs/archunit-conditional-on-property-3-layer-pattern.md#AUCP-C2`, `#AUCP-C3` | high | classpath가 영향을 주는 *유일한* 좁은 지점 |
| rule은 `ArchRule.check(classes)` / `@ArchTest`로 평가되고, `@ArchTest`는 지정 class를 자동 import해 평가 | `raw/official-docs/archunit-user-guide.md#ARCHUNIT-UG-C3`, `#ARCHUNIT-UG-C6` | high | 공식 vendor doc |
| `that()` 매칭 결과가 비면 기본적으로 `failed to check any classes` 실패 — 빈 anchor가 의도면 `allowEmptyShould(true)` 필요 | `raw/errors/archunit-empty-should-anchor-2026-05-27.md` | medium | 프로젝트 트러블슈팅 사실(`error-note`). 빈 *should* 동작 |
| 검사 대상 class가 import scope에 빠지면 위반이 있어도 vacuous pass(`BUILD SUCCESSFUL`, 에러 신호 없음) — sample/fixture를 test import scope에 포함 + negative fixture로 보완 | `raw/errors/archunit-test-scope-sample-ticket-inclusion-2026-05-28.md` | medium | 프로젝트 트러블슈팅 사실(`error-note`). 빈 *that* / import-scope 누락 동작 |
## 내가 설명할 수 있어야 하는 것
- ArchUnit의 import scope와 classpath 의존성은 각각 무엇을 결정하는가?
- package glob(`..application..`)을 썼는데도 위반을 놓치는 경우는 왜 생기는가?
- `failed to check any classes` 에러가 *나는* 경우와 *나지 않고 통과해 버리는* 경우의 차이는 무엇인가?
- `allowEmptyShould(true)`는 무엇을 허용하고, 무엇을 ** 막는가?
- vacuous pass를 어떻게 commit 수준에서 막는가(violations-as-data)?
## Interview Questions
- ArchUnit rule이 통과했는데도 실제로는 boundary가 깨져 있을 수 있는 시나리오는? 어떻게 방지하는가?
- ArchUnit의 분석이 JVM classpath에 의존하는 부분과 의존하지 않는 부분은 각각 무엇인가?
- 빈 anchor package가 많은 skeleton에서 architecture test를 신뢰 가능하게 유지하려면 무엇이 필요한가?
## Do Not Overclaim
- "package glob을 쓰면 그 package의 모든 class를 검사한다"는 단정 금지. 검사 대상은 *import scope ∩ glob*이며, scope에 없으면 검사되지 않는다.
- "ArchUnit은 classpath가 필요하다/필요 없다"는 단정 금지. default rule 평가는 classpath 독립이지만 typed annotation 접근 같은 ergonomics는 classpath에 의존한다 — 부분적이다.
- "`allowEmptyShould(true)`를 켜면 안전하다"는 단정 금지. 빈 should를 허용할 뿐, import scope 누락으로 인한 vacuous pass는 막지 못한다.
- 위 빈-집합/scope 동작의 정밀한 경계는 ArchUnit 버전·import 옵션에 따라 달라질 수 있어 일부는 `needs-confirmation`이다.
## Sources
- [[raw/official-docs/archunit-user-guide]] — ArchUnit User Guide (import 진입점, rule 평가, JUnit 통합)
- [[raw/official-docs/archunit-conditional-on-property-3-layer-pattern]] — classpath 유무에 따른 annotation 접근 + rule API의 classpath 독립성
- [[raw/errors/archunit-empty-should-anchor-2026-05-27]] — 빈 anchor에서의 `failed to check any classes` + `allowEmptyShould` 해결(프로젝트 사실)
- [[raw/errors/archunit-test-scope-sample-ticket-inclusion-2026-05-28]] — import scope 누락으로 인한 vacuous pass + sample module을 test scope에 포함해 해결(프로젝트 사실)
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/boundary-validation-and-dto-mapping.md
@@ -0,0 +1,86 @@
---
title: 경계 검증과 DTO↔도메인 매핑 (Bean Validation · MapStruct vs 수기 mapper · Patch partial-update)
source_type: llm-generated
status: draft
confidence: medium
tags: [backend, validation, mapper, dto, bean-validation, boundary]
related_projects: [ca-skeleton, ca-tmpl]
last_reviewed: 2026-06-04
---
# 경계 검증과 DTO↔도메인 매핑
> Layer: `wiki/concepts/` — 일반 개념. 내 프로젝트 사실은 [[wiki/projects/ca-tmpl/boundary-validation-mapping]] 참조.
## Summary
웹 애플리케이션의 **입력 경계**(request boundary)에서는 두 가지 책임이 동시에 생긴다: (1) 들어온 데이터가 형식적으로 올바른지 **검증**하고, (2) 외부 표현(DTO)을 내부 모델(domain / command)로 **변환(mapping)** 하는 것이다.
- **Bean Validation (Jakarta Validation, JSR 380 / 3.0)**: `@NotNull`, `@Size`, `@Valid` 같은 선언적 제약을 DTO 필드/메서드에 붙여 프레임워크가 자동 검증하게 하는 표준. Spring MVC 는 컨트롤러 파라미터에 `@Valid`/`@Validated` 가 붙으면 본문 바인딩 직후 검증을 수행하고, 실패 시 `MethodArgumentNotValidException` 을 던진다.
- **validation-at-boundary 원칙**: 검증은 가능한 한 *입력 경계 한 곳* 에서 fail-fast 로 끝내고, 안쪽 레이어(application/domain)는 이미 검증된 값만 받는다는 설계. 단, 형식(syntax) 검증과 도메인 불변식(invariant) 검증은 책임이 다르므로 같은 어노테이션 한 줄로 뭉뚱그리지 않는다.
- **DTO↔domain mapping**: 외부에 노출되는 DTO 와 내부 도메인 객체를 분리하고 그 사이를 변환하는 코드. 변환 도구는 **수기(manual) mapper****MapStruct 같은 코드 생성기(generator)** 두 갈래가 있다.
- **partial-update (PATCH) semantics**: PATCH 요청에서 "필드 없음(absent) / 명시적 null / 값 있음" 세 상태를 구분해야 silent overwrite 를 막을 수 있다.
## Standard (공식 정의)
- **Jakarta Bean Validation 3.0** (official-standard): class-level constraint 는 "한 클래스의 여러 property 를 동시에 보는 상태 검증"을 위한 것이고(JBV-3.0-C1), `ConstraintValidator` 는 클래스 인스턴스를 받아 여러 필드에 동시 접근할 수 있다(JBV-3.0-C2). `@GroupSequence` 를 쓰면 group 을 순서대로 실행하다 한 group 이 실패하면 **다음 group 을 건너뛴다(short-circuit)** — syntax 검증을 먼저 통과해야 invariant 검증이 돈다는 패턴의 normative 근거(JBV-3.0-C3). `@Valid` 는 중첩 객체로 검증을 **cascade(전파)** 시킨다(JBV-3.0-C4). 단, Bean Validation 자체는 syntax/invariant 라는 **레이어 이름을 정의하지 않는다** — 그 분류는 애플리케이션 설계 결정이다.
- **Spring MVC REST exception handling** (official-vendor-doc): `HttpMessageNotReadableException`(JSON 파싱 실패) 과 `MethodArgumentNotValidException`(Bean Validation 실패) 은 모두 Spring 내장 `ErrorResponse` 구현체이고 `ResponseEntityExceptionHandler` 가 normative 하게 처리한다(SPRING-MVC-EXC-C1/C2/C4/C5). 즉 이 두 예외는 표준적으로 검증 실패(400) 카테고리로 분류된다.
- **RFC 7396 (JSON Merge Patch)** (official-standard): merge patch 에서 `null` 값은 "해당 필드 삭제"를 의미한다(RFC7396-C2). 따라서 "명시적 null" 을 다른 의미로 쓰려는 API 는 RFC 7396 merge patch 를 그대로 채택하면 충돌한다(RFC7396-C3). 배열 부분 수정도 불가하다(RFC7396-C4).
- **MapStruct** (도구): 컴파일 타임에 mapper 구현 코드를 생성하는 어노테이션 프로세서. 리플렉션 없이 동작하지만, 생성된 코드가 architecture 규칙(예: 도메인 직접 접근 금지)을 우회할 수 있어 별도 exemption 관리가 필요하다. (※ MapStruct 도구 선택 자체는 공식 표준이 권고하는 사항이 아니라 프로젝트 trade-off 결정이다.)
## 한계 / 주의점
- **4-layer validation 분류(syntax / policy / invariant / persistence integrity)는 표준이 아니다.** Bean Validation spec 은 이런 taxonomy 를 정의하지 않는다. 레이어를 나누는 것은 설계 결정이며, 잘못 나누면 같은 검증이 두 곳에서 중복되거나 빠진다.
- **MapStruct vs 수기 mapper 는 정답이 없는 trade-off.** 수기 mapper 는 boilerplate 가 많지만 동작이 투명하다. MapStruct 는 코드량을 줄이지만 generated code 가 architecture 경계를 silent 하게 leak 할 수 있고, 매핑 누락이 컴파일 시점에 드러나지 않을 수 있다.
- **PATCH 의 null/absent 혼동**은 흔한 버그다. Java record 의 기본 매핑으로 PATCH 를 구현하면 요청에 없던 필드가 `null` 로 들어와 기존 값을 덮어쓰는 silent overwrite 가 발생한다. `Optional<T>` 또는 `JsonNullable<T>`(openapi-generator) 같은 3-state wrapper 가 필요하다.
- **검증을 경계에서만 한다고 도메인 불변식이 보장되지는 않는다.** 형식 검증(DTO)과 도메인 불변식(application/domain)은 별개다. DTO 검증만으로 "도메인이 안전하다"고 말하면 안 된다.
- **`@Valid` cascade 의 무한/깊은 재귀**는 DoS 표면이 될 수 있다. 중첩 깊이에 상한을 두는 것은 spec 이 아니라 운영적 방어 결정이다.
## Project Application
- ca-tmpl 은 입력 경계의 검증/매핑 책임을 명시적으로 고정하고, 일부 정책을 ArchUnit fitness function 으로 정적 강제했다. 구체적 구현 사실·검증 등급은 [[wiki/projects/ca-tmpl/boundary-validation-mapping]] 참조.
- 관련 트랜잭션 경계 추상화는 [[wiki/concepts/transaction-boundary-abstraction]] / [[wiki/projects/ca-tmpl/transaction-boundary-abstraction]].
## Claim-backed Knowledge
> 아래는 본 개념을 뒷받침하는 raw official-doc claim 인용. company-tech-blog 는 사례일 뿐 공식 best practice 로 격상하지 않는다.
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| class-level constraint 는 한 클래스의 여러 property 상태를 함께 검증한다 | [[raw/official-docs/validation-jakarta-bean-validation-3.0-spec]] JBV-3.0-C1 | high | constraint 의 *목적* 근거. syntax/invariant 레이어 이름은 spec 미규정 |
| `@GroupSequence` 는 group 을 순차 실행하다 실패 시 후속 group 을 short-circuit 한다 | [[raw/official-docs/validation-jakarta-bean-validation-3.0-spec]] JBV-3.0-C3 | high | syntax→invariant 단계 분리 패턴의 normative 근거 |
| `@Valid` 는 중첩 객체로 검증을 cascade 한다 | [[raw/official-docs/validation-jakarta-bean-validation-3.0-spec]] JBV-3.0-C4 | high | cascade *메커니즘* 근거. depth 상한은 설계 결정 (spec 미규정) |
| `HttpMessageNotReadableException` 은 Spring 이 normative 하게 처리하는 내장 예외 | [[raw/official-docs/spring-mvc-rest-exception-handling]] SPRING-MVC-EXC-C4 | high | JSON 파싱 실패 → 검증(400) 분류 근거 |
| `MethodArgumentNotValidException` 은 field error 를 담아 normative 처리된다 | [[raw/official-docs/spring-mvc-rest-exception-handling]] SPRING-MVC-EXC-C5 | high | Bean Validation 실패 → 검증(400) + field error shape 근거 |
| JSON Merge Patch 의 `null` 은 필드 삭제를 의미한다 | [[raw/official-docs/patch-json-merge-rfc7396]] RFC7396-C2 | high | PATCH 에서 null/absent 구분이 필요한 이유. ca-tmpl 은 merge patch *미채택* |
## 내가 설명할 수 있어야 하는 것
- Bean Validation 의 `@Valid`/`@Validated`/`@GroupSequence` 가 각각 무엇이고, syntax 검증과 도메인 invariant 검증을 왜 분리하는가.
- `MethodArgumentNotValidException``HttpMessageNotReadableException` 이 왜 둘 다 "검증 실패(400)" 로 분류되는가, mapper 내부 예외는 왜 별도 카테고리가 필요한가.
- DTO↔domain mapping 에서 MapStruct 와 수기 mapper 의 trade-off (boilerplate vs architecture leak / 컴파일 안전성).
- PATCH 의 absent / explicit-null / value 3-state 를 구분하지 않으면 어떤 버그(silent overwrite)가 생기는가, `Optional`/`JsonNullable` 로 어떻게 구분하는가.
- RFC 7396 merge patch 의 null=deletion semantics 와, 이를 채택하지 않는 API 가 왜 `application/merge-patch+json` content type 을 쓰면 안 되는가.
## Interview Questions
- "request 검증을 어디서 하나요? 컨트롤러? 서비스? 도메인?" → 형식 검증은 경계(DTO), 도메인 불변식은 application/domain. 한 줄 어노테이션으로 다 끝낸다는 답은 위험.
- "`@Valid``@Validated` 차이는?" → `@Validated` 는 Spring 의 group 지원 + 메서드 레벨 검증, `@Valid` 는 표준 cascade.
- "PATCH 에서 어떤 필드만 바꾸고 싶을 때 null 을 어떻게 처리하나요?" → absent vs explicit-null 구분, 3-state wrapper.
- "DTO 와 도메인 객체를 왜 분리하나요? MapStruct 와 수기 매핑 중 무엇을 쓰나요?" → 노출 경계 분리 + 도구 trade-off.
## Do Not Overclaim
- **"Bean Validation 이 syntax/invariant 를 알아서 나눠준다" → 금지.** spec 은 레이어를 정의하지 않는다. `@GroupSequence`*순서* 는 줄 수 있지만 분류는 설계자가 한다.
- **"MapStruct 가 수기 mapper 보다 우월하다" → 금지.** generated code 의 architecture leak / 매핑 누락 trade-off 가 있다.
- **"DTO 검증을 했으니 도메인이 안전하다" → 금지.** 형식 검증과 도메인 불변식은 별개.
- **"PATCH 의 null 은 항상 삭제다(RFC 7396)" → 단정 금지.** RFC 7396 의 정의일 뿐, 이를 채택하지 않는 API 도 많다.
## Sources
- [[raw/official-docs/validation-jakarta-bean-validation-3.0-spec]] — Jakarta Bean Validation 3.0 normative (class-level constraint, group sequence, `@Valid` cascade)
- [[raw/official-docs/spring-mvc-rest-exception-handling]] — Spring MVC `ResponseEntityExceptionHandler` 처리 예외 목록 (`HttpMessageNotReadableException` / `MethodArgumentNotValidException`)
- [[raw/official-docs/patch-json-merge-rfc7396]] — RFC 7396 JSON Merge Patch (null=deletion semantics)
- [[raw/official-docs/schema-jackson-polymorphic-deserialization]] — Jackson polymorphic deserialization 보안 지침 (allowlist, CVE-2019-14379) — 경계 역직렬화 보안 맥락
- [[raw/branch-notes/feature-boundary-validation-mapping-contract]] — 본 개념을 도출한 ca-tmpl 경계 검증/매핑 계약 branch
- [[wiki/projects/ca-tmpl/boundary-validation-mapping]] — 내 프로젝트 적용 사실
-1
View File
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/circuit-breaker.md
+64
View File
@@ -0,0 +1,64 @@
---
title: concept / Circuit Breaker
source_type: llm-generated
status: reviewed
confidence: high
tags: [concept, ca-tmpl, architecture, spring-boot, circuit-breaker]
related_projects: [ca-tmpl]
last_reviewed: 2026-06-15
---
# concept / Circuit Breaker
## Summary
외부 서비스(의존성) 호출의 실패율을 감시하여, 실패율이 임계치를 초과하면 연동을 즉시 차단(OPEN)함으로써 시스템 전체로 장애가 전파되는 것을 차단하고 빠른 실패(Fail-Fast)를 유도하는 리질리언스 패턴.
## Standard (공식 정의)
서킷 브레이커는 크게 세 가지 상태를 가지며, 유한 상태 머신(FSM)으로 동작한다.
- **CLOSED**: 정상 상태. 모든 요청을 외부 서비스로 통과시킨다. 최근 N개 호출(Count-Based) 또는 T초간 호출(Time-Based)의 실패율을 측정한다.
- **OPEN**: 차단 상태. 외부 서비스로 요청을 보내지 않고 즉시 예외(CallNotPermittedException)를 던져 빠른 실패를 유도한다. 특정 대기 시간(Wait Duration)이 지나면 HALF_OPEN 상태로 전이한다.
- **HALF_OPEN**: 감시 통과 상태. 설정된 횟수만큼 제한된 요청을 외부로 전송하여 성공 여부를 측정한다. 만약 재발한 실패율이 임계치 이하면 CLOSED로 복귀하고, 또다시 임계치를 초과하면 OPEN으로 회귀한다.
## 한계 / 주의점
- **지표 누수(Metric Cardinality Explosion)**: Resilience4j 등 라이브러리는 기본적으로 매우 세부적인 게이지와 카운터 지표(예: slow call rate, buffered calls 등)를 대량 방출한다. 이를 모니터링 시스템(Prometheus 등)에 그대로 전송하면 시계열 데이터 개수가 급증하여 저장소 과부하를 초래한다. 실무에서는 엄격히 합의된 저카디널리티(low-cardinality) 필수 지표만 필터링하여 통과시켜야 한다.
- **Retry와의 충돌**: 서킷 브레이커와 리트라이를 무작정 함께 배치하면, 하나의 외부 요청 실패가 리트라이 3회로 증폭되어 서킷 브레이커가 오작동하거나 윈도우 슬라이딩의 실패율이 왜곡될 수 있다.
## Project Application
- [[wiki/explainer/adapter-outbound.md]]
- `OutboundHttpResilience`에서 각 의존성별로 독립된 `CircuitBreaker``Retry`를 구성함.
- `OutboundHttpResilienceConfig`에서 D3/D4 가이드라인을 강제하여:
- 리질리언스를 켤 때 지표 수집기(`MeterRegistry`)가 없으면 애플리케이션 기동을 에러로 즉시 차단(Activation Guard).
- Prometheus 지표 수집을 위해 `resilience4j.retry.calls`, `resilience4j.circuitbreaker.calls`, `resilience4j.circuitbreaker.state` 딱 3가지 필수 지표만 허용하고 나머지는 강제 차단(Deny Filter)함.
- 가시성을 높이기 위해 벤더 사양의 태그를 `outcome` (SUCCESS/FAILURE) 및 대문자 `state` (CLOSED, OPEN, HALF_OPEN)로 정형화(Metric Normalisation)하여 바인딩함.
## Claim-backed Knowledge
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| 서킷 브레이커의 표준 구조 및 Resilience4j 사양 | `raw/official-docs/outbound-resilience4j-vs-spring-retry.md` | `high` | Resilience4j 공식 사양 |
| 지표 카디널리티 폭발 문제 및 모니터링 필터링 규칙 | `raw/official-docs/resilience4j-micrometer-module.md` | `high` | Micrometer 통합 모범 사례 |
## 내가 설명할 수 있어야 하는 것
- 서킷 브레이커의 세 가지 상태와 그 전이 조건은 무엇인가?
- 왜 리트라이와 서킷 브레이커를 결합할 때 데코레이팅 순서가 중요한가? (CB가 Retry의 바깥쪽에 위치해야 각 재시도 실패가 개별적으로 서킷 실패율에 반영되지 않고 전체 실패로 깔끔하게 묶이거나, 혹은 구조에 따라 왜곡이 발생할 수 있음을 알아야 한다.)
- 카디널리티 폭발(Metric Cardinality Explosion)이란 무엇이며, 우리 프로젝트는 이를 어떻게 대처했는가?
## Interview Questions
- 마이크로서비스 환경에서 서킷 브레이커의 필요성과 작동 방식(FSM)을 설명하십시오.
- 서킷 브레이커를 적용한 후 모니터링 시스템의 시계열 부하(Cardinality)가 급증하는 문제를 해결하기 위해 구체적으로 어떤 조치를 취할 수 있습니까?
## Do Not Overclaim
- "서킷 브레이커가 동작하면 분산 시스템의 네트워크 순단에 대비해 무조건 가용성이 높아진다"고 단정하면 안 된다. 서킷이 열려 있는(OPEN) 동안은 정상 요청조차 즉시 거절되므로, 가용성은 일시적으로 0이 된다. 서킷 브레이커의 목표는 가용성 향상뿐 아니라 **호출 측의 스레드 고갈 방지 및 업스트림 서버 보호**임을 명시해야 한다.
## Sources
- [Resilience4j CircuitBreaker Core Guide](https://resilience4j.readme.io/docs/circuitbreaker)
- [[raw/official-docs/outbound-resilience4j-vs-spring-retry.md]]
- [[raw/official-docs/resilience4j-micrometer-module.md]]
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/clean-architecture-package-layout.md
@@ -0,0 +1,124 @@
---
title: Clean Architecture 패키지 레이아웃 (feature-first vs layer-first vs hexagonal vs modulith vs onion)
source_type: llm-generated
status: draft
confidence: medium
tags: [clean-architecture, package-layout, hexagonal, modulith]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Clean Architecture 패키지 레이아웃 (feature-first vs layer-first vs hexagonal vs modulith vs onion)
> Layer: `wiki/concepts/` — 일반 개념. 내 프로젝트 사실은 `project-template` 사용.
## Summary
feature-first 패키지 레이아웃은 최상위를 도메인 feature(`features/{name}/`)로 자르고 그 내부에 `presentation/application/domain/infrastructure`를 두는 구조로, 각 feature가 자체 inbound/outbound adapter와 application core를 갖는다는 점에서 본질적으로 "feature 단위로 잘린 mini-Hexagonal"과 동형이다. layer-first는 최상위가 기술 계층이고 도메인이 그 안에 흩어지는 점에서 응집도 축이 정반대다.
## Standard (공식 정의)
- **Uncle Bob, Screaming Architecture (2011)**: 시스템의 최상위 디렉터리는 사용된 framework이 아니라 시스템이 "외치는" use case / business 영역이어야 한다고 주장. controller/service/repository로 자르는 layer-first는 framework가 외치는 구조라는 점을 비판한다. 출처: [[raw/official-docs/feature-first-uncle-bob-screaming-architecture-2011]].
- **Cockburn, Hexagonal (Ports and Adapters)**: 응용 코어(application + domain)를 inbound adapter(driving)와 outbound adapter(driven)로부터 port interface로 격리. driving/driven adapter 분리가 본질이며 패키지 형태 자체는 비강제. 출처: [[raw/official-docs/hexagonal-cockburn-wikipedia-summary]].
- **Thombergs, BuckPal reference**: Cockburn Hexagonal을 자바/스프링 부트로 구현한 reference. 최상위가 feature이고 내부에 `domain/application/adapter(in|out)` 3-tier로 잘려 feature-first + Hexagonal이 같은 구조에서 만난다는 점을 보여줌. 출처: [[raw/official-docs/hexagonal-thombergs-buckpal-github]].
- **Palermo, Onion Architecture (2008)**: 의존성은 외부 layer(infrastructure/UI)에서 내부 layer(domain model)로만 향하며, 안쪽이 바깥쪽 interface를 알지 않는다는 의존성 역전 규칙. layer를 동심원으로 표현. 출처: [[raw/official-docs/onion-palermo-original-2008]].
- **Spring Modulith (공식 문서)**: Spring Boot 위에서 패키지 자체가 모듈 경계가 되며 `@ApplicationModule`/named-interface로 cross-module 접근을 강제. JPA event SPI 위에서 transactional event publication 등 운영 contract를 framework가 제공. 출처: [[raw/official-docs/modulith-spring-official-doc]].
## 한계 / 주의점
각 레이아웃은 다른 트레이드오프를 가진다.
- **feature-first**
- cross-feature shared kernel(공통 value object, 공통 정책)을 어디에 둘지가 모호. `common/`을 두되 business concept가 새지 않도록 별도 규칙이 필요.
- 도메인 인접성이 강한 feature 사이에서 model 중복 위험(같은 개념을 두 feature가 따로 정의).
- feature 사이 호출은 직접 import보다는 port 또는 명시적 application API를 통해 통제해야 함 (그렇지 않으면 사실상 layer-first로 회귀).
- **layer-first**
- 도메인 수가 늘어나면 같은 도메인의 코드가 `controller/`, `service/`, `repository/`에 흩어져 응집도가 폭락. 한 도메인을 수정할 때 패키지 3~4곳을 동시에 건드림. Sahibinden 기술블로그는 이를 "패키지가 도메인을 외치지 않는다"로 비판함. 출처: [[raw/company-tech-blogs/feature-first-sahibinden-package-by-layer-vs-feature]].
- Baeldung식 Clean Architecture Spring Boot 가이드는 입문 학습 비용이 가장 낮지만 결과적으로 도메인 응집을 보장하지 않음. 출처: [[raw/official-docs/layer-first-baeldung-clean-architecture-spring-boot]], [[raw/company-tech-blogs/layer-first-kamilmazurek-github-template]].
- **hexagonal pure (feature 슬라이스 없음)**
- 최상위가 `application/domain/adapter`로만 잘리고 feature 슬라이스가 없으면 도메인이 늘어날수록 `application``domain` 패키지가 비대해짐.
- inbound/outbound 분리는 명확하지만 도메인 간 boundary가 약함. 우아한형제들 기술블로그의 Hexagonal 적용도 결국 도메인별 module로 분리하는 방향으로 진화. 출처: [[raw/company-tech-blogs/hexagonal-woowahan-techblog-2023]].
- **Spring Modulith**
- Spring Framework / Spring Boot 종속. framework-neutral 도메인을 외부 강제로 보호하기 어려움 (도메인까지 Spring scan에 들어옴).
- transactional event publication은 JPA event SPI에 의존하는 구현체가 다수라 persistence 선택에 영향. 카카오뱅크 수신상품 사례는 Modulith가 "느슨한 modular monolith"의 좋은 진화 경로임을 보여주지만 framework lock-in 비용을 수반. 출처: [[raw/company-tech-blogs/modulith-kakaobank-techblog-2025]], [[raw/company-tech-blogs/modulith-arawn-github-modular-monoliths-spring]].
- Spring Modulith 공식 문서는 module boundary 위반을 verification API로 잡지만 빌드 실패 강제 여부는 적용 프로젝트의 CI 설정에 의존. 출처: [[raw/official-docs/modulith-spring-official-doc]].
- **onion**
- 의존성 방향 규칙은 Hexagonal과 동등 (안쪽으로만 의존).
- 그러나 boundary verification 도구가 framework 자체로는 제공되지 않음. ArchUnit 같은 별도 정적 분석 없이는 layer 우회를 build-time에 잡기 어려움. Allegro 기술블로그도 onion의 이상은 인정하면서 실제 강제는 별도 도구가 필요하다고 명시. 출처: [[raw/company-tech-blogs/onion-allegro-tech-blog-2023]].
5종 모두 "의존성은 안쪽으로만"이라는 동일한 핵심 원칙을 공유하며, 차이는 (a) 최상위 자름의 기준(feature vs layer) (b) framework가 boundary를 강제하는지 (c) inbound/outbound adapter 명시 여부에 있다.
### 경계를 *강제*하는 방법 (enforcement)
레이아웃을 고른 것만으로 경계가 지켜지지 않는다. 어느 레이아웃이든 boundary drift를 막으려면 별도의 강제 수단이 필요하며, 일반적으로 두 축으로 나뉜다.
- **Build-graph 검사**: multi-module 빌드에서 module 간 허용 dependency를 화이트리스트로 두고, 허용 외 module dependency 선언 시 빌드를 실패시킨다(예: Gradle custom verification task). module 경계 자체가 1차 방어선이 된다.
- **Source/bytecode import 검사**: ArchUnit 같은 정적 분석 도구로 package/class 레벨 import·call·annotation을 검사한다. "`..domain..``org.springframework..`에 의존 금지", "특정 class(예: `ApplicationContext`) 의존 금지(banned-class)", "특정 annotation 사용 금지", "DTO는 web adapter 안에서만 접근" 같은 fitness function을 test로 강제한다.
정적 분석의 한계는 분명하다. import/call/annotation은 bytecode에 남지만, runtime container lookup(`ApplicationContext.getBean(String)` 같은 string-key 조회), `Class.forName(String)` reflection, classloader 우회는 bytecode가 *문자열 내용*을 노출하지 않으므로 catch할 수 없다. class-literal `getBean(Class<T>)`까지는 method-call target으로 잡히지만 string-key 변종은 false-negative가 되며, 이 영역은 code review·runtime 검증(Actuator `/beans`, Modulith verifier 등)으로만 보완 가능하다. 또 ArchUnit의 `should()` 조건이 매칭 대상이 0개인 빈 module에서 vacuous하게 통과하는 empty-anchor 함정이 있어, `allowEmptyShould` 정책과 "위반을 데이터로 보는(violations-as-data)" negative fixture로 rule이 실제로 catch하는지 별도 보증하는 패턴이 쓰인다. ArchUnit 분석 scope(classpath import vs package filter)와 empty-should 함정의 일반 지식은 [[wiki/concepts/archunit-scope-classpath-vs-package-filter]] 참조.
## Claim-backed Knowledge
> 인용 가능한 출처가 직접 뒷받침하는 일반 지식만 둔다. "어느 레이아웃이 옳다"는 추론·취향은 §한계 / 주의점과 §Do Not Overclaim에서 다룬다.
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| 최상위 디렉터리는 framework가 아니라 use case / business 영역을 드러내야 한다(layer-first 비판) | [[raw/official-docs/feature-first-uncle-bob-screaming-architecture-2011]] | medium | Uncle Bob Screaming Architecture (2011), `engineering-blog` — 공식 표준이 아닌 영향력 있는 블로그 주장 |
| Hexagonal의 본질은 응용 코어를 inbound(driving)/outbound(driven) adapter로부터 port interface로 격리하는 것이며 package 형태 자체는 비강제 | [[raw/official-docs/hexagonal-cockburn-wikipedia-summary]] | medium | Cockburn Ports & Adapters, `engineering-blog` |
| 의존성은 외부 layer(infra/UI)→내부 layer(domain model) 방향으로만 향하고 안쪽은 바깥쪽 interface를 알지 않는다 | [[raw/official-docs/onion-palermo-original-2008]] | medium | Palermo Onion (2008), `engineering-blog` |
| Spring Modulith는 package를 module 경계로 삼고 `@ApplicationModule`/named-interface로 접근을 강제하나, 위반의 build 실패 강제 여부는 적용 프로젝트 CI 설정에 의존(framework는 verification API만 제공) | [[raw/official-docs/modulith-spring-official-doc]] | high | 공식 문서. build 실패는 자동이 아님 |
| onion/hexagonal 의존성 방향 규칙은 framework 자체로 build-time 강제되지 않으며, ArchUnit 등 별도 정적 분석 없이는 layer 우회를 빌드 시점에 잡기 어렵다 | [[raw/company-tech-blogs/onion-allegro-tech-blog-2023]] | medium | `company-tech-blog` 관점 — 공식 best practice로 승격 금지 |
| 도메인 수가 늘면 layer-first에서 한 도메인 코드가 controller/·service/·repository/에 흩어져 응집도가 떨어진다 | [[raw/company-tech-blogs/feature-first-sahibinden-package-by-layer-vs-feature]] | medium | `company-tech-blog` 사례 |
## Project Application
- [[wiki/projects/ca-tmpl/clean-architecture-package-layout]] — ca-tmpl package/module blueprint + enforcement-rules 적용 기록. Gradle multi-module boundary(8 module, production root `dev.caskeleton`)와 ArchUnit/Gradle guardrail은 `locally-verified`(2026-06-04 ground-truth 대조). enforcement dimension: `domain_is_pure`(Lombok ban 포함), application↔adapter 격리, `ApplicationContext` banned-class rule(D11, string-key bypass는 한계), `verifyCleanArchitectureDependencies` build-graph 검사, violations-as-data negative fixture를 기록. `sample-portfolio` fixture business flow와 Spring Modulith verifier는 범위 밖.
- [[raw/branch-notes/feature-architecture-enforcement-rules]] — 경계 의존성 규칙과 forbidden annotation/import의 ArchUnit 강제 기준.
- [[raw/branch-notes/feature-skeleton-package-blueprint-contract]] — Gradle multi-module Clean Architecture / Hexagonal module blueprint SSOT.
- [[raw/branch-notes/feature-domain-feature-onboarding-contract]] — 새 도메인 추가 시 New Domain Module Slice + Read/Write Difference Table 기준.
- [[raw/project-notes/ca-skeleton-operational-contract]] §20 Skeleton Blueprint Contract — 위 3개 branch-note를 통합한 canonical SSOT.
## 내가 설명할 수 있어야 하는 것
- feature-first / layer-first / hexagonal / onion / modulith 5종의 공식 정의와 공통 핵심 원칙("의존성은 안쪽으로만")은 무엇인가?
- 각 레이아웃이 어떤 문제를 해결하고, 어떤 상황에서는 무너지는가(특히 layer-first의 응집도 붕괴 시점)?
- 레이아웃 선택만으로 경계가 지켜지지 않는 이유와, build-graph 검사 / 정적 분석(ArchUnit) 두 축의 enforcement가 각각 무엇을 막는가?
- 공식 문서가 말하지 않는 부분(예: Spring Modulith가 위반의 build 실패를 자동 강제하지 않음)은 무엇인가?
- 회사 기술 블로그 사례(우아한형제들·카카오뱅크·Allegro 등)를 일반 법칙처럼 말하면 안 되는 지점은?
- 내 프로젝트(ca-tmpl)에서는 어떤 branch decision과 ArchUnit/Gradle rule로 연결됐는가?
- 정적 분석으로 잡히지 않는 우회(runtime lookup, reflection)는 코드/운영에서 어떻게 검증·보완하는가?
## Interview Questions
- feature-first 패키지 레이아웃과 layer-first(controller/service/repository) 레이아웃의 차이는 무엇인가? 어느 시점에 후자가 무너지는가?
- feature-first 레이아웃이 Hexagonal Architecture와 "동형"이라는 표현은 무슨 뜻인가? buckpal 예시로 설명하라.
- 도메인 수가 늘어났을 때 layer-first가 응집도 면에서 무너지는 이유는 무엇인가? 어떤 운영 신호로 그것을 감지하는가?
- Spring Modulith를 즉시 도입하지 않고 Gradle multi-module + ArchUnit/Gradle guardrail로 시작하는 트레이드오프는 무엇인가? 향후 Modulith로 이행할 수 있는 조건은?
- 패키지 규약을 문서로만 두지 않고 ArchUnit 같은 architecture test로 boundary를 강제하는 이유는 무엇인가? 정적 분석으로 잡히지 않는 우회(runtime lookup 등)는 어떻게 보완하는가?
## Do Not Overclaim
- "feature-first가 항상 layer-first보다 우월하다"는 금지. 학습 비용은 layer-first가 가장 낮고, 도메인 수가 적은 초기 단계에서는 layer-first도 합리적인 선택이다.
- "ca-tmpl이 Hexagonal Architecture다"는 단정 금지. ca-tmpl은 Gradle module boundary로 application/domain과 adapter를 물리 분리한 Clean Architecture / Hexagonal-inspired template이다. 현재 구현 어휘는 inbound = `adapter-web`, outbound = `adapter-persistence` / `adapter-outbound`이며, Cockburn 원전의 모든 어휘를 그대로 차용한 구현은 아님.
- "Spring Modulith를 곧 도입할 것"이라는 단정 금지. Modulith는 framework가 boundary를 강제하는 자연스러운 진화 경로이지만, 도입은 framework lock-in과 JPA 의존 비용을 수반하며 ca-tmpl의 framework-neutral 도메인 원칙과 일부 충돌한다. 향후 검토 대안 중 하나일 뿐 도입 결정이 아니다.
- "ArchUnit이 모든 경계 위반을 잡아낸다"는 단정 금지. 정적 분석은 ApplicationContext lookup, `@Lazy` reflection, runtime classloader 우회를 감지할 수 없으며 별도 코드 리뷰/SonarQube 보완이 필요하다.
## Sources
- [[raw/official-docs/feature-first-uncle-bob-screaming-architecture-2011]] — Uncle Bob Screaming Architecture (2011)
- [[raw/official-docs/hexagonal-cockburn-wikipedia-summary]] — Cockburn Hexagonal Architecture (Ports & Adapters)
- [[raw/official-docs/hexagonal-thombergs-buckpal-github]] — Thombergs BuckPal reference (feature 단위로 잘린 Hexagonal)
- [[raw/official-docs/layer-first-baeldung-clean-architecture-spring-boot]] — Baeldung Clean Architecture Spring Boot
- [[raw/official-docs/onion-palermo-original-2008]] — Palermo Onion Architecture (2008)
- [[raw/official-docs/modulith-spring-official-doc]] — Spring Modulith 공식 문서
- [[raw/company-tech-blogs/feature-first-sahibinden-package-by-layer-vs-feature]] — Sahibinden: feature vs layer 응집도 비교
- [[raw/company-tech-blogs/layer-first-kamilmazurek-github-template]] — layer-first Spring Boot template
- [[raw/company-tech-blogs/hexagonal-woowahan-techblog-2023]] — 우아한형제들 Hexagonal 적용 사례
- [[raw/company-tech-blogs/modulith-kakaobank-techblog-2025]] — 카카오뱅크 수신상품 Modulith 적용
- [[raw/company-tech-blogs/modulith-arawn-github-modular-monoliths-spring]] — Modular Monoliths with Spring 참조 구현
- [[raw/company-tech-blogs/onion-allegro-tech-blog-2023]] — Allegro Onion Architecture 적용기
- [[raw/project-notes/ca-skeleton-operational-contract]] — canonical operational contract (§20 Skeleton Blueprint Contract, §29 Topic 1)
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/config-and-adapter-templates.md
@@ -0,0 +1,96 @@
---
title: Config & Adapter Templates (env-driven + optional module)
source_type: llm-generated
status: draft
confidence: medium
tags: [12-factor, config, spring-boot, adapter, conditional-on-property]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Config & Adapter Templates (env-driven + optional module)
> Layer: `wiki/concepts/` — env 기반 runtime configuration과 optional adapter template를 동시에 다루는 일반 개념 문서. 구체적인 프로젝트 결정은 [[raw/project-notes/ca-skeleton-operational-contract]] §9 및 [[raw/branch-notes/feature-env-driven-runtime-configuration]], [[raw/branch-notes/feature-integration-adapter-templates]] 참조.
## Summary
**Env config**: 12-factor §III. Config 원칙을 따라 application-owned env에 `APP_` prefix, Duration은 `30s` 형식 1택, boolean은 `true/false` only, runtime reload는 기본 금지, `.env.example` drift 검증 도구로 누락 감지를 강제하는 설계.
**Adapter templates**: 선택형 adapter(Kafka/Redis/Slack/Email)는 기본 dependency가 아닌 optional module로 두고, `@ConditionalOnProperty` 3-layer(Layer 1 Spring bean 등록 조건, Layer 2 ArchUnit static dependency 검사, Layer 3 runtime `AdapterDisabledException` fail-fast)로 disabled adapter가 use case path에 새지 않게 막는 설계.
## Standard (공식 정의)
### Env-driven runtime configuration
- **12-factor §III. Config** — config는 코드와 분리된 환경 변수에 두고, 배포 환경별로 달라지는 값(자격 증명, hostname, profile)은 모두 env로 주입. config dump가 가능하면 안 됨.
- **Spring Boot externalized configuration** — `@ConfigurationProperties + @Validated`로 env 바인딩, `application.yml` profile-specific override, Spring `Duration` (`30s`/`PT30S`) / `DataSize` (`10MB`) 타입 지원.
- **검토된 대안**:
- **Spring Cloud Config Server** — 중앙 git-backed config + `@RefreshScope`로 runtime reload. config server 자체가 인프라 SPOF가 되고 bootstrap에 의존.
- **k8s ConfigMap + Spring Cloud Kubernetes auto-reload** — 3-level reload (`refresh` / `restart_context` / `shutdown`).
- **HashiCorp Consul KV** — KV store + watch.
- **AWS Parameter Store / AppConfig** — managed validator + CloudWatch auto-rollback + deployment strategy.
- **LaunchDarkly / Unleash** — feature flag SaaS. A/B/canary, user-targeting, percentage rollout 등 product-grade 기능 제공.
### Adapter templates (optional module)
- **Spring `@ConditionalOnProperty`** — `name`/`havingValue` 조건이 일치할 때만 bean 등록. Spring Boot 3.5.0+에서 `@ConditionalOnBooleanProperty` 도입.
- **Spring Boot AutoConfiguration** — `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에 등록된 `@AutoConfiguration` 클래스가 조건부 bean을 제공. custom starter의 표준 방식.
- **검토된 대안**:
- **Java SPI / `ServiceLoader`** — `META-INF/services/<interface>`에 구현체 등록, classpath에서 발견된 모든 provider를 load.
- **Spring `@Profile` 기반** — profile 활성화로 bean 선택.
- **OSGi plugin architecture** — runtime module 동적 load/unload.
- **Feature flag library (FF4J / Togglz)** — runtime flag로 코드 path 분기.
## 한계 / 주의점
### Env config
- **12-factor env (process env 노출)** — secret이 process env에 남아 `/proc/<pid>/environ`, container metadata API, `env` actuator endpoint로 leak 가능. secret manager 별도 필요.
- **Spring Cloud Config Server** — 인프라 SPOF. config server 장애 시 client startup 차단 (bootstrap 의존).
- **k8s ConfigMap auto-reload** — pod별로 reload 타이밍이 다르면 partial-state가 생겨 디버깅 어려움. k8s lock-in 발생.
- **AWS AppConfig** — AWS lock-in + per-call billing.
- **LaunchDarkly / Unleash** — 외부 SaaS 의존, flag debt(제거되지 않은 flag 누적), cost. product-grade A/B/canary 요구가 발생하기 전에는 over-engineering.
### Adapter templates
- **Spring `@ConditionalOnProperty` Layer 1** — Spring 공식이 cover하는 영역은 bean 등록 조건뿐. application code가 disabled adapter package를 import해도 Spring 자체는 막지 못함.
- **ArchUnit Layer 2** — 별도 source가 필요한 미흡 영역. `noClasses().that().resideInAPackage("..application..").should().dependOnClassesThat().resideInAPackage("..adapters.{disabled}..")` 같은 정적 rule을 작성해야 하며, ca-tmpl 자체 contract로 G-I 후속 보강 대상.
- **ArchUnit Layer 2 정적 검사 한계** (2026-05-22 보강) — ArchUnit User Guide의 `DescribedPredicate` / `ArchCondition` API와 `JavaClass.getAnnotationOfType(...)`로 정적 추출 가능한 것은 (a) adapter 후보 class가 `@ConditionalOnProperty`를 부착했는지, (b) `name`/`havingValue` parameter 값이 `app.adapter.<name>.enabled` 패턴을 따르는지, (c) application layer가 adapter package를 직접 import하지 않는지(CA 경계)까지. **"현재 빌드/배포 환경에서 어떤 adapter가 실제 disabled인지"는 runtime config 평가이므로 ArchUnit 능력 밖**이며, Layer 3 (`AdapterDisabledException` runtime fail-fast)에 위임해야 함. 즉 Layer 2는 "annotation 존재 + naming pattern 강제" fitness function까지가 실효 범위. 자세한 평가는 [[raw/official-docs/archunit-conditional-on-property-3-layer-pattern]] 참조. status `needs-confirmation`.
- **`AdapterDisabledException` Layer 3** — branch 자체 contract. 표준 라이브러리가 제공하지 않으며 직접 구현.
- **Java SPI** — on/off boolean 표현 불가(classpath 존재 = enable), default constructor 강제, Spring DI 미통합. ca-tmpl의 `APP_ADAPTER_*_ENABLED` 결정과 정면 충돌.
- **Togglz / FF4J** — runtime branching tool로, startup-time adapter on/off와 시맨틱이 다름. ca-tmpl `@ConditionalOnProperty`(startup 결정)와 feature flag service(runtime 결정)는 분리 영역으로 취급해야 함.
## Project Application
- [[wiki/projects/ca-tmpl/config-and-adapter-templates]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
- [[raw/branch-notes/feature-env-driven-runtime-configuration]] — `APP_` prefix, Duration `30s`, boolean `true/false`, no-runtime-reload, `.env.example` drift 검증 결정.
- [[raw/branch-notes/feature-integration-adapter-templates]] — optional module + `@ConditionalOnProperty` 3-layer detection + `AdapterDisabledException` fail-fast 결정.
- [[raw/project-notes/ca-skeleton-operational-contract]] — §9 Env-driven Runtime Configuration, §11 Adapter Failure Contract, §29 Group G-I.
## Interview Questions
- 12-factor §III. Config가 의미하는 "config와 코드 분리"는 구체적으로 무엇을 강제하는지 설명해 주세요.
- runtime config reload를 기본 금지(no-runtime-reload)로 결정한 근거와, 그 결정이 운영에서 갖는 trade-off는 무엇인가요?
- `@ConditionalOnProperty` 3-layer 검출(Spring bean 조건 + ArchUnit static + runtime fail-fast)이 각각 어떤 실패 시나리오를 잡아내려는 것인지 설명해 주세요.
- Java SPI `ServiceLoader`와 Spring `@ConditionalOnProperty`는 adapter on/off 표현에서 어떤 차이가 있나요?
- LaunchDarkly 같은 feature flag SaaS와 `@ConditionalOnProperty` 기반 startup toggle은 어떤 운영 요구가 생겼을 때 갈라지는지 설명해 주세요.
## Do Not Overclaim
- "`@RefreshScope`만 도입하면 dynamic config가 된다" 같은 단정은 피해야 함. ca-tmpl은 runtime reload를 기본 금지로 두며, reload가 필요한 경우는 secret manager + startup validation을 별도 branch로 분리하는 것이 결정 사항.
- "`@ConditionalOnProperty` 3-layer가 disabled adapter 호출을 완전 검증한다"고 단정하면 안 됨. Layer 1만 Spring 공식 cover이고, Layer 2(ArchUnit)는 source 부재로 G-I 후속 보강 대상, Layer 3(`AdapterDisabledException`)는 branch 자체 contract.
- "12-factor env가 secret 관리까지 책임진다"는 표현은 과장. process env 노출 위험은 12-factor 자체가 해결하지 않으며 secret manager가 별도 책임.
- "ca-tmpl이 LaunchDarkly/Togglz를 거부했다"가 아니라 "ca-tmpl scope에서 위임한 영역"이라는 표현이 정확.
## Sources
- [The Twelve-Factor App — III. Config](https://12factor.net/config) — [[raw/official-docs/config-12-factor-app-config]]
- [Spring Cloud Config (official)](https://docs.spring.io/spring-cloud-config/reference/) — [[raw/official-docs/config-spring-cloud-config-server-official]]
- [Spring Cloud Kubernetes — ConfigMap auto-reload](https://docs.spring.io/spring-cloud-kubernetes/reference/) — [[raw/official-docs/config-spring-cloud-kubernetes-configmap-reload]]
- [AWS AppConfig — Feature flag & deployment strategy](https://docs.aws.amazon.com/appconfig/) — [[raw/official-docs/config-aws-appconfig-feature-flag-deployment]]
- [LaunchDarkly — Feature flag best practice](https://launchdarkly.com/) — [[raw/company-tech-blogs/config-launchdarkly-feature-flag-best-practice]]
- [Spring Boot — Custom AutoConfiguration / starter](https://docs.spring.io/spring-boot/reference/features/developing-auto-configuration.html) — [[raw/official-docs/adapter-spring-boot-autoconfig-custom-starter]]
- [Java SPI — `java.util.ServiceLoader`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/ServiceLoader.html) — [[raw/official-docs/adapter-java-spi-serviceloader]]
- [Togglz / FF4J — Feature toggle library](https://www.togglz.org/) — [[raw/company-tech-blogs/adapter-togglz-ff4j-feature-toggle-library]]
- [ArchUnit — Writing Custom Rules / Accessing Annotation](https://www.archunit.org/userguide/html/000_Index.html) — [[raw/official-docs/archunit-conditional-on-property-3-layer-pattern]] (Layer 2 정적 검사 가능 범위 평가, needs-confirmation)
- Canonical: [[raw/project-notes/ca-skeleton-operational-contract]] (§9, §11, §29 Group G-I)
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/data-layer-persistence-cache-outbound.md
@@ -0,0 +1,128 @@
---
title: Data Layer Baseline (Persistence + Cache + Outbound HTTP)
source_type: llm-generated
status: draft
confidence: medium
tags: [persistence, jpa, cache, http-client, resilience]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Data Layer Baseline (Persistence + Cache + Outbound HTTP)
> Layer: `wiki/concepts/` — Phase E Group G-C 합성. 3개 sub-topic(Persistence failure / Cache consistency / Outbound HTTP)을 하나의 baseline canonical로 묶음. 프로젝트 적용 사실은 `wiki/projects/`에 별도 작성하고 본 문서에서는 링크만 둠.
## Summary
Data layer baseline은 세 가지 축으로 구성된다.
- **Persistence**: SQLState 매트릭스로 DB 실패를 분류하고, Spring `DataAccessException` 계층 위에 매핑하여 `PERSISTENCE / CONFLICT / TRANSIENT_DEPENDENCY` 카테고리를 만든다. OSIV는 off가 기본.
- **Cache**: cache-aside default + Caffeine local lock(single-instance) + Redisson `RLock` distributed mutex(multi-instance HPA) + after-commit invalidation + eventual consistency window 5초.
- **Outbound HTTP**: Spring RestClient를 baseline으로 두고, retry/circuit breaker는 Resilience4j로 일원화. timeout default = connect 2s / read 5s / global 10s.
## Standard (공식 정의)
### Persistence — SQLState + Spring DAO hierarchy
- **SQLState** (ISO/IEC 9075): 5-char code로 DB 오류를 표준 분류. `08*` = connection exception, `40001` = serialization failure, `40P01` = deadlock(Postgres), `23xxx` = integrity constraint, `57014` = query canceled.
- **Spring `DataAccessException` hierarchy**: `TransientDataAccessException` / `NonTransientDataAccessException` / `RecoverableDataAccessException`로 retryable/non-retryable 1차 분리. JPA `PersistenceException``JpaSystemException`으로 흡수.
- **OSIV (Open Session In View)**: Hibernate session을 view rendering까지 열어두는 패턴. Vlad Mihalcea가 anti-pattern으로 명시했고 Spring Boot는 활성화 시 startup WARN 로그를 출력. 운영 baseline은 off.
- **HikariCP pool sizing**: 공식 wiki는 `connections = ((core_count * 2) + effective_spindle_count)` 공식과 단일 small pool 권장. pool wait p99 / pool exhaustion이 1차 alert 지표.
### Cache — cache-aside + stampede control
- **Cache-aside** (Microsoft Cloud Design Patterns / AWS ElastiCache): application이 cache miss 시 DB 조회 → cache 채움. invalidation도 application 책임. write-through는 cache layer가 sync 책임, write-behind는 async, read-through는 cache layer가 loader를 안다. 책임 위치가 다름.
- **Caffeine `AsyncLoadingCache` / `@Cacheable(sync = true)`**: 동일 key 동시 miss를 단일 loader 호출로 직렬화 (in-process stampede 방지).
- **Redisson `RLock`**: Redis 기반 reentrant lock + watchdog lease extension. Kleppmann의 Redlock 비판을 회피하기 위해 단일 master 기반 RLock + fence token 사용.
- **after-commit invalidation**: Spring `TransactionSynchronizationManager.registerSynchronization``afterCommit()` hook에서만 cache mutation 수행. tx rollback 시 stale write 차단.
### Outbound HTTP — RestClient + Resilience4j
- **Spring RestClient** (6.1+): `RestTemplate`의 fluent 후속 API. RestTemplate은 Spring 공식 maintenance-only 상태로 신규 기능 추가 없음.
- **Resilience4j**: Netflix Hystrix의 사실상 후속. Hystrix는 2018년 maintenance mode 진입. Retry / CircuitBreaker / TimeLimiter / Bulkhead / RateLimiter를 functional decorator로 제공.
- **Circuit breaker 상태**: `CLOSED``OPEN` (failure rate threshold 초과) → `HALF_OPEN` (probe) → `CLOSED` 복귀. Micrometer로 state transition을 metric으로 노출.
- **Timeout 계층**: connect timeout(소켓 연결) < read timeout(응답 첫 바이트 대기) < global call timeout(전체 호출). 셋 중 하나라도 미설정이면 무한 대기 위험.
## 한계 / 주의점
### Persistence
- SQLState 9-row matrix의 vendor-specific row(PostgreSQL `23505`, `40P01` 등)는 DB 변경 시 재검증 필요. MySQL은 `40001`만 공유하고 `40P01` 대신 다른 코드를 사용.
- OSIV off는 lazy loading exception을 presentation까지 새지 않게 막아주지만, application 경계에서 명시적 fetch 전략(`@EntityGraph`, fetch join, DTO projection)을 강제한다. 익숙하지 않은 팀은 운영 부담이 늘 수 있음.
- R2DBC reactive는 throughput 우위가 있으나 JPA tooling을 포기해야 한다. baseline은 JPA blocking으로 고정한 trade-off의 반대편.
### Cache
- cache-aside의 eventual consistency window가 5초로 잡혀 있어 **strict consistency가 요구되는 use case(잔액, 인증, idempotency 검증)에는 부적합**. 해당 use case는 cache bypass를 명시.
- Caffeine local cache + Redisson 분산 mutex 조합은 노드 간 sync lag이 존재. 한 노드가 invalidation을 발행한 뒤 다른 노드의 local cache가 비워질 때까지 lag 발생.
- Redisson `RLock`도 Kleppmann의 분산 lock 비판에서 완전히 자유롭지 않다. 정확한 fencing을 요구하는 경우 token + DB-level optimistic lock 병행이 필요.
- negative cache(존재하지 않는 row, TTL 60s)는 invalidation 채널 적용 대상에서 제외 — 의도된 분리이지만 row가 실제로 생성된 직후 60초간 stale empty 응답이 나갈 수 있음.
### Outbound HTTP
- RestClient는 Spring 6.1+ 한정. 기존 RestTemplate 코드는 마이그레이션 비용이 따른다.
- WebClient는 reactor event-loop 위에서 동작하므로 MVC(servlet) baseline에 강제 도입하면 blocking risk가 있다. baseline에서는 extension 문서로 분리.
- OpenFeign은 declarative interface로 편리하지만 Spring Cloud 의존이 붙는다. Spring 6.1+ `@HttpExchange`가 framework-level 대안.
- Stripe engineering blog는 retry default-on을 옹호하지만 **이는 idempotency-key 헤더 보장이 전제**. 일반 API에 default-on retry를 적용하면 비-idempotent endpoint의 중복 write 위험이 생긴다.
- Resilience4j는 Spring Boot starter 통합이 매끄럽지만, Spring 외 환경(plain Java, Vert.x 등)에서는 verbose한 functional decorator 작성이 필요. "vendor-neutral"로 단언하기에는 일부 마찰이 있음.
## Project Application
- [[wiki/projects/ca-tmpl/data-layer-persistence-cache-outbound]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
ca-skeleton operational contract와 owning branch-notes:
- [[raw/branch-notes/feature-persistence-failure-baseline]] — SQLState 9-row matrix, Hikari alert threshold, OSIV off 결정
- [[raw/branch-notes/feature-cache-consistency-contract]] — cache-aside default, Caffeine + Redisson, after-commit invalidation, 5s window
- [[raw/branch-notes/feature-outbound-http-client-baseline]] — RestClient baseline, Resilience4j, timeout 2s/5s/10s, shutdown retry suppression
- [[raw/project-notes/ca-skeleton-operational-contract]] — §6 Operational Error Category, §11 Adapter Failure Contract, §29 G-C 외부 근거
## Interview Questions
- SQLState 코드를 어떻게 retryable / non-retryable로 매핑했고 그 분류가 Spring `DataAccessException` hierarchy와 어떻게 정합한가?
- OSIV가 anti-pattern으로 평가되는 이유는 무엇이고 off로 두었을 때 lazy loading은 어떻게 해결하는가?
- cache-aside의 eventual consistency window 5초가 의미하는 바와, 그 안에서 stale read가 허용되지 않는 use case는 어떻게 분리하는가?
- Resilience4j를 Hystrix 대신 선택한 이유와 두 라이브러리의 차이는?
- outbound HTTP timeout을 connect 2s / read 5s / global 10s로 둔 의도와 셋 중 어떤 게 빠지면 어떤 위험이 생기는가?
- after-commit invalidation을 강제하는 이유와, transaction rollback 시 cache 일관성이 어떻게 보장되는가?
## Do Not Overclaim
- "cache-aside면 항상 안전하다" — strict consistency가 요구되는 use case에서는 cache bypass가 필요하다. cache-aside는 eventual consistency 모델이다.
- "Resilience4j는 vendor-neutral이라 어디서나 동일하게 동작" — Spring Boot starter 통합 외 환경에서는 functional decorator를 직접 조립해야 하고 boilerplate가 늘어난다.
- "RestClient가 RestTemplate를 완전히 대체했다" — Spring 6.1+ 한정이고 기존 코드 마이그레이션 비용이 있다.
- "Redisson RLock이면 분산 lock 문제 해결" — Kleppmann 비판은 완화되었지만 fencing token / DB optimistic lock 병행이 필요한 경우가 있다.
- "Stripe처럼 retry default-on이 좋은 패턴이다" — Stripe는 idempotency-key 보장이 전제. 일반 API에 그대로 적용하면 위험하다.
## Sources
### 공식 근거 (Persistence)
- [[raw/official-docs/persistence-spring-dataaccessexception-hierarchy]] — Spring `DataAccessException` 계층 (SQLState 분류의 framework-level anchor)
- [[raw/official-docs/persistence-osiv-antipattern-hibernate-vladmihalcea]] — Hibernate 권위자의 OSIV anti-pattern 명시 + Spring Boot WARN
- [[raw/official-docs/persistence-hikaricp-pool-sizing-wiki]] — pool sizing 공식과 alert threshold 출처
- [[raw/official-docs/persistence-r2dbc-reactive-spring]] — JPA blocking baseline의 trade-off 반대편(R2DBC reactive)
### 공식 근거 (Cache)
- [[raw/official-docs/cache-aside-vs-write-through-aws]] — cache-aside / write-through / write-behind / read-through trade-off 공식 분류
- [[raw/official-docs/cache-caffeine-asyncloadingcache-readme]] — single-instance stampede 방지(`@Cacheable(sync = true)`, `AsyncLoadingCache`) 공식 매핑
- [[raw/official-docs/cache-redisson-rlock-vs-setnx]] — multi-instance HPA에서 RLock 채택 + SETNX/Redlock 배제 (Kleppmann 비판 포함)
### 사례 (Cache)
- [[raw/company-tech-blogs/cache-woowahan-after-commit-invalidation]] — after-commit invalidation의 한국 사례 + Spring `TransactionSynchronizationManager` 강제 근거 (회사 기술블로그 — 사례 취급)
### 공식 근거 (Outbound HTTP)
- [[raw/official-docs/outbound-spring-restclient-baseline]] — RestClient baseline + RestTemplate maintenance-only 명시
- [[raw/official-docs/outbound-resilience4j-vs-spring-retry]] — Resilience4j 채택 + Spring Retry 좁은 예외 허용 + Hystrix 배제
- [[raw/official-docs/outbound-webclient-vs-restclient-spring]] — WebClient baseline 배제 이유(reactor event-loop blocking risk)
- [[raw/official-docs/outbound-openfeign-declarative-client]] — Feign declarative 대안 + maintenance status + Spring 6.1+ `@HttpExchange`
### 사례 (Outbound HTTP)
- [[raw/company-tech-blogs/outbound-stripe-rate-limit-retry-engineering]] — retry + idempotency-key 결합, full-jitter backoff. ca-tmpl default-disabled의 보수성 대비 (회사 기술블로그 — 사례 취급)
### Canonical contract
- [[raw/project-notes/ca-skeleton-operational-contract]] — §6 Operational Error Category, §11 Adapter Failure Contract, §29 Group G-C 외부 근거 인덱스
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/devops-ci-supply-chain-dx.md
+130
View File
@@ -0,0 +1,130 @@
---
title: DevOps Baseline (CI + Supply chain + DX)
source_type: llm-generated
status: draft
confidence: medium
tags: [devops, ci-cd, supply-chain, sigstore, developer-experience]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# DevOps Baseline (CI + Supply chain + DX)
> Layer: `wiki/concepts/` — 일반 개념. 내 프로젝트 사실은 `project-template` / project 문서 사용.
## Summary
운영 가능한 백엔드 skeleton의 DevOps baseline은 세 축으로 구성된다.
**(1) CI quality gate** — GitHub Actions `needs:` + `if: success()`로 contract test ↔ release-blocking 의존성을 단일 yaml에서 강제하고, flaky test는 14일 sunset 기한이 붙은 quarantine bucket으로 분리한다.
**(2) Build / release supply chain** — Cosign keyless signing (Sigstore Fulcio + Rekor transparency log)으로 artifact를 서명하고, SLSA provenance attestation으로 build 출처를 검증하며, Gradle dependency-locking으로 transitive 버전 drift를 차단한다.
**(3) Developer experience** — `./gradlew bootstrap` 같은 단일 진입점 + Testcontainers `@ServiceConnection` 기반 integration test + `.tool-versions`로 핀된 JDK LTS로 새 개발자가 clean clone 직후 smoke까지 5단계로 도달한다.
## Standard (공식 정의)
### CI quality gate
- **GitHub Actions** (`docs.github.com/en/actions/`): YAML workflow의 `jobs.<id>.needs` 의존성과 `if: success() | failure()` 조건으로 단계별 gate를 표현. job status가 `failure`이면 workflow status도 `failure`.
- **GitLab CI/CD** (`docs.gitlab.com/ee/ci/pipelines/`): `stages` + `jobs` + `needs:` + `rules:` 키워드로 같은 모델을 구성. `parallel: matrix:` 키워드로 matrix job.
- **Jenkins Declarative Pipeline** (`jenkins.io/doc/book/pipeline/syntax/`): `agent` 디렉티브 + `post { failure { ... } }` block으로 실패 처리.
- **CircleCI configuration reference** (`circleci.com/docs/configuration-reference/`): orbs + workflow + job 모델.
- **Tekton Pipelines** (`tekton.dev/docs/pipelines/`): `Pipeline` = `Tasks`의 모음, 각 `Task`는 Kubernetes Pod로 실행.
### Supply chain
- **Sigstore Cosign** (`docs.sigstore.dev/cosign/signing/overview/`): OIDC identity token으로 Fulcio가 단명(10분) 서명 cert 발급, 서명 직후 private key 파기. 서명 이벤트는 **Rekor transparency log**에 immutable 기록. 검증 측은 `cosign verify --certificate-identity=... --certificate-oidc-issuer=...`로 issuer와 identity를 함께 강제.
- **SLSA v1.0 spec** (`slsa.dev/spec/v1.0/`): "Supply-chain Levels for Software Artifacts". provenance는 build platform, top-level build invocation, materials(sources + dependencies)를 최소 식별. Build L1 = provenance 존재, L2 = hosted build platform, L3 = hardened/hermetic build.
- **in-toto attestation** (`github.com/in-toto/attestation`): 인증된 statement = subject(artifact digest 목록) + predicate(예: SLSA Provenance). DSSE envelope으로 서명되며 Cosign이 같은 envelope을 서명한다.
- **Gradle dependency locking** (`docs.gradle.org/current/userguide/dependency_locking.html`): `dependencyLocking { lockAllConfigurations() }` + `--write-locks`로 lockfile 생성. `lockMode = STRICT`일 때 lock state와 다른 해석은 build fail.
- **Maven Enforcer Plugin** `dependencyConvergence` 룰: transitive lockfile은 부재. 부분 대응만 가능.
### Developer experience
- **Testcontainers for Java** (`java.testcontainers.org/`): Docker container 기반 throwaway dependency. Spring Boot 3.1+ `@ServiceConnection` annotation으로 JDBC URL, credentials, host, port가 ApplicationContext에 자동 주입. reuse 옵션은 CI 금지, 로컬만.
- **Devcontainer spec** (`containers.dev/implementors/spec/`): `.devcontainer/devcontainer.json`이 VSCode/Codespaces용 dev container 정의. tool version과 OS-level dep을 통일하지만 첫 진입점/smoke/migration 순서는 별도 필요.
- **mise / asdf** (`mise.jdx.dev/`, `asdf-vm.com/`) — `.tool-versions` 형식이 사실상 표준. **SDKMAN!** (`sdkman.io/`)은 별도 `.sdkmanrc` 사용.
- **Eclipse Temurin 21 LTS** (`adoptium.net/temurin/releases/?version=21`): 2028-09까지 무료 LTS 보안 패치.
## 한계 / 주의점
### CI
- **GitHub Actions**는 vendor lock-in(workflow yaml 문법, OIDC issuer URL, marketplace action 등)과 hosted runner 비용 모델이 다른 provider와 다르다. provider-agnostic하게 gate를 정의하지 않으면 이식 비용이 크다.
- **Jenkins / Tekton**은 인프라(k8s cluster, plugin ecosystem)에 대한 의존도가 커서 skeleton 단계에서는 과한 선택일 수 있다.
- **Flaky test quarantine**은 Spotify/Google/Microsoft가 운영 도구로 인정한 반면 Martin Fowler는 *"Eradicating Non-Determinism in Tests"*에서 quarantine 자체를 anti-pattern으로 본다. "Spotify가 한다 = 공식 best practice"로 표현 금지. 14일 sunset 같은 절충은 *어느 한쪽도 공식이 아니라는 인정*이다.
- **OpenAPI snapshot diff** (springdoc + openapi-diff/oasdiff)는 controller annotation을 정적 추출하므로 dynamic routing(예: webflux functional routes)이 있으면 누락된다. "ground truth"는 이 범위 안에서만 참.
### Supply chain
- **Cosign keyless**의 "signature 누락 시 deploy block"만으로는 부족하다. `--certificate-identity` + `--certificate-oidc-issuer`로 **identity 매칭 정책**을 별도로 명시해야 임의의 OIDC identity가 만든 서명도 통과되는 사고를 막을 수 있다. Sigstore 공식은 키리스 모드에서 두 flag를 **검증 진입 전제 조건**으로 강제하며(`--certificate-identity ... is required for verification in keyless mode`), GitHub Actions OIDC 환경의 expected identity는 `https://github.com/<ORG>/<REPO>/.github/workflows/<file>@refs/heads/<branch>` 형식, issuer는 `https://token.actions.githubusercontent.com`이다. 클러스터 측 강제는 policy-controller / Kyverno `verifyImages` 등 admission controller에서 expected identity/issuer를 정책으로 선언. — `needs-confirmation`: 정책 표현 형식은 조직별로 다름.
- **SLSA v1.0 spec**의 실제 필드명은 두 최상위 객체로 구성된다. `buildDefinition.{buildType, externalParameters, internalParameters, resolvedDependencies}` + `runDetails.{builder.id, builder.version, builder.builderDependencies, metadata.invocationId, metadata.startedOn, metadata.finishedOn, byproducts}`. in-toto Statement 래퍼는 `_type`(`https://in-toto.io/Statement/v1`) + `subject[*].digest` + `predicateType`(`https://slsa.dev/provenance/v1`) + `predicate`. 약식 표현(`build.config.source`, `build.invocation`, `materials`)은 spec 필드명과 다르므로 slsa-verifier가 `--builder-id``runDetails.builder.id` 등의 필드를 찾지 못해 검증이 실패한다. provenance 생성 단계에서 spec 필드명을 그대로 사용해야 한다. — 출처: [[raw/official-docs/slsa-v1-provenance-schema]].
- **SLSA Build L3** (hardened build, hermetic, tamper-resistant builder)는 GitHub Actions hosted runner만으로는 도달 불가. 실무적으로는 L2(hosted build platform)가 현실적 목표지점.
- **Gradle dependency-locking**이 있어도 plugin 버전과 toolchain(JDK)은 별도 핀이 필요. `.tool-versions` / `gradle/wrapper/gradle-wrapper.properties` 핀과 함께 봐야 reproducible build가 완성된다.
- **Maven**에는 transitive lockfile이 1급 시민으로 존재하지 않는다. Maven 기반 프로젝트에서 같은 수준의 reproducibility를 요구하면 추가 도구가 필요.
### Developer experience
- **`.tool-versions`(asdf/mise) vs `.sdkmanrc`(SDKMAN)** 포맷 차이. 두 파일을 동시에 두면 drift 위험. 단일 source로 좁히는 편이 안전하다.
- **Devcontainer**는 VSCode/Codespaces에 의존한다. IntelliJ + 로컬 JDK 사용자에게는 중복 환경이 되며 bootstrap 단일 진입점/smoke는 devcontainer 안에서도 별도로 정의되어야 한다.
- **Testcontainers**는 Apple Silicon(arm64) 환경에서 일부 image가 emulation(amd64) 위에서 동작해 bootstrap 시간이 늘어날 수 있다.
- **Testcontainers reuse 옵션**은 CI에서는 반드시 비활성화. test 간 isolation을 깬다.
- **Bootstrap 한 줄 명령**은 ergonomic 강점이 있으나 단계가 합쳐져 있어 *어느 단계에서 실패했는지* 추적이 어려울 수 있다. 실패 단계별 exit code 또는 step 출력 분리가 필요.
## Project Application
- [[wiki/projects/ca-tmpl/devops-ci-supply-chain-dx]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
내 프로젝트(ca-skeleton)에서 이 개념과 관련된 문서로 **링크**. 실제 구현 여부·검증 등급은 해당 project / branch 문서에서 판정 (concept 문서는 등급을 직접 매기지 않음).
- [[raw/project-notes/ca-skeleton-operational-contract]] — §29 G-E (외부 근거 / 대안 조사 인덱스, DevOps / CI).
- [[raw/branch-notes/feature-ci-quality-gates-contract]] — Gate ↔ Branch Contract Test 소유권 매트릭스 20행, flaky quarantine 14d sunset SSOT, OpenAPI snapshot diff.
- [[raw/branch-notes/feature-build-release-supply-chain-contract]] — Cosign keyless 의무, SLSA provenance attestation 의무, Gradle dependency-locking, SemVer + git sha suffix, reproducibility.
- [[raw/branch-notes/feature-developer-experience-contract]] — `./gradlew bootstrap` 5단계, Temurin 21 LTS, Testcontainers integration, markdown-link-check.
## Interview Questions
- "CI에서 Gate ↔ Branch Contract Test 소유권 매트릭스란 무엇이고 왜 필요한가? 누가 어떤 gate를 깨질 때 책임지는지 어떻게 표현하는가?"
- "Flaky test quarantine bucket에 sunset deadline을 14일로 두는 근거는 무엇인가? quarantine 자체를 반대하는 입장(Fowler)과 어떻게 절충하는가?"
- "Cosign keyless signing이 GPG signing과 비교해 어떤 운영 비용을 제거하고, 어떤 새 의존성(OIDC IdP, Rekor 가용성)을 추가하는가?"
- "SLSA build level L1/L2/L3가 각각 무엇을 보장하는가? skeleton 단계에서 현실적으로 도달 가능한 level은 어디까지인가?"
- "Gradle dependency-locking이 필요한 이유는 무엇이고, Maven에는 왜 같은 수준의 lockfile이 없으며 어떻게 대체하는가?"
- "Integration test backend로 Testcontainers를 H2 같은 in-memory DB 대신 선택하는 이유는 무엇인가? 그 비용은 무엇인가?"
## Do Not Overclaim
- "Cosign signature 누락만 차단하면 supply chain이 안전하다"고 단정 금지. **identity 매칭 정책**(`--certificate-identity` + `--certificate-oidc-issuer`)이 없으면 임의 OIDC identity가 만든 서명도 통과될 수 있다.
- "SLSA Build L3를 달성했다"고 단정 금지. ca-skeleton 단계에서 L3는 hermetic build / tamper-resistant builder를 요구하며 GitHub Actions hosted runner만으로는 도달 어렵다. branch note의 약식 매핑(`build.config.source` 등)은 spec 실제 필드명(`buildDefinition.externalParameters`)과 다르므로 정정 필요.
- "Google/Spotify/Microsoft가 flaky test quarantine을 운영하므로 공식 best practice다"라고 표현 금지. 이들은 *company-tech-blog* 등급이며 Fowler의 반대 입장이 함께 존재한다.
- "GitHub Actions가 CI provider의 정답이다"로 단정 금지. ca-skeleton은 `needs:` + `if: success()` 모델이 contract gate에 맞물려 채택된 것이며, gate 정의 자체는 provider-agnostic하게 작성되어야 이식 가능하다.
- "`./gradlew bootstrap` 한 줄이 끝났다 = 모든 게 정상이다"로 표현 금지. 5단계(compileTestJava → docker compose up → Flyway migrate → sample profile seed → smoke) 중 어디서 실패했는지 step 단위 검증이 필요.
- "Devcontainer가 있으면 bootstrap이 필요 없다"로 표현 금지. devcontainer는 tool version과 OS-level dep만 통일하며, 진입점/smoke/migration 순서는 별도로 정의되어야 한다.
- LLM 생성 문서이므로 본 concept 문서의 모든 진술은 `confidence: medium`. 검증 전 high confidence로 분류 금지.
## Sources
### 공식 문서 / spec
- [GitHub Actions — Migrating from GitLab CI/CD](https://docs.github.com/en/actions/learn-github-actions/migrating-from-gitlab-cicd-to-github-actions) / [GitLab CI/CD pipelines](https://docs.gitlab.com/ee/ci/pipelines/) / [Jenkins Declarative Pipeline](https://www.jenkins.io/doc/book/pipeline/syntax/) / [CircleCI configuration reference](https://circleci.com/docs/configuration-reference/) / [Tekton Pipelines overview](https://tekton.dev/docs/pipelines/) — CI provider 모델 비교.
- [Sigstore Cosign overview](https://docs.sigstore.dev/cosign/signing/overview/) + [Fulcio](https://docs.sigstore.dev/certificate_authority/overview/) + [Rekor](https://docs.sigstore.dev/logging/overview/) — keyless signing 체인.
- [SLSA v1.0 spec](https://slsa.dev/spec/v1.0/) + [Build levels](https://slsa.dev/spec/v1.0/levels) + [Provenance schema](https://slsa.dev/spec/v1.0/provenance) + [in-toto attestation](https://github.com/in-toto/attestation) — supply chain provenance.
- [Gradle dependency locking](https://docs.gradle.org/current/userguide/dependency_locking.html) + [Maven Enforcer dependencyConvergence](https://maven.apache.org/enforcer/enforcer-rules/dependencyConvergence.html) — dependency lockfile 정책.
- [Testcontainers for Java](https://java.testcontainers.org/) + [reuse](https://java.testcontainers.org/features/reuse/) + [Spring Boot Testcontainers support](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.testing.testcontainers) — integration test backend.
- [Devcontainer spec](https://containers.dev/implementors/spec/) + [VS Code Dev Containers](https://code.visualstudio.com/docs/devcontainers/containers) + [GitHub Codespaces](https://docs.github.com/en/codespaces/overview) — dev environment 통일.
- [mise](https://mise.jdx.dev/) + [asdf](https://asdf-vm.com/) + [SDKMAN!](https://sdkman.io/usage#env) + [Adoptium Temurin 21](https://adoptium.net/temurin/releases/?version=21) — tool versioning + JDK LTS.
- [springdoc-openapi](https://springdoc.org/) + [OpenAPITools/openapi-diff](https://github.com/OpenAPITools/openapi-diff) + [Tufin/oasdiff](https://github.com/Tufin/oasdiff) + [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) — OpenAPI snapshot diff.
### Raw 원본 (저장소 내 발췌)
- [[raw/official-docs/ci-github-actions-vs-gitlab-comparison]] — GitHub Actions `needs:` + `if: success()`가 contract gate 매트릭스에 맞물리는 근거, Jenkins/Tekton의 k8s 인프라 부담.
- [[raw/official-docs/ci-openapi-snapshot-diff-tooling]] — springdoc 런타임 추출 + openapi-diff/oasdiff CI 실패 조건, dynamic routing 함정.
- [[raw/company-tech-blogs/ci-flaky-test-quarantine-spotify-google]] — Spotify/Google/MS quarantine 인정 vs Fowler 반대 양립, 14d sunset은 절충.
- [[raw/official-docs/supply-chain-cosign-keyless-sigstore]] — Fulcio 단명 cert + Rekor transparency log + identity 매칭 정책 필요성.
- [[raw/official-docs/cosign-keyless-identity-verification-policy]] — `--certificate-identity` + `--certificate-oidc-issuer` 키리스 검증 강제 (Sigstore docs / cosign issue #3671), GitHub Actions OIDC identity 포맷.
- [[raw/official-docs/supply-chain-slsa-provenance-framework]] — SLSA v1.0 build levels, provenance 최소 필드, in-toto attestation, 약식 매핑 정정 필요.
- [[raw/official-docs/slsa-v1-provenance-schema]] — SLSA v1.0 provenance 실제 필드명 표(`buildDefinition.*` / `runDetails.*`) + in-toto Statement v1 래퍼 + slsa-verifier 검사 동작. ca-tmpl 약식 명명 정정 근거.
- [[raw/official-docs/supply-chain-gradle-vs-maven-dependency-locking]] — Gradle `lockMode = STRICT`, Maven transitive lockfile 부재.
- [[raw/official-docs/dx-testcontainers-java-best-practices]] — Spring Boot 3.1+ `@ServiceConnection`, singleton 패턴, CI에서 reuse 금지.
- [[raw/official-docs/dx-mise-asdf-tool-versioning]] — `.tool-versions` 사실상 표준, `.sdkmanrc`와의 drift 위험, Temurin 21 LTS.
- [[raw/official-docs/dx-devcontainer-spring-boot]] — devcontainer가 보장하는 것/보장하지 않는 것, IDE 종속성.
### Canonical 참조
- [[raw/project-notes/ca-skeleton-operational-contract]] §29 Group G-E — DevOps / CI / Supply chain / DX 대안 조사 인덱스.
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/distributed-tracing-baggage.md
@@ -0,0 +1,64 @@
---
title: concept / Distributed Tracing & Baggage
source_type: llm-generated
status: reviewed
confidence: high
tags: [concept, ca-tmpl, observability, mdc, span-event]
related_projects: [ca-tmpl]
last_reviewed: 2026-06-15
---
# concept / Distributed Tracing & Baggage
## Summary
여러 마이크로서비스를 거쳐 흐르는 단일 요청의 실행 흐름을 시각화하고 진단할 수 있도록 트레이스 ID와 스팬 ID 등의 메타데이터(TraceContext)를 전파하고, 전체 트레이스 수명 주기 동안 요청 전반에 걸쳐 데이터를 전달(Baggage)하는 기술.
## Standard (공식 정의)
W3C Distributed Tracing 및 OpenTelemetry 표준 명세에 따른 정의는 다음과 같다.
- **traceparent**: 실행 중인 분산 요청의 컨텍스트를 규격화한 W3C 공식 헤더.
- 형식: `version-traceId-parentId-traceFlags` (예: `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`)
- `traceFlags`의 마지막 비트가 `01`이면 샘플링됨(Sampled), `00`이면 샘플링되지 않음(Not-Sampled)을 나타낸다.
- **baggage**: 분산 트레이스 경계 전반에 걸쳐 임의의 키-값 쌍 메타데이터를 전파하기 위한 W3C 헤더 규격. 클라이언트 요청 처리 중 하위 모든 마이크로서비스 호출 시에 함께 흘러간다.
- 형식: `key1=value1,key2=value2`
## 한계 / 주의점
- **보안 경계 허점 (Security Boundary Risk)**: Baggage는 하위 시스템과 외부 네트워크 경계까지 쉽게 유실/전파될 수 있으므로, 민감 정보(자격증명, 개인정보(PII), 비밀 토큰)가 포함될 경우 데이터 유출의 주요 통로가 된다. 따라서 반드시 어댑터 송출 단계에서 엄격한 허용 목록(Allowlist) 필터링을 거치거나 원천 차단해야 한다.
- **샘플링 불일치 (Sampling Mismatch)**: 마이크로서비스 상위 계층에서 샘플링되지 않은(`00`) 트레이스 헤더가 다운스트림으로 내려가면 하위 서비스들은 해당 요청에 대한 상세 스팬 지표를 수집하지 않고 드랍할 수 있어, 트레이스 경로가 끊어지는 현상이 발생할 수 있다.
## Project Application
- [[wiki/explainer/adapter-outbound.md]]
- `TraceContextPropagationInterceptor`가 RestClient 요청 송출 시 MDC(Mapped Diagnostic Context)에 저장된 트레이스 및 배기지 컨텍스트를 가로채 전파함.
- `traceparent`는 MDC `trace_id``span_id`를 기반으로 동적으로 조립되어 전송됨 (현재는 추적 서버로 전송하지 않는 기본 뼈대이므로 샘플 플래그는 `00`으로 고정함).
- `baggage`의 경우 보안 누출 방지를 위해 오직 **`request_id`**와 **`tenant_id`** 두 가지만 통과시키는 허용 목록 필터링(`BaggageAllowlist.filter`)을 적용함.
## Claim-backed Knowledge
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| W3C traceparent 헤더 포맷 및 전파 규격 | `raw/official-docs/trace-context-w3c-recommendation.md` | `high` | W3C 공식 권고안 |
| Baggage API 스펙 및 데이터 필터링 필요성 | `raw/official-docs/baggage-w3c-baggage-spec.md` | `high` | W3C Baggage 사양 |
## 내가 설명할 수 있어야 하는 것
- `traceparent` 헤더의 구성 요소와 샘플링 플래그(`01`/`00`)의 역할은 무엇인가?
- 왜 Baggage 전파 시 Allowlist 기반의 보안 필터링이 필수적으로 수반되어야 하는가?
- 우리 아웃바운드 HTTP 클라이언트의 트레이싱 전파 시 뼈대 코드(Skeleton)의 한계는 무엇이며, 향후 실무 OTel SDK 연동 시 어떻게 대응해야 하는가? (하드코딩된 `00` 샘플링 해제 및 OTel RestClient Interceptor로의 전환)
## Interview Questions
- 마이크로서비스 간 분산 트레이싱을 구현할 때 HTTP 헤더 전파(Propagation) 과정과 Baggage 활용 시 주의해야 할 보안 위협에 대해 설명해 주세요.
- MDC 기반 트레이싱 컨텍스트와 실제 OpenTelemetry / Micrometer Tracing API의 생명 주기를 멀티스레드 환경에서 어떻게 안전하게 바인딩할 수 있습니까?
## Do Not Overclaim
- "MDC 정보가 자동으로 헤더로 전파되므로 어떤 환경에서든 분산 트레이싱이 정상 작동한다"고 과장해서는 안 된다. 멀티스레드 비동기 작업(TaskExecutor 사용 시)이나 리액티브 환경에서는 MDC가 유실되므로 별도의 Context Propagator를 직접 정의하여 스레드 경계를 가로지르는 전파 설계를 갖춰야만 보장된다.
## Sources
- [W3C Recommendation for Trace Context](https://www.w3c.org/TR/trace-context/)
- [[raw/official-docs/trace-context-w3c-recommendation.md]]
- [[raw/official-docs/baggage-w3c-baggage-spec.md]]
-1
View File
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/fail-open-fail-closed.md
+61
View File
@@ -0,0 +1,61 @@
---
title: concept / Fail-Open & Fail-Closed
source_type: llm-generated
status: reviewed
confidence: high
tags: [concept, ca-tmpl, architecture, spring-boot, circuit-breaker]
related_projects: [ca-tmpl]
last_reviewed: 2026-06-15
---
# concept / Fail-Open & Fail-Closed
## Summary
장애가 발생했을 때 시스템이 취하는 두 가지 상반된 처리 모델.
- **Fail-Open (실패 개방)**: 외부 시스템/인프라 장애 시 요청을 통과시키거나 대체 수단(Cache-Miss 등)으로 우회하여 핵심 비즈니스 기능을 계속 수행한다.
- **Fail-Closed (실패 폐쇄)**: 외부 시스템/인프라 장애 발생 시 즉시 시스템 전체 또는 해당 기능을 중단하고 예외를 전파하여 불완전한 상태에서의 처리를 강력히 차단한다.
## Standard (공식 정의)
공식적인 소프트웨어 및 인프라 설계 기법(SRE 및 분산 아키텍처)에 따르면 두 모델의 정의는 다음과 같다.
- **Fail-Open**: 보안 게이트웨이나 캐시 계층 같은 비핵심 인프라가 먹통이 되었을 때, 인프라 부재 상태를 '허용'하여 전체 서비스 가용성을 최대화하는 모델. 예컨대 캐시 서버가 죽으면 DB를 조회(Cache-miss로 취급)하도록 하여 기능 정지를 막는다.
- **Fail-Closed**: 원격 트랜잭션, 아웃박스 발행기 등 데이터 정합성이 극도로 중요한 구간에서 하위 시스템이 오류를 뱉으면 호출자에게 오류를 전파하고 전체 처리를 롤백하는 모델.
## 한계 / 주의점
- **Fail-Open의 함정**: 가용성은 유지되나 백엔드 DB에 트래픽이 폭증(Cache Stampede)하거나, 장애가 전파되어 전체 시스템이 도미노처럼 무너질 위험이 있다. 따라서 반드시 서킷 브레이커, Rate Limiter 같은 보호막이 함께 작동해야 한다.
- **Fail-Closed의 함정**: 가용성이 급격히 떨어진다. 단 하나의 마이크로서비스나 인프라 장애로 인해 전체 서비스가 5xx 에러를 뿜으며 중단될 수 있다.
## Project Application
- [[wiki/explainer/adapter-outbound.md]]
- `FailOpenCacheStore`에서는 캐시 인프라 장애 시 예외를 삼키고 캐시 미스로 처리하는 Fail-Open을 적용함.
- `KafkaOutboxMessagePublishAdapter`는 아웃박스 이벤트 유실 방지를 위해 Fail-Closed를 적용하여 예외를 반드시 상위로 전파함.
## Claim-backed Knowledge
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| 캐시 붕괴 시 DB 조회 등으로 가용성을 지키는 것 | `raw/official-docs/cache-aside-vs-write-through-aws.md` | `high` | AWS 캐시 아키텍처 가이드라인 |
| Fail-Open 구조에서 유실되지 않아야 할 이벤트 처리 | `raw/official-docs/event-sourcing-vs-outbox-microservices-io.md` | `high` | 마이크로서비스 트랜잭션 보장 기법 |
## 내가 설명할 수 있어야 하는 것
- Fail-Open과 Fail-Closed의 극명한 결정 기준은 무엇인가? (가용성 우선 vs 정합성/안전성 우선)
- 우리 프로젝트의 캐시 스토어와 아웃박스 발행기는 각각 어떤 모델을 따르며 그 이유는 무엇인가?
- Fail-Open 적용 시 백엔드 DB 보호를 위해 어떤 추가 장치가 필요한가?
## Interview Questions
- Redis 캐시 서버가 갑자기 중단되었을 때, 귀하의 시스템은 어떻게 동작하며 이를 위해 어떤 resilience 패턴을 적용했습니까?
- 메시지 발행 실패 시 예외를 상위로 전파하는 구조(Fail-Closed)와 삼켜버리는 구조(Fail-Open)의 아키텍처적 트레이드오프를 설명하십시오.
## Do Not Overclaim
- "Fail-Open을 적용했으므로 인프라가 죽어도 시스템에 아무런 영향이 없다"고 과장해서는 안 된다. 캐시가 없으면 DB 부하가 치솟으므로 성능 저하와 2차 장애 위험이 상존함을 인정해야 한다.
## Sources
- [AWS Cache-Aside caching strategy](https://aws.amazon.com/caching/)
- [[raw/official-docs/cache-aside-vs-write-through-aws.md]]
-1
View File
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/idempotency-key-design.md
+141
View File
@@ -0,0 +1,141 @@
---
title: Idempotency Key 설계 (triple scope vs Stripe/Square/Toss)
source_type: llm-generated
status: draft
confidence: medium
tags: [idempotency, api-design, distributed-systems]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Idempotency Key 설계 (triple scope vs Stripe/Square/Toss)
> Layer: `wiki/concepts/` — 일반 개념. 내 프로젝트 사실은 [[raw/branch-notes/feature-rate-limit-idempotency-contract]] / [[raw/project-notes/ca-skeleton-operational-contract]] §29 Topic 5 참조.
## Summary
Idempotency key는 동일한 mutating request의 재시도를 서버가 인식하도록 클라이언트가 생성하는 고유 값입니다. ca-tmpl은 key shape를 `(authenticatedPrincipal, idempotencyKey, useCaseName)` triple + DB table + 24h TTL + 200ms in-flight wait + fingerprint mismatch 시 HTTP 422로 정의합니다. 이 설계는 (a) triple scope로 endpoint dimension을 명시해 cross-use-case 충돌을 방지하고, (b) 24h TTL로 스토리지·키 추측 공격면을 최소화하며, (c) 200ms wait로 IETF draft의 즉시 409보다 retry 친화적인 hybrid를 채택하고, (d) body fingerprint mismatch를 409(in-flight)와 분리해 422로 표현한 점이 특징입니다.
## Standard (공식 정의)
### IETF draft (`draft-ietf-httpapi-idempotency-key-header`, draft-07, 2025-10)
- `Idempotency-Key` HTTP request header를 정의 — Stripe / PayPal / Square / Adyen이 공통 참조하는 사실상의 헤더 표준 초안 (정식 RFC 아님).
- 인용: *"Uniqueness of the key MUST be defined by the resource owner and MUST be implemented by the clients."* — key scope 정의는 **resource owner의 책임**으로 위임.
- 인용: *"If there is an attempt to reuse an idempotency key with a different request payload, the resource SHOULD reply with a HTTP `422` status code."*
- 인용: *"The request was retried before the original request completed. The resource SHOULD respond with a resource conflict error"* (HTTP `409`).
- TTL은 시간을 명시하지 않고 "정책을 정해 문서화하라"만 강제.
### Stripe v1 pair → v2 triple
- v1: `(account, Idempotency-Key)` pair. TTL 24h minimum. 5xx 응답까지 그대로 replay됨(결정적 응답).
- v2: *"idempotent request replay occurs when requests use the same idempotency key, are made to the same API, occur within the scope of the same account or sandbox, and occur within 30 days of each other."*`(account/sandbox, API, key)` triple. TTL 30일.
- fingerprint mismatch: *"The idempotency layer compares incoming parameters to those of the original request and errors if they're not the same."* (status code는 명시 안 함).
### Square (Common API patterns)
- `idempotency_key`를 **body 필드**로 받음 (header 표준 미준수). endpoint별 dedup → `(merchant_account, endpoint, idempotency_key)` 사실상 triple.
- fingerprint mismatch: *"If you use the same idempotency key but change the `CreatePayment` request ... you get an error indicating that you used the idempotency key previously."*
- TTL 미공개, in-flight 동작 미정의.
- 특수 디자인: `cancel-payment-by-idempotency-key` — 키 자체를 resource handle로 사용.
### PayPal (Idempotency-Replay / `PayPal-Request-Id`)
- header 이름이 `Idempotency-Key`가 아닌 `PayPal-Request-Id` (Stripe·IETF와 다름).
- scope: `(request-id, API call type)`. TTL **45일** — 조사된 reference 중 최장.
### Toss Payments (기술블로그)
- 4-tuple `(account, key, URL, method)` + TTL **15일**. ca-tmpl보다 dimension 1개 많고 TTL 더 김.
- header 이름은 `Idempotency-Key`로 IETF/Stripe와 동일.
### AWS Lambda Powertools (idempotency utility)
- key를 **server-derived content-hash** `(function_name, payload_hash)`로 도출 → 클라이언트가 header를 보낼 필요 없음.
- 동일 payload면 동일 hash → 자동 dedup. body 변경 = 서로 다른 operation으로 취급.
### GitHub REST API
- API-level idempotency dedup을 제공하지 않음. 클라이언트 측 retry 정책에만 의존.
### Brandur (Stripe 엔지니어 글) — Postgres locked_at lock
- Postgres 테이블 + atomic phase 모델 + `locked_at` column으로 in-flight를 표현. abandoned key 회수는 별도 정책 필요.
- Stripe 내부 구현의 가장 자세한 reference 문서.
## 한계 / 주의점
| 옵션 | 한계 / 주의점 |
|------|-----------|
| **Stripe v1 pair `(account, key)`** | endpoint dimension 부재 → API 추가 시 같은 키가 의도하지 않은 use case에 재사용될 위험. v2에서 API dimension 추가로 직접 보강. |
| **Stripe v2 triple `(account, API, key)`** | IETF "resource owner가 정의" 범위 내에서 가장 엄격한 reference. TTL 30일은 보안 surface와 비용에 부담. |
| **Square endpoint-scoped (body field)** | header 표준 미준수 → 미들웨어/게이트웨이 레벨에서 dedup 불가. URL path 변경 시 endpoint dimension 매핑이 깨질 수 있음. TTL 미공개로 클라이언트가 retry window를 가늠 못 함. |
| **PayPal 45일 TTL** | 스토리지 비용 크고 키 추측 공격면이 가장 넓음. header 이름이 표준과 달라 멀티 PG 통합 비용 발생. |
| **Toss 4-tuple `(account, key, URL, method)`** | URL/method가 scope에 들어가 HTTP path 변경(예: `/v1/payments``/v2/payments`) 시 같은 의미의 재시도가 다른 키로 인식. version migration에 취약. |
| **AWS Powertools content-hash** | 클라이언트가 키를 누락해도 동작하는 장점이 있으나, body의 사소한 변경(여백/필드 순서)이 다른 operation으로 분류 — JSON canonicalization 정책 필수. |
| **Brandur Postgres lock (`locked_at`)** | `locked_at`만으로는 process crash 후 stale lock이 남을 수 있음 → abandoned key 회수(timeout-based release) 정책이 별도로 필요. |
| **IETF draft 자체** | draft 단계로 정식 RFC 아님. TTL / 저장 layer / lock 정책 등 운영 핵심을 표준이 다루지 않아 구현체별 동작이 제각각. |
| **No API-level dedup (GitHub)** | 인프라/미들웨어 부담은 없으나 클라이언트가 모든 중복 위험을 책임 → 결제·금융 도메인에는 부적합. |
### 흔한 오해
- "Stripe pair보다 ca-tmpl이 무조건 안전" — **v1 한정** 비교. Stripe v2 triple과는 사실상 동등.
- "IETF draft 422는 fingerprint mismatch의 표준" — draft는 `SHOULD`이지 `MUST` 아님. 구현체별로 400/409/422가 혼재.
- "TTL은 길수록 안전하다" — 길수록 클라이언트 retry window는 늘지만 스토리지 비용과 키 추측 공격면도 함께 증가.
## Project Application
- [[wiki/projects/ca-tmpl/idempotency-key-design]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
- [[raw/branch-notes/feature-rate-limit-idempotency-contract]] — key shape / TTL / 저장소 SSOT (triple scope + DB table + 24h TTL + 200ms wait + 422 fingerprint mismatch + 409 in-flight 결정의 owning branch).
- [[raw/branch-notes/feature-api-contract-baseline]] — `Idempotency-Key` HTTP header 표준 (consume only, shape은 위 branch가 owns).
- [[raw/project-notes/ca-skeleton-operational-contract]] §29 Topic 5 — 비교표·결정 라인.
## Interview Questions
- **Q1.** `useCaseName` (또는 endpoint) dimension을 scope에 포함시키는 이유는? Stripe v1 pair에서 어떤 충돌이 발생할 수 있는가?
- **Q2.** TTL을 24h로 잡은 trade-off는? PayPal 45일·Stripe v2 30일과 비교했을 때 어떤 비용·위험을 줄이고, 어떤 use case(예: 결제·송금 long-running)에서는 부족한가?
- **Q3.** 동시 도착 요청에 대해 200ms wait를 둔 의미는? IETF draft의 즉시 409와 비교했을 때 client retry 동작이 어떻게 달라지는가?
- **Q4.** 같은 key + 다른 body를 422로, in-flight 충돌을 409로 분리한 이유는? 두 상황을 같은 코드로 합치면 어떤 클라이언트 버그가 가려지는가?
- **Q5.** key가 클라이언트 생성 unique value라면 추측 공격면은 어떻게 평가해야 하는가? TTL이 길수록 공격면이 어떻게 변하고, AWS Powertools content-hash 방식은 이 문제를 어떻게 우회하는가?
## Do Not Overclaim
- "ca-tmpl triple이 Stripe pair보다 무조건 안전하다"고 말하지 않습니다. **v1 pair 한정** 비교이며, Stripe v2 triple과는 사실상 동급.
- "ca-tmpl이 IETF Idempotency-Key spec을 완전히 준수한다"고 단정하지 않습니다. **draft 단계**이고, 422 fingerprint mismatch는 `SHOULD`이며, ca-tmpl의 200ms wait는 draft의 "즉시 409" 권고와 다른 선택입니다.
- "Square가 표준 미준수라서 열등하다"고 단정하지 않습니다. body 필드 방식은 `cancel-by-idempotency-key`처럼 키를 resource handle로 쓰는 API 디자인의 장점이 있습니다.
- "AWS Powertools content-hash가 header 방식의 상위 호환"이라고 말하지 않습니다. body의 사소한 변경(여백/필드 순서/timestamp)이 다른 operation으로 분류되므로 canonicalization 정책이 함께 가야 동작합니다.
- "Brandur lock 패턴을 그대로 채택했다"고 말하지 않습니다. ca-tmpl은 200ms wait + unique constraint hybrid이며 Brandur `locked_at` lock의 변형입니다.
- ca-tmpl 24h TTL이 "업계 표준"이라고 표현하지 않습니다. Stripe v1 최소값과 일치할 뿐이고, 다른 도메인 reference는 모두 더 길게 잡습니다.
## Sources
### 공식 / 표준
- [IETF draft — The Idempotency-Key HTTP Header Field](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/) — 422/409 status code 근거, "resource owner가 scope 정의" 권한 위임.
- [Stripe API Reference — Idempotent requests](https://docs.stripe.com/api/idempotent_requests) — v1 pair / v2 triple scope, 24h30d TTL, 5xx replay.
- [Square API — Idempotency (Common API patterns)](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency) — body 필드 방식, fingerprint mismatch error.
- [PayPal — Idempotency](https://developer.paypal.com/api/rest/reference/idempotency/) — `PayPal-Request-Id`, 45일 TTL.
- [AWS Lambda Powertools — Idempotency utility](https://docs.powertools.aws.dev/lambda/python/latest/utilities/idempotency/) — content-hash 기반.
- [GitHub REST API](https://docs.github.com/en/rest) — API-level dedup 없음.
### 구현 reference
- [Brandur Leach — Implementing Stripe-like Idempotency Keys in Postgres](https://brandur.org/idempotency-keys) — atomic phase + `locked_at` lock.
### raw 보존본
- [[raw/official-docs/idempotency-ietf-draft]]
- [[raw/official-docs/idempotency-stripe-api-ref]]
- [[raw/official-docs/idempotency-square-api]]
- [[raw/official-docs/idempotency-paypal-docs]]
- [[raw/official-docs/idempotency-aws-lambda-powertools]]
- [[raw/official-docs/idempotency-no-api-level-github-rest]]
- [[raw/company-tech-blogs/idempotency-brandur-stripe-postgres]]
- [[raw/company-tech-blogs/idempotency-toss-payments-techblog]]
- [[raw/company-tech-blogs/idempotency-redis-vs-db-storage]]
### canonical 참조
- [[raw/project-notes/ca-skeleton-operational-contract]] §29 Topic 5
- [[raw/branch-notes/feature-rate-limit-idempotency-contract]]
- [[raw/branch-notes/feature-api-contract-baseline]]
-1
View File
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/idempotency.md
+60
View File
@@ -0,0 +1,60 @@
---
title: concept / Idempotency
source_type: llm-generated
status: reviewed
confidence: high
tags: [concept, ca-tmpl, api-design, spring-boot, idempotency]
related_projects: [ca-tmpl]
last_reviewed: 2026-06-15
---
# concept / Idempotency
## Summary
동일한 요청을 한 번 보내는 것과 여러 번 연속해서 보내는 것이 서버의 상태에 미치는 영향이 동일한 성질.
- 안전한 메서드(Safe Methods) 및 멱등한 메서드(Idempotent Methods)를 구분하여 HTTP 클라이언트의 재시도 안전성을 보장하는 기반이 된다.
## Standard (공식 정의)
RFC 9110 HTTP Semantics 규격에 따른 정의는 다음과 같다.
- **Idempotent Methods**: `GET`, `HEAD`, `PUT`, `DELETE`, `OPTIONS`, `TRACE`는 여러 번 수행해도 리소스의 최종 상태가 동일하다. 따라서 transient network failure 발생 시 클라이언트가 안전하게 재시도할 수 있다.
- **Non-Idempotent Methods**: `POST``PATCH`는 호출할 때마다 새로운 리소스가 생성되거나 상태 변경이 누적될 수 있어, 재시도가 안전하지 않다. 중복 처리를 방지하려면 별도의 `Idempotency-Key` 헤더와 같은 고유 분산 락/식별 메커니즘이 합의되어야 한다.
## 한계 / 주의점
- **멱등성은 서버가 보장해야 하는 계약이다**: 클라이언트 입장에서 단순히 `GET`을 보낸다고 해서 서버가 내부적으로 멱등하게 처리하지 않고 사이드 이펙트(예: 조회수 1 증가 등)를 누적한다면 엄격한 의미의 멱등성은 깨질 수 있다. 그러나 HTTP 명세상 클라이언트는 RFC 규격을 신뢰하고 재시도를 감행하게 된다.
- **Idempotency-Key 계약의 부재**: 아웃바운드 연동 시 상대방 서버가 `Idempotency-Key` 사양을 구현하지 않았다면, `POST``PATCH` 호출 실패 시 클라이언트는 네트워크 지연 등의 원인으로 인해 요청이 이미 처리되었는지 알 수 없어 재시도가 불가능하다.
## Project Application
- [[wiki/explainer/adapter-outbound.md]]
- `OutboundRetryPolicy`는 RFC 9110 규격에 정의된 멱등한 메서드(`GET`, `HEAD`, `PUT`, `DELETE`)에 대해서만 `shouldRetry``true`를 반환하도록 설계되어 있음. `POST`/`PATCH`는 부작용 방지를 위해 즉시 `false`를 뱉고 재시도를 전면 금지함.
## Claim-backed Knowledge
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| RFC 9110 기반 멱등 메서드 리스트 및 재시도 타당성 | `raw/official-docs/rfc9110-http-semantics.md` | `high` | RFC 9110 표준 명세 |
| non-idempotent API 재시도를 위한 Idempotency-Key 계약 | `raw/official-docs/idempotency-stripe-api-ref.md` | `high` | Stripe의 실무 멱등 키 처리 패턴 |
## 내가 설명할 수 있어야 하는 것
- `GET``PUT`은 왜 멱등하고 `POST``PATCH`는 왜 비멱등한가?
- 왜 우리 아웃바운드 HTTP 클라이언트는 `POST`/`PATCH` 요청에 대해 재시도를 원천 차단하는가? (Idempotency-Key 계약 미정의에 따른 사이드 이펙트 방지)
- 비멱등 메서드를 꼭 재시도해야 할 경우, 인프라 및 애플리케이션 계층에서 어떤 설계를 보완해야 하는가?
## Interview Questions
- HTTP 메서드 중 멱등성을 보장하는 메서드와 그렇지 않은 메서드를 구분하고, 네트워크 타임아웃 발생 시 각각에 대한 재시도 전략을 설명해 주세요.
- 아웃바운드 호출 시 POST 요청의 재시도를 제한하는 시스템에서, 일시적인 네트워크 순단 상황을 어떻게 극복할 수 있겠습니까?
## Do Not Overclaim
- "멱등한 메서드만 재시도하므로 어떠한 데이터 정합성 문제도 발생하지 않는다"고 확언해서는 안 된다. 업스트림(상대방 서버)이 표준을 무시하고 내부 구현을 비멱등하게 작성했을 경우 여전히 사이드 이펙트가 발생할 수 있음을 인지해야 한다.
## Sources
- [RFC 9110 Section 9.3: Idempotent Methods](https://www.rfc-editor.org/rfc/rfc9110.html)
- [[raw/official-docs/rfc9110-http-semantics.md]]
- [[raw/official-docs/idempotency-stripe-api-ref.md]]
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/multi-tenancy-isolation-patterns.md
@@ -0,0 +1,142 @@
---
title: Multi-tenancy Isolation 패턴 (Pool vs Silo vs Bridge)
source_type: llm-generated
status: draft
confidence: medium
tags: [multi-tenancy, saas, isolation]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Multi-tenancy Isolation 패턴 (Pool vs Silo vs Bridge)
> Layer: `wiki/concepts/` — 일반 개념. 실제 적용은 `wiki/projects/` 또는 raw 브랜치 노트 참조.
## Summary
Multi-tenancy isolation은 "여러 tenant가 같은 소프트웨어 인스턴스를 어느 수준까지 공유하는가"의 스펙트럼이다. AWS SaaS Lens는 이를 **Silo / Pool / Bridge** 3분류로 정리하고, Hibernate는 ORM 레벨에서 **DATABASE / SCHEMA / DISCRIMINATOR** 3 strategy로 공식 지원하며, Azure는 **Deployment Stamps** 패턴으로 hybrid를 다룬다. ca-tmpl은 **opt-in(`APP_TENANT_ENABLED=true` 시만 활성) + shared DB + `tenant_id` column(ULID) + JWT claim 우선 resolution** 조합을 baseline으로 채택한다. 이는 AWS Pool 모델 + Hibernate DISCRIMINATOR 전략에 해당하며, B2B 초기 단계(tenant 수 수십~수백 단위)에 isolation 비용 대비 운영 단순성을 우선한 의도적 선택이다. opt-in 설계의 의의는 single-tenant deployment에서는 tenant 로직 자체를 비활성화하여 skeleton의 적용 범위를 넓힌 점에 있다. **Migration trigger 3가지**는 (a) 규제(금융·의료) isolation 강제, (b) tenant 수 수백~수천 + 단일 row 수 수억 도달, (c) enterprise tier 등장으로 isolation을 가격에 반영해야 할 때다.
## Standard (공식 정의)
### AWS SaaS Tenant Isolation Strategies (Whitepaper) — Silo / Pool / Bridge
- **Silo**: tenant마다 별도 stack(compute/DB/network까지 분리). isolation 최강, 비용 최대.
- **Pool**: 모든 tenant가 동일 infra와 schema를 공유, `tenant_id` 컬럼으로 row-level 구분.
- **Bridge**: 일부 리소스는 silo, 일부는 pool. 예) DB는 silo, app server는 pool.
- AWS는 "Authentication is not isolation. You must enforce isolation at the resource layer"라고 명시한다.
### Hibernate ORM Multi-tenancy — DATABASE / SCHEMA / DISCRIMINATOR
- **DATABASE**: tenant별 별도 데이터베이스.
- **SCHEMA**: 동일 DB, tenant별 별도 schema.
- **DISCRIMINATOR**: 동일 schema, `tenant_id` 컬럼. Hibernate 6부터 native 지원(이전엔 Filter로 우회).
- 활성화는 `hibernate.tenant_identifier_resolver` + `hibernate.multi_tenant_connection_provider` 설정으로 수행. `CurrentTenantIdentifierResolver`가 ThreadLocal/SecurityContext에서 tenant를 결정.
### Azure Architecture Center — Deployment Stamps (Hybrid)
- Tenancy를 "fully shared → shared compute, isolated DB → isolated stamp → isolated subscription" **스펙트럼**으로 정의.
- **Deployment Stamps**: 동일한 스택을 단위(stamp)로 복제하고, stamp 안에 N개 tenant를 pool. tier별로 stamp 크기와 isolation 수준을 다르게 둘 수 있음.
- Microsoft는 "There's no single right approach to multitenancy"라고 명시 — 비즈니스 모델·규제·확장성·비용에 따라 모델이 달라진다.
### Tenant Resolution 방식 (isolation과 직교)
- **JWT claim**: token 서명 검증으로 위변조 방지. 가장 안전.
- **Subdomain (`{tenant}.app.com`)**: UX 친화적, 단 wildcard DNS/TLS 필요.
- **Custom header (`X-Tenant-Id`)**: 단순하나 외부 trust boundary에서 단독 신뢰 금지.
- **Path (`/t/{tenant}/...`)**: routing 자연스럽지만 모든 client URL 변경.
## 한계 / 주의점
각 대안의 한계는 다음과 같다.
### shared DB + tenant_id (Pool / Hibernate DISCRIMINATOR)
- **Noisy neighbor**: hot tenant가 같은 인스턴스 전체에 영향.
- **규제 isolation 불가**: application bug 한 줄로 cross-tenant leak 가능. HIPAA·FedRAMP·금융권은 storage 레벨 분리를 요구하는 경우가 있어 Pool로 충족 어려움.
- **Index 비용**: tenant로 filter하는 모든 index에 `tenant_id`를 leading column으로 포함해야 plan이 효율적.
- **Native query/JDBC bypass 위험**: JPQL 경로 외에서 tenant filter 누락 시 leak.
### Subdomain-based resolution
- **Wildcard DNS와 wildcard TLS 인증서** 필요. custom domain 지원 시 per-domain 인증서 자동화 추가.
- Let's Encrypt rate limit은 "registered domain당 주 50개 인증서"로 보고되나 — 정확 수치와 적용 범위는 `needs-confirmation` (raw 발췌 기준).
- **DNS propagation 지연**, **subdomain takeover 위험**(tenant 삭제 후 DNS record 미정리), **CORS/cookie domain 설정 복잡성**.
- Local dev는 `lvh.me`/`nip.io`/hosts 수정 필요.
### JWT claim only
- claim 검증을 한 곳이라도 빠뜨리면 cross-tenant 위험.
- token 재발급 없이 tenant 전환 불가 → admin/support 운영 동선 제약.
- IdP와 강결합 → tenant 정보 변경 시 token rotation 정책 필요.
### Schema-per-tenant (Hibernate SCHEMA)
- Postgres metadata(`pg_class`, `pg_attribute`) overhead가 tenant 수 증가에 따라 누적.
- Stripe/Citus 자료에 따르면 "수백~수천 tenant"에서 catalog bloat·autovacuum·plan cache miss가 문제로 보고됨 — 다만 정확한 임계 수치 인용은 `needs-confirmation`.
- **Connection pooling 난이도**: `search_path` 전환이 plan cache를 무효화. HikariCP per tenant vs single pool 설계 선택 필요.
- 마이그레이션이 tenant 수만큼 반복(Flyway `schemas` 옵션으로 일괄 처리 가능하나 추가/삭제 자동화 필요).
### Database-per-tenant (Silo)
- Isolation 가장 강함, **운영 비용 폭증**: 마이그레이션·백업·모니터링이 모두 tenant 수에 비례.
- Connection pool이 (tenant 수 × pool size)로 폭발 → connection multiplexing(예: PgBouncer) 필수.
- AWS 계정·서비스 limit에 부딪힐 수 있음.
- 비용은 silo > bridge > pool 순.
### Hybrid (Azure Deployment Stamps / AWS Bridge)
- 두 가지 이상 모델을 동시 운영 → **운영 복잡도 최고**.
- Tier 승급(pool → silo) 시 **데이터 이동 절차** 필요.
- Routing layer + tenant catalog가 사실상 control plane이 되어, 가용성 single point가 되지 않도록 분산 필요.
- 작은 팀에서 도입하면 ROI 부정. 일반적으로 product-market fit 이후 단계에서 검토.
### 공통 오해
- "Pool이면 무조건 싸다"는 거짓 — 노이즈/검증 비용이 일정 규모 이상에선 silo와 역전될 수 있음.
- "Subdomain이면 자동 isolation" 거짓 — resolution과 isolation은 직교. subdomain은 routing일 뿐 storage 분리를 보장하지 않음.
- "JWT claim만 있으면 안전" 거짓 — repository·query 레이어에서 tenant filter를 강제하지 않으면 claim의 의미가 없음.
## Project Application
- [[wiki/projects/ca-tmpl/multi-tenancy-isolation-patterns]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
ca-tmpl은 본 개념을 다음 위치에서 적용·문서화한다. concept 문서는 등급을 매기지 않으며, 검증 수준은 각 프로젝트/브랜치 노트에서 판정한다.
- [[raw/branch-notes/feature-tenant-context-policy]] — tenant resolution(JWT > header admin only > subdomain fallback) + isolation SSOT
- [[raw/branch-notes/feature-repository-access-permission-contract]] — `CROSS_TENANT_ADMIN` capability, repository 레벨 tenant filter 강제 contract
- [[raw/project-notes/ca-skeleton-operational-contract]] — §10 Repository Access Permission Contract, §29 Topic 6 Multi-tenancy Isolation
## Interview Questions
- AWS SaaS Lens의 Pool/Silo/Bridge는 무엇이 다르고, 어떤 상황에서 어떤 모델을 선택하나?
- Tenant ID를 JWT claim과 HTTP header 중 어디서 읽어야 하며, 둘을 동시에 허용한다면 어떤 trust 기준을 두는가?
- shared DB + tenant_id에서 schema-per-tenant 또는 db-per-tenant로 마이그레이션을 트리거하는 조건은 무엇인가?
- Cross-tenant 침해를 막기 위해 어느 레이어(JWT 검증 / SecurityContext / repository / DB)에 어떤 방어가 필요한가?
- Tenant 식별자에 ULID와 UUID 중 어느 쪽을 쓰는 게 적합하며, 각 선택의 trade-off는 무엇인가?
## Do Not Overclaim
- "shared DB + tenant_id가 항상 우월하다"고 말하지 말 것 — 규제 산업·data residency 요구가 있는 도메인에서는 Silo가 필수 또는 사실상 강제다.
- Stripe/Citus의 schema-per-tenant 한계치(예: "정확히 N tenant에서 한계")는 **정확 인용 wording이 미완**이며 raw 자료는 `needs-confirmation` 상태다. 면접/이력서에서는 "수백~수천 단위에서 catalog overhead가 보고된다" 정도로 출처(Citus blog)와 함께만 언급할 것.
- "Atlassian이 그렇게 하니까 best practice"라고 말하지 말 것 — company-tech-blog 사례는 관점·증거이지 공식 기준이 아니다.
- "JWT claim만 검증하면 multi-tenant가 안전하다"는 단정 금지 — claim은 입구일 뿐 storage layer 강제가 별도로 필요하다.
- ca-tmpl 적용 사실(예: ULID 채택 이유, capability 설계)은 본 concept 문서가 아니라 `wiki/projects/` 또는 branch-notes에서 검증 등급과 함께 진술할 것. "내가 했다"는 표현은 concept 레이어에 두지 않는다.
## Sources
- [AWS Whitepaper — SaaS Tenant Isolation Strategies](https://docs.aws.amazon.com/whitepapers/latest/saas-tenant-isolation-strategies/saas-tenant-isolation-strategies.html) — Silo/Pool/Bridge 분류 baseline
- [Hibernate ORM User Guide — Multi-tenancy](https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#multitenacy) — DATABASE/SCHEMA/DISCRIMINATOR 공식 strategy
- [Azure Architecture Center — Multitenant SaaS](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/overview) — Deployment Stamps / hybrid spectrum
- [Citus — Designing your SaaS DB for High Scalability](https://www.citusdata.com/blog/2016/10/03/designing-your-saas-database-for-high-scalability/) — schema vs shared schema 한계치 (company-tech-blog, needs-confirmation)
- [Auth0 — Multi-tenant applications](https://auth0.com/docs/get-started/auth0-overview/create-tenants/multiple-tenants) — tenant resolution(subdomain/JWT/header) 비교
- [Vercel — Multi-tenant Next.js Guide](https://vercel.com/guides/nextjs-multi-tenant-application) — subdomain routing 실무
- [AWS APN Blog — Hybrid Tenant Isolation](https://aws.amazon.com/blogs/apn/) — tier-based hybrid 사례
- [Atlassian Engineering — Cloud Architecture Guidelines](https://www.atlassian.com/engineering/cloud-architecture-and-guidelines) — shard 단위 isolation + tenant context propagation 사례
- [[raw/official-docs/multitenancy-aws-saas-tenant-isolation-whitepaper]]
- [[raw/official-docs/multitenancy-hibernate-user-guide]]
- [[raw/official-docs/multitenancy-azure-architecture-patterns]]
- [[raw/company-tech-blogs/multitenancy-stripe-citus-schema-per-tenant]]
- [[raw/company-tech-blogs/multitenancy-auth0-tenant-resolution]]
- [[raw/company-tech-blogs/multitenancy-subdomain-resolution-patterns]]
- [[raw/company-tech-blogs/multitenancy-hybrid-pooled-siloed-mix]]
- [[raw/company-tech-blogs/multitenancy-atlassian-tenant-context]]
- [[raw/project-notes/ca-skeleton-operational-contract]] — §10, §29 Topic 6
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/observability-log-metric-trace-runbook.md
@@ -0,0 +1,155 @@
---
title: Observability Baseline (Log + Metric + Trace + Runbook)
source_type: llm-generated
status: draft
confidence: medium
tags: [observability, logging, metrics, tracing, runbook, sre]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Observability Baseline (Log + Metric + Trace + Runbook)
> Layer: `wiki/concepts/` — 일반 개념. 내 프로젝트 사실은 project 문서에서 다룬다.
## Summary
Observability는 세 가지 신호(structured log, metric, distributed trace)와 이를 운영 행위로 잇는 runbook이 결합될 때 성립한다. ca-tmpl은 **JSON Logback + Micrometer dot.case 이름 규칙 + W3C tracecontext 전파 + `runbook://` URI 스킴**을 기본선으로 잡아 네 축을 하나의 운영 계약으로 묶는다. 어느 한 축만 갖추면 인시던트 시 "왜·어디서·어떻게 대응할지"를 답할 수 없다.
## Standard (공식 정의)
### Log
- **ECS (Elastic Common Schema)**: `@timestamp`, `log.level`, `service.name`, `trace.id`, `event.dataset` 등 필드명을 표준화. Elastic이 정의한 공개 스키마지만 OTel·Loki·Datadog도 부분 호환.
- **OpenTelemetry Log Data Model**: log record를 trace/metric과 동일 SDK로 다루는 신호. `SeverityNumber`, `Body`, `Attributes`, `TraceId`/`SpanId` correlation을 정의.
- **Structured logging best practice**: 자유 텍스트가 아닌 key-value JSON. PII는 발신 측에서 마스킹 (Logback `ch.qos.logback.classic.pattern` 또는 `MaskingPatternLayout`).
### Metric
- **Micrometer**: JVM 표준 facade. 이름은 `dot.case` (`http.server.requests`), `meterRegistry`가 backend별 변환을 담당.
- **Prometheus**: pull-based, label cardinality bound 권장. exporter가 dot을 `_`로 변환 (`http_server_requests_seconds_count`).
- **OpenTelemetry Metrics Data Model**: counter / gauge / histogram / exponential histogram을 정의. instrument 종류와 aggregation을 분리.
- **RED method (Tom Wilkie)**: Request rate / Error rate / Duration. request-driven 서비스 표준.
- **USE method (Brendan Gregg)**: Utilization / Saturation / Errors. 리소스 관점.
- **SLO burn-rate alert (Google SRE Workbook)**: error budget 소진 속도를 multi-window multi-burn-rate로 측정 (예: 1h 14.4× burn AND 5m 14.4× burn).
### Trace
- **W3C Trace Context (W3C TR)**: `traceparent` 헤더 — `version-trace-id-parent-id-trace-flags`. 128-bit trace-id, 64-bit span-id, vendor-neutral.
- **Micrometer Tracing**: Spring 진영의 facade. Brave(Zipkin) 또는 OpenTelemetry bridge로 backend 교체 가능.
- **B3 propagation (Zipkin legacy)**: `X-B3-TraceId`(64 or 128-bit), `X-B3-SpanId`, `X-B3-Sampled`. 일부 레거시 서비스 호환용.
- **Sampling**: head-based (요청 시점 결정, 저비용) vs tail-based (span 완료 후 결정, 고비용·고정밀). OTel Collector가 tail processor 제공.
### Runbook
- **Google SRE Workbook**: incident response·postmortem·error budget을 한 묶음으로 본다. runbook은 "on-call이 새벽 3시에 따라할 수 있어야" 한다.
- **PagerDuty Incident Response**: severity(SEV-1~5), incident commander, scribe, communication template을 표준화.
- **PagerDuty Runbook Automation (구 Rundeck)**: runbook을 코드/스크립트로 실행. drift 감소.
- **ITIL**: 광의의 service operation 프로세스 (incident / problem / change). runbook은 ITIL의 procedure에 해당.
- **Runbook-as-code (GitOps)**: markdown runbook을 git에 두고 alert payload에 URL을 박는다. `runbook://` 같은 내부 스킴은 ca-tmpl 관례.
## 한계 / 주의점
### Log
| 항목 | 한계 |
|------|------|
| ECS schema | Elastic이 사실상 owner — Loki/Datadog 채택은 부분적, **vendor lock-in 위험**. |
| OTel log signal | 2024년 기준 GA 진입했지만 ecosystem maturity는 metric/trace 대비 낮음. SDK·Collector 버전 호환에 주의. |
| SaaS 백엔드 (Loki/Datadog/Splunk) | 필드 매핑·인덱싱 정책이 제품마다 달라 schema drift 발생. 마이그레이션 비용 큼. |
| Masking | Logback `MaskingPatternLayout`은 정규식 기반 — false negative (놓침)·false positive (과다 마스킹) 모두 가능. 정책은 발신지에서. |
### Metric
| 항목 | 한계 |
|------|------|
| Naming drift | Micrometer dot.case → Prometheus exporter underscore 변환은 자동이지만, 대시보드·alert rule은 backend 표기를 직접 참조 → 코드와 alert 사이 표기 분리. |
| Cardinality | `userId`·`requestId`처럼 unbounded label을 metric에 박으면 시계열 폭증. trace/log로 보내야 함. |
| SLO burn-rate | 식이 직관적이지 않음. SLO 자체가 없는 단계에선 traffic-based threshold가 더 합리적. |
| Histogram | exponential histogram은 OTel·Prometheus 양쪽에서 채택 중이나 client/server 호환 매트릭스 확인 필요. |
### Trace
| 항목 | 한계 |
|------|------|
| Sampling | head-based 1% sampling은 rare-error 누락 위험. tail-based는 Collector 메모리·CPU 비용 큼. |
| Adaptive sampling | "에러는 100%, 정상은 N%" 같은 정책 — 검증·재현이 어렵고 비교 분석을 깨뜨릴 수 있음. |
| B3 non-호환 | B3 64-bit trace-id는 W3C 128-bit와 1:1 호환 안 됨. 게이트웨이에서 변환 정책 필요. |
| Backend lock-in | Datadog APM·New Relic의 auto-instrumentation은 강력하지만 OTel exporter로 동등하게 옮기기 어려움. |
| 비용 | full-trace 보관은 비싸다. 보존 기간·sampling rate가 곧 비용. |
### Runbook
| 항목 | 한계 |
|------|------|
| Drift | Confluence·Notion runbook은 코드와 따로 움직여 stale 되기 쉽다. |
| Automation lock-in | PagerDuty Runbook Automation·Rundeck 같은 도구는 ops 표면을 그 제품에 묶는다. |
| `runbook://` scheme | git markdown 링크는 repo 이동·이름 변경 시 link rot. CI에서 link check 필요. |
| 적용 한계 | runbook은 "이미 알려진 장애"에 강하다. novel incident에는 framework(SEV·comm·IC)만 도움이 되고 절차 자체는 비워둬야 한다. |
## Project Application
- [[wiki/projects/ca-tmpl/observability-log-metric-trace-runbook]] — ca-tmpl 의사결정 기록 (`verified` — foundation observability 토대 slice는 MDC snake_case 표준 + 응답-로그 상관 + 헤더 sanitization으로 코드 구현·로컬 검증됨; 4축 full 기능은 여전히 `documented-only`). 실제 구현 범위·검증 수준은 project 문서 참조.
- [[raw/project-notes/ca-skeleton-operational-contract]] — ca-tmpl 운영 계약 SSOT (§8 Structured Log, §6 Operational Error, §29 G-A).
- [[raw/branch-notes/feature-log-management-contract]] — JSON Logback + masking + trace 상관관계 계약.
- [[raw/branch-notes/feature-metrics-alerting-contract]] — Micrometer dot.case + SLO burn-rate alert 계약.
- [[raw/branch-notes/feature-distributed-tracing-contract]] — W3C tracecontext 전파 + sampling 계약.
- [[raw/branch-notes/feature-operational-runbook-contract]] — `runbook://` scheme · alert payload 연동 계약.
- [[raw/branch-notes/feature-operational-error-observability-foundation]] — error code · severity · 3 pillars 연계 토대.
## Claim-backed Knowledge
> 이 개념 문서의 핵심 설명은 raw source claim 으로 뒷받침되어야 한다.
> 공식 문서 claim, 회사 사례 claim, 내 프로젝트 decision 을 분리한다.
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| ECS는 `@timestamp`/`log.level`/`service.name`/`trace.id` 등 로그 필드명을 표준화한 공개 스키마다 | [[raw/official-docs/log-ecs-schema-elastic-official]] | `high` | 공식(Elastic) — 사실상 Elastic이 owner라 Loki/Datadog 채택은 부분적, vendor lock-in 위험 |
| OpenTelemetry는 log를 trace/metric과 동일 SDK 신호로 다루며 `TraceId`/`SpanId` correlation을 정의한다 | [[raw/official-docs/log-otel-log-data-model-spec]], [[raw/official-docs/metric-otel-metrics-data-model-spec]] | `high` | 공식 spec — log signal은 metric/trace 대비 ecosystem maturity 낮음 |
| Micrometer는 `dot.case` 이름 규칙을 쓰고 Prometheus exporter가 `_`로 변환한다 (`http.server.requests``http_server_requests_seconds_count`) | [[raw/official-docs/metric-micrometer-naming-convention-official]] | `high` | 공식 — 대시보드·alert rule은 backend 표기를 직접 참조해 코드/alert 표기 분리 발생 |
| W3C Trace Context `traceparent`는 128-bit trace-id·64-bit span-id의 vendor-neutral 표준이며 B3(64-bit)와 1:1 lossless 변환이 안 된다 | [[raw/official-docs/tracing-w3c-trace-context-spec]], [[raw/official-docs/tracing-b3-propagation-zipkin-spec]] | `high` | 공식 — hybrid 환경에서 게이트웨이 변환 정책 필요 |
| trace sampling은 head-based(저비용, rare-error 누락 위험) vs tail-based(고정밀, Collector 메모리/CPU 비용)의 trade-off다 | [[raw/official-docs/tracing-otel-sampling-tail-vs-head-spec]] | `high` | 공식 — full-trace 보관 비용이 곧 보존기간·sampling rate |
| SLO burn-rate alert는 error budget 소진 속도를 multi-window multi-burn-rate로 측정한다 | [[raw/official-docs/metric-google-sre-slo-burn-rate]] | `high` | 공식(Google SRE Workbook) — SLO 미합의 단계에선 traffic-based threshold가 더 운영 가능 |
| PagerDuty는 severity·incident commander·comm template로 incident response를 표준화하며 runbook은 "on-call이 새벽 3시에 따라할 수 있어야" 한다 | [[raw/official-docs/runbook-pagerduty-incident-response-doc]] | `high` | 공식 — runbook은 알려진 장애에 강하고 novel incident엔 framework만 유효 |
## 내가 설명할 수 있어야 하는 것
- Observability 3 pillars(log/metric/trace)의 공식 정의와 각 신호가 서로 대체 불가능한 이유는?
- 각 축의 공개 표준(ECS / OTel data model / Micrometer / W3C Trace Context / SLO burn-rate)은 무엇을 규정하는가?
- 어떤 상황에서는 특정 선택을 쓰면 안 되는가(SLO 미합의 시 burn-rate alert, unbounded label을 metric에 박기 등)?
- 공식 표준이 말하지 않는 부분(backend lock-in, schema drift, masking false negative/positive)은 무엇인가?
- Datadog APM vs OTel 같은 tech-blog 비교를 공식 best practice처럼 일반화하면 안 되는 지점은?
- 내 프로젝트에서는 어떤 branch decision(MDC snake_case 표준, W3C traceparent 채택, `runbook://` scheme 등)으로 연결됐는가?
- 이 개념을 코드/운영에서 검증하려면 무엇을 확인해야 하는가(MDC 키 일관성, 응답-로그 상관, 헤더 sanitization, alert 발화 등)?
## Interview Questions
- Observability **3 pillars**(log/metric/trace)를 정의하고, 각각이 다른 신호로 대체될 수 없는 이유는?
- **SLO burn-rate alert**의 원리와 단순 threshold alert 대비 장점은?
- **W3C tracecontext와 B3 propagation**의 차이, 그리고 hybrid 환경에서 변환 전략은?
- **trace sampling rate 1%**를 선택할 때의 근거와 rare-error 누락 위험을 어떻게 보완하는가?
- **log masking**은 어디서(발신/수신) 수행해야 하며, false negative를 어떻게 줄이는가?
- **runbook drift**(코드와 문서 불일치)를 방지하는 운영적 장치는?
## Do Not Overclaim
- "OpenTelemetry만 쓰면 vendor-neutral이다"라고 단정하지 말 것. instrument 표준은 중립이지만 **backend (Datadog/New Relic/Tempo/Jaeger)** 선택 시점에 다시 lock-in이 발생한다.
- "SLO burn-rate alert가 정답이다"라고 단정하지 말 것. SLO·error budget이 합의되지 않은 단계에선 traffic-based threshold (RPS·5xx rate)가 더 운영 가능하다.
- "structured logging만 하면 PII는 안전하다"고 단정하지 말 것. 필드 단위 마스킹 정책과 sink(Elastic/Loki/Datadog)별 접근 통제가 함께 있어야 한다.
- "B3과 W3C는 호환된다"고 단정하지 말 것. 64-bit B3 trace-id는 128-bit W3C로 lossless 변환되지 않는다.
- "runbook이 있으면 incident가 빨라진다"고 단정하지 말 것. drift된 runbook은 오히려 잘못된 행동을 유도한다.
## Sources
- [[raw/official-docs/log-ecs-schema-elastic-official]] — ECS schema 공식 정의.
- [[raw/official-docs/log-otel-log-data-model-spec]] — OpenTelemetry log data model spec.
- [[raw/official-docs/log-logback-mask-pattern-converter-official]] — Logback masking pattern 공식.
- [[raw/official-docs/metric-micrometer-naming-convention-official]] — Micrometer dot.case 이름 규칙.
- [[raw/official-docs/metric-otel-metrics-data-model-spec]] — OTel metrics data model spec.
- [[raw/official-docs/metric-google-sre-slo-burn-rate]] — Google SRE Workbook burn-rate alert.
- [[raw/official-docs/tracing-w3c-trace-context-spec]] — W3C Trace Context spec.
- [[raw/official-docs/tracing-b3-propagation-zipkin-spec]] — Zipkin B3 propagation spec.
- [[raw/official-docs/tracing-otel-sampling-tail-vs-head-spec]] — OTel sampling head/tail 비교.
- [[raw/official-docs/runbook-pagerduty-incident-response-doc]] — PagerDuty incident response 공식 문서.
- [[raw/company-tech-blogs/tracing-datadog-apm-vs-opentelemetry]] — Datadog APM vs OTel 비교 (tech blog 관점).
- [[raw/project-notes/ca-skeleton-operational-contract]] — ca-tmpl 운영 계약 canonical SSOT.
-1
View File
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/outbox-pattern.md
+65
View File
@@ -0,0 +1,65 @@
---
title: concept / Transactional Outbox Pattern
source_type: llm-generated
status: reviewed
confidence: high
tags: [concept, ca-tmpl, messaging, kafka, outbox-pattern]
related_projects: [ca-tmpl]
last_reviewed: 2026-06-15
---
# concept / Transactional Outbox Pattern
## Summary
로컬 트랜잭션의 일부로 비즈니스 상태 변경과 이벤트를 동일한 데이터베이스(Outbox 테이블)에 저장한 후, 독립적인 프로세스(Outbox Relay)가 이 이벤트를 비동기적으로 메시지 브로커(Kafka 등)로 발행하는 디자인 패턴.
- 이를 통해 분산 환경에서 비즈니스 로직 성공과 메시지 발행 간의 원자성(Atomicity)을 보장하고, 이중 쓰기(Dual-Write) 안티패턴을 방지한다.
## Standard (공식 정의)
- **Dual-Write Anti-Pattern**: 하나의 비즈니스 유스케이스 내에서 데이터베이스 업데이트와 외부 메시지 발행을 동시에 시도하는 방식. 데이터베이스 트랜잭션은 커밋되었으나 브로커 연결 실패로 메시지가 유실되거나, 반대로 메시지는 발행되었으나 데이터베이스 커밋이 롤백되는 불일치 문제가 상존한다.
- **Transactional Outbox**:
1. 비즈니스 원장 데이터 수정과 함께, 발행할 메시지를 동일 트랜잭션 하에서 `Outbox` 테이블에 인서트한다. (DB 로컬 트랜잭션의 원자성으로 인해 메시지 저장도 100% 보장된다.)
2. 별도의 백그라운드 워커(Outbox Relay)가 Outbox 테이블을 주기적으로 폴링(또는 CDC를 활용)하여 `PENDING` 상태의 이벤트를 읽어온다.
3. 릴레이 워커가 메시지를 브로커로 발행(Publish)한 뒤, 데이터베이스에 해당 Outbox 레코드를 `COMPLETED` 등으로 상태를 업데이트하거나 삭제한다.
## 한계 / 주의점
- **중복 메시지 발행 (At-Least-Once Delivery)**: 릴레이가 브로커에 메시지를 정상적으로 보냈으나, DB에 상태를 `COMPLETED`로 업데이트하기 직전에 시스템이 다운되면 동일한 메시지가 재전송될 수 있다. 따라서 소비처(Consumer)는 반드시 **멱등적 메시지 처리(Idempotent Consumer)** 구조를 갖춰야 한다.
- **순서 보장 (Ordering)**: 멀티 스레드로 릴레이를 돌릴 때 동일 Aggregate의 이벤트가 뒤집혀서 발행되지 않도록 Aggregate ID 기반의 분산 락이나 시퀀스 제어가 필요할 수 있다.
## Project Application
- [[wiki/explainer/adapter-outbound.md]]
- 우리 프로젝트에서는 메시지 발행 시 직접 발행과 아웃복스 릴레이 발행의 결합을 지원함.
- **직접 발행 (`KafkaMessagePublisher`)**: 비즈니스 트랜잭션 흐름 중 메시지를 즉시 발행함. 이미 로컬 DB 트랜잭션에 아웃복스가 커밋되므로, 실시간 발행은 **Fail-Open** 계약을 맺어 예외가 발생하더라도 사용자 API를 중단시키지 않고 백그라운드 릴레이에 유실 복구를 위임함.
- **릴레이 발행 (`KafkaOutboxMessagePublishAdapter`)**: 백그라운드에서 Outbox 레코드를 전달받아 브로커에 실제 전달하는 역할. 브로커가 장애를 내면 반드시 예외를 다시 던지는 **Fail-Closed** 계약을 가짐. 예외가 전파되어야 릴레이 트랜잭션이 롤백되어 해당 레코드가 `IN_FLIGHT`에 고립되지 않고 재시도(Retry) 루프를 타거나 운영 경보(Runbook)가 정상 작동하기 때문임.
## Claim-backed Knowledge
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| 이중 쓰기(Dual-write)의 근본적 문제점과 일관성 결여 | `raw/official-docs/dual-write-antipattern-microservices-io.md` | `high` | 마이크로서비스 데이터 패턴 |
| 트랜잭셔널 아웃복스 패턴의 기본 구성 요소 | `raw/official-docs/transactional-outbox-aws-prescriptive-guidance.md` | `high` | AWS 마이크로서비스 설계 패턴 |
| Outbox 데이터 상태 변경 및 중복 처리 주의점 | `raw/official-docs/microservices-io-transactional-outbox.md` | `high` | Microservices.io 패턴 정의 |
## 내가 설명할 수 있어야 하는 것
- 이중 쓰기(Dual-Write)의 위험성과 이를 아웃복스 패턴이 어떻게 해결하는지 메커니즘을 상세히 설명할 수 있어야 함.
- 실시간 API 단의 메시지 발행기와 백그라운드 릴레이 단의 메시지 발행기가 예외 처리 정책(Fail-Open vs Fail-Closed)을 다르게 맺는 이유는 무엇인가?
- 카프카 외에 다른 메시징 시스템(RabbitMQ, AWS SQS)으로 아웃복스 발행기를 대체하려면 어떻게 설계해야 하는가? (Port-Adapter 인터페이스 구현을 통해 어댑터만 교체)
## Interview Questions
- 메시지 큐와 RDB를 동시에 업데이트할 때 발생할 수 있는 데이터 정합성 문제와 이를 해결하기 위한 Transactional Outbox Pattern에 대해 설명해 주세요.
- 아웃복스 릴레이 컴포넌트의 실패 상황 시 가용성과 정합성 설계 관점에서 어떻게 실패 복구를 처리해야 하는지 설명하십시오.
## Do Not Overclaim
- "아웃복스 패턴을 도입했으므로 분산 트레이싱 환경에서 완벽한 1회성 전송(Exactly-Once)을 달성할 수 있다"고 장담하면 안 된다. 분산 네트워크 상에서 릴레이 DB 업데이트 실패 시 중복 메시지가 무조건 나갈 수 있으므로, 최종 소비자의 멱등 수신 설계가 반드시 동반되어야 보장된다.
## Sources
- [Microservices.io - Transactional Outbox](https://microservices.io/patterns/data/transactional-outbox.html)
- [[raw/official-docs/dual-write-antipattern-microservices-io.md]]
- [[raw/official-docs/transactional-outbox-aws-prescriptive-guidance.md]]
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/privacy-file-domain-modeling.md
@@ -0,0 +1,116 @@
---
title: Privacy / File / Domain Modeling (GDPR + ICAP + Vernon)
source_type: llm-generated
status: draft
confidence: medium
tags: [privacy, gdpr, file-upload, ddd, domain-modeling]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Privacy / File / Domain Modeling (GDPR + ICAP + Vernon)
> Layer: `wiki/concepts/` — 일반 개념. Phase E Group G-J(3 branch / 10 raw) 통합. 내 프로젝트 사실 판정은 [[raw/project-notes/ca-skeleton-operational-contract]] §19, §29 G-J 와 각 branch-note에서 별도로 다룸.
## Summary
서비스가 도메인을 얹기 전에도 (1) **개인정보·로그의 보존/삭제 계약**, (2) **파일 업로드/다운로드의 안전성 계약**, (3) **도메인 모델의 프레임워크 격리 계약** 세 축이 사전에 정의되어야 한다. 본 문서는 이 세 축의 공식 기준과 그 한계를 묶어서 다룬다. 대표 결정값(예: 30/180/365일 retention, HMAC-SHA-256 + 90일 salt rotation, DSR SLA 30/14일, 3-layer file size limit, content-type allowlist 6종, VO private constructor, aggregate root mutator non-public)은 모두 개별 branch-note의 결정 사항을 따른다.
## Standard (공식 정의)
### Privacy / Retention
- **GDPR Art.25 — Data protection by design and by default**: 처리 시작 시점부터 "최소한의 데이터, 가능한 짧은 보존, 가능한 적은 노출"이 기본값이어야 한다. Art.17(Right to erasure)은 controller가 합리적 조치로 backup·복제본을 포함해 삭제하도록 요구한다.
- **NIST SP 800-88 Rev.1 — Cryptographic Erase (CE)**: 키를 안전하게 폐기함으로써 데이터 자체를 sanitize한 것으로 인정하는 공식 방법. backup·offline media의 GDPR Art.17 대응 수단으로 사용 가능.
- **ENISA / IAPP — Pseudonymization techniques**: HMAC-with-secret-key, tokenization, encryption 등을 pseudonymization 기법으로 분류. salt rotation, lookup table 분리 보관, brute-force input space 등을 비교 기준으로 제시.
- **DSR (Data Subject Request) 운영 패턴**: intake → identity verification → scope classification(export/delete) → execution → audit evidence. GDPR Art.12는 응답을 "원칙적으로 1개월(연장 시 +2개월)" 내로 요구.
### File / Resource Handling
- **ICAP / RFC 3507 — Internet Content Adaptation Protocol**: HTTP proxy/gateway가 antivirus engine(예: ClamAV)에 payload를 위임 검사하는 표준 프로토콜. 업로드 단의 외부 콘텐츠 검사를 app 외부에서 수행하는 정석.
- **AWS S3 — Presigned URL upload**: 서버가 서명된 PUT URL을 발급하면 클라이언트가 직접 S3에 업로드. app/gateway의 대역폭/CPU 부담 없이 large object 처리 가능.
- **tus.io — Resumable upload protocol (v1.0.0)**: HTTP `PATCH` 기반 resumable upload. 대용량/장시간 업로드를 chunk 단위 재개 가능하도록 표준화.
- **multipart/form-data + size limit**: Spring `spring.servlet.multipart.max-file-size` 등 framework 단의 1차 enforcement는 envelope error 변환의 책임을 진다. gateway/WAF는 raw 차단 보조.
### Domain Modeling
- **Vaughn Vernon — Effective Aggregate Design (IDDD)**: 4 rules — (1) protect true invariants in consistency boundary, (2) design small aggregates, (3) reference other aggregates by identity, (4) update other aggregates eventually. ORM-friendly constructor / package-private setter를 통해 ORM과 도메인 모델의 분리를 권장(이하 "Option A: ORM 외부 매핑").
- **Martin Fowler — Anemic Domain Model**: 데이터만 있는 entity + 모든 로직이 service에 모이는 구조를 anti-pattern으로 정의. rich model(state + behavior + invariant 동소화)을 기본으로 제시.
- **Greg Young — CQRS / Event Sourcing**: domain event는 transport-free fact, command와 query 모델 분리, event stream을 source of truth로 두는 패턴. event sourcing과 CQRS는 동일 개념이 아님(Young 본인이 구분).
## 한계 / 주의점
### Privacy
- **HMAC + salt rotation을 anonymization으로 단정 금지**: ENISA·IAPP 기준으로도 HMAC은 pseudonymization이지 anonymization이 아니다. brute-force 가능한 input space(예: 한국 휴대폰 11자리, 주민번호 일부 자리)에서는 attacker가 가능한 모든 입력을 미리 HMAC 계산할 수 있으므로 tokenization(랜덤 토큰 + 별도 lookup table)이 우위인 구간이 존재한다. 또한 HMAC + salt rotation은 **forward security만** 제공한다 — 새로 기록되는 식별자에 한해 rotation 이전 hash가 무효화될 뿐, 이미 작성된 backup 안의 hash는 그대로 잔존한다. 따라서 HMAC을 backup erasure 수단으로 오해하면 안 된다.
- **salt rotation interval (예: 90일)** 자체로 안전성이 증명되지 않음. 회전 주기 동안의 collision/lookup 정책, 옛 salt 보관 기간(예: 90일 retain), 키 저장소의 안전성이 별도로 요구된다.
- **GDPR Art.17 + backup → envelope key 필요**: backup·snapshot에서의 erasure는 단건 삭제가 어렵다. NIST SP 800-88 Rev.1 § 2.5 Cryptographic Erase (CE)는 인정되는 방법이나, **per-principal envelope key** 구조(주체별 DEK를 master CMK로 wrap, 삭제 요청 시 해당 principal의 DEK 폐기 → 모든 backup ciphertext가 동시에 unreadable)가 사전에 설계되어 있어야 한다. HMAC + salt rotation은 이 단건 erasure를 제공하지 **못한다**. 비용 trade-off에 따라 (a) per-principal CMK / (b) per-principal DEK + master CMK envelope (AWS KMS·GCP KMS 권장) / (c) tenant-level CMK (Stripe·Twilio·Shopify 류 SaaS 일반 패턴) 중 선택이 필요하다. 일반적 대량 KEK 폐기로는 Art.17 단건 요청을 만족하기 어렵다.
- **PII detection SaaS(AWS Macie / OneTrust / TrustArc)** 채택은 vendor 종속을 만든다. skeleton 단계의 기본값으로 두는 것은 부적절.
### File / Resource
- **ICAP gateway가 모든 위협을 막는다고 단정 금지**: HTTPS end-to-end TLS 환경에서는 gateway가 payload를 평문으로 보지 못해 ICAP 검사가 어려운 구간이 있다. 그 경우 post-upload async scan(예: quarantine bucket + worker)이 대안.
- **Direct S3 presigned URL**: 앱이 payload를 보지 못하므로 in-app validation(예: content-type 재검증, watermark, business rule)이 부재한다. content-type/size 검증은 S3 측 정책 + 후행 worker로 분산되어야 한다.
- **tus resumable upload**: session 식별자와 orphan temp file이 충돌한다. ca-tmpl 류의 "temp file > 1h not closed = orphan, sweeper가 삭제" 정책은 tus의 정상 long session을 잘못 삭제할 수 있어 threshold 분리가 필요하다.
- **in-app ClamAV daemon**: 앱 인스턴스마다 daemon dependency가 늘고, scaling/CPU 비용이 함께 증가한다. skeleton 단계의 기본값으로는 부적절.
- **content-type "sniffing 금지" vs "allowlist"**: client-supplied Content-Type 신뢰는 위험하나, 동시에 서버측 sniffing(magic byte 추론)도 우회 가능. allowlist + endpoint별 검증이 현실적 절충.
- **size limit 3-layer (예: app 10MB / global 12MB / gateway 20MB)**: 의도된 defense-in-depth지만, gateway 단의 raw 413은 envelope을 우회한다는 점이 trade-off다. 어느 layer에서 어떤 응답 형태를 보장할지 사전에 정해야 한다.
### Domain Modeling
- **Functional domain modeling (Scala / F#)**: 패러다임은 매력적이나 JVM Java 중심 팀의 학습 비용이 크다. skeleton 기본 채택은 부적절.
- **Anemic model**: 로직이 service로 흩어져 invariant 위치가 불명확해진다. Fowler가 anti-pattern으로 명시.
- **Pure DDD aggregates**: 작은 도메인에 과한 학습 비용 / 코드량을 강제할 수 있다. Vernon 본인도 "small aggregate"를 강조.
- **Event sourcing**: event store, snapshot, projection 등 운영 비용이 크다. 도메인 event = transport-free fact라는 정의만 차용하고 event sourcing은 채택하지 않는 절충이 일반적.
- **JPA direct annotation in domain (Vernon Option B / 우아한형제들 초기 글 스타일)**: `@Entity` / `@Column` 등을 domain class에 직접 두는 방식. 도메인이 persistence를 "안다"는 점에서 framework 격리 규칙과 충돌. forbidden import 규칙을 둔 코드베이스에서는 채택 불가.
- **`@Entity` / `@Service` / Logger / HTTP type을 도메인이 import**: 도메인의 framework neutrality가 깨진다. ArchUnit 등의 forbidden-import 테스트로 강제할 수 있다.
## Project Application
- [[wiki/projects/ca-tmpl/privacy-file-domain-modeling]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
- [[raw/branch-notes/feature-data-retention-privacy-contract]] — log retention by profile, HMAC pseudonymization, DSR SLA, backup retention 결정
- [[raw/branch-notes/feature-file-resource-handling-contract]] — upload size 3-layer, content-type allowlist, temp file cleanup, antivirus position 결정
- [[raw/branch-notes/feature-domain-modeling-guardrails]] — VO private constructor, aggregate mutator non-public, domain forbidden import 결정
- [[raw/project-notes/ca-skeleton-operational-contract]] §19 Domain Application Readiness Contract, §29 G-J 외부 근거 / 대안 조사
## Interview Questions
- GDPR Art.17 erasure 요청이 들어왔을 때, backup·snapshot까지 어떻게 처리하는가? Cryptographic erase와 per-principal envelope key 구조가 왜 필요한가?
- HMAC + salt rotation을 pseudonymization으로 채택할 때 salt rotation 주기(예: 90일)는 어떤 의미를 갖는가? brute-force 가능한 input space에서는 왜 tokenization이 더 안전할 수 있는가?
- 파일 업로드 size limit을 app(예: 10MB) / global(예: 12MB) / gateway(예: 20MB) 3-layer로 두는 이유는? 각 layer가 어떤 실패 모드를 책임지는가?
- ICAP / RFC 3507 기반 gateway antivirus의 한계는? HTTPS end-to-end TLS 환경과 in-app ClamAV daemon은 각각 어떤 trade-off를 만드는가?
- Value Object의 생성자를 private/factory only로 두는 이유는? aggregate root의 mutator를 package-private/protected로 강제하는 이유는?
- ORM 매핑을 도메인 외부에서 수행(Vernon Option A)하는 방식과, JPA annotation을 도메인에 직접 다는 방식(Option B / 우아한형제들 초기 글 스타일)의 trade-off는?
## Do Not Overclaim
- **"HMAC + salt = anonymization"으로 단정 금지**. ENISA·IAPP 기준 pseudonymization. brute-force 가능 input(휴대폰·주민번호 일부 등)에서는 tokenization이 우위인 구간이 존재.
- **"backup도 GDPR Art.17로 완전 삭제했다"고 단정 금지**. cryptographic erase + per-principal envelope key 구조가 실제로 설계되어 있어야 가능한 진술이다. 단순 backup 보존만으로는 단건 삭제 불가.
- **"DSR SLA 30/14일은 GDPR 요구치"라고 단정 금지**. GDPR Art.12는 "원칙적으로 1개월(연장 시 +2개월)"이며, 30/14일은 내부 운영 결정값이다.
- **"ICAP gateway antivirus가 모든 위협을 막는다"고 단정 금지**. HTTPS E2E TLS 환경 한계와 post-upload async scan 필요성이 있다.
- **"Direct S3 presigned URL이 가장 안전하다"고 단정 금지**. in-app validation 부재 → quarantine bucket + 후행 worker 분리가 추가로 필요.
- **"우리는 pure DDD 기반"이라고 단정 금지**. Vernon Option A(ORM 외부 매핑) 차용이며, CQRS / event sourcing은 채택하지 않은 절충이다. "transport-free domain event 정의만 차용했다"가 더 정확한 표현.
- **"Vernon Option B(JPA direct annotation)도 DDD이니 동일하다"고 단정 금지**. domain의 framework 격리 규칙을 두는 코드베이스에서는 양립 불가.
- **"functional domain modeling(Scala/F#) 도입했다"고 단정 금지**(JVM Java 기준 코드베이스에서). 패러다임 학습 비용과 팀 적합성이 별도로 필요.
## Sources
### Privacy
- [GDPR Article 25 — Data protection by design and by default](https://gdpr-info.eu/art-25-gdpr/) — [[raw/official-docs/privacy-gdpr-article-25-design]]
- [NIST SP 800-88 Rev.1 — Cryptographic Erase](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-88r1.pdf) — [[raw/official-docs/privacy-cryptographic-erasure-nist-sp800-88]]
- [Per-Principal Envelope Key for GDPR Art.17 (NIST SP 800-88 + AWS/GCP KMS envelope)](https://csrc.nist.gov/publications/detail/sp/800-88/rev-1/final) — [[raw/official-docs/gdpr-cryptographic-erasure-envelope-key-pattern]]
- [ENISA / IAPP — Pseudonymization techniques](https://www.enisa.europa.eu/publications/pseudonymisation-techniques-and-best-practices) — [[raw/company-tech-blogs/privacy-pseudonymization-hmac-vs-tokenization-iapp]]
### File / Resource
- [ClamAV / ICAP — Gateway antivirus scan](https://docs.clamav.net/manual/Usage/Scanning.html) — [[raw/company-tech-blogs/file-clamav-icap-gateway-scan]]
- [AWS S3 — Presigned URL upload](https://docs.aws.amazon.com/AmazonS3/latest/userguide/PresignedUrlUploadObject.html) — [[raw/official-docs/file-s3-presigned-url-upload]]
- [tus.io — Resumable upload protocol v1.0.0](https://tus.io/protocols/resumable-upload) — [[raw/official-docs/file-tus-resumable-upload-protocol]]
### Domain Modeling
- [Vaughn Vernon — Aggregate root rules (IDDD)](https://www.dddcommunity.org/library/vernon_2011/) — [[raw/official-docs/domain-vaughn-vernon-aggregate-root]]
- [Martin Fowler — Anemic Domain Model](https://martinfowler.com/bliki/AnemicDomainModel.html) — [[raw/official-docs/domain-fowler-anemic-vs-rich-model]]
- [우아한형제들 — DDD Aggregate 구현](https://techblog.woowahan.com/2711/) — [[raw/company-tech-blogs/domain-woowahan-ddd-aggregate-techblog]]
- [Greg Young — CQRS Documents (Event sourcing vs CQRS 구분)](https://cqrs.files.wordpress.com/2010/11/cqrs_documents.pdf) — [[raw/company-tech-blogs/domain-event-sourcing-vs-cqrs-greg-young]]
### Canonical
- [[raw/project-notes/ca-skeleton-operational-contract]] §19, §29 G-J
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/resource-identifier-format.md
+135
View File
@@ -0,0 +1,135 @@
---
title: Resource Identifier Format (ULID vs UUIDv7 vs UUIDv4 vs Snowflake)
source_type: llm-generated
status: draft
confidence: medium
tags: [resource-identifier, ulid, uuid, backend]
related_projects: [ca-skeleton]
last_reviewed: 2026-06-04
---
# Resource Identifier Format (ULID vs UUIDv7 vs UUIDv4 vs Snowflake)
> Layer: `wiki/concepts/` — 일반 개념. 특정 프로젝트(ca-tmpl)의 적용 사실은 [[wiki/projects/ca-tmpl/resource-identifier-format]] 로 분리.
## Summary
Resource identifier format 결정은 API resource 를 가리키는 public ID 의 *형식*(random vs time-ordered, charset, 길이, prefix)을 고르는 일이다. 후보는 크게 random 계열(UUID v4, NanoID)과 time-ordered 계열(UUID v7, ULID, KSUID, Snowflake, TSID)로 갈린다. 핵심 trade-off 축은 **(1) 정렬성/DB index locality, (2) timestamp leak(privacy), (3) URL 길이/charset, (4) 조율 부담, (5) 표준 여부**다. ID 는 URL·log·DB PK·cache key·FK 에 한 번 박히면 변경이 breaking 이므로, 형식 선택은 되돌리기 어려운 결정이다.
## Standard (공식 정의)
### UUID (RFC 9562, 2024)
IETF RFC 9562 는 UUID 의 128-bit 구조와 버전을 정의한다. v4 는 순수 random, v7 은 48-bit Unix millisecond timestamp 를 앞에 두는 **time-ordered** 변형이며, 같은 timestamp 내 단조성을 위한 monotonicity 메커니즘을 규정한다. RFC 는 새 ID 가 필요할 때 time-ordered 변형(v6/v7)을 SHOULD 로 권고한다. §8 은 timestamp 노출의 attack surface 를 "very small" 로 기술한다.
출처: [[raw/official-docs/rfc9562-uuid]] (RFC9562-C1~C5).
### ULID (공식 spec)
ULID 는 128-bit 를 **26-char Crockford base32** 로 인코딩한 형식이다. 앞 48-bit 가 millisecond timestamp(정렬 가능), 뒤 80-bit 가 random. `getMonotonicUlid()` 류의 monotonic factory 는 동일 ms 내 단조 증가를 보장한다. 128-bit 이므로 UUID 와 binary 호환(상호 변환 가능)이다.
출처: [[raw/official-docs/ulid-spec.md]] (ULID-C1~C6).
### Crockford base32 / RFC 3986
- **Crockford base32**: 32-char alphabet 에서 사람이 혼동하는 **I / L / O / U 를 제외**한다. 디코딩 시 `I`/`L``1`, `O``0` 으로 정규화하고 대소문자를 구분하지 않는다(case-insensitive). 출처: [[raw/official-docs/crockford-base32-spec.md]] (CROCKFORD-C1~C4).
- **RFC 3986 (URI generic syntax)**: `unreserved` charset 은 `ALPHA / DIGIT / "-" / "." / "_" / "~"`. path component 는 case-sensitive 로 취급되며 §6.2.2.1 의 case normalization 규칙은 scheme/host 에만 적용된다. ULID 의 `0-9A-Z``unreserved` 의 진부분집합이라 percent-encoding 없이 URL path 에 안전하다. 출처: [[raw/official-docs/rfc3986-uri-generic-syntax]] (RFC3986-C1/C3/C4).
### 식별자 관례 (벤더 표준 — best practice 아님)
- **Google AIP-148**: `name`(server-assigned), `uid`(system-assigned opaque, non-PII), `display_name`(mutable), `parent`(계층 resource name) 표준 필드. 출처: [[raw/official-docs/google-aip-148-standard-fields]] (AIP148-C1~C5).
- **Stripe**: typed prefix opaque ID(`ch_`, `cus_`, `pi_`). 단 Stripe 스스로 prefix 변경을 *backward-compatible* 로 분류 → prefix 영구 불변 보장이 아니므로 prefix 의존 코드는 lock-in 위험. Idempotency-Key 는 client-generated 로 resource ID 와 별개. 출처: [[raw/official-docs/stripe-resource-id-convention]] (STRIPE-C1~C5).
> AIP-148·Stripe 는 `official-vendor-doc`/벤더 관례다. RFC 9562·RFC 3986·ULID spec 같은 `official-standard` 와 달리 "공식 best practice" 로 일반화하면 안 된다.
## 한계 / 주의점
후보별 trade-off:
| 형식 | 정렬성(DB index) | timestamp leak | URL 길이 | 조율 부담 | 표준 |
| --- | --- | --- | --- | --- | --- |
| Sequential integer | 최상 | 없음(but enumeration/count leak) | 짧음 | 없음 | — |
| UUID v4 | 나쁨(random → B-tree 단편화) | 없음 | 36자(dashed) | 없음 | RFC 9562 |
| UUID v7 | 좋음(time-ordered) | **48-bit ms 노출** | 36자 | 없음 | RFC 9562 |
| ULID | 좋음(time-ordered) | **48-bit ms 노출** | 26자 | 없음 | ULID spec(비-IETF) |
| NanoID | 나쁨(random) | 없음 | 21자(default) | 없음 | 라이브러리 |
| KSUID | 좋음 | 초 단위 노출 | 27자(base62) | 없음 | 라이브러리 |
| Snowflake | 좋음(k-sorted) | ms 노출 + machine ID | ~19자(64-bit) | **worker/datacenter id 조율** | 라이브러리 |
| TSID | 좋음 | ms 노출 | BIGINT fit | 일부 | 라이브러리 |
| CUID2 | 없음(보안 우선) | **없음(저자 주장)** | 24자(base36) | 없음 | 라이브러리 |
주요 함정:
- **Sequential ID**: enumeration attack + count leak + tenant 격리 위반. public ID 로 부적합.
- **random UUID v4 의 DB 비용**: time-ordered 가 아니라 B-tree index 에 random insert → page split + WAL/디스크 증가. Percona 의 MySQL InnoDB 25M-row 벤치마크에서 random UUID PK 가 ordered UUID 대비 +50% 디스크, ordered UUID ≈ BIGINT 성능. 단 이는 MySQL InnoDB clustered index 기준 — PostgreSQL HEAP/MVCC 등 다른 엔진에는 *parallel evidence* 로만 적용된다. 출처: [[raw/company-tech-blogs/percona-uuid-storage-mysql]] (PERCONA-UUID-C2~C5).
- **timestamp leak**: UUID v7 / ULID 는 48-bit ms timestamp 가 평문 노출 → 작성 시각·가입 순서·활동 패턴 추론 가능. *user-facing* ID 에서 실질 문제. 완화책은 수용 / random scramble / CUID2 채택. CUID2 의 timestamp 비노출은 *저자 주장*이며 독립 감사로 확인된 것은 아니다. 출처: [[raw/official-docs/cuid2-spec.md]] (CUID2-C1).
- **Snowflake 의 조율 부담**: worker_id / datacenter_id 를 노드마다 사전 할당해야 함 → 단일 generator 환경에는 과한 운영 부담. 출처: [[raw/company-tech-blogs/snowflake-twitter-id]] (SNOWFLAKE-C1~C5).
- **case-insensitive charset 의 함정**: Crockford base32(ULID)는 입력이 case-insensitive 라 서버가 URL boundary 에서 canonical uppercase 로 normalize 하지 않으면 cache key miss 가 발생한다.
- **typed prefix lock-in**: Stripe 자신이 prefix 변경을 backward-compatible 로 본다 → prefix 를 파싱·의존하는 코드는 깨질 수 있다.
- **public ID vs internal sequence**: external-only(ULID 하나가 public ID = PK, Stripe)는 단순하지만, dual column(internal BIGINT + external ULID, Shopify/Linear/PlanetScale)은 audit/JOIN 성능을 회수한다. 후자는 cache key/FK 를 어느 쪽으로 둘지 추가 결정을 부른다. 출처: [[raw/company-tech-blogs/planetscale-nanoid-api]] (PLANETSCALE-NANOID-C4).
## Project Application
- ca-tmpl(Clean Architecture skeleton)에서의 실제 ULID 채택 + `adapter-identifier` 모듈 구현 사실은 [[wiki/projects/ca-tmpl/resource-identifier-format]] 참조. (본 개념 문서는 일반론만 다룬다.)
## Claim-backed Knowledge
> 인용된 raw source 의 claim 만. 출처 없는 일반화 금지.
| Knowledge Point | Supporting Claims | Confidence | Notes |
| --- | --- | --- | --- |
| RFC 9562 가 UUID v7 = time-ordered(48-bit Unix ms) 를 정의하고 새 ID 에 time-ordered 를 SHOULD 권고 | [[raw/official-docs/rfc9562-uuid]] RFC9562-C1/C3 | high | `official-standard` |
| RFC 9562 §8 이 timestamp 노출 attack surface 를 "very small" 로 기술 | [[raw/official-docs/rfc9562-uuid]] RFC9562-C5 | high | `official-standard` |
| ULID = 26-char Crockford base32, 48-bit ms timestamp + 80-bit random, monotonic 정렬 | [[raw/official-docs/ulid-spec.md]] ULID-C1~C5 | high | `official-reference`(비-IETF spec) |
| Crockford base32 가 I/L/O/U 제외 + 디코딩 시 정규화(case-insensitive) | [[raw/official-docs/crockford-base32-spec.md]] CROCKFORD-C1~C3 | high | `official-reference` |
| RFC 3986 `unreserved` = `ALPHA / DIGIT / "-" / "." / "_" / "~"`, path case-sensitive | [[raw/official-docs/rfc3986-uri-generic-syntax]] RFC3986-C1/C3 | high | `official-standard` |
| Google AIP-148 의 uid = system-assigned opaque(non-PII), display_name 과 분리 | [[raw/official-docs/google-aip-148-standard-fields]] AIP148-C2/C3 | medium | `official-vendor-doc` (벤더 관례, 공식 표준 아님) |
| Stripe 가 typed prefix 변경을 backward-compatible 로 분류(영구 불변 보장 아님) | [[raw/official-docs/stripe-resource-id-convention]] STRIPE-C2 | medium | `official-vendor-doc` |
| Percona: MySQL InnoDB 에서 random UUID PK 가 ordered UUID 대비 +50% 디스크, ordered UUID ≈ BIGINT (25M-row) | [[raw/company-tech-blogs/percona-uuid-storage-mysql]] PERCONA-UUID-C2/C5 | medium | `company-case-study` (MySQL 5.x, 타 엔진엔 parallel evidence) |
| CUID2 가 timestamp leak 없음 | [[raw/official-docs/cuid2-spec.md]] CUID2-C1 | low | `official-reference` (저자 주장, 독립 감사 미확인) |
| Snowflake 가 worker/datacenter id 사전 조율을 요구 | [[raw/company-tech-blogs/snowflake-twitter-id]] SNOWFLAKE-C1 | medium | `company-case-study` |
| NanoID 21자 default + URL-safe alphabet `A-Za-z0-9_-` + crypto-strong random | [[raw/official-docs/nanoid-spec]] NANOID-C1/C2/C4 | high | `official-reference` |
| Brandur(전 Stripe): Idempotency-Key 는 client-generated, ~24h TTL, request fingerprint 비교 | [[raw/company-tech-blogs/brandur-stripe-idempotency-keys]] BRANDUR-IDEMP-C8~C12 | medium | `engineering-blog` |
## 내가 설명할 수 있어야 하는 것
- time-ordered ID(UUID v7 / ULID)가 random UUID v4 대비 DB index locality 에 유리한 *원리*(B-tree 에 정렬된 키가 append 우세).
- timestamp leak 가 왜 *user-facing* ID 에서만 실질 문제인지, 완화책(수용 / scramble / CUID2)의 trade-off.
- Crockford base32 가 I/L/O/U 를 제외하는 이유 + 그래서 생기는 canonical uppercase 출력 + case-insensitive 입력 정규화 의무.
- public ID vs internal sequence(external-only vs dual column)의 trade-off.
- Idempotency-Key(client-generated, ephemeral) 와 resource ID(server-assigned, persistent)가 왜 별개 형식인지.
- "Netflix/Stripe 가 X 를 쓰니까 공식이다" 가 아니라, RFC(official-standard) 와 벤더 관례(vendor-doc)·사례(case-study)를 구분해 말하는 것.
## Interview Questions
- ULID 와 UUID v7 은 둘 다 time-ordered 인데 왜 ULID 를 고를 수 있는가? (URL 길이 26 vs 36, Crockford base32 의 human-friendliness, Java 21 `java.util.UUID` 의 v7 native 미지원.)
- random UUID v4 를 DB PK 로 쓰면 어떤 비용이 있는가? 어느 엔진 기준 벤치마크인가?
- ULID/UUID v7 의 timestamp leak 가 실제로 어떤 정보를 노출하는가? 언제 문제이고 어떻게 완화하나?
- typed prefix(`tk_`)를 쓰는 것의 장단점은? Stripe 가 prefix 변경을 어떻게 분류하는가?
- public ID 와 internal sequence 를 분리(dual column)하는 동기와 비용은?
## Do Not Overclaim
- **"ULID 가 UUID 보다 항상 우월하다" → 금지.** timestamp leak(privacy), 비-IETF 표준, 라이브러리 의존이라는 trade-off 존재.
- **"random UUID 는 PostgreSQL 에서도 느리다" → 단정 금지.** 인용 벤치마크는 MySQL InnoDB clustered index 기준 — 다른 엔진에는 parallel evidence 일 뿐.
- **"CUID2 는 timestamp 가 절대 안 샌다" → 단정 금지.** spec 저자 주장이며 독립 감사로 확인된 것은 아니다.
- **"Google AIP / Stripe 관례 = 업계 공식 표준" → 금지.** 벤더 관례·사례이지 RFC 같은 official-standard 가 아니다.
- **"sequential ID 는 무조건 나쁘다" → 맥락 의존.** internal-only(외부 비노출) 라면 합리적일 수 있고, dual column 의 internal PK 가 그 예다.
## Sources
- [[raw/official-docs/rfc9562-uuid]] — IETF RFC 9562 (UUID v4/v6/v7/v8, monotonicity, §8 attack surface).
- [[raw/official-docs/ulid-spec.md]] — ULID 공식 spec (26-char Crockford base32, monotonic).
- [[raw/official-docs/crockford-base32-spec.md]] — Crockford base32 (I/L/O/U 제외, case-insensitive 디코딩).
- [[raw/official-docs/rfc3986-uri-generic-syntax]] — URI generic syntax (`unreserved` charset, case normalization).
- [[raw/official-docs/cuid2-spec.md]] — CUID2 (timestamp-leak-free 저자 주장).
- [[raw/official-docs/nanoid-spec]] — NanoID (21자 URL-safe, crypto random).
- [[raw/official-docs/google-aip-148-standard-fields]] — Google AIP-148 standard fields.
- [[raw/official-docs/stripe-resource-id-convention]] — Stripe typed prefix opaque ID 관례.
- [[raw/company-tech-blogs/percona-uuid-storage-mysql]] — Percona MySQL InnoDB UUID PK 벤치마크.
- [[raw/company-tech-blogs/snowflake-twitter-id]] — Twitter Snowflake (조율 부담).
- [[raw/company-tech-blogs/planetscale-nanoid-api]] — PlanetScale NanoID + dual column 사례.
- [[raw/company-tech-blogs/brandur-stripe-idempotency-keys]] — Brandur: Idempotency-Key vs resource ID.
- [[raw/company-tech-blogs/segment-ksuid]] — Segment KSUID (base62, 초 단위 timestamp).
- [[raw/company-tech-blogs/github-graphql-global-node-id]] — GitHub global node ID (base64 type-encoded).
- [[raw/company-tech-blogs/aws-iam-arn-format]] — AWS ARN 계층 prefix.
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/runtime-container-health-migration.md
@@ -0,0 +1,158 @@
---
title: Runtime / Container / Health / Migration Baseline
source_type: llm-generated
status: draft
confidence: medium
tags: [runtime, container, kubernetes, health, migration, flyway]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Runtime / Container / Health / Migration Baseline
> Layer: `wiki/concepts/` — JVM 서비스의 container runtime · runtime health · migration startup 세 sub-topic을 한 문서로 통합한 baseline. 내 프로젝트 사실은 `project-template` 사용.
## Summary
JVM 서비스의 **runtime baseline**은 세 축으로 구성된다.
1. **Container**: Eclipse Temurin (Adoptium) JRE slim + JVM ergonomics (`-XX:MaxRAMPercentage=75`, `-XX:+UseContainerSupport`).
2. **Health**: Kubernetes Probes (liveness/readiness/startup)를 **세 endpoint로 분리** + Spring Boot Actuator Health Groups로 dependency 범위를 명시.
3. **Migration**: Flyway forward-only migration을 **readiness gated**로 실행 + 표준 startup exit code (sysexits 계열 78/70/71/72).
세 축은 **graceful shutdown 35s budget** (app 20s + preStop 5s + grace 10s margin)으로 묶인다.
## Standard (공식 정의)
### Container
- **Eclipse Temurin (Adoptium)** — JEP/JCK 인증 OpenJDK 빌드. JRE slim 이미지는 JDK 대비 footprint 작고 production runtime에 권장.
- **OCI Image spec** — base image, layer, label 표준. Dockerfile은 OCI 호환 image를 산출.
- **JVM container ergonomics**:
- `-XX:+UseContainerSupport` — JDK 10+ default. cgroup memory/cpu limit을 JVM이 인식.
- `-XX:MaxRAMPercentage=<N>` — container memory limit의 N%를 max heap으로 사용. 절대값 `-Xmx`보다 container 환경에서 안전.
- `-XX:+ExitOnOutOfMemoryError` — JVM `OutOfMemoryError` 발생 시 즉시 process exit (137).
- `-XX:HeapDumpPath=...` — OOM 진단용 heap dump.
### Health
- **Kubernetes Probes** (kubelet 공식 모델):
- **liveness** — process가 살아있는가. 실패 시 container restart.
- **readiness** — traffic을 받을 수 있는가. 실패 시 Service endpoint 제거 (drain).
- **startup** — startup이 끝났는가. startup probe가 success할 때까지 liveness/readiness 비활성. 긴 migration/warmup 시 liveness 오판 방지.
- probe 분리는 K8s 공식 권장. single `/health`로 묶지 않는다.
- **Spring Boot Actuator Health Groups** — `management.endpoint.health.group.liveness.include`, `.readiness.include`로 endpoint별 HealthIndicator set을 분리.
- Spring default readiness는 외부 dependency 미포함이므로 DB/broker 등 required dependency는 명시적 group 등록 필요.
### Migration
- **Flyway 공식**:
- forward-only versioned migration이 기본 model.
- `flyway.repair` — checksum/state 수정 도구. **prod 사용은 공식이 직접 위험성 경고** (실제 schema 변경 없이 metadata만 수정).
- `flyway.baselineOnMigrate` — 기존 DB에 처음 Flyway 적용 시. 잘못 켜면 누락 migration이 skip된 채 baseline.
- `flyway.outOfOrder` — version 순서 외 migration 허용. 협업 환경에서 일관성 깨짐.
- **sysexits.h** (BSD `sysexits.h`, 1990s) — Unix 관례적 exit code 의미.
- `64` — usage error
- `70` — internal software error
- `71` — OS error
- `72` — critical OS file missing
- `78` — config error
- 표준이 강제하는 enum은 아니지만 ops/CI 진단에 관례적으로 사용.
## 한계 / 주의점
### Container 선택 트레이드오프
- **Temurin JRE slim (base)**:
- 운영/디버깅 친숙도 우위 (shell, JDK tools 가용).
- security surface는 distroless보다 크다 (apt, libc 등 OS 패키지 포함).
- **Distroless (Google)**:
- OS 패키지 제거 → 보안 surface 축소 + image 크기 감소.
- shell·debug tool 없음 → in-container 디버깅 손실. 별도 sidecar/ephemeral container 필요.
- **Alpine + musl libc**:
- image 크기 작음.
- musl libc는 glibc 호환성 risk (DNS resolver 차이, native lib 미지원 등). Java 일부 native lib는 alpine에서 동작 미보장.
- **GraalVM Native Image / Spring Boot Native**:
- cold start/메모리 우위 (수십 MB heap, ms 단위 startup).
- reflection·dynamic proxy는 build-time metadata 필요. peak throughput은 HotSpot JIT보다 손실.
- Spring Boot Native는 Spring 6+ + Spring Boot 3+ AOT compile 의존.
- 우아한형제들 도입기는 전체 native 전환이 아닌 **hybrid 채택** 결론.
### Health 분리의 한계
- **Single `/health` endpoint (legacy)**:
- liveness/readiness 구분 불가.
- K8s rolling update 시 dependency 일시 outage가 container restart loop 유발 가능. traffic 유실 risk.
- **Custom HealthIndicator만 사용**:
- Spring default readiness는 외부 dependency 미포함. DB/broker 등은 명시적으로 readiness group에 묶지 않으면 readiness가 traffic 가능 여부를 반영하지 않음.
- **Service mesh-based health (Istio sidecar)**:
- mTLS 환경에서 편의성. 단 sidecar 살아있음 / app 살아있음 구분이 mesh layer에서 불명확.
- 추가 infra 의존 (sidecar 주입, mesh control plane).
### Migration tool 트레이드오프
- **Liquibase (XML/YAML changelog)**:
- DB-agnostic + rollback 기능.
- XML/YAML 기반은 SQL 대비 verbose. migration speed Flyway 대비 느림 (changelog parser 오버헤드).
- rollback 안전 보장 없음 (rollback script 사람이 작성).
- **Hibernate `hbm2ddl=update` 등**:
- 공식 anti-pattern. prod 사용 금지가 일반 권고. schema drift 추적 불가.
- **Atlas / Tern (schema-as-code)**:
- declarative + integrity hash 강점.
- Java/Spring 생태계 성숙도 부족. JVM 외부 CLI tool.
- **K8s Init Container 패턴**:
- replica마다 init container 실행 → multi-instance migration race.
- **K8s Job + migration lock**이 race 회피에 구조적 우월.
- **Flyway 자체 한계**:
- `repair` / `baselineOnMigrate` / `outOfOrder`는 잘못 쓰면 schema state corruption. 공식이 직접 위험 경고.
- forward-only 모델이라 rollback은 별도 forward migration으로 처리.
### Exit code 한계
- sysexits.h는 관례. POSIX 강제 표준 아님. 조직 표준으로 명시적 enum 필요.
## Project Application
- [[wiki/projects/ca-tmpl/runtime-container-health-migration]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
- [[raw/branch-notes/feature-container-runtime-contract]] — container runtime 결정 (Temurin JRE slim, `MaxRAMPercentage=75`, UTC/UTF-8, graceful shutdown 35s).
- [[raw/branch-notes/feature-runtime-health-lifecycle-contract]] — liveness/readiness/startup 3-endpoint 분리, Required vs Optional Dependency Matrix.
- [[raw/branch-notes/feature-migration-startup-contract]] — Flyway baseline + readiness gated + exit code 78/70/71/72.
- [[raw/project-notes/ca-skeleton-operational-contract]] (§15 Runtime / Lifecycle Contract).
## Interview Questions
- JRE slim과 distroless 중 어떤 base image를 선택하고, 그 근거는 무엇인가?
- `-XX:MaxRAMPercentage=75`로 설정한 이유는 무엇이고, 절대값 `-Xmx`와 어떤 차이가 있는가?
- liveness / readiness / startup 세 probe를 분리하는 이유는 무엇인가? single `/health`로 묶으면 어떤 운영 문제가 생기는가?
- graceful shutdown을 app 20s + preStop 5s + terminationGracePeriodSeconds 35s로 잡았다면 각 단계가 어떤 의미를 가지는가?
- Flyway `repair`가 prod에서 위험하다고 보는 근거는? 어떤 대안 경로가 있는가?
- startup exit code 78 / 70 / 71 / 72로 분리하면 어떤 진단상 이점이 생기는가? (config error / internal error / OS error / critical OS file missing)
## Do Not Overclaim
- "GraalVM native-image가 곧 standard"라고 단정하지 말 것. reflection-heavy 코드와 peak throughput 손실은 실측 trade-off. 우아한형제들 사례도 hybrid 채택.
- "Flyway가 항상 우월"이라고 단정하지 말 것. 조직이 XML/YAML 기반 schema-as-doc을 요구하거나 DB-agnostic이 강제일 때는 Liquibase가 합리.
- "distroless가 보안상 무조건 정답"이라고 단정하지 말 것. in-container 디버깅 손실은 incident 대응 시간을 늘릴 수 있다.
- "K8s probe만 있으면 graceful shutdown은 자동"이라고 말하지 말 것. app shutdown timeout과 manifest grace period가 sync되지 않으면 SIGKILL로 inflight 요청 유실.
- "exit code 70/78은 표준"이라고 말하지 말 것. sysexits.h는 관례이고 조직 enum 명시가 필요.
## Sources
- [Eclipse Temurin / Adoptium project](https://adoptium.net/) — 공식 OpenJDK 배포.
- [Kubernetes — Configure Liveness, Readiness and Startup Probes (공식)](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/)
- [Spring Boot Actuator — Health (공식)](https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html#actuator.endpoints.health)
- [Flyway — Concepts / Repair (공식)](https://documentation.red-gate.com/flyway/) — repair / baseline_on_migrate / out_of_order 위험성 경고 명시.
- [sysexits.h — BSD man page](https://man.freebsd.org/cgi/man.cgi?sysexits) — 64/70/71/72/78 등 관례적 exit code.
- [[raw/official-docs/container-distroless-google-github]] — Distroless 보안 surface vs 디버깅 손실.
- [[raw/official-docs/container-alpine-java-musl-tradeoffs]] — Alpine + musl libc 호환성 risk.
- [[raw/official-docs/container-graalvm-native-image-spring-boot]] — GraalVM native-image / Spring Boot Native AOT 비용·이득.
- [[raw/company-tech-blogs/container-woowahan-spring-native-tradeoffs]] — 우아한형제들 Spring Native 도입기 (hybrid 채택).
- [[raw/official-docs/runtime-health-k8s-probes-official]] — K8s liveness/readiness/startup 공식.
- [[raw/official-docs/runtime-health-spring-actuator-groups]] — Spring Boot Actuator Health Groups.
- [[raw/official-docs/runtime-health-istio-mesh-health-check]] — Istio mesh health 대안과 한계.
- [[raw/company-tech-blogs/runtime-health-datadog-engineering-graceful-shutdown]] — Datadog graceful shutdown preStop/drain/grace 비율 사례.
- [[raw/official-docs/migration-flyway-official-concepts-and-repair]] — Flyway 공식 repair/baseline_on_migrate/out_of_order 위험성.
- [[raw/official-docs/migration-liquibase-official-changelog-xml-yaml]] — Liquibase XML/YAML changelog.
- [[raw/official-docs/migration-atlas-schema-as-code]] — Atlas schema-as-code 대안.
- [[raw/official-docs/migration-k8s-init-container-job-pattern]] — K8s Init Container vs Job 패턴 비교.
- [[raw/project-notes/ca-skeleton-operational-contract]] — §15 Runtime / Lifecycle Contract.
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/sample-fixture-and-adoption.md
@@ -0,0 +1,83 @@
---
title: Sample Fixture & Adoption (skeleton template lifecycle)
source_type: llm-generated
status: draft
confidence: medium
tags: [skeleton, sample-fixture, template, adoption]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Sample Fixture & Adoption (skeleton template lifecycle)
> Layer: `wiki/concepts/` — skeleton/template lifecycle 일반 개념. 구체 결정과 검증 등급은 `wiki/projects/` 또는 `raw/branch-notes/`에서 판정.
## Summary
skeleton/template repository 라이프사이클은 두 축으로 분해된다. 첫째, **sample fixture**는 비즈니스 기능이 아니라 skeleton 계약(envelope/error/capability/transaction/idempotency)을 트리거하는 contract 검증 도구이다. 둘째, **sample-off/adoption**은 실제 도메인을 얹을 때 sample을 production runtime에서 비활성화하면서도 운영 계약이 함께 사라지지 않도록 보장하는 절차이다. 두 영역의 대표 안: sample-ticket 12 scenario matrix + 6-field minimum model + `OPEN→IN_PROGRESS→CLOSED` state machine + optimistic lock + idempotency key, 그리고 sample-off profile + production dependency 차단 + dual-mode CI matrix(sample-on / sample-off 둘 다 release-blocking) + multi-module adoption checklist.
## Standard (공식 정의 / 업계 사례)
### Sample fixture 계열
- **Spring Petclinic**: Spring Framework 공식 데모. README에 "demo지 best-practice 아님" 본인 선언. 학습/시연 목적, contract 검증 매트릭스는 부재.
- **RealWorld (gothinkster Conduit)**: cross-stack spec (Article/Comment/User/Follow/Favorite). 백엔드 언어/프레임워크 호환성을 검증하는 reference. spec은 풍부하지만 minimum이 아니고, envelope/idempotency/optimistic lock 같은 contract scenario는 정의 범위 밖.
- **Spring Cloud Microservices sample**: microservices 변형 (config server, eureka, gateway). fixture 수준을 초과해 인프라 다수 component를 함께 보여줌.
- **Stripe testmode**: SaaS sandbox. payment 도메인에 한정된 sandbox key/카드 번호.
### Removal / adoption 계열 (template scaffolding)
- **Yeoman / Maven archetype**: generator 시점에 sample 제외 옵션을 노출하는 전통적 generator 모델. 생성 후에는 sample 자취가 남지 않음.
- **Cookiecutter (Python)**: `{{cookiecutter.*}}` 변수 치환 기반 generator. 생성 시점 sample-off가 기본.
- **degit (Svelte)**: git history 없이 repo를 clone하는 경량 도구. 생성 후에도 원본 sample 그대로 존재.
- **Spring Initializr**: Spring Boot 공식 generator. dependency / build tool / language / Java version 선택 기반이며 contract sample은 포함되지 않음.
- **GitHub Template Repository**: GitHub 공식 기능. 한 번의 클릭으로 코드뿐 아니라 CI/Actions workflow 파일까지 그대로 복제됨. friction이 가장 낮은 reference scaffolding 모델.
- **Backstage golden path (Spotify IDP)**: Spotify가 발표한 internal developer platform. service template / scorecard / catalog를 묶어 조직 차원에서 표준 stack 진입점을 제공.
## 한계 / 주의점
- **Spring Petclinic**: README가 "demo"라고 자기 부정. best-practice baseline으로 사용하기에는 contract enforcement test/registry/profile isolation이 없어 부족.
- **RealWorld**: domain spec은 풍부하나 "minimum"이 아니며, validation/conflict/optimistic lock/idempotency를 trigger하는 contract 시나리오 매트릭스는 정의되지 않음. backend cross-stack 호환성 reference로는 적합.
- **Stripe testmode**: SaaS-side sandbox. OSS skeleton repo가 채택할 수 있는 모델은 아니며 payment 도메인에 한정.
- **No fixture (unit test only)**: contract test를 트리거할 도메인 흐름 자체가 없어 envelope/capability/transaction 일관성을 행위로 검증할 수단이 없음.
- **Yeoman / Maven archetype**: generator 시점에 sample을 제거하므로, "sample-on / sample-off 두 mode를 CI에서 동시에 green으로 유지"하는 운영 모델과는 시맨틱이 다름.
- **Cookiecutter**: Python ecosystem에 정착. JVM/Spring 환경에서는 직접 도구로 들이기 어렵고, 동일하게 generator 시점 sample-off 모델.
- **degit**: 단일 repo 단순 clone에 최적화. monorepo / multi-module 구조나 CI/Actions 동반 복제에는 친화적이지 않음.
- **Spring Initializr**: dependency-only generator. operational contract / sample fixture / contract test 같은 운영 계약 묶음은 제공하지 않음.
- **GitHub Template Repository**: CI/Actions 파일까지 그대로 복제되어 friction이 낮다. skeleton repo 모델의 reference 1순위로 평가되지만, 그 자체로 sample-off profile이나 adoption 절차를 보장하지는 않음. 별도 sample-off/adoption 절차가 함께 정의되어야 함.
- **Backstage**: 조직 규모가 service template / scorecard / catalog를 따로 운영할 수준에 도달한 이후 적합. 1인 / 소규모 단계에서는 IDP 도입 자체가 과투자.
## Project Application
- [[wiki/projects/ca-tmpl/sample-fixture-and-adoption]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
- [[raw/branch-notes/feature-sample-domain-contract-fixture]] — sample-ticket 12 scenario matrix + 6-field minimum model + state machine + optimistic lock + idempotency key 결정 SSOT branch.
- [[raw/branch-notes/feature-sample-removal-adoption-contract]] — `sample-ticket` fixture module 유지 + sample-off runtime isolation + dual-mode CI matrix 결정 SSOT branch.
- [[raw/project-notes/ca-skeleton-operational-contract]] — canonical operational contract (§17 Sample Domain Fixture, §22 Sample-ticket Contract Matrix, §29 G-H Sample / adoption).
## Interview Questions
- sample-ticket 12 scenario matrix는 어떤 의미를 갖나요? 왜 단순한 CRUD 예제가 아니어야 하나요?
- sample-ticket이 6개 필드(`TicketId`, `TicketTitle`, `TicketStatus`, `TicketVersion`, `TicketOwner`, `IdempotencyKey`)만 가지는 근거는 무엇인가요?
- "dual-mode CI matrix(sample-on / sample-off 둘 다 release-blocking)"는 어떤 문제를 막기 위한 장치인가요?
- sample-off first adoption이 즉시 코드 삭제보다 좋은 이유는 무엇인가요?
- Spring Petclinic이나 RealWorld 같은 기존 sample 대신 자체 fixture(sample-ticket)를 둔 이유는 무엇인가요?
## Do Not Overclaim
- sample-ticket을 "도메인 모델"로 단정하면 안 된다. sample은 skeleton 계약을 트리거하기 위한 **contract 검증 도구(fixture)**이며 production feature가 아니다.
- Spring Initializr / Cookiecutter를 "ca-tmpl과 동급 alternative"로 단정하면 안 된다. 두 도구 모두 **generator 시점에 sample을 빼는 모델**이라 sample-on / sample-off 두 mode를 동시에 release-blocking으로 검증하는 운영 모델과 시맨틱이 다르다.
- "GitHub Template Repository가 reference 1순위"라는 평가는 friction(=초기 복제 단계의 마찰) 기준일 뿐이다. sample-off 절차, adoption checklist, operational contract 보존은 별도로 정의되어야 한다.
- Backstage는 조직 규모 임계점 이후의 IDP 진입점이며, 일반적인 skeleton repo와 동일 레이어가 아니다.
- 위 비교는 외부 raw 자료 발췌와 ca-skeleton operational contract canonical을 기반으로 한 정리이며, 본 문서는 status `draft` / confidence `medium`이다. 실제 채택 / 검증 등급은 관련 `wiki/projects/` 문서에서 판정한다.
## Sources
- [[raw/official-docs/sample-spring-petclinic-github]] — Spring Petclinic README (demo 선언)
- [[raw/official-docs/sample-realworld-gothinkster-github]] — RealWorld (Conduit) spec
- [[raw/official-docs/sample-microservices-spring-cloud-github]] — Spring Cloud microservices sample
- [[raw/official-docs/scaffolding-spring-initializr]] — Spring Initializr generator
- [[raw/official-docs/scaffolding-cookiecutter-official]] — Cookiecutter (Python)
- [[raw/official-docs/scaffolding-degit-svelte-github]] — degit (Svelte)
- [[raw/official-docs/scaffolding-github-template-repository]] — GitHub Template Repository
- [[raw/company-tech-blogs/scaffolding-backstage-golden-path-spotify]] — Backstage golden path (Spotify IDP)
- [[raw/project-notes/ca-skeleton-operational-contract]] — §17 Sample Domain Fixture, §22 Sample-ticket Contract Matrix, §29 Group G-H
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/security-baseline-jwt-actuator-secrets.md
@@ -0,0 +1,138 @@
---
title: Security Baseline (JWT Resource Server + Actuator + Secrets)
source_type: llm-generated
status: draft
confidence: medium
tags: [security, jwt, oauth2, actuator, secrets]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Security Baseline (JWT Resource Server + Actuator + Secrets)
> Layer: `wiki/concepts/` — JWT Resource Server 기반 인증/인가, Actuator 관리면 보안, secret 소스/rotation 세 가지를 한 묶음으로 다루는 백엔드 보안 baseline 개념 문서. 실무 적용은 `wiki/projects/` 문서로 분리.
## Summary
운영 가능한 백엔드 보안 baseline은 **세 축**으로 구성된다. ① 데이터면 인증/인가는 **JWT Resource Server**(RFC 7519/8725, OAuth2 Resource Server) 기준으로 표준화하고, 토큰 실패를 `missing / malformed / expired / invalid signature / issuer / audience / unknown kid / claim mapping` 등으로 분류한다. JWKS는 주기 refresh(예: 10분 + unknown kid 시 on-demand)로 키 회전을 흡수하고, JWT 시간 검증은 **clock skew tolerance 60s** 정도를 둔다. ② 제어면(Actuator)은 **management port 분리**(예: 9001) + prod allowlist(health / prometheus / info) + heapdump/threaddump/env/configprops/shutdown forbidden을 default로 한다. ③ Secret은 **prod = secret manager 또는 mounted secret**, local만 `.env` 허용, runtime reload 금지, rotation은 restart 또는 명시적 dual-bind/overlap window로만 한다.
## Standard (공식 정의)
### JWT / OAuth2 / 인가
- **RFC 7519 (JSON Web Token)**: JWT 구조와 `iss`, `aud`, `exp`, `nbf`, `iat`, `jti`, `sub` 등 표준 claim, 서명/검증 의무를 규정. `exp`/`nbf` 검증 시 "a few minutes leeway"가 일반적이며 구현은 명시된 허용치를 설정해야 한다.
- **RFC 8725 (JWT Best Current Practices)**: algorithm confusion 회피(`alg: none` 금지, `HS256``RS256` 혼용 금지), `kid` 사용, audience/issuer 명시 검증, `typ: JWT` 검증 등 운영상 함정 정리.
- **RFC 6749/6750 + OAuth2 Resource Server**: bearer token으로 보호된 리소스에서 token validation 책임을 resource server에 두는 모델. Spring Security 6의 `spring-boot-starter-oauth2-resource-server`가 표준 구현 경로.
- **RFC 8252 (OAuth 2.0 for Native Apps) + PKCE**: public client(SPA, mobile)의 authorization code flow에서 code interception 방어. **issuance flow** 영역으로 resource server JWT 검증과는 보완재.
- **RFC 8705 (Mutual-TLS Client Authentication and Certificate-Bound Access Tokens)**: mTLS 또는 sender-constrained token. JWT보다 강한 보장이나 PKI 운영 비용이 큼.
- **OWASP Authorization Cheatsheet**: deny-by-default, least privilege, server-side enforcement, ABAC/RBAC 혼합, audit logging 등 인가 설계 원칙.
### Actuator / 관리면
- **Spring Boot Actuator 공식 문서**: 기본적으로 `health`, `info`만 web exposure, 그 외(`env`, `configprops`, `heapdump`, `threaddump`, `loggers`, `shutdown`)는 default disabled. `management.endpoints.web.exposure.include`로 명시 허용 + `SecurityFilterChain`으로 별도 보호 권고.
- **`management.server.port`**: app port(8080)와 별도의 management port(예: 9001)로 분리 가능. 네트워크 ACL/Ingress에서 외부 노출 차단을 단순화하는 것이 분리 권고의 핵심.
- **Istio sidecar / service mesh**: mTLS, AuthorizationPolicy로 management endpoint 보호 가능. mesh 가정이 강하므로 framework-neutral skeleton에서는 대안.
### Secrets / Config
- **12-factor App §III. Config**: 환경 사이에서 변하는 값은 **환경변수**로 외부화, 코드와 분리. config dump 금지의 이론 근거.
- **AWS Secrets Manager (auto-rotation)**: Lambda 기반 rotation function 표준. dual-binding window 동안 old/new credential을 둘 다 유효하게 두어 connection pool/검증자 캐시가 흡수하도록 설계.
- **HashiCorp Vault (dynamic secrets)**: lease 기반 짧은 수명 credential 발급. lease renewal 책임을 클라이언트가 짊.
- **K8s Secret + External Secrets Operator (ESO)**: 외부 secret manager → K8s Secret → 컨테이너 mount/env 경로. etcd 암호화 미설정 시 평문 저장 한계.
- **NIST SP 800-57 (Recommendation for Key Management)**: cryptoperiod, key rotation, key destruction의 표준. HMAC salt/JWT signing key rotation 주기 결정의 reference.
## 한계 / 주의점
### JWT Resource Server
- **Revocation 한계**: 표준 JWT는 stateless 검증이므로 발급 후 강제 무효화가 어렵다. 회수 수단은 ① short expiry + refresh token, ② JWKS rotation + 작은 key overlap, ③ deny-list cache(상태 부활), ④ token introspection(stateless 포기) 중 trade-off. "JWT라 안전하다"는 단정 금지.
- **algorithm confusion**: RFC 8725가 명시적으로 경고. 구현 단에서 server-side로 허용 알고리즘을 fix해야 함(`alg: none`/HS↔RS 혼용 금지).
- **clock skew**: 너무 작게 잡으면 서버 시계 drift로 false negative, 너무 크면 expired token 수용 창 확대. 일반적으로 30~60s 권고.
- **JWKS endpoint outage**: cache miss + IdP 장애 시 모든 인증이 막힘. 캐시 TTL + on-demand refresh + 명시적 outage status 분류가 필요.
### Session + Cookie
- stateless 확장성 손실(서버 측 session store 필요).
- CSRF 방어, SameSite/HttpOnly/Secure cookie 운영 복잡도.
- revocation은 session 삭제로 즉시 가능 — 보안상 강점이지만 비용은 분산 session store.
### mTLS
- sender-constrained로 token theft 위협에 강함.
- 단점: PKI(발급/갱신/폐기) 운영 비용, public client(브라우저 SPA, 모바일 일반 사용자) 사용 어려움.
### OPA (Open Policy Engine)
- 정책-코드 분리, 외부에서 정책 변경/감사 가능.
- 단점: 외부 호출 latency, sidecar/agent 운영, in-process 인가 2~3종에는 과한 인프라.
### Actuator
- **single-port + path ACL**: cloud ingress가 path 기반 차단을 강하게 보장할 때만 안전. 잘못된 filter ordering, regex 매칭 우회 risk.
- **mTLS for management**: 강하지만 cert 운영 부담.
- **mesh sidecar (Istio)**: mesh 도입을 전제 → skeleton/framework-neutral 가정과 충돌.
- **info endpoint**: build info 외에 commit hash/branch만 노출해도 attack surface가 될 수 있음 — 무엇이 들어가는지 명시 필요.
- **한국 사례 (토스/우아한형제들 등) 일부 참조 가능 (G-B 후속 보강 결과).** Actuator 노출 보안에 대한 한국 도메인 사례가 존재하며, JWT/secret 관리 직접 사례는 follow-up 후보로 남음.
### Secrets
- **Vault dynamic secrets**: 짧은 lease가 보안 우위이나, **Spring `@RefreshScope` + bean 재생성** 흐름을 강제 → connection pool/캐시 lifecycle과 충돌. ca-tmpl처럼 `@RefreshScope` 금지 환경에서는 정면 충돌.
- **AWS Secrets Manager auto-rotation**: dual-binding window 60s 패턴과 정합하지만, rotation Lambda 자체가 운영/감사 대상.
- **ESO**: K8s native이지만 etcd 평문 저장은 cluster operator의 별도 책임.
- **Doppler / 1Password SDK**: dev 머신까지 reference 보호 강점이지만 SaaS 외부 의존.
- **plain env**: prod에서 ps/dump/log 노출 가능성 — 단독 baseline으로는 거부 대상.
## Project Application
- [[wiki/projects/ca-tmpl/security-baseline-jwt-actuator-secrets]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
이 baseline은 ca-skeleton 운영 계약과 세 개의 branch-note 결정에 적용된다(검증 등급은 각 branch/project 문서가 판정한다 — 이 concept 문서는 등급을 매기지 않는다).
- [[raw/project-notes/ca-skeleton-operational-contract]] — §18 Control Plane Contract (Secrets / Config Source, Management / Actuator Security)
- [[raw/branch-notes/feature-security-operational-baseline]] — JWT Resource Server + AuthN/AuthZ Matrix 12행 + JWKS 10min refresh + clock skew 60s + rotation overlap 24h + public path snapshot diff
- [[raw/branch-notes/feature-management-actuator-security-contract]] — management port 9001 + prod allowlist + heapdump/threaddump prod forbidden + loggers prod read-only + metrics network ACL default
- [[raw/branch-notes/feature-secrets-config-source-contract]] — prod = secret manager OR mounted env + `no-runtime-reload` default + `__LOCAL_DEV_` sentinel + JWT key 24h overlap / DB credential dual-bind 60s / API key restart-reload
## Interview Questions
- JWT vs Session 기반 인증을 어떤 기준으로 선택하는가? (stateless 확장성 / revocation 용이성 / cookie 운영 비용 / 클라이언트 타입)
- JWKS rotation 주기와 unknown `kid` 처리 정책을 어떻게 설계하는가? (refresh 주기, on-demand refresh, overlap window)
- Spring Boot Actuator를 운영에서 노출할 때 management port를 분리하는 이유는? (network 경계 단순화, ingress 정책, single-port + path ACL 위험)
- secret rotation을 zero-downtime으로 만들 때 어떤 패턴을 쓰는가? (dual-bind window, JWT key overlap, restart-only vs runtime reload)
- HMAC salt rotation을 90일 등으로 두는 근거는? (NIST cryptoperiod 권고, 누적 노출량 한도, downstream re-hash 비용)
- JWT 검증의 `clock skew tolerance`를 어떻게 정하는가? (NTP drift 가정, 발급자/검증자 분산도, expired vs replay trade-off)
## Do Not Overclaim
- **"JWT는 안전하다"는 단정 금지.** 토큰 탈취 시 revocation이 어렵다는 한계가 있다. JWT의 보안성은 발급/저장/전송/회수 전 과정 설계에 좌우된다.
- **"HashiCorp Vault가 secret 관리의 표준"이라는 단정 금지.** dynamic secrets는 강력하지만 `@RefreshScope`/bean refresh 패턴을 전제로 하며, 이를 금지하는 운영 계약(예: ca-skeleton)과는 충돌한다. AWS Secrets Manager, K8s + ESO, 1Password 등은 각자 다른 운영 상충점을 갖는다.
- **"actuator를 켜두는 것은 항상 안전하다"는 단정 금지.** default exposure가 `health`/`info`로 좁아도 `env`, `configprops`, `heapdump`, `threaddump`, `shutdown`이 잘못 열리면 그대로 공격 표면이 된다. allowlist + 네트워크 경계 + 인증의 다층 방어가 필요하다.
- **"company tech blog가 JWT/secret를 이렇게 쓴다 = 공식 best practice"** 로 격상 금지. 사례는 참고일 뿐 RFC/OWASP/공식 문서 기준과 구분해야 한다.
## Sources
### Canonical project SSOT
- [[raw/project-notes/ca-skeleton-operational-contract]] — §18 Control Plane Contract, §29 Group G-B 외부 근거 인덱스
### JWT / OAuth2 / 인가 (raw)
- [[raw/official-docs/security-jwt-rfc-7519-validation]] — RFC 7519 JWT claim 검증 표준
- [[raw/official-docs/security-oauth2-pkce-rfc-8252]] — OAuth2 PKCE (RFC 8252) issuance flow 표준
- [[raw/official-docs/security-mtls-rfc-8705]] — mTLS sender-constrained token (RFC 8705)
- [[raw/official-docs/security-aws-sigv4-hmac-signing]] — AWS SigV4 HMAC signing (webhook/외부 호출 인증 영역)
- [[raw/official-docs/security-authorization-cheatsheet-owasp]] — OWASP Authorization Cheatsheet (deny-by-default)
### Actuator / 관리면 (raw)
- [[raw/official-docs/actuator-endpoint-exposure-spring-official]] — Spring 공식 actuator default exposure 정책
- [[raw/official-docs/actuator-management-port-spring-official]] — Spring 공식 separate management port 권고
- [[raw/official-docs/actuator-istio-sidecar-management-alt]] — Istio sidecar 기반 management 보호 (대안)
- [[raw/company-tech-blogs/security-woowahan-actuator-safe-usage]] — 우아한형제들 SOC팀 Actuator 안전 사용 사례 (한국 도메인)
- [[raw/company-tech-blogs/security-toss-actuator-healthcheck]] — 토스 Spring Boot Actuator 헬스체크 (health detail 민감성, 한국 도메인)
### Secrets / Config (raw)
- [[raw/official-docs/secrets-aws-secrets-manager-rotation]] — AWS Secrets Manager + auto-rotation (dual-bind 패턴 정합)
- [[raw/official-docs/secrets-vault-dynamic-secrets-hashicorp]] — HashiCorp Vault dynamic secrets (short lease)
- [[raw/official-docs/secrets-k8s-secret-external-secrets-operator]] — K8s Secret + External Secrets Operator
- [[raw/company-tech-blogs/secrets-1password-developer-secret-references]] — 1Password developer secret references (dev 머신 보호 사례)
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/skeleton-governance-registry-verification-test-scorecard.md
@@ -0,0 +1,153 @@
---
title: Skeleton Governance (Registry + Verification + Test taxonomy + Scorecard)
source_type: llm-generated
status: draft
confidence: medium
tags: [skeleton, governance, archunit, testcontainers, scorecard]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Skeleton Governance (Registry + Verification + Test taxonomy + Scorecard)
> Layer: `wiki/concepts/` — 일반 개념. 내 프로젝트 사실은 `project-template` 사용.
## Summary
스켈레톤 거버넌스는 네 축으로 구성된다. (1) **Contract registry** — markdown SSOT(canonical 운영 계약) + YAML 파생을 단일 진실 원천으로 두고 ADR/스키마 레지스트리 같은 외부 대안을 트레이드오프 관점에서 선택, (2) **Verification suite** — Pact CDC · Spring Cloud Contract · Spring REST Docs · WireMock/Hoverfly 등으로 계약-구현 일치를 자동 검증, (3) **Test taxonomy** — 단위/얇은 슬라이스/통합/E2E/계약/성능의 6 레벨로 피라미드와 트로피의 절충을 명시, (4) **Readiness scorecard** — 11개 릴리즈 차단 게이트의 binary pass/fail로 채택 가능 여부를 판정. 네 축은 서로 참조 관계이며 어느 하나가 빠지면 거버넌스가 깨진다.
## Standard (공식 정의)
### Contract registry
- **Architecture Decision Records (ADR)**: Michael Nygard이 제안한 결정 단위 markdown 문서. 컨텍스트·결정·결과를 명시하며 한번 채택된 ADR은 변경 대신 새 ADR로 교체. branch-note의 "결정/근거/측정값" 패턴과 구조가 유사하다.
- **Schema/Protobuf/Smithy registry**: 데이터/인터페이스 계약을 IDL로 선언하고 빌드 산출물(jar, 코드)로 분배. 멀티 언어·멀티 팀에서 단일 출처를 강제하는 방식.
- **Markdown SSOT + YAML 파생**: 운영 계약을 사람이 읽는 markdown 한 곳에만 두고, machine-readable 형식은 빌드 시점에 파생. drift는 빌드 스크립트가 검사.
- **Code-only registry (enum/annotation)**: ArchUnit·custom annotation에 메타정보를 박는 방식. verifier 가깝지만 사람이 읽기 어려움.
### Verification suite
- **Pact (Consumer-Driven Contract)**: consumer가 기대를 pact 파일로 선언 → provider가 pact broker에서 받아 검증. 외부 consumer가 많을 때 효과.
- **Spring Cloud Contract**: provider 쪽 DSL/YAML로 계약 정의 → consumer stub 자동 생성. JVM 단일 생태계에 최적.
- **Spring REST Docs**: 테스트 통과 시점에 asciidoc 스니펫을 자동 추출. 문서-구현 일치 보장 강하지만 "계약 위반 시 빌드 실패" 강제력은 약함.
- **ApprovalTests / JSON snapshot**: 출력 스냅샷을 파일로 저장, diff로 회귀 감지. 단일 팀에서 가장 가볍다.
- **WireMock / Hoverfly**: 외부 의존성 mock/record-replay. 통합 테스트에서 외부 시스템을 격리.
- **ArchUnit**: 패키지 의존 방향·네이밍·어노테이션 규칙을 JUnit 테스트로 표현해 빌드 차단.
### Test taxonomy
- **Test pyramid (Mike Cohn, *Succeeding with Agile*)**: 단위 다수 → 서비스 일부 → UI 소수. 비용/속도 기반.
- **Test trophy (Kent C. Dodds)**: 정적 분석 + 단위 + 통합(가장 두꺼움) + E2E. 통합이 ROI가 높다는 주장.
- **Honeycomb (Spotify)**: 마이크로서비스에서는 통합 중심이 현실적이라는 변형.
- **Fitness functions (*Building Evolutionary Architectures*, Ford et al.)**: 아키텍처 특성(레이어 의존성, 성능 SLO, 보안 룰)을 실행 가능한 테스트로 표현.
- **Testcontainers**: real DB/Kafka/Redis를 Docker로 띄워 통합 테스트. mock의 false confidence를 줄인다는 입장.
### Readiness scorecard
- **AWS Well-Architected Framework**: 6 pillar(운영·보안·신뢰성·성능·비용·지속가능성)에 대한 review 질문. 점진적 maturity.
- **CIS Benchmark**: 구성 항목별 pass/fail. 보안 baseline에 가까움.
- **SLSA (Supply-chain Levels for Software Artifacts)**: build 단계의 무결성을 1~4 레벨로 나눔.
- **CMMI**: 조직 프로세스 성숙도 1~5.
- **OpenTelemetry Maturity Model**: observability 도입 단계.
스켈레톤은 이 중 **CIS/Well-Architected의 binary pass/fail** 접근에 가깝다. "릴리즈 가능한가"만 판정.
## 한계 / 주의점
### Registry 축
- **Markdown SSOT + YAML 파생**: drift 검증 도구를 **자체 작성**해야 함. CI에 통합되지 않으면 SSOT가 깨져도 모름.
- **Code-only enum/annotation**: SSOT가 코드 곳곳에 분산. 사람이 한눈에 보기 어렵고 외부 리뷰어가 접근 못 함.
- **Protobuf/Smithy registry**: IDL 학습·빌드 파이프라인 추가·breaking change 정책까지 필요. 단일 팀 스켈레톤에는 도입 비용이 효익을 초과할 수 있음.
- **ArchUnit annotations as registry**: verifier 한정. "왜 이 규칙인지"를 표현하지 못함 — registry라기보다 enforcement. (2026-05-22 후속 평가: framework-neutral 부재 / git diff review 약함 / 외부 도구 호환 불가로 ca-tmpl에서 채택 보류, markdown SSOT 유지. [[raw/official-docs/archunit-annotation-as-registry-evaluation]])
- **DB-stored registry (config service)**: 런타임 의존성·운영 부담. 빌드 타임 결정에는 부적합.
### Verification 축
- **Pact CDC**: 외부 consumer가 다수일 때 강점. **single-team / single-repo 환경에선 JSON snapshot이 우위** — broker 운영 비용, consumer-provider 협업 오버헤드가 효익을 초과.
- **Spring Cloud Contract**: JVM 외 consumer가 있으면 stub 활용도 떨어짐.
- **Spring REST Docs**: 문서 자동 생성에는 좋지만 "계약을 깨면 빌드가 실패"하는 강제력은 약함 — 문서가 코드와 같이 갱신될 뿐, 변경 자체는 막지 않음.
- **WireMock/Hoverfly**: real system과 mock의 차이로 false green 가능. Testcontainers와 병행 필요.
- **ArchUnit**: 규칙이 많아지면 테스트 시간·유지보수 부담. annotation 기반 규칙은 어노테이션 누락 시 silently pass.
### Test taxonomy 축
- **6 level (unit / slice / integration / e2e / contract / performance)**: 전체 budget 5분 등 시간 제약을 두면 레벨이 늘수록 budget 준수가 어려움. **레벨 분리 + 병렬화 + nightly 분리**가 필요.
- **Testcontainers integration**: real DB/Redis로 mock보다 정확하지만 CI 시간 증가. cache layer warm-up 비용 큼.
- **Trophy/Honeycomb 모델**: "통합이 ROI 높다"는 주장은 도메인 의존적. 순수 라이브러리·CLI에는 과한 권고.
- **Fitness functions**: 빌드 차단력은 강하지만 룰을 잘못 짜면 false positive로 개발 흐름을 막음.
### Scorecard 축
- **Binary pass/fail**: **adoption gate 판단에 적합**. "이 스켈레톤으로 신규 프로젝트를 시작해도 되는가" 같은 컷오프 결정에 단순·명확.
- 그러나 **점진적 개선이 필요한 기존 시스템 평가**에는 부적합 — "50% 만족"을 표현 못 함. 한 게이트를 못 넘으면 전체가 not-ready로 표시되어, 개선 우선순위를 가리기 어려움.
- **AWS Well-Architected / CIS**: 운영 중 시스템의 점진적 개선·우선순위 매기기에 적합. 새 스켈레톤 평가엔 항목이 너무 많아 noise.
- **SLSA**: 공급망에 한정. registry/test 영역은 다루지 않음.
- **CMMI / OpenTelemetry maturity**: 조직·도메인 단위 평가. 단일 skeleton repo 단위에는 과대.
### 4축의 결합 한계
- 네 축이 서로 참조되도록 강제하지 않으면 거버넌스가 깨짐. 예: scorecard가 verification suite를 "통과" 표시했는데 실제로는 일부 contract만 검증된 경우. **메타 검증(scorecard ↔ verification ↔ registry 교차 확인)이 별도로 필요**.
- branch-note ≈ mini-ADR로 운용하면 결정 이력은 보존되나, 시간이 지나며 ADR이 누락된 결정이 코드에 생길 수 있음 — registry 정기 audit 필요.
## Project Application
- [[wiki/projects/ca-tmpl/skeleton-governance-registry-verification-test-scorecard]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
- [[raw/project-notes/ca-skeleton-operational-contract]] — §12 Test Contract, §21 Contract Registry, §27 Readiness Scorecard, §29 Group G-G
- [[raw/branch-notes/feature-contract-registry-governance]]
- [[raw/branch-notes/feature-contract-verification-test-suite]]
- [[raw/branch-notes/feature-test-taxonomy-fixture-contract]]
- [[raw/branch-notes/feature-implementation-readiness-scorecard]]
(실제 구현 여부·검증 등급은 위 project / branch 문서에서 판정. 본 concept 문서는 등급을 직접 매기지 않음.)
## Interview Questions
- Contract registry의 SSOT 위치를 markdown SSOT vs code-only(enum/annotation) vs IDL(Protobuf/Smithy) 중 어떻게 선택했고, 각 선택의 트레이드오프는 무엇인가?
- Consumer-Driven Contract(Pact)와 단순 JSON snapshot(ApprovalTests) 중 single-team skeleton에 어느 쪽을 택해야 하고 이유는?
- Testcontainers를 통합 테스트에 강제하는 이유와, 대신 mock으로 갈 때 잃는 보장은 무엇인가?
- 단위/슬라이스/통합/E2E/계약/성능의 6 test level이 각각 무엇을 보장하며, budget 5분을 어떻게 지키는가?
- Readiness scorecard에서 binary pass/fail vs maturity score(AWS WAF·CMMI 류) 중 binary를 택하는 상황은 언제인가?
- branch-note를 mini-ADR처럼 사용한다는 것은 구체적으로 무엇을 의미하며, ADR과 어떤 부분이 같고 어떤 부분이 다른가?
## Do Not Overclaim
- "Pact CDC가 항상 우월하다"고 말하지 말 것. **외부 consumer가 다수일 때만 효익이 비용을 넘는다**. single-team 환경에서는 over-engineering이 되며, JSON snapshot이 더 적합할 수 있다.
- "Binary pass/fail이 절대적 기준"이라고 말하지 말 것. **adoption gate(채택 가능 여부) 한정**이다. 운영 중 시스템의 점진적 개선 평가에는 AWS Well-Architected / CIS 형태가 적합하다.
- "ArchUnit으로 모든 거버넌스를 강제할 수 있다"고 말하지 말 것. 어노테이션 누락 시 silently pass하는 등 enforcement 한계가 있다.
- "Spring REST Docs가 계약을 강제한다"고 말하지 말 것. 문서-구현 일치를 자동화할 뿐, 계약 위반 자체를 막는 강제력은 약하다.
- "Markdown SSOT + YAML 파생이 다른 registry보다 우월하다"고 말하지 말 것. **drift 검증 도구를 자체 작성·CI 통합**해야 비로소 신뢰 가능하다.
- "Test taxonomy 6 level이면 항상 5분 budget을 지킬 수 있다"고 말하지 말 것. 병렬화·nightly 분리·캐시 전략이 같이 가야 한다.
## Sources
### Canonical (내 프로젝트 운영 계약)
- [[raw/project-notes/ca-skeleton-operational-contract]] — §12 Test Contract, §21 Contract Registry, §27 Readiness Scorecard, §29 Group G-G
### Registry
- [[raw/official-docs/registry-adr-official]] — Architecture Decision Records
- [[raw/official-docs/schema-protobuf-vs-json-evolution]] — IDL registry / 호환성
- [[raw/official-docs/governance-archunit-official]] — code-only enforcement registry
- [[raw/official-docs/archunit-annotation-as-registry-evaluation]] — annotation-as-registry 대안 평가 (2026-05-22, ca-tmpl 채택 보류)
### Verification
- [[raw/official-docs/verification-pact-cdc-official]] — Consumer-Driven Contract
- [[raw/official-docs/verification-spring-cloud-contract-official]] — provider-side contract
- [[raw/official-docs/verification-spring-restdocs-official]] — 문서-구현 일치
- [[raw/official-docs/verification-approvaltests-snapshot-official]] — JSON snapshot 대안
### Test taxonomy
- [[raw/official-docs/test-taxonomy-practical-pyramid-fowler]] — Practical Test Pyramid
- [[raw/official-docs/test-taxonomy-testcontainers-official]] — Testcontainers
- [[raw/official-docs/dx-testcontainers-java-best-practices]] — Testcontainers Java DX
- [[raw/company-tech-blogs/test-pyramid-vs-trophy-kent-dodds]] — Trophy 모델 (회사 블로그 — 공식 기준 아님)
### Scorecard
- [[raw/official-docs/scorecard-aws-well-architected]] — Well-Architected Framework
- [[raw/official-docs/scorecard-cis-benchmarks-slsa]] — CIS / SLSA
- [[raw/official-docs/scorecard-opentelemetry-maturity]] — OTel Maturity Model
-1
View File
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/spring-smart-lifecycle.md
+66
View File
@@ -0,0 +1,66 @@
---
title: concept / Spring SmartLifecycle
source_type: llm-generated
status: reviewed
confidence: high
tags: [concept, ca-tmpl, runtime, spring-framework, graceful-shutdown]
related_projects: [ca-tmpl]
last_reviewed: 2026-06-15
---
# concept / Spring SmartLifecycle
## Summary
Spring 컨텍스트의 생명 주기(start / stop)에 통합되어, 빈의 시작 및 종료 순서를 결정론적으로(Deterministic) 제어할 수 있게 해주는 인터페이스.
- 애플리케이션 종료 시점에 리소스 반납 및 진행 중인 트랜잭션/재시도의 중단을 순서대로 조율하여 우아한 종료(Graceful Shutdown)를 돕는다.
## Standard (공식 정의)
Spring Framework 공식 명세에 따른 정의는 다음과 같다.
- **SmartLifecycle**: `Lifecycle``Phased` 인터페이스의 확장판.
- **isAutoStartup()**: 컨텍스트 리프레시 시점에 `start()`가 자동으로 실행될지 여부를 결정한다.
- **getPhase()**: 생명 주기 상의 실행 단계를 나타낸다.
- **시작(Start) 순서**: `getPhase()`가 **작은 순**에서 **큰 순**으로 기동된다.
- **종료(Stop) 순서**: `getPhase()`**큰 순**에서 **작은 순**(내림차순)으로 정지된다.
- 따라서, phase가 `Integer.MAX_VALUE`인 빈은 가장 마지막에 기동되고, **종료 시점에는 가장 먼저** 멈춘다.
## 한계 / 주의점
- **ContextClosedEvent 와의 차이**: Spring의 `ContextClosedEvent` 리스너는 애플리케이션 컨텍스트가 닫히기 시작했다는 신호만 전달할 뿐, 빈의 소멸(destroy) 순서와 비결정론적으로 얽혀 있다. 예컨대 어떤 DB 소스 빈이 이미 소멸된 후에 커넥션을 수립하려는 리스너 코드가 호출되면 NPE나 의존성 부재 예외가 터진다.
- **SmartLifecycle은 비동기 셧다운을 차단할 수 있다**: `stop(Runnable callback)` 메서드가 호출되면 종료 작업을 수행하고 반드시 callback을 호출해 주어야 한다. 그렇지 않으면 Spring이 설정된 셧다운 타임아웃까지 대기하여 기동 종료 과정이 지연될 수 있다.
## Project Application
- [[wiki/explainer/adapter-outbound.md]]
- `OutboundHttpShutdownGuard``SmartLifecycle`을 구현하고 `getPhase()`에서 `Integer.MAX_VALUE`를 반환함.
- 이로 인해 Spring 컨텍스트가 종료 과정을 개시할 때, 다른 어떤 데이터베이스 빈이나 아웃바운드 의존성 어댑터가 종료되기 전에 **가장 먼저** 셧다운 가드의 `stop()`이 실행되어 `shuttingDown` 플래그를 세우게 됨.
- 리트라이 정책(`OutboundRetryPolicy`)은 루프 도중 이 플래그를 관찰하여 즉시 중단(short-circuit)하며, 신규 요청 또한 `OutboundHttpClient` 단에서 즉시 거부(`DEPENDENCY_CIRCUIT_OPEN` 예외)함으로써, 애플리케이션 종료 시 불필요한 HTTP 커넥션 맺기나 타임아웃 예산 낭비를 미연에 방지함.
## Claim-backed Knowledge
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| Spring SmartLifecycle 생명 주기 제어 및 phase 결정 규칙 | `raw/official-docs/spring-smartlifecycle-reference.md` | `high` | Spring Framework 공식 참조 |
| Spring Boot Graceful Shutdown 시그널 수신 및 정리 과정 | `raw/official-docs/spring-boot-graceful-shutdown-reference.md` | `high` | Spring Boot Reference Guide |
## 내가 설명할 수 있어야 하는 것
- `Lifecycle``SmartLifecycle` 인터페이스의 근본적인 차이는 무엇인가?
- 왜 Graceful Shutdown 구현 시 `ContextClosedEvent` 리스너를 사용하는 대신 `SmartLifecycle` phase를 활용하는 것이 안전한가?
- `getPhase()` 반환값이 `Integer.MAX_VALUE`일 때, 종료 시점의 제어 순서는 어떻게 보장되는가?
## Interview Questions
- Spring Framework에서 애플리케이션이 안전하게 종료(Graceful Shutdown)되도록 빈의 소멸 순서를 조율하는 방법에 대해 설명하고, `SmartLifecycle` 인터페이스의 동작 방식을 설명하십시오.
- Kubernetes 환경에서 Pod가 종료 신호(SIGTERM)를 받았을 때 Spring Boot 애플리케이션이 수신 중인 API 및 아웃바운드 재시도 요청을 처리하는 우아한 종료 흐름을 설계해 보십시오.
## Do Not Overclaim
- "SmartLifecycle을 적용했기 때문에 종료 과정에서 어떠한 데이터 유실도 물리적으로 발생하지 않는다"고 보장해서는 안 된다. 컨테이너 셧다운 유예 기간(Kubernetes `terminationGracePeriodSeconds`)을 넘어가면 강제 종료(SIGKILL)가 발생하므로, 애플리케이션의 우아한 정리 시간이 유예 기간보다 짧도록 세심히 설정해야만 보장된다.
## Sources
- [Spring Framework Reference - SmartLifecycle](https://docs.spring.org/spring-framework/reference/core/beans/factory-nature.html#beans-factory-lifecycle)
- [[raw/official-docs/spring-smartlifecycle-reference.md]]
- [[raw/official-docs/spring-boot-graceful-shutdown-reference.md]]
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/streaming-response-patterns.md
@@ -0,0 +1,86 @@
---
title: Streaming Response Patterns (SSE vs WebSocket vs Long-Polling vs Chunked)
source_type: llm-generated
status: draft
confidence: medium
tags: [streaming, sse, websocket, http, backend]
related_projects: [ca-skeleton]
last_reviewed: 2026-06-04
---
# Streaming Response Patterns (SSE vs WebSocket vs Long-Polling vs Chunked)
> Layer: `wiki/concepts/` — 일반 개념. ca-skeleton 이 이 개념을 *미지원으로 결정하고 ArchUnit 으로 차단한* 사실은 [[wiki/projects/ca-tmpl/streaming-response-support]] 참조.
## Summary
HTTP 의 기본 통신 모델은 *request-response*(클라이언트가 묻고 서버가 한 번 답함)다. 이를 넘어 서버가 클라이언트로 데이터를 *지속적으로/능동적으로* 보내려면 별도 메커니즘이 필요하다 — 대표적으로 **SSE**(서버→클라이언트 단방향 push), **WebSocket**(양방향 full-duplex), **long-polling**(요청을 응답 없이 오래 붙잡아 둠), **chunked transfer encoding**(크기 미상 응답을 조각으로 흘려보냄)이 있다. 핵심 구분 축은 *통신 방향(단/양방향)**통신 모델이 request-response 를 유지하는가, server-push 로 바뀌는가* 다.
## Standard (공식 정의)
- **SSE (Server-Sent Events)**: MIME type `text/event-stream`, UTF-8 인코딩 필수. `data:` / `event:` / `id:` / `retry:` 필드를 가진 line-based text protocol. 클라이언트 측 API 는 `EventSource`(브라우저 `Window`/`Worker` context 전용 — 서버는 직접 `text/event-stream` 응답을 구현해야 함). 재연결 시 `Last-Event-ID` 헤더로 마지막 수신 event 를 서버에 전달. (WHATWG HTML §9.2)
- **WebSocket**: 단일 TCP 연결 위의 *full-duplex*(양방향) 통신 — 각 side 가 독립적으로 언제든 송신 가능. HTTP Upgrade handshake(`GET` + `Upgrade: websocket``101 Switching Protocols`)로 연결을 수립하고, handshake 이후 TCP 는 HTTP 가 아닌 WebSocket 프레임 전송에 쓰인다. HTTP 와의 *유일한* 관계는 handshake 가 HTTP Upgrade 로 해석되는 것뿐인 독립 프로토콜. (IETF RFC 6455 §1.2, §1.7)
- **Chunked transfer encoding**: *크기를 알 수 없는* content stream 을 length-delimited buffer 의 연속으로 전송 — 전체 크기 없이 connection 을 유지하며 메시지 완료를 수신자가 알 수 있게 함(`Transfer-Encoding: chunked`, last-chunk = size 0). HTTP/1.1 한정 (HTTP/2 는 DATA frame 으로 별도 framing, `Transfer-Encoding` 자체 금지). (IETF RFC 9112 §7.1)
- **Long-polling**: 클라이언트가 요청을 보내고 서버가 *이벤트가 생길 때까지* 응답을 지연시키는 패턴 — RFC 6455 는 WebSocket 의 탄생 배경으로 "HTTP polling/long-polling 은 HTTP 의 남용(abuse)이며 서버가 클라이언트마다 여러 TCP 연결을 유지해야 했다"고 기술한다. (RFC 6455 §1.1)
- **Spring MVC(servlet) 매핑**: `request.startAsync()` 로 Servlet/filter 는 exit 하고 response 만 열어 둠. 응답 타입별로 — `StreamingResponseBody`(message conversion 우회, `OutputStream` 직접 write, *파일 다운로드* 용), `ResponseBodyEmitter`(객체 stream emit, 각 객체를 `HttpMessageConverter` 로 직렬화), `SseEmitter`(`ResponseBodyEmitter` 의 subclass, W3C SSE 포맷). (Spring MVC vendor doc)
## 한계 / 주의점
- **"streaming" 이라는 단어가 두 개의 다른 것을 가리킨다**: ① *통신 모델 자체* 가 server-push 로 바뀌는 것(SSE/WebSocket) ② request-response 모델을 유지한 채 *응답 body 만 조각 전송* 하는 것(`StreamingResponseBody` / chunked 다운로드). 둘은 운영 부담·계약이 전혀 다르므로 묶어서 다루면 안 된다.
- **SSE 는 단방향**: 서버→클라이언트만. 클라이언트→서버 메시지는 별도 일반 HTTP 요청으로. 양방향이 필요하면 WebSocket.
- **WebSocket 은 기존 HTTP 인프라와 자동 호환되지 않는다**: HTTP 와 독립 프로토콜이라 reverse proxy(Nginx 등)에 Upgrade 처리 설정이 별도로 필요. envelope/필터/미들웨어 같은 기존 request-response 자산도 그대로 못 씀.
- **server-push 는 운영 비용을 키운다**: connection 수 관리, 서버 재시작 시 동시 재연결(thundering herd), 멀티 서버 fan-out, timeout/heartbeat/reconnect, load balancer sticky session 등. 단발 request-response 에는 없던 부담.
- **chunked 는 HTTP/1.1 전용**: HTTP/2·HTTP/3 에서 `Transfer-Encoding: chunked` 는 금지(별도 framing). 브라우저의 trailer section 지원도 일반화 보장 안 됨.
- **YAGNI 경계**: 실제 server-push use case 가 없으면 스트리밍 도입은 speculative generality — request-response + 비동기 우회(LRO polling, webhook)로 대부분 충분.
## Project Application
- [[wiki/projects/ca-tmpl/streaming-response-support]] — ca-skeleton 이 이벤트/server-push 스트리밍을 *미지원으로 결정* 하고 ArchUnit import-ban 3개(`no_sse_emitter` / `no_response_body_emitter` / `no_websocket_handler`)로 강제. `StreamingResponseBody`(다운로드)는 차단 제외.
## Claim-backed Knowledge
> 이 개념 문서의 핵심 설명은 raw source claim 으로 뒷받침된다. 공식 standard / vendor doc / 회사 사례를 분리한다.
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| SSE 는 `text/event-stream`(UTF-8) line-based protocol, `data:/event:/id:/retry:` 필드 | `raw/official-docs/whatwg-html-server-sent-events.md#WHATWG-SSE-C1`, `#WHATWG-SSE-C2` | `high` | WHATWG HTML (official-standard) |
| SSE 재연결은 `Last-Event-ID` 헤더로 마지막 event 전달, `retry:` 로 대기시간 설정 | `#WHATWG-SSE-C3`, `#WHATWG-SSE-C4` | `high` | 서버 활용은 구현 책임 (MAY 수준) |
| `EventSource` 는 브라우저 클라이언트 API — 서버는 `text/event-stream` 을 직접 구현 | `#WHATWG-SSE-C5` | `high` | Spring 서버 측에 EventSource 직접 적용 불가 |
| WebSocket 은 단일 TCP 위 full-duplex, 양 side 독립 송신 | `raw/official-docs/rfc6455-websocket.md#RFC6455-C1` | `high` | RFC 6455 (official-standard) |
| WebSocket 은 HTTP Upgrade handshake(101) 이후 HTTP 와 독립 프로토콜 | `#RFC6455-C3`, `#RFC6455-C5` | `high` | reverse proxy 자동 호환 아님 — 별도 설정 필요 |
| WebSocket 탄생 배경 = HTTP polling/long-polling 의 "HTTP 남용" + 클라이언트당 다중 TCP | `#RFC6455-C2` | `high` | "항상 polling 보다 우수" 는 아님 — 희소 업데이트엔 SSE/polling 적합 |
| chunked = 크기 미상 stream 을 length-delimited buffer 로, HTTP/1.1 한정 | `raw/official-docs/rfc9112-http-1-1-chunked-transfer.md#RFC9112-CHUNK-C1` | `high` | HTTP/2 에선 `Transfer-Encoding` 금지 |
| `SseEmitter` = `ResponseBodyEmitter` subclass, W3C SSE 포맷 / `StreamingResponseBody` = 파일 다운로드용 | `raw/official-docs/spring-mvc-async-streaming.md#SPRING-ASYNC-C4`, `#SPRING-ASYNC-C2`, `#SPRING-ASYNC-C3` | `high` | Spring vendor doc — server-push(SSE) vs 다운로드(StreamingResponseBody) 구분 |
| SSE 멀티서버 운영 시 thundering herd(재시작 시 동시 재연결 CPU spike), 해결로 random jitter | `raw/company-tech-blogs/sse-realtime-notification-woowahan.md#WOOWA-SSE-C2`, `#WOOWA-SSE-C3` | `medium` | 우아한형제들 사례 (company-case-study) — 공식 best practice 아님, 규모별 심각도 다름 |
## 내가 설명할 수 있어야 하는 것
- SSE / WebSocket / long-polling / chunked 각각의 공식 정의와 통신 방향(단/양방향).
- "streaming" 이 *통신 모델 변경(server-push)**응답 body 청크 전송(다운로드)* 두 개를 가리킨다는 점, 그리고 왜 둘을 구분해야 하는지.
- WebSocket 이 왜 기존 HTTP 인프라(envelope, proxy)와 자동 호환되지 않는가.
- 언제 스트리밍이 가치 있고(실시간 push, LLM token streaming), 언제 request-response + 비동기 우회(LRO polling, webhook)로 충분한가.
- 우아한형제들 SSE/WebSocket 운영 부담 사례를 *일반 법칙처럼* 말하면 안 되는 지점.
## Interview Questions
- SSE 와 WebSocket 의 차이는? 어떤 상황에 각각을 고르나?
- 서버가 클라이언트에 능동적으로 데이터를 보내야 할 때, 스트리밍 없이 해결하는 방법은? (LRO polling, webhook)
- `StreamingResponseBody``SseEmitter` 는 둘 다 "스트리밍" 인데 무엇이 다른가?
- WebSocket 을 도입하면 reverse proxy/load balancer 설정이 왜 달라지나?
- 스트리밍을 *도입하지 않기로* 결정한다면, 그 결정을 코드 레벨에서 어떻게 강제할 수 있나?
## Do Not Overclaim
- **회사 기술 블로그(우아한형제들) 사례 = 공식 best practice 아님.** thundering herd / jitter / fan-out 은 *그 회사 규모·스택*(WebFlux + Coroutine + Kafka 등) 특화이며 일반 법칙으로 단정 금지.
- **"WebSocket 이 polling 보다 항상 우월" → 금지.** RFC 6455 자체가 희소 업데이트엔 다른 선택이 적합할 수 있다고 시사.
- **"SseEmitter 가 Last-Event-ID replay 를 자동 지원" → 금지.** 서버 측 event store 를 별도 구현해야 함 (vendor doc 주의).
- **개념 문서는 구현 등급을 매기지 않는다.** 실제 구현/검증 여부는 [[wiki/projects/ca-tmpl/streaming-response-support]] 에서 판정.
## Sources
- [[raw/official-docs/whatwg-html-server-sent-events]] — WHATWG HTML SSE spec (`text/event-stream`, EventSource, Last-Event-ID, retry). official-standard.
- [[raw/official-docs/rfc6455-websocket]] — IETF RFC 6455 WebSocket (full-duplex, HTTP Upgrade handshake, masking). official-standard.
- [[raw/official-docs/rfc9112-http-1-1-chunked-transfer]] — HTTP/1.1 chunked transfer encoding (§7.1 framing). official-standard.
- [[raw/official-docs/spring-mvc-async-streaming]] — Spring MVC `SseEmitter` / `ResponseBodyEmitter` / `StreamingResponseBody`. official-vendor-doc.
- [[raw/company-tech-blogs/sse-realtime-notification-woowahan]] — 우아한형제들 SSE 운영 사례 (thundering herd, jitter, Kafka fan-out). company-case-study — 공식 best practice 아님.
- [[raw/company-tech-blogs/realtime-service-experience-woowahan-websocket]] — 우아한형제들 WebSocket 운영 사례 (이벤트 유실, 모바일 네트워크, 클러스터링). company-case-study.
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/transaction-boundary-abstraction.md
@@ -0,0 +1,172 @@
---
title: Transaction Boundary Abstraction (TransactionPort vs @Transactional)
source_type: llm-generated
status: draft
confidence: medium
tags: [transaction, clean-architecture, spring]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Transaction Boundary Abstraction (TransactionPort vs @Transactional)
> Layer: `wiki/concepts/` — 일반 개념. 특정 프로젝트의 적용 사실은 `wiki/projects/`로 분리.
## Summary
Transaction boundary abstraction은 application layer가 Spring transaction API(`@Transactional`, `PlatformTransactionManager`)를 직접 의존하지 않고, `TransactionPort` 또는 `TransactionalUseCaseRunner` 같은 port abstraction을 통해 트랜잭션 경계를 선언하는 패턴이다. Clean Architecture / Hexagonal에서 "application은 framework를 모른다"는 원칙을 트랜잭션 경계까지 일관되게 적용하기 위한 선택지 중 하나이며, 다수파인 `@Transactional` 직접 부착의 대안으로 testability와 framework lock-in 완화를 노린다.
## Standard (공식 정의)
Spring Framework는 트랜잭션 경계 선언을 위해 세 가지 표준 메커니즘을 제공한다.
- **`PlatformTransactionManager`**: 모든 트랜잭션 추상화의 SPI. JDBC, JPA, JTA 구현체가 존재.
- **선언적 트랜잭션 (`@Transactional`)**: AOP proxy 기반. method/class 단위 attribute로 propagation, isolation, timeout, rollbackFor, readOnly 등을 선언.
- **프로그래매틱 트랜잭션 (`TransactionTemplate`, `TransactionManager`)**: 명시적 코드로 트랜잭션 범위를 둘러쌈.
### Propagation 7종 (Spring `Propagation` enum)
| 값 | 의미 |
| --- | --- |
| `REQUIRED` (default) | 기존 트랜잭션 참여, 없으면 새로 생성 |
| `SUPPORTS` | 있으면 참여, 없으면 non-transactional |
| `MANDATORY` | 반드시 존재해야 함, 없으면 예외 |
| `REQUIRES_NEW` | 항상 새 물리 트랜잭션 (기존은 suspend) |
| `NOT_SUPPORTED` | non-transactional로 실행 (기존은 suspend) |
| `NEVER` | 트랜잭션 존재 시 예외 |
| `NESTED` | savepoint 기반 nested 트랜잭션 (JDBC 한정, JPA는 일반적으로 미지원) |
### Isolation 5종 (Spring `Isolation` enum)
`DEFAULT`, `READ_UNCOMMITTED`, `READ_COMMITTED`, `REPEATABLE_READ`, `SERIALIZABLE`. PostgreSQL은 `READ_COMMITTED`가 default, MySQL InnoDB는 `REPEATABLE_READ`가 default라서 vendor default 묵시 사용은 의미 차이를 만든다.
출처: [[raw/official-docs/at-transactional-spring-official]], [[raw/official-docs/transaction-template-spring-official]].
## 한계 / 주의점
트랜잭션 경계를 어떻게 선언할지에 대한 5가지 대안과 그 한계.
### 대안 1: `@Transactional` direct (다수파)
- **장점**: boilerplate 최저, Spring/Hexagonal 표준 다수파, IDE 가시성 좋음.
- **한계**:
- **AOP self-invocation 문제**: 같은 클래스 내부 메서드 호출은 proxy를 거치지 않아 `@Transactional`이 무시됨. self-injection이나 별도 bean 분리 같은 우회가 필요.
- **Testability 낮음**: application use case 단위 테스트에서 트랜잭션 경계를 검증하려면 Spring context 또는 `@DataJpaTest` 등 통합 환경이 필요.
- **Framework lock-in**: application package가 `org.springframework.transaction.annotation.Transactional`을 직접 import → Clean Architecture 의존성 규칙 위반 (application은 framework를 모른다).
- **선언과 실행 분리**: annotation은 attribute 선언일 뿐 실제 실행은 proxy/interceptor가 담당. 디버깅 시 호출 경로 추적이 간접적.
- 출처: [[raw/official-docs/at-transactional-spring-official]], [[raw/company-tech-blogs/hexagonal-reflectoring-transactional-placement]].
### 대안 2: `TransactionTemplate` programmatic
- **장점**: 명시적 코드, self-invocation 문제 없음, propagation/isolation을 객체로 다룸.
- **한계**:
- Boilerplate 증가 — 매 use case마다 `template.execute(status -> { ... })` 작성.
- 여전히 `org.springframework.transaction.support.TransactionTemplate`를 application이 직접 import → framework lock-in은 그대로.
- 출처: [[raw/official-docs/transaction-template-spring-official]].
### 대안 3: Functional Resource monad (예: Arrow Kt `Resource`, `transaction { }`)
- **장점**: testability 최고 (순수 함수 합성으로 검증 가능), 명시적 effect, type-level 보장.
- **한계**:
- 팀 학습 비용 큼 — Kotlin/함수형 코드 스타일에 익숙하지 않은 팀에선 채택 장벽이 높다.
- Java 위주 Spring 팀에선 패턴 매칭 / monad 사용이 자연스럽지 않음.
- Spring의 propagation/isolation 기본 의미를 monad 위에 재구현해야 하는 경우 있음.
- 출처: [[raw/official-docs/functional-tx-arrow-kt-resource-docs]].
### 대안 4: Custom `TransactionInterceptor` (AOP)
- **장점**: 자체 annotation 정의 가능, 커스텀 정책 주입(예: capability 검증과 결합) 가능.
- **한계**:
- AOP 자체의 self-invocation 문제 동일하게 잔존.
- interceptor 구현 자체가 Spring AOP 의존을 가짐.
- 표준 `@Transactional` 도구(`@TransactionalEventListener` 등) 호환성 추가 검증 필요.
- 출처: [[raw/company-tech-blogs/custom-transaction-interceptor-catnipcoder]].
### 대안 5: TransactionPort / TransactionalUseCaseRunner abstraction (소수파)
- **장점**:
- Application package가 Spring transaction import 없이 트랜잭션 경계를 선언.
- Test에서는 in-memory fake port로 트랜잭션 경계 검증 가능 → use case 단위 테스트가 Spring context 없이 성립.
- Framework 교체(예: Spring → Micronaut) 시 application 코드 변경 최소화.
- **한계**:
- 소수파 — 일반적 hexagonal 사례에서도 `@Transactional`을 application service에 부착하는 경우가 다수.
- Port interface 추가, infrastructure 구현체 추가, propagation/isolation을 port 시그니처로 어떻게 표현할지 결정 비용.
- Spring 도구(`@TransactionalEventListener`, JPA OSIV, AOP 기반 audit 등)와의 호환을 직접 챙겨야 함.
- 단순 CRUD 위주 프로젝트에서는 over-engineering이 될 수 있음.
- 출처: [[raw/company-tech-blogs/transaction-port-clean-ddd-spring-medium]], [[raw/company-tech-blogs/transaction-port-vassilis-soum-github-readme]].
### 공통 주의점
- **묵시적 vendor default isolation**: `Isolation.DEFAULT`로 두면 PostgreSQL은 `READ_COMMITTED`, MySQL InnoDB는 `REPEATABLE_READ`로 달라진다. multi-vendor 환경에서는 명시 선언이 안전.
- **`NESTED`는 JDBC savepoint 기반**: JPA EntityManager는 일반적으로 nested 트랜잭션을 지원하지 않음 (provider 의존).
- **`REQUIRES_NEW`는 비싸다**: 기존 트랜잭션을 suspend하고 새 connection을 잡는 비용이 있음. outbox/audit 같은 명시적 케이스에만 사용.
## Claim-backed Knowledge
> 이 표는 일반 개념 지식이 어떤 raw 근거로 뒷받침되는지 명시한다. 프로젝트 구현 주장은 여기에 넣지 않는다 (project 문서 참조).
| Knowledge Point | Supporting Claims | Confidence | Notes |
|---|---|---|---|
| Spring 은 트랜잭션 경계 선언에 declarative(`@Transactional`) / programmatic(`TransactionTemplate`) / SPI(`PlatformTransactionManager`) 메커니즘을 제공 | [[raw/official-docs/at-transactional-spring-official]], [[raw/official-docs/transaction-template-spring-official]] | high | `official-vendor-doc` (Spring 공식) |
| `@Transactional` 은 AOP proxy 기반이라 self-invocation 시 무시될 수 있음 | [[raw/official-docs/at-transactional-spring-official]]#AT-TX-C5 | high | 표준 우회(self-injection 등) 존재 — 치명적 결함 아님 |
| Propagation 기본값은 `REQUIRED`, `readOnly` 는 REQUIRED/REQUIRES_NEW 한정 적용 | [[raw/official-docs/spring-tx-management-reference]]#SPRING-TX-MGR-C3, #SPRING-TX-MGR-C6 | high | `official-vendor-doc` |
| `REQUIRES_NEW` 는 독립 physical transaction + 새 connection → pool 소모, exhaustion/deadlock 위험 | [[raw/official-docs/spring-tx-propagation-required-new-nested-official]]#SPRING-PROP-C1~C4 | high | `official-vendor-doc` |
| closure-based transaction abstraction 은 enterprise OSS 선례 존재(Axon `executeInTransaction`/`fetchInTransaction`) | [[raw/company-tech-blogs/axonframework-transactionmanager-spring-adapter]]#AXON-TX-C1~C3 | medium | `company-case-study` — 공식 best practice 아님 |
| 다수파 hexagonal 사례는 오히려 application service 에 `@Transactional` 직접 부착(abstraction 없음) | [[raw/company-tech-blogs/buckpal-archunit-lombok-allowlist-direct-transactional]]#BUCKPAL-TX-C1~C2, [[raw/company-tech-blogs/hexagonal-reflectoring-transactional-placement]]#HEX-REFL-C1 | medium | `engineering-blog`/`company-case-study` — TransactionPort 가 소수파임을 보여주는 contrary evidence |
| Spring 공식 incubator(Modulith)는 `@ApplicationModuleListener``@Transactional(REQUIRES_NEW)` 를 meta-annotation 재노출 | [[raw/company-tech-blogs/spring-modulith-archunit-generated-exemption-and-violations-as-data]]#SPRING-MOD-TX-C1 | medium | abstraction-only forbidden 정책과 반대 방향 |
## Project Application
- [[wiki/projects/ca-tmpl/transaction-boundary-abstraction]] — ca-tmpl 의사결정 + 구현 기록 (`TransactionPort` + `SpringTransactionPort` + ArchUnit 강제, 로컬 검증까지 완료). 실제 구현·검증 범위는 project 문서 참조 — 이 개념 문서에는 프로젝트 구현 주장을 넣지 않는다.
- [[raw/project-notes/ca-skeleton-operational-contract]] (§14 Transaction/Concurrency, §19 Domain Application Readiness, §29 Topic 2)
- [[raw/branch-notes/feature-application-port-usecase-contract]] — TransactionPort interface spec, forbidden import 규칙
- [[raw/branch-notes/feature-transaction-concurrency-contract]] — isolation default, propagation default, idempotency / lock 분류
## 내가 설명할 수 있어야 하는 것
- transaction boundary abstraction 의 공식 정의 — Spring 의 declarative / programmatic / SPI 메커니즘과의 관계.
- 어떤 문제를 해결하는가 — application 패키지의 framework lock-in 차단 + use case 단위 테스트의 Spring context 분리(testability).
- 어떤 상황에서는 쓰면 안 되는가 — 단순 CRUD 위주 + framework 교체 계획 없음 + Spring 숙련 팀이면 `@Transactional` 직접 부착이 합리적. abstraction 은 over-engineering 이 될 수 있다.
- 공식 문서가 말하지 않는 부분 — Spring 공식은 `@Transactional`/`TransactionTemplate` 을 권장하지 abstraction port 를 권장하지 않는다. port 화는 자체 taste.
- 회사 기술 블로그 사례를 일반 법칙처럼 말하면 안 되는 지점 — UNIL / Axon / Buckpal / Modulith 는 case-study/engineering-blog 등급. 특히 Buckpal·Modulith 는 오히려 `@Transactional` 직접/meta 부착이라 abstraction-only 가 다수파라고 말하면 안 된다.
- 내 프로젝트에서는 어떤 branch decision 으로 연결됐는가 — [[raw/branch-notes/feature-application-port-usecase-contract]] D3(TransactionPort 채택) / D11(callback 시그니처) / D12(`inNew` pool 비용). 구현 사실은 [[wiki/projects/ca-tmpl/transaction-boundary-abstraction]].
- 코드/운영에서 검증하려면 — ArchUnit 으로 application 패키지의 `@Transactional` import 차단을 확인, `readOnly` flush-mode 는 Hibernate session statistics 로 측정, `REQUIRES_NEW` 는 connection pool 사용량을 통합 테스트로 확인.
## Interview Questions
- 왜 application layer에서 Spring `@Transactional` 직접 import를 금지할 수 있는가? 어떤 trade-off가 있는가?
- AOP self-invocation 문제는 무엇이고, TransactionPort abstraction은 이 문제를 어떻게 회피하는가?
- `REQUIRES_NEW``NESTED`의 차이는 무엇이며, 왜 `NESTED`는 JPA에서 일반적으로 권장되지 않는가?
- Isolation level 4단계(READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE)와 phantom read / non-repeatable read / dirty read의 관계를 설명할 수 있는가?
- TransactionPort 도입의 trade-off를 단순 CRUD 프로젝트와 도메인 복잡도가 큰 프로젝트로 나눠 어떻게 다르게 평가하는가?
## Do Not Overclaim
- **"TransactionPort가 무조건 우월하다"고 말하지 않는다.** 단순 CRUD가 대부분이고 framework 교체 계획이 없으며 팀이 Spring에 익숙하다면, `@Transactional` 직접 부착이 boilerplate / 가시성 / 표준 도구 호환성 측면에서 합리적인 선택이다. Hexagonal/Clean Architecture 사례 다수도 application service에 `@Transactional`을 부착한다.
- **UNIL 팀 사례를 "ca-tmpl이 영감을 받았다"고 단정하지 않는다.** [[raw/company-tech-blogs/transaction-port-clean-ddd-spring-medium]](UNIL, 2024-05)와 ca-tmpl은 동일한 evolution path(@Transactional → AOP → TransactionPort)를 거친 별개 사례로 다루며, 인용은 "동일한 결론에 도달한 외부 사례" 수준에서만 한다.
- **"AOP 기반 transaction은 항상 self-invocation 문제 때문에 깨진다"고 말하지 않는다.** self-injection, public method 분리, 별도 bean 분리 같은 표준 우회가 존재하며, 다수 프로덕션에서 잘 동작한다. self-invocation은 "주의해야 할 함정"이지 "치명적 결함"이 아니다.
- **"Functional monad가 testability에서 항상 우월하다"고 말하지 않는다.** test 친화성은 높지만 팀 역량 / 언어 / 기존 코드베이스에 따라 실제 도입 비용이 매우 크다.
- 본 문서의 5종 비교는 **외부 source를 기반으로 정리한 trade-off 표**이며, 모든 항목이 자체 측정 결과는 아니다. status `draft` / confidence `medium`로 둔다.
## Sources
### 공식 문서
- [[raw/official-docs/at-transactional-spring-official]] — Spring `@Transactional` 선언적 트랜잭션 공식 정의
- [[raw/official-docs/transaction-template-spring-official]] — Spring `TransactionTemplate` 프로그래매틱 API
- [[raw/official-docs/functional-tx-arrow-kt-resource-docs]] — Arrow Kt Resource / Functional transaction
### 사례 / 블로그 (공식 best practice 아님)
- [[raw/company-tech-blogs/transaction-port-clean-ddd-spring-medium]] — UNIL (2024-05), 동일 진화 경로 사례
- [[raw/company-tech-blogs/transaction-port-vassilis-soum-github-readme]] — TransactionPort 참고 구현
- [[raw/company-tech-blogs/hexagonal-reflectoring-transactional-placement]] — Hexagonal에서 `@Transactional` 부착 위치 (다수파)
- [[raw/company-tech-blogs/custom-transaction-interceptor-catnipcoder]] — Custom TransactionInterceptor (AOP) 사례
- [[raw/company-tech-blogs/woowahan-hexagonal-multimodule]] — 보완(대체 아님): hexagonal multi-module 분리
### 프로젝트 canonical / branch-notes
- [[raw/project-notes/ca-skeleton-operational-contract]] — §14, §19, §29
- [[raw/branch-notes/feature-application-port-usecase-contract]]
- [[raw/branch-notes/feature-transaction-concurrency-contract]]
@@ -1 +0,0 @@
../../vault/30-knowledge/concepts/transactional-outbox-pattern.md
@@ -0,0 +1,112 @@
---
title: Transactional Outbox Pattern (SKIP LOCKED polling vs CDC)
source_type: llm-generated
status: draft
confidence: medium
tags: [outbox, event-driven, distributed-systems]
related_projects: [ca-skeleton]
last_reviewed: 2026-05-22
---
# Transactional Outbox Pattern (SKIP LOCKED polling vs CDC)
> Layer: `wiki/concepts/` — 일반 개념. 프로젝트 적용 사실은 [[raw/project-notes/ca-skeleton-operational-contract]] 등 project 문서 참조.
## Summary
Transactional outbox는 "DB write + 외부 메시지 publish"라는 두 시스템에 걸친 원자성 요구를 **단일 RDB 트랜잭션 + 비동기 publisher**로 우회하는 패턴입니다. 도메인 변경과 같은 트랜잭션에서 `outbox` 테이블에 이벤트 row를 INSERT하고, 별도 publisher가 그 row를 polling(또는 CDC)으로 읽어 broker에 발행함으로써 dual-write 문제(두 시스템 중 하나만 성공)를 제거합니다. polling 구현체에서는 PostgreSQL/MySQL의 `FOR UPDATE SKIP LOCKED`로 다중 publisher 간 row 경합을 해소합니다.
## Standard (공식 정의)
- **microservices.io / Chris Richardson**: outbox 패턴의 원형 정의. 서비스가 DB 트랜잭션 내에 `OUTBOX` 테이블에 이벤트를 기록하고, 별도 message relay가 이 테이블을 읽어 broker로 publish. dual-write를 명시적 anti-pattern으로 두고 outbox/event sourcing을 두 정식 대안으로 제시.
- **PostgreSQL `FOR UPDATE SKIP LOCKED`**: 9.5+. `SELECT ... FOR UPDATE` 대상 row 중 다른 트랜잭션이 이미 잠근 row를 **차단 없이 skip**. queue 형태의 워크로드(outbox claim, job queue)에 사용 권장. 잠금은 row 단위, 트랜잭션 종료 시 해제.
- **MySQL 8.0+ `SKIP LOCKED`**: PostgreSQL과 동일한 의미. 8.0 이전 버전은 미지원 — advisory lock으로 fallback.
- **Debezium**: 오픈소스 CDC 플랫폼. DB write-ahead log(Postgres logical replication / MySQL binlog)을 읽어 변경 이벤트를 Kafka 등 broker로 전달. outbox 테이블도 다른 테이블과 동일하게 WAL/binlog로 캡처.
- **Kafka Connect Outbox Event Router (Debezium SMT)**: Debezium이 캡처한 outbox row를 Single Message Transform 단계에서 Kafka topic/key/headers로 라우팅. outbox row schema 규약(`aggregatetype`, `aggregateid`, `type`, `payload`)을 요구.
- **delivery semantic**: outbox + 비동기 publish는 **at-least-once**가 기본이며 exactly-once가 아님. consumer 측에서 `eventId` 또는 `idempotencyKey` 기반 dedupe가 필수.
## 한계 / 주의점
각 구현 옵션별 trade-off.
### SKIP LOCKED polling
- publish lag = polling interval + claim transaction + broker publish. 일반적으로 **수 초~수 분** 수준이며 sub-second lag 요구에는 부적합.
- outbox 테이블이 단조 증가 → archived/published row cleanup 정책 필수 (TTL 삭제 또는 partition rotation). 누락 시 인덱스 비대 및 vacuum 비용 증가.
- 단일 DB가 SSOT여야 함. 멀티 DB에 도메인 write가 분산되면 outbox 1개로 해소 불가.
- multi-instance publisher 운영 시 동일 row 중복 claim 방지는 SKIP LOCKED 자체가 보장하지만, publish 후 commit 실패 시 재시도로 인한 중복 publish 가능 → consumer dedupe가 정합성의 일부.
### Debezium CDC
- WAL/binlog 기반이므로 publish lag이 polling보다 짧음(밀리초~초 단위).
- 단, Kafka Connect 클러스터, connector 설정/스키마, replica slot 관리, snapshot 운영 인력이 추가로 필요. **인프라 비용·운영 학습 비용이 폴링 대비 크게 큼**.
- Postgres에서는 logical replication slot이 누적되면 WAL 디스크가 증가하는 운영 risk가 있음(slot lag 모니터링 필수).
- 마이그레이션 트리거는 보통 "polling lag SLO 위반" 또는 "DB load가 polling 쿼리로 포화"이며, 그 가정이 깨지지 않으면 도입 정당화 어려움.
### Kafka Connect Outbox SMT (Debezium event router)
- payload 변환·라우팅 로직이 connector 설정 + SMT 규약에 묶임. 복잡한 payload 가공이나 multi-topic fan-out은 SMT 표현력의 한계가 있음.
- outbox row schema가 Debezium event router 규약에 종속 → 자유로운 컬럼 설계가 어려움.
### Dual-write (anti-pattern, negative reference)
- 애플리케이션 코드에서 DB commit과 broker publish를 **순차로 직접 호출**하는 형태. 둘 사이에 프로세스 종료/장애가 끼면 정합성이 깨짐.
- outbox 도입의 근거 그 자체이므로, "왜 outbox인가"의 답은 항상 dual-write 실패 시나리오에서 출발.
- 외부 publish 없이 in-process consumer만 있는 경우라면 트랜잭션 commit 후 in-process dispatch도 허용 가능 — 하지만 외부 transport가 끼는 순간 outbox가 기본값.
### Event sourcing
- 흔히 "outbox 대안"으로 묶이지만 실제로는 **도메인 모델 자체를 이벤트 스트림으로 교체**하는 결정이며, 단순 publish 정합성 문제 해결이 아님.
- 도메인 재설계, 스냅샷·재구성 운영, 쿼리 모델(CQRS) 분리 비용 동반. 단지 "이벤트 발행이 필요해서" event sourcing으로 가는 것은 trade-off 오판.
### Spring `@TransactionalEventListener`
- `AFTER_COMMIT` phase에서 in-process bean으로 이벤트 dispatch. **JVM 프로세스 내부에서만 동작**.
- commit 직후 publish 실패(예: 외부 broker 호출 예외, 프로세스 강제 종료)에 대한 영속 큐가 없음 → **재시작 시 유실**. 외부 broker로 가는 integration event 발행에는 부적합.
- 도메인 이벤트의 in-process side effect 트리거 용도로만 안전.
### Netflix DBLog 류 자체 CDC
- Debezium보다 더 큰 자체 인프라 투자. 일반 백엔드 팀이 도입할 baseline 아님. 비교 시 "왜 Debezium도 부담이라 polling을 골랐는가"의 대조군으로만 사용.
## Project Application
- [[wiki/projects/ca-tmpl/transactional-outbox-pattern]] — ca-tmpl 의사결정 기록 (현재 `documented-only`, Phase C2 미진입). 실제 구현 여부는 project 문서 참조.
- [[raw/branch-notes/feature-domain-event-outbox-contract]] — outbox publisher SSOT, row status(`PENDING/IN_FLIGHT/PUBLISHED/FAILED/DEAD`), per-aggregate FIFO, claim transaction(`READ_COMMITTED` + `FOR UPDATE SKIP LOCKED`), at-least-once + consumer dedupe 결정.
- [[raw/branch-notes/feature-background-job-async-contract]] — outbox publisher가 consume하는 retry/DLQ vocabulary(exp backoff with jitter, max 3, DLQ exhausted) SSOT.
- [[raw/project-notes/ca-skeleton-operational-contract]] (§11 Adapter Failure, §14 Transaction/Concurrency, §29 Topic 3) — outbox 패턴이 어떤 운영 계약 안에서 어떤 위치를 차지하는지의 canonical map.
## Interview Questions
- 왜 dual-write는 안 되는가? outbox는 dual-write의 어떤 실패 모드를 어떻게 제거하는가?
- SKIP LOCKED polling은 publish lag과 어떤 trade-off를 가지는가? lag을 줄이려면 polling interval만 줄이면 되는가?
- Debezium CDC로 마이그레이션을 결정하는 트리거는 무엇인가? (어떤 가정이 깨졌을 때?)
- outbox 테이블 cleanup(archived row 삭제/파티셔닝)을 누락하면 어떤 문제가 생기는가?
- outbox가 exactly-once를 보장하지 않는 이유와, 그 위에서 consumer가 정합성을 유지하는 메커니즘(idempotency key)을 설명할 수 있는가?
## Do Not Overclaim
- "outbox = exactly-once delivery"라고 말하지 않기. 정확한 표현은 **at-least-once delivery + idempotent consumer**.
- "Debezium을 곧 도입할 것"이라고 말하지 않기. CDC migration은 polling lag SLO나 DB 부하 가정이 깨질 때만 정당화되며, 현 시점에는 가정이 유지된다고만 말할 것.
- "outbox만 있으면 정합성이 보장된다"고 말하지 않기. publisher 측의 retry/DLQ, consumer 측의 dedupe, outbox row cleanup 정책이 함께 있어야 운영 가능.
- "SKIP LOCKED가 race condition을 다 막아준다"고 말하지 않기. SKIP LOCKED는 **claim 단계의 row 경합**만 해소하며, publish 후 commit 실패로 인한 재발행은 별개의 문제.
- "event sourcing이 outbox의 상위 호환이다"라고 말하지 않기. 둘은 해결하려는 문제의 층위가 다름(전달 정합성 vs 도메인 모델링).
- 본인이 polling publisher를 운영해 본 측정값이 없다면 lag 수치를 단정적으로 말하지 않기.
## Sources
- [Pattern: Transactional outbox (microservices.io)](https://microservices.io/patterns/data/transactional-outbox.html) — outbox 원형 정의 / Chris Richardson
- [PostgreSQL: SELECT — The Locking Clause](https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE) — `FOR UPDATE SKIP LOCKED` 의미론
- [Debezium documentation — Outbox Event Router](https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html) — Kafka Connect SMT
- [Spring Framework — `@TransactionalEventListener`](https://docs.spring.io/spring-framework/reference/data-access/transaction/event.html) — in-process only 한계
- [[raw/official-docs/outbox-skip-locked-microservices-io]] — outbox 원형 raw 발췌
- [[raw/official-docs/skip-locked-postgres-docs]] — Postgres SKIP LOCKED 원리
- [[raw/official-docs/outbox-debezium-official-docs]] — Debezium 공식 문서
- [[raw/official-docs/spring-transactional-event-listener]] — Spring 공식 문서
- [[raw/official-docs/event-sourcing-vs-outbox-microservices-io]] — outbox vs event sourcing
- [[raw/official-docs/dual-write-antipattern-microservices-io]] — dual-write negative reference
- [[raw/company-tech-blogs/outbox-woowahan-techblog-pattern]] — 우아한형제들 polling 사례
- [[raw/company-tech-blogs/outbox-wix-engineering-debezium]] — Wix Debezium migration 사례
- [[raw/company-tech-blogs/outbox-confluent-kafka-connect-smt]] — Confluent Kafka Connect outbox SMT
- [[raw/company-tech-blogs/outbox-netflix-domain-events-cdc]] — Netflix DBLog 자체 CDC
- [[raw/project-notes/ca-skeleton-operational-contract]] — §11 / §14 / §29 Topic 3 canonical map