읽기 설정: 읽기 부하 분산하기
학습자는 primary, primaryPreferred, secondary, nearest 및 태그가 지정된 읽기 설정을 구성해 복제 세트 전체로 읽기를 분산합니다.
읽기 설정: 읽기 부하 분산하기은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is a Read Preference?
A read preference controls which replica set member the driver sends read operations to. By default, all reads go to the primary to ensure you always see the latest data. However, redirecting reads to secondaries can reduce load on the primary and bring reads geographically closer to users — at the cost of potentially reading slightly stale data.
primary: Always Read From Primary
primary (the default) routes every read to the primary. This guarantees strong consistency — you will always read your own writes and see the most up-to-date data. The downside is that the primary handles all read and write traffic. Use this mode whenever stale data would be unacceptable, such as in financial applications or user-facing dashboards.
// Explicit primary read preference (this is the default)
const col = db.collection('accounts', {
readPreference: 'primary'
})
await col.findOne({ _id: userId })primaryPreferred: Fallback to Secondary
primaryPreferred reads from the primary when it is available but falls back to a secondary if the primary is unreachable. This provides a balance: you normally get fresh data, but the application degrades gracefully during primary elections. Be aware that during the fallback, you may read data that is a few seconds behind.
const col = db.collection('products', {
readPreference: 'primaryPreferred'
})
await col.find({}).toArray()secondary: Read Only From Secondaries
secondary sends all reads to available secondaries, never touching the primary. This is ideal for analytics queries, batch jobs, or reporting that can tolerate eventual consistency. It offloads significant read pressure from the primary. If no secondary is available, the operation fails — it will NOT fall back to the primary.
// Route analytics query to secondary
const col = db.collection('events', {
readPreference: 'secondary'
})
const count = await col.countDocuments({ type: 'click' })secondaryPreferred: Secondary With Fallback
secondaryPreferred prefers secondaries but falls back to the primary if no secondary is available. This is the most commonly used non-default mode — it spreads read load across secondaries under normal conditions while remaining available when a secondary goes down. The caveat is the same as secondary: reads may be slightly stale.
const col = db.collection('catalog', {
readPreference: 'secondaryPreferred'
})
await col.find({ category: 'books' }).toArray()nearest: Lowest Network Latency
nearest sends reads to the member with the lowest measured network round-trip time, regardless of whether it is primary or secondary. This is perfect for globally distributed applications where users in different regions should read from the closest data center. Note that different users may read from different members, so they may temporarily see different data states.
const col = db.collection('content', {
readPreference: 'nearest'
})
await col.findOne({ slug: 'hello-world' })Tag Sets: Targeting Specific Members
Tag sets let you label replica set members (e.g., { region: 'us-east' }, { purpose: 'analytics' }) and then write read preferences that target only matching members. This enables sophisticated routing: send application reads to the nearest region and analytics queries to a dedicated secondary, all within the same replica set.
// Tag a member in replica set config
let cfg = rs.conf()
cfg.members[2].tags = { region: 'eu-west', purpose: 'analytics' }
rs.reconfig(cfg)
// Read from eu-west analytics member
const col = db.collection('reports', {
readPreference: new ReadPreference('secondary', [{ region: 'eu-west' }])
})Stale Reads and Replication Lag
When reading from secondaries, you may encounter stale reads — the secondary hasn't replicated the latest writes from the primary yet. The staleness depends on replication lag. MongoDB 3.6 introduced maxStalenessSeconds: the driver refuses to use a secondary lagging more than the specified number of seconds, preventing very stale reads.
// Reject secondaries more than 90 seconds behind
const col = db.collection('products', {
readPreference: new ReadPreference(
'secondaryPreferred',
[],
{ maxStalenessSeconds: 90 }
)
})Read Preference in the Connection String
You can set the default read preference for all operations in the connection string using the readPreference parameter. This is the easiest way to configure the default without changing every call site. Individual operations can still override it by passing a readPreference option explicitly.
// Connection string with secondaryPreferred default
const uri = 'mongodb+srv://host/db?readPreference=secondaryPreferred&maxStalenessSeconds=120'
const client = new MongoClient(uri)Read Preference and Transactions
Multi-document transactions must always use primary read preference. Operations inside a transaction that specify a different read preference will throw an error. This ensures that all reads within the same transaction see a consistent snapshot as of the transaction's start time on the primary.
// Inside a transaction, reads always go to primary
const session = client.startSession()
await session.withTransaction(async () => {
// This implicitly uses primary read preference
const order = await db.orders.findOne({ _id: orderId }, { session })
await db.inventory.updateOne({ sku: order.sku }, { $inc: { qty: -1 } }, { session })
})Choosing Read Preference in Practice
Use this guide: Real-time user data (cart, profile, notifications) → primary. Product catalog, content → secondaryPreferred. Reports and analytics → secondary with a dedicated analytics member. Global CDN-like reads → nearest. Always measure replication lag before routing critical reads to secondaries.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: read preferences control which replica set member handles read operations, secondary and secondaryPreferred offload read traffic at the cost of eventual consistency, and nearest minimises latency in geo-distributed deployments. Next up we explore sharding — MongoDB's strategy for scaling beyond a single replica set.
자주 묻는 질문
“읽기 설정: 읽기 부하 분산하기” 강의는 무료인가요?
네 — “읽기 설정: 읽기 부하 분산하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“읽기 설정: 읽기 부하 분산하기”에서 뭘 배우나요?
학습자는 primary, primaryPreferred, secondary, nearest 및 태그가 지정된 읽기 설정을 구성해 복제 세트 전체로 읽기를 분산합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“읽기 설정: 읽기 부하 분산하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 복제 세트 구성원: 프라이머리, 세컨더리, 중재자
- 선출 및 자동 장애 조치
- 쓰기 고려 사항 및 확인된 내구성
- 읽기 설정: 읽기 부하 분산하기