Files
document-haness/docs/n+1liner/tech-log-studio/jpa-feed-query-performance/case/case-projection-row-over-fetch.md
T
DongHyeonkaandClaude Opus 5 b2963105a8 docs(keycloak-session-store): import the session-storage lab as a new project
The keycloak project ended with four open questions that design could not
settle. A two-VM lab was built to answer them by measurement, and this is
that material: 26 experiments, 125 raw command outputs, 22 browser captures.

Follows the import procedure in README.md.

  source/     the originating repository verbatim — 78 documents, 28 SVGs,
              8 manifests, plus .source-revision recording the commit
  final/      the SSOT
    document.md   729 lines written from the 29 experiment documents, not
                  concatenated: what was predicted, what was measured, and
                  where the measurement itself was wrong
    evidence/raw    125 outputs, flattened to <experiment>__<file> because
                    the originals collided (01-baseline.txt appeared three
                    times) and the audit only globs the top level
    evidence/meta   one per raw file; command and exitCode are null and the
                    README says why rather than inventing them
    evidence/browser  22 captures
    assets/       three diagrams through techviz
    .techviz/     their VizSpecs

A separate project rather than an addition to keycloak: the B-layer answers
that project's four questions, but the A, C and D layers are about cluster
failure, SSO and operations, and one document.md should hold one subject.
The four question records there can point here through 관계.

Recorded rather than papered over: only three of the 28 diagrams were
remade. The repository forbids hand-drawn SVG and forbids titles inside the
canvas; all 28 originals carry both, so converting them is redrawing, not
reformatting. They stay in source/ and the gap is written into the document.

verify-pipeline.py passes. audit-records.py reports no issues.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 22:51:59 +09:00

9.2 KiB

id, kind, slug, title, topic, topicName, project, status, studio, assets, evidence
id kind slug title topic topicName project status studio assets evidence
4c9c3b90-bc89-4300-9334-088ea95d37d8 CASE projection-row-over-fetch Projection 이후에도 1,509행을 읽은 Row Over-fetch jpa-feed-query-performance JPA 피드 조회 성능 Liner N + 1문제 게시 전 https://hyeonworks.com/studio/documents/4c9c3b90-bc89-4300-9334-088ea95d37d8/edit
key file
projection-row-over-fetch ../../../final/assets/tech-log-studio/projection-row-over-fetch.svg
../../../final/evidence/raw/explain/l6-parent-projection.txt

Projection 이후에도 1,509행을 읽은 Row Over-fetch

DTO 프로젝션으로 하이드레이트한 엔티티가 1,569개에서 0개로 줄고 쿼리도 2개로 고정됐다. 그런데 자식 IN 쿼리는 페이지 부모 20개의 하이라이트를 전부 가져와 1,509행이었다. 화면에 필요한 것은 부모당 최신 3개, 최대 60행이었다.

관계

  • 화면 조회는 Read Projection을 사용한다 이 관측에서 나온 결정이다.
  • Top-N-per-group 선택 기준 남은 행 과조회를 푼 다음 단계의 기준이다.
  • Fetch Join · Batch · Projection 선택 기준 왕복과 적재를 각각 어느 전략이 푸는지 정리한 기록이다.

문제

Batch Fetch로 왕복 수와 페이징 문제를 풀었지만 엔티티는 여전히 통째로 하이드레이트했다. seed 1,000의 첫 페이지 20건에서 FeedItem·User·Page·Highlight를 합해 1,569개가 영속 객체로 올라왔다.

화면에는 일부 컬럼만 필요했다. 적재 대상을 줄이려고 필요한 스칼라 값만 조회하는 프로젝션을 추가했다.

결론

프로젝션은 하이드레이트한 엔티티를 0개로 만들었다. SELECT new 캐리어는 영속 엔티티 대신 스칼라 값으로 record를 만들므로 1차 캐시·더티체킹·지연 프록시도 생기지 않는다. join도 컬럼을 읽기 위한 경로일 뿐 엔티티를 만들지 않는다.

발행 쿼리는 N과 관계없이 2개로 고정됐다. 부모 스칼라 쿼리 1개와 자식 IN 쿼리 1개다. 페이지 부모가 최대 20개라 자식 IN도 한 번만 실행된다.

남은 문제는 행 수였다. 단순한 IN 쿼리의 LIMIT은 부모별로 적용되지 않으므로 페이지 부모의 하이라이트를 전부 가져온다. seed 1,000의 첫 페이지에서 자식 행은 1,509개였고 화면에 필요한 것은 60개였다.

필요한 컬럼만 선택하면 EXPLAIN의 width도 줄어들 것으로 예상했지만 부모 프로젝션의 width는 2088로 엔티티 조회의 1194보다 컸다. users와 pages 조인의 행폭이 반영되고, PostgreSQL의 width가 실제 전송 바이트가 아니라 컬럼 타입의 평균폭 추정치이기 때문이다.

검증 환경

Java 21 Spring Boot 4.0.0 Hibernate ORM 7.1.8.Final PostgreSQL : postgres:16-alpine (Testcontainers)

격리 프로젝션 측정은 배치 설정이 없는 별도 IT 클래스 loadFeedProjection은 loadFeed를 두고 추가한 sibling 메서드

측정 지표 entitiesLoaded : Statistics.getEntityLoadCount() prepared : Statistics.getPrepareStatementCount() collectionFetch : Statistics.getCollectionFetchCount()

재현 조건

  1. 부모 스칼라 프로젝션과 자식 IN 스칼라 프로젝션 두 쿼리로 loadFeedProjection을 구현한다.

  2. seed 1,000에서 loadFeedProjection(0, 20)을 실행하고 getEntityLoadCount()를 읽는다.

  3. N ∈ {10, 100, 1000}에서 prepared가 항상 2인지 확인한다.

  4. 프로젝션 결과가 기준선 loadFeed와 같은 형태인지 대조한다.

  5. 자식 IN 쿼리가 반환한 행수를 세어 화면에 필요한 60행과 비교한다.

  6. 부모 프로젝션과 엔티티 페이징의 EXPLAIN width를 비교한다.

본문

두 개의 스칼라 프로젝션

// (A) 부모 스칼라 프로젝션 — 조인은 컬럼 접근용, 페이징은 엔티티에
select new FeedItemProjectionRow(f.id, u.name, u.username, p.url, p.title, f.firstHighlightedAt)
  from FeedItemJpaEntity f join f.user u join f.page p
  order by f.firstHighlightedAt desc, f.id asc          // + setMaxResults(20) → LIMIT
// (B) 그 20개 부모의 하이라이트를 필요 컬럼만 IN 한 방으로 → feedItemId 로 그룹핑
select new HighlightProjectionRow(h.feedItem.id, h.color, h.text, h.createdAt)
  from HighlightJpaEntity h where h.feedItem.id in (:pageIds)

FeedSummary의 마지막 인자가 리스트라 생성자 표현식 한 번으로 만들 수 없었다. 부모와 자식을 각각 스칼라 캐리어로 조회한 뒤 메모리에서 조립했다.

엔티티 로드가 0으로 줄어든다

지표 배치 프로젝션
entitiesLoaded (seed 1,000) 1,569 0
prepared (N=1,000) 23 2
collectionFetch (N=1,000) 10 0

N이 늘어도 쿼리는 2개다

N 순진(1+N) 배치(1+ceil(N/batch)·연관) 프로젝션(상수)
10 25 5 2
100 222 5 2
1,000 2,022 23 2

기준선의 쿼리 수는 N을 따라 늘고 배치는 배치 크기 단위로 늘었다. 프로젝션은 두 개로 유지된다.

남은 비용 — 페이지당 전량

:::evidence key="projection-row-over-fetch" alt="왼쪽 엔티티 적재에서 가운데 스칼라 프로젝션으로 넘어가면서 엔티티 생성이 사라지지만, 오른쪽 자식 조회는 페이지 부모의 자식을 전부 가져와 행수가 그대로 남는 것을 보여 주는 그림." caption=" " zoom="true" :::

항목
페이지 부모 20
자식 IN이 반환한 행 1,509
화면에 필요한 행 60 (부모당 3)

단순한 IN 쿼리의 LIMIT은 최종 결과 집합 전체에 적용되므로 부모별 상위 N개를 만들 수 없다.

width는 좁아지지 않았다

-- (a) Limit 존재하나 width=2088 (users·pages 조인이 행폭에 흘러든다)
Limit  (... rows=20 width=2088) (actual ... rows=20 loops=1)
  ->  Sort  Sort Method: top-N heapsort  Memory: 27kB
        ->  Hash Join  (fi.page_id = p.id)      ← pages 조인
              ->  Hash Join  (fi.user_id = u.id) ← users 조인
                    ->  Seq Scan on feed_items fi (width=56)   ← feed_items 자체는 좁다
-- (b) 자식 스칼라 IN — Hash Semi Join, 자식 행만 반환 (곱셈 없음)
Hash Semi Join  (... rows=1509 loops=1)

프로젝션의 효과는 SQL 플랜의 width가 아니라 ORM 층의 엔티티 로드 수에서 확인해야 한다.

배치와 프로젝션은 다른 것을 줄인다

배치는 SQL 왕복 횟수를 줄이고 프로젝션은 적재할 대상을 줄인다. 두 효과는 서로를 대신하지 않는다. 프로젝션이 엔티티를 만들지 않는 동작은 배치 설정 여부와 관계없이 성립한다.

기존 loadFeed를 바로 교체하지 않고 sibling 메서드로 둔 이유는 앞 단계의 기준선을 다시 측정하기 위해서다. 기준선부터 배치까지의 테스트도 다시 실행해 결과가 유지되는지 확인했다.

로컬 미리보기

본문 「두 개의 스칼라 프로젝션

// (A) 부모 스칼라 프로젝션 — 조인은 컬럼 접근용, 페이징은 엔티티에
select new FeedItemProjectionRow(f.id, u.name, u.username, p.url, p.title, f.firstHighlightedAt)
  from FeedItemJpaEntity f join f.user u join f.page p
  order by f.firstHighlightedAt desc, f.id asc          // + setMaxResults(20) → LIMIT
// (B) 그 20개 부모의 하이라이트를 필요 컬럼만 IN 한 방으로 → feedItemId 로 그룹핑
select new HighlightProjectionRow(h.feedItem.id, h.color, h.text, h.createdAt)
  from HighlightJpaEntity h where h.feedItem.id in (:pageIds)

FeedSummary의 마지막 인자가 리스트라 생성자 표현식 한 번으로 만들 수 없었다. 부모와 자식을 각각 스칼라 캐리어로 조회한 뒤 메모리에서 조립했다.

엔티티 로드가 0으로 줄어든다

지표 배치 프로젝션
entitiesLoaded (seed 1,000) 1,569 0
prepared (N=1,000) 23 2
collectionFetch (N=1,000) 10 0

N이 늘어도 쿼리는 2개다

N 순진(1+N) 배치(1+ceil(N/batch)·연관) 프로젝션(상수)
10 25 5 2
100 222 5 2
1,000 2,022 23 2

기준선의 쿼리 수는 N을 따라 늘고 배치는 배치 크기 단위로 늘었다. 프로젝션은 두 개로 유지된다.

남은 비용 — 페이지당 전량」 아래 :::evidence key="projection-row-over-fetch" 자리에 들어갈 그림이다.

왼쪽 엔티티 적재에서 가운데 스칼라 프로젝션으로 넘어가면서 엔티티 생성이 사라지지만, 오른쪽 자식 조회는 페이지 부모의 자식을 전부 가져와 행수가 그대로 남는 것을 보여 주는 그림.