샤딩 개념: 청크, 밸런서, 샤드 키
학습자는 청크를 정의하고 밸런서가 데이터의 균등한 분포를 유지하기 위해 청크를 샤드 간에 이동하는 방식을 설명합니다.
샤딩 개념: 청크, 밸런서, 샤드 키은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is Sharding?
Sharding is MongoDB's horizontal scaling strategy. Instead of storing all data on a single replica set, a sharded cluster divides the data across multiple shards, each of which is itself a replica set. This lets you scale storage, throughput, and memory horizontally by adding more shards as your data grows.
Sharded Cluster Components
A sharded cluster has three roles: Shards — replica sets that store the actual data. mongos — a query router that receives client connections and routes operations to the correct shard(s). Config servers — a replica set that stores cluster metadata, including the shard key ranges and chunk locations. Clients always connect to mongos, never directly to shards.
// Connect to the cluster via mongos (same URI format as a standalone)
const client = new MongoClient('mongodb://mongos-host:27017/mydb')The Shard Key: Data Distribution Axis
The shard key is a field (or compound of fields) you choose when sharding a collection. MongoDB uses the shard key value to determine which shard a document belongs to. Every document in a sharded collection must contain the shard key, and the key is immutable — you cannot change it after sharding. Choosing the wrong shard key is the most common MongoDB scaling mistake.
// Enable sharding on a database
sh.enableSharding('mydb')
// Shard a collection by userId
sh.shardCollection('mydb.events', { userId: 1 })What Is a Chunk?
MongoDB divides the shard key range into chunks — contiguous ranges of shard key values. Each chunk lives on exactly one shard. By default, a chunk grows up to 128 MB before MongoDB splits it into two smaller chunks. The shard each chunk lives on is tracked in the config server metadata.
// View the chunks for a collection
use config
db.chunks.find(
{ ns: 'mydb.events' },
{ shard: 1, min: 1, max: 1 }
).limit(10)The Balancer: Evening Out Data
The balancer is a background process that monitors chunk distribution across shards. If one shard has significantly more chunks than others (by default, a difference of 8 or more), the balancer migrates chunks from the busiest shard to less-loaded shards. Migrations happen automatically and try to avoid peak traffic windows.
// Check if the balancer is running
sh.getBalancerState()
// Check balancer status
sh.status()
// Pause the balancer during a maintenance window
sh.stopBalancer()Targeted vs Scatter-Gather Queries
When a query includes the shard key, mongos routes it directly to the one (or few) shards that hold matching documents — a targeted query. When the query does not include the shard key, mongos must send it to all shards and merge results — a scatter-gather query. Targeted queries are dramatically faster. Design your queries around the shard key for best performance.
// Targeted: mongos routes to one shard
db.events.find({ userId: 'u123', date: { $gt: ISODate('2025-01-01') } })
// Scatter-gather: mongos fans out to all shards
db.events.find({ eventType: 'click' })Hot Shards: The Anti-Pattern
A hot shard (or hot spot) occurs when a disproportionate share of reads or writes land on a single shard. Common causes: using a monotonically increasing shard key (like createdAt or ObjectId) so all new inserts always go to the highest chunk, or using a low-cardinality key (like a boolean) that limits parallelism. Hot shards negate the benefits of sharding.
// BAD: ObjectId is monotonically increasing
// All new inserts go to the 'max' chunk on one shard
sh.shardCollection('mydb.events', { _id: 1 }) // AVOID
// BETTER: Use hashed sharding to distribute new inserts
sh.shardCollection('mydb.events', { _id: 'hashed' })Jump Consistent and Jumbo Chunks
A jumbo chunk is a chunk that has grown beyond the maximum size but cannot be split because all of its documents share the same shard key value. Jumbo chunks cannot be migrated by the balancer and create a persistent imbalance. The fix is to choose a shard key with sufficient cardinality so that no single key value maps to more documents than fit in one chunk.
// Identify jumbo chunks (jumbo: true in chunk metadata)
use config
db.chunks.find({ ns: 'mydb.events', jumbo: true }).count()Viewing Shard Distribution With sh.status()
sh.status() gives a complete picture of your sharded cluster: which collections are sharded, how many chunks exist per shard, and the key ranges each shard owns. Use it to quickly spot imbalanced chunk distribution and confirm that the balancer has completed migrations after adding a new shard.
// Full cluster status
sh.status()
// Targeted collection info
db.runCommand({ collStats: 'events' })
// Look at 'sharded', 'count', 'nchunks', 'shards' fieldsAdding a New Shard
Adding a shard to a running cluster is an online operation. The balancer automatically migrates chunks from existing shards to the new one over time. You can pre-split chunks before adding a shard to speed up initial distribution, especially when bulk-loading data. No downtime is required when adding shards.
// Add a new shard (replica set format)
sh.addShard('rs1/new-shard-host:27017')
// Monitor migration progress
sh.status()
db.adminCommand({ balancerCollectionStatus: 'mydb.events' })When to Shard: The Decision Threshold
Sharding adds operational complexity. Before sharding, exhaust vertical scaling and indexing options. Common triggers to shard: data volume > 1–2 TB on a single replica set, write throughput that saturates a single primary, or working set that no longer fits in RAM. Always benchmark with explain() and profiling before deciding to shard.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: sharding distributes data across multiple shards (replica sets) using a shard key, chunks are contiguous shard key ranges the balancer migrates to maintain even distribution, and targeted queries (including the shard key) are far more efficient than scatter-gather queries. Next up we explore how to choose the right shard key.
자주 묻는 질문
“샤딩 개념: 청크, 밸런서, 샤드 키” 강의는 무료인가요?
네 — “샤딩 개념: 청크, 밸런서, 샤드 키” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“샤딩 개념: 청크, 밸런서, 샤드 키”에서 뭘 배우나요?
학습자는 청크를 정의하고 밸런서가 데이터의 균등한 분포를 유지하기 위해 청크를 샤드 간에 이동하는 방식을 설명합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“샤딩 개념: 청크, 밸런서, 샤드 키” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 샤딩 개념: 청크, 밸런서, 샤드 키
- 샤드 키 선택하기: 카디널리티, 빈도, 단조성
- 범위 기반 샤딩과 해시 기반 샤딩 전략
- 영역 샤딩: 지역에 데이터 고정하기