0Pricing
MongoDB Academy · บทเรียน

การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ

ผู้เรียนจะจำลองความล้มเหลวของสมาชิกหลัก และสังเกตอัลกอริทึมการเลือกตั้งที่เลื่อนสมาชิกสำรองขึ้นมา โดยคงช่วงหยุดให้บริการไว้ต่ำกว่า 10 วินาที

การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Automatic Failover Matters

Automatic failover is the ability of a MongoDB replica set to recover from a primary node failure without human intervention. When the primary becomes unreachable, the remaining members automatically elect a new primary — typically within 10 to 30 seconds — so that applications experience only a brief pause rather than a full outage.

Heartbeats: Detecting Failures

Replica set members continuously exchange heartbeat messages every 2 seconds. If a member does not receive a heartbeat response within electionTimeoutMillis (default 10 seconds), it marks the silent member as inaccessible. If the missing member is the primary, the remaining eligible members begin an election.

// Check heartbeat interval and election timeout in replica set config
rs.conf().settings.heartbeatIntervalMillis   // 2000 ms
rs.conf().settings.electionTimeoutMillis     // 10000 ms

Triggering an Election

An election is triggered in three scenarios: 1) the primary becomes unreachable (network partition or crash), 2) a user manually steps down the primary with rs.stepDown(), or 3) a secondary with higher priority joins and the current primary has lower priority. Only members with votes: 1 and priority > 0 are eligible to become the new primary.

// Manually step down the current primary (useful for maintenance)
rs.stepDown(60)  // yield primary for at least 60 seconds

Raft-Inspired Consensus Protocol

MongoDB elections use a protocol inspired by Raft consensus. Each candidate increments its term counter and solicits votes from other members. A candidate wins if it receives votes from a majority of the voting members. The candidate with the most up-to-date oplog (highest optime) is preferred — this prevents data loss by ensuring the new primary has seen all acknowledged writes.

// Inspect the term number and optime of all members
rs.status().members.forEach(m => {
  print(m.name, 'term:', m.configTerm, 'optime:', m.optimeDate)
})

Majority Vote Requirement

A candidate needs votes from more than half of all voting members (not just the ones currently reachable). In a 3-member set with 3 votes, a majority is 2. This means that if 2 members go down simultaneously, the surviving member cannot elect itself — it would be operating on stale data with no way to know if the other two members have newer writes.

// With 3 members:
// majority = floor(3/2) + 1 = 2
// If only 1 member survives, it cannot elect itself
// The set becomes read-only until connectivity is restored

The Election Process Step by Step

The election unfolds as follows: 1) A secondary notices the primary is gone after the timeout. 2) It transitions to CANDIDATE state. 3) It sends RequestVote messages to all other members. 4) Members grant votes if the candidate's oplog is at least as current as theirs and they haven't already voted. 5) The winner transitions to PRIMARY and begins accepting writes.

Write Unavailability During Election

During the election window (typically a few seconds), writes are refused because there is no primary. The MongoDB driver buffers write operations and retries them once a new primary is elected. With retryable writes enabled (the default in modern drivers), transient election errors are transparently retried once.

// Retryable writes are enabled by default in the connection string
const client = new MongoClient(
  'mongodb+srv://host/db?retryWrites=true'
)

Priority and Election Preference

When multiple candidates are equally up to date, priority breaks the tie — the member with the highest priority wins. If a secondary with higher priority rejoins after being offline, it will trigger a new election to take the primary role. Setting priority to 0 permanently excludes a member from ever becoming primary.

// Boost priority on the preferred primary node
let cfg = rs.conf()
cfg.members[0].priority = 2   // preferred
cfg.members[1].priority = 1
cfg.members[2].priority = 1
rs.reconfig(cfg)

Network Partition Scenarios

In a network partition, members on one side of the split cannot communicate with the other. The side with the majority of votes can elect a primary; the minority side enters a read-only state. This prevents a split-brain scenario where two members simultaneously believe they are primary and accept conflicting writes.

Monitoring Failover Events

You can monitor elections and failovers by examining the MongoDB log or querying the system.replset config. Atlas provides real-time alerts for election events. In your application logs, you will see MongoNotPrimaryError or MongoNetworkError spikes during an election — retryable writes handle these automatically.

// Check the number of elections in the current status
rs.status().electionHighestObservedTime
// Or watch change streams on 'admin.$cmd' for electionId changes

Keeping Failover Fast: Best Practices

To minimise failover time: 1) Keep replica sets with odd member counts (3 or 5) to avoid needing arbiters. 2) Use a majority write concern to ensure the elected secondary has all committed writes. 3) Minimise oplog lag by providing sufficient oplog size. 4) Place replica set members in the same region for low-latency heartbeats.

// Increase oplog size at runtime (requires 4.4+)
db.adminCommand({ replSetResizeOplog: 1, size: 16384 })
// size in MB — 16 GB is suitable for busy clusters

Quick Check

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

Lesson Recap

In this lesson you learned: heartbeats detect primary failure within electionTimeoutMillis (10 s default), the candidate with the most current oplog and highest priority wins the election, and retryable writes let applications survive brief election windows transparently. Next up we explore write concerns and how to control the durability of writes across the replica set.

คำถามที่พบบ่อย

บทเรียน “การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ”

ผู้เรียนจะจำลองความล้มเหลวของสมาชิกหลัก และสังเกตอัลกอริทึมการเลือกตั้งที่เลื่อนสมาชิกสำรองขึ้นมา โดยคงช่วงหยุดให้บริการไว้ต่ำกว่า 10 วินาที คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. สมาชิกชุดแบบจำลอง: หลัก รอง และอาร์บิเตอร์
  2. การเลือกตั้งและการสลับทำงานแทนอัตโนมัติ
  3. ข้อกังวลด้านการเขียนและความคงทนที่มีการยืนยัน
  4. ค่ากำหนดการอ่าน: การกระจายภาระการอ่าน
← กลับไปที่ MongoDB Academy