0Pricing
MongoDB Academy · 강의

복제 세트 구성원: 프라이머리, 세컨더리, 중재자

학습자는 각 복제 세트 구성원의 역할을 설명하고 oplog를 통해 쓰기 작업이 프라이머리에서 세컨더리로 흐르는 과정을 추적합니다.

복제 세트 구성원: 프라이머리, 세컨더리, 중재자은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is a Replica Set?

A replica set is a group of MongoDB servers that all hold the same data, providing high availability and redundancy. If one server fails, another automatically takes over. A typical replica set has three or more members: at least one primary, one or more secondaries, and optionally an arbiter.

The Primary: Source of Truth

The primary is the only member that accepts write operations. All clients send inserts, updates, and deletes to the primary. It records every write operation in a special log called the oplog (operations log), which secondaries then read to stay in sync.

// Check which member is primary in mongosh
rs.isMaster()
// or
rs.status()

The Secondary: Hot Standby

A secondary replicates data from the primary by continuously tailing the primary's oplog and applying the same operations to its own copy of the data. Secondaries can serve read queries (with the right read preference) and will take over as primary if the current primary becomes unavailable.

// View oplog on a secondary
use local
db.oplog.rs.find().sort({$natural: -1}).limit(5)

Oplog: The Replication Backbone

The oplog (operations log) is a special capped collection stored in the local database on every replica set member. Every write to the primary is appended to the oplog. Secondaries read the oplog and replay each entry in order, keeping their data identical to the primary. The oplog's size determines how far behind a secondary can fall before needing a full resync.

// Check oplog size and time range
use local
db.oplog.rs.stats().maxSize
db.oplog.rs.find({},{ts:1,op:1,ns:1}).sort({$natural:-1}).limit(3)

The Arbiter: Tiebreaker Member

An arbiter is a lightweight replica set member that holds no data. Its sole purpose is to participate in elections by casting a vote when a new primary needs to be chosen. Arbiters are used in even-member sets (e.g., two data-bearing members) to ensure a majority can always be reached without the cost of a third full data node.

// Add an arbiter to the replica set
rs.addArb('hostname:27017')

Votes and Elections Overview

Each replica set member has a vote (0 or 1). A primary is elected by majority vote. With 3 members (each with 1 vote), a majority is 2. If the primary goes down, the remaining two members hold an election and the one with the most up-to-date oplog typically wins. Elections complete in seconds under normal network conditions.

// View all members and their vote configuration
rs.conf().members.forEach(m => {
  print(m.host, 'votes:', m.votes, 'priority:', m.priority)
})

Member Priorities

Each member has a priority value (default 1). A member with higher priority is preferred as primary in elections. Setting priority to 0 prevents a member from ever becoming primary — useful for secondaries in distant data centers that should serve local reads but not take writes from the primary region.

// Set a member to never become primary (priority 0)
let cfg = rs.conf()
cfg.members[2].priority = 0
rs.reconfig(cfg)

Hidden and Delayed Secondaries

Hidden secondaries (priority 0, hidden: true) are invisible to drivers and used only for backups or analytics without affecting the primary election pool. Delayed secondaries intentionally lag behind the primary by a configured number of seconds, providing a rolling recovery window in case of accidental data corruption.

// Configure a delayed secondary (e.g., 1 hour behind)
let cfg = rs.conf()
cfg.members[2].hidden = true
cfg.members[2].priority = 0
cfg.members[2].secondaryDelaySecs = 3600
rs.reconfig(cfg)

Checking Replication Lag

Replication lag is the delay between when a write is committed on the primary and when it appears on a secondary. High lag means secondaries serve stale data. You can monitor lag with rs.printSecondaryReplicationInfo() or by comparing the oplog timestamps between members. Atlas provides built-in lag alerts.

// Print replication lag for each secondary
rs.printSecondaryReplicationInfo()

// Example output:
// source: secondary1:27017
// syncedTo: Sat Jun 21 2025 10:00:00
// 0 secs (0 hrs) behind the primary

rs.status() Output Explained

rs.status() returns the full health snapshot of the replica set. Key fields to inspect: stateStr (PRIMARY / SECONDARY / ARBITER / DOWN), optimeDate (last applied oplog entry), health (1 = healthy, 0 = unreachable), and lastHeartbeatMessage for error details on troubled members.

rs.status().members.forEach(m => {
  print(m.name, m.stateStr, 'health:', m.health)
})

Data Writes Flow End to End

When a client writes a document, the flow is: 1) Driver sends write to the primary. 2) Primary applies the write to WiredTiger storage. 3) Primary appends the operation to its oplog. 4) Secondaries pull the oplog entry and apply it. 5) Primary acknowledges the client according to the configured writeConcern.

// Write with w:majority ensures secondaries have acknowledged
db.orders.insertOne(
  { item: 'laptop', qty: 1 },
  { writeConcern: { w: 'majority', wtimeout: 5000 } }
)

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: the primary accepts all writes and records them in the oplog, secondaries replicate from the oplog to maintain identical copies, and arbiters hold no data but cast votes in elections. Next up we explore how MongoDB automatically elects a new primary when the current one fails.

자주 묻는 질문

“복제 세트 구성원: 프라이머리, 세컨더리, 중재자” 강의는 무료인가요?

네 — “복제 세트 구성원: 프라이머리, 세컨더리, 중재자” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“복제 세트 구성원: 프라이머리, 세컨더리, 중재자”에서 뭘 배우나요?

학습자는 각 복제 세트 구성원의 역할을 설명하고 oplog를 통해 쓰기 작업이 프라이머리에서 세컨더리로 흐르는 과정을 추적합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“복제 세트 구성원: 프라이머리, 세컨더리, 중재자” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 복제 세트 구성원: 프라이머리, 세컨더리, 중재자
  2. 선출 및 자동 장애 조치
  3. 쓰기 고려 사항 및 확인된 내구성
  4. 읽기 설정: 읽기 부하 분산하기
← MongoDB Academy(으)로 돌아가기