Files
clean-architecture-backend-…/docs/mongodb/advanced/sharding.md
T
DongHyeonkaandClaude Opus 5.5 6d27356e2b refactor: 부가 기능을 capability 모듈로 포장하고 기본 조립을 web-only로 전환
설계: docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md
계획/진행 기록: docs/superpowers/plans/2026-09-25-capability-module-packaging.md

- Wave 0: 규칙 고정(AGENTS.md capability 완료 기준·테스트 규칙) + 차단 결함 7건
  (compose overlay 검사, redis-sdk CI job, 적용된 V9/V13 원복 + V16, @EnableScheduling,
  messaging bridge 순서, prod 에러 상세 validator, sample loggers read-only)
- Wave 1: 데이터·보안 Critical 10건 (durable operation 25P02, operation 유스케이스 이동,
  outbox 재인코딩, Kafka TLS/SASL, 알림 트랜잭션, SNS 서명, tus checksum, GraphQL fragment,
  Redis lane, gRPC FAILED_TERMINAL)
- Wave 2: 리팩터링 잔재·실험용 자리 삭제, outbox v1 fencing(V17), 멱등성 V2 정본화
- Wave 3: 라이브러리형 코드 정리(동작하지 않는 설정·인터페이스·gate 제거, web-advanced 분리)
- Wave 4: capability 11개를 "있으면 켜짐" 모듈로 포장, 끄는 장치 제거, 기본 조립 web-only,
  qualificationBootJar 분리
- Wave 5: 빌드 로직 축소(17.2k -> 10.8k줄), sample 테스트 컨벤션 적용

삭제한 코드는 docs/capability-status.md "제거된 코드" 표에 복구 커밋(208077fd)과 함께 기록.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 12:49:07 +09:00

4.4 KiB

Advanced — Sharding

Capability: MongoCapability.SHARDING Enablement: library API, no configuration property. The service's own adapter constructs the entry point with a MongoAdvancedCapabilityGuard built from MongoAdvancedCapabilityFlags that enables the capability; construction is refused otherwise. Status: Advanced. Reshard orchestration remains Experimental.

Requirements

Topology A real sharded cluster. A replica set cannot exercise routing.
Server MongoDB 7.0 or 8.0.
Privilege MongoPrincipalRole.SHARD_ADMIN for the admin plane; the application role is unchanged.
Gate Not promoted. No mongoShardedTest lane is registered, and a sharded cluster is not an environment this repository stands up. Listed under experimental_contracts in src/config/mongodb/release-contracts.json; promoting it needs the lane, its required class, and protected-environment evidence to exist first.

Shard key

ShardKeyDescriptor declares the key as an ordered list of ShardKeyPart plus a ShardStrategy:

Strategy Distributes Cost
RANGE by value ranges Range queries stay targeted; a monotonic key (a timestamp, an ObjectId) sends every insert to one shard.
HASHED by hash of the key Inserts spread evenly; every range query becomes scatter-gather.

There is no strategy that is good at both, which is why the choice is a declaration rather than a default.

Routing classification

ShardAwareQueryValidator classifies each query before execution:

MongoRoutingClassification Meaning
TARGETED The full shard key is present. One shard answers.
PREFIX_TARGETED A prefix of a compound key is present. A subset of shards answers.
SCATTER_GATHER No shard-key predicate. Every shard answers.
REJECTED Scatter-gather where the profile forbids it.

A scatter-gather query is not an error — some queries legitimately need every shard — but it must be declared. Undeclared scatter-gather raises MongoShardRoutingException. The reason is that scatter-gather passes every test on a single-shard development cluster and only degrades once the cluster grows, at which point the query is already in production and the fix is a schema change.

Unsupported combinations

  • Unique index on a field that is not a prefix of the shard key. MongoDB cannot enforce it across shards, and it fails at index creation, not at query time.
  • Transactions that touch documents on multiple shards remain supported but cost a cross-shard two-phase commit. Prefer a shard key that keeps a transaction's documents co-located.
  • CSFLE on a sharded collection: see encryption.md for the combinations that are refused.

Admin plane

MongoShardingAdminGateway (D4, SHARD_ADMIN credential) covers shard-collection, refine-shard-key and reshard.

ShardKeyAnalyzer produces a ShardKeyReadinessReport before sharding a collection: cardinality, frequency skew and monotonicity. A key with low cardinality creates jumbo chunks that cannot be split; a monotonic key creates a hot shard. Both are visible in the report and invisible in a functional test.

ReshardApproval is required for a reshard — a named approver and a stated window. Resharding rewrites the collection: it duplicates the data during the operation and saturates IO. It is not a runtime operation and the type refuses to pretend otherwise.

Failure recovery

Symptom Cause Action
MongoShardRoutingException Undeclared scatter-gather Add the shard key to the predicate, or declare the query as scatter-gather in its profile after review.
Jumbo chunks Low-cardinality shard key Refine the shard key (adds a suffix, non-destructive) before considering a reshard.
One hot shard Monotonic range key Refine with a high-cardinality prefix, or reshard to hashed if range queries are not needed.
Balancer never converges Chunk migration blocked by long-running operations Check for long transactions and cursors; the balancer waits on them.

Promotion evidence

Per ADR-MONGO-ADV-001: actual sharded-cluster evidence, security review of the SHARD_ADMIN role, a migration path for an existing unsharded collection, failure cases (undeclared scatter-gather refused, jumbo chunk detected), and this document as the runbook. Reshard orchestration stays Experimental until operational scale evidence exists.