Files
clean-architecture-backend-…/docs/jpa/transaction-guide.md
T
DongHyeonka 1400dc1506 feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다
문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지
크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의
500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본
(TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR
테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로
만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져
객체 저장소 lane이 돌지 않았다.

방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은
결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD,
S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한).
MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자·
mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고,
scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과
왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와
결정은 리뷰 README 14절에 있다.

위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서
H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC·
WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체,
샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개
(composition:durable-operation, adapter:inbound:messaging)와 새
마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1,
grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면
실패한다(runbook에 확인 쿼리).

검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함
전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과.

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절
BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션
기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가,
샘플 Idempotency-Key 오류 코드 변경.
2026-11-03 19:52:06 +09:00

68 lines
3.6 KiB
Markdown

# Transaction Guide
Design §15-§20. What owns a transaction, what may be retried, and what must never be.
## The application service owns the boundary
Repository adapters do not open transactions. The use case does, through `TransactionPort`,
because the unit of work is a business decision and only the use case knows where it starts and
ends. `SpringTransaction` is the only implementation: one pre-built `TransactionTemplate` per
mode over Spring's `PlatformTransactionManager`, every mode running at `READ_COMMITTED` and
bounded in time.
- **Isolation** is pinned on the pool, not per transaction: the module defaults set
`spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED` and
`HikariPoolConstraintValidator` refuses any other level. A template that names the level makes
pgjdbc ask the server for it (`SHOW TRANSACTION ISOLATION LEVEL`) at every begin.
- **Time bound**: `app.persistence-jpa.transaction.write-timeout` (`inWrite`, `inRootWrite`) and
`read-timeout` (`inRead`), 30 s each by default; `inNew` is fixed at 30 s. Spring hands the
remaining time to each statement, so the server cancels a slow statement or lock wait
(`DB_QUERY_CANCELED`) and the connection returns to the pool. A unit of work that needs longer
is usually a batch job that should be split, not a reason to raise the bound.
| Call | Propagation | When |
|---|---|---|
| `inWrite` | `REQUIRED`, read-write | command default |
| `inRootWrite` | `REQUIRED`, read-write, rejects an ambient transaction before running | orchestration that must prove a physical commit |
| `inRead` | `REQUIRED`, read-only | query default |
| `inNew` | `REQUIRES_NEW`, read-write | outbox / audit / compensation that must commit on its own |
Open Session In View is off in every runtime profile. It is on by default in Spring Boot, which is
why `JpaDangerousConfigurationGuard` fails startup rather than trusting configuration review.
`REQUIRES_NEW` acquires a second physical connection while pinning the first, so the pool must
satisfy:
```text
maximumPoolSize >= (concurrent_threads x (1 + max_requires_new_depth)) + 1
```
## Nothing is retried by the port
`SpringTransaction` runs the action once. A failure rolls back and propagates, translated to
the shared persistence error codes where the SQLSTATE is known; a lost `@Version` race has no
SQLSTATE and is reported as `DB_OPTIMISTIC_CONFLICT` (409). A caller that decides to retry must
re-run the whole use case in a new transaction — never re-issue one statement — because an
optimistic conflict or a serialization failure means the state the attempt computed against is no
longer the committed state.
A second engine with named policies, deadline budgets, transaction-local timeouts and automatic
full-transaction retry (`SpringJpaTransactionExecutor`, `FullTransactionRetryCoordinator`,
`PolicyTransactionPort`) existed next to this one and was removed on 2026-09-25. Its last commit is
recorded in `docs/capability-status.md`.
## Completion unknown
A connection can break while a commit is in flight; the server may have committed and only the
acknowledgement was lost. `TransactionCompletionUnknownException` is never retried, and the type
system enforces it: `JpaFailureContext` refuses to represent a retryable completion-unknown failure.
The port itself retries nothing, so such a commit surfaces to the caller as a failure exactly once
(`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried`).
Recovery is reconciliation, not retry:
```text
check the idempotency record -> check the business row -> check the outbox
-> still undetermined? escalate
```