In a distributed database, high availability is not achieved by launching instances across multiple cloud zones—it is governed by strict quorum mathematics, symmetric election priorities, and transport-layer standardization.

TL;DR

  • Problem: Two-AZ replica set placement loses 2 of 3 votes on a single-zone outage, asymmetric member priorities cause priorityTakeover election flapping, and legacy net.ssl directives permit downgraded TLS handshakes.
  • Answer: Deploy a symmetric 3-AZ Primary-Secondary-Secondary (PSS) replica set with priority: 1 and votes: 1 on every node, net.tls.mode: requireTLS with disabledProtocols: TLS1_0,TLS1_1,TLS1_2, and w: "majority" plus retryWrites=true.
  • Watch out: Cross-AZ w: "majority" writes incur an inescapable inter-AZ network round-trip compared to w: 1, and replication.enableMajorityReadConcern was removed from user configurability (permanently true) starting in MongoDB 5.0.

Comparison of 2-AZ placement losing quorum on AZ-A outage against 3-AZ symmetric placement preserving 2/3 majority

Situation

Running self-managed MongoDB Community Edition on AWS EC2 gives platform teams direct control over Linux kernel tuning, dedicated gp3 or io2 EBS volumes, NUMA memory allocation, and instance sizing without managed-service markups. Across multi-cluster estates, however, ad-hoc provisioning introduces three recurring structural weaknesses:

  1. Two-Availability-Zone Quorum Vulnerability: Placing two voting members in AZ-A and one in AZ-B leaves only 1 of 3 votes if AZ-A fails or partitions, dropping below the strict majority threshold and forcing the surviving node to step down to read-only.
  2. Asymmetric Priority Flapping: Assigning skewed priorities (such as 10, 5, 1) to pin the primary to a preferred AZ triggers priorityTakeover elections whenever a transient link recovers, causing repeated write pauses.
  3. Transport Layer Drift: Mixing deprecated net.ssl.mode settings (deprecated in MongoDB 4.2, removed in 8.0) with modern net.tls.mode directives permits unencrypted or legacy TLS 1.0/1.1/1.2 connections and breaks strict modern drivers.

Standardizing these three surfaces in Terraform and Ansible turns failover behavior from an emergent accident into a deterministic property.

The Problem

MongoDB replica sets use a Raft-derived consensus protocol where electing or sustaining a primary requires a strict majority of voting members:

$$\text{Quorum Threshold} = \left\lfloor \frac{N}{2} \right\rfloor + 1$$

For $N = 3$ voting members, quorum is 2 (tolerating 1 failure). For $N = 5$, quorum is 3 (tolerating 2 failures). Notice why even-numbered voting sets are an operational anti-pattern: for $N = 4$, floor(4/2) + 1 = 3, which still tolerates only 1 node failure—paying for a fourth voting node yields zero additional fault tolerance while increasing replication fanout and risking 2-versus-2 network splits where neither side can elect a primary.

Three consensus and security constraints: strict majority floor(N/2)+1, 10000ms default electionTimeoutMillis, and net.ssl to net.tls migration

Three documented protocol and configuration constraints define the design space:

  • Single-AZ Failure Math: In a 2-AZ deployment (2 + 1), losing the 2-node zone removes 66.7% of votes at once. The surviving single node holds 1 of 3 votes, cannot elect a primary, and rejects all writes until the partitioned zone returns or an operator forces a risky single-node reconfiguration. Even if an operator runs rs.reconfig(..., { force: true }) to strip the dead nodes, any writes accepted by the old primary before the partition that did not replicate to the surviving node are lost or rolled back when the original zone reconnects.
  • Heartbeat and Election Timing (electionTimeoutMillis): MongoDB defaults electionTimeoutMillis to 10000 ms (10 seconds), with nodes exchanging heartbeats every 2 seconds. When a primary becomes unreachable for the electionTimeoutMillis window, eligible secondaries call an election. If priorities are skewed, a recovering higher-priority secondary within 10 seconds of the primary’s latest optime initiates a priorityTakeover election even when the active primary is healthy—turning minor packet loss into election thrashing. Furthermore, while a priorityTakeover election is in flight, the replica set briefly has no writable primary, forcing application drivers to buffer or retry in-flight writes.
  • TLS Deprecation Boundary: MongoDB 4.2 deprecated net.ssl in favor of net.tls, and MongoDB 8.0 removed net.ssl entirely. Leaving preferSSL or omitting disabledProtocols allows older cipher suites and causes handshake failures when client drivers enforce TLS 1.3 or strict certificate verification. In addition, MongoDB nodes authenticate intra-cluster replication traffic using either a shared security.keyFile or x509 client certificates; drifting certificate SANs or mismatched CA chains across nodes can silently break replication even when client ports appear open.

Before standardizing a cluster, inspect current priorities, heartbeat round-trip times (pingMs), and the latency delta between w: 1 and w: "majority":

mongosh --eval "rs.conf().members.map(m => ({ host: m.host, priority: m.priority, votes: m.votes }))"
mongosh --eval "rs.status().members.map(m => ({ name: m.name, stateStr: m.stateStr, pingMs: m.pingMs }))"

How can platform teams design an immutable 3-AZ MongoDB topology on AWS EC2 that survives any single-zone outage, eliminates priority takeover thrashing, and enforces TLS 1.3 while budgeting for cross-AZ w: "majority" latency?

Options Considered

Platform teams selecting a 3-node MongoDB topology on AWS generally compare three layouts.

TopologyPlacementDurability & QuorumWhere It BreaksDecision
2-AZ PSS (2 + 1)2 data nodes in AZ-A, 1 in AZ-B3 data copies, 3 votesLosing AZ-A drops 2/3 votes and halts all writesRejected
3-AZ PSA (Arbiter)2 data nodes + 1 vote-only arbiter2 data copies, 3 votesLosing 1 data node leaves 1 data copy; w:majority stalls or triggers cache pressureRejected
3-AZ Symmetric PSS1 data node per AZ (priority: 1 each)3 data copies, 3 votesCross-AZ w: "majority" incurs 1 inter-AZ network RTT per writeChosen

A 2-AZ PSS layout works only if you accept total write unavailability whenever the 2-node zone experiences an outage or transit severance. A 3-AZ PSA topology saves one EBS volume and one compute instance by replacing the third data node with an arbiter, but if one data node goes down for maintenance or failure, only a single data copy remains and w: "majority" writes block or force WiredTiger cache pressure while awaiting the missing data node. Even worse, in MongoDB 5.0+, writeConcernMajorityJournalDefault and the PSA majority commit-point lag can cause the surviving data node’s WiredTiger cache to fill with uncommitted historical versions until the second data node returns.

The 3-AZ Symmetric PSS topology places one full data-bearing voting member in each of three Availability Zones with equal priority. Any single-zone outage leaves two healthy data copies and 2 of 3 votes intact.

Comparison of 2-AZ PSS, 3-AZ PSA with Arbiter, and 3-AZ Symmetric PSS topologies

Standardized 3-AZ Architecture

The production standard deploys three identical EC2 instances (for example, ARM64 Graviton r6g.2xlarge with 64 GB RAM) across three private subnets in us-east-1a, us-east-1b, and us-east-1c, each backed by a dedicated XFS-formatted gp3 EBS data volume mounted at /var/lib/mongodb.

Reference 3-AZ EC2 topology showing application subnets connecting via TLS 1.3 to symmetric priority-1 PSS nodes

1. Symmetric Consensus

Every member receives identical voting and priority weights:

// Symmetric 3-AZ member weights
members[0]: { priority: 1, votes: 1 } // AZ-a
members[1]: { priority: 1, votes: 1 } // AZ-b
members[2]: { priority: 1, votes: 1 } // AZ-c

With symmetric priorities, whichever node holds the primary role keeps it until an actual failure or operator rs.stepDown() occurs. A recovering node rejoins quietly as a SECONDARY without forcing a priorityTakeover election.

Pair symmetric priorities with explicit read and write preferences in application drivers. Route transactional reads to readPreference=primary (or primaryPreferred only when stale reads during a brief election are acceptable) so callers do not observe replication-lag anomalies from secondaries. When a workload genuinely requires scaling read throughput onto secondaries, enforce readConcern: { level: "majority" } on those queries so secondaries only return data that has already been majority-committed and cannot be rolled back.

2. Hardened mongod.conf Baseline

Enforce TLS 1.3 by setting net.tls.mode: requireTLS and listing TLS1_0,TLS1_1,TLS1_2 in net.tls.disabledProtocols (comma-separated, no spaces). Bound wiredTiger.engineConfig.cacheSizeGB explicitly—28 GB on a 64 GB r6g.2xlarge leaves ample RAM for the Linux page cache and monitoring agents. Setting wiredTiger.engineConfig.directoryForIndexes: true separates collection .wt files and index .wt files into distinct subdirectories under /var/lib/mongodb, allowing operators to mount separate EBS volumes for data and indexes on I/O-intensive clusters without rewriting dbPath. Mount the underlying XFS volume with noatime so metadata access-time writes do not amplify EBS IOPS during high-concurrency reads, and verify that ulimit -n (LimitNOFILE in systemd) is at least 64000 so maxIncomingConnections: 10000 plus WiredTiger’s open .wt file descriptors never hit EMFILE errors. Note that replication.enableMajorityReadConcern is configurable in MongoDB 4.4, but starting in MongoDB 5.0 it is permanently true and should be omitted from 5.0+ configs.

# /etc/mongod.conf — Standardized Production Baseline (MongoDB 4.4 / 5.0+)
net:
  port: 27017
  bindIp: 0.0.0.0
  maxIncomingConnections: 10000
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongodb/mongodb.pem
    CAFile: /etc/ssl/mongodb/ca.crt
    allowInvalidCertificates: false
    allowInvalidHostnames: false
    disabledProtocols: TLS1_0,TLS1_1,TLS1_2   # forces TLS 1.3: needs OpenSSL 1.1.1+ and TLS 1.3-capable drivers

storage:
  dbPath: /var/lib/mongodb
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 28
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: snappy
    indexConfig:
      prefixCompression: true

operationProfiling:
  mode: slowOp
  slowOpThresholdMs: 100
  rateLimit: 100

replication:
  replSetName: prod-rs01

3. Immutable Terraform Provisioning

Encode the 3-AZ subnet placement and gp3 storage in Terraform so clusters cannot drift into 2-AZ placement:

locals {
  availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]
}

resource "aws_instance" "mongo_node" {
  count                  = 3
  ami                    = data.aws_ami.al2023_arm64.id
  instance_type          = "r6g.2xlarge"
  subnet_id              = var.private_subnet_ids[count.index]
  vpc_security_group_ids = [aws_security_group.mongo_cluster.id]
  tags = {
    Name = "mongodb-prod-node-${count.index + 1}"
    AZ   = local.availability_zones[count.index]
  }
}

How It Rolls Out

Standardizing an existing cluster to TLS 1.3 and symmetric priorities runs in four gated phases to avoid unplanned failovers.

Four-phase rolling TLS 1.3 and symmetric priority standardization flow

  1. Certificate Deployment: Distribute the CA bundle and node .pem certificates across all three hosts (chmod 400, chown mongodb:mongodb). Validation gate: verify certificate SANs match each node’s private DNS hostname with openssl x509 -noout -text. Rollback: remove unused cert files; mongod is untouched.
  2. Rolling Secondary Reload: Update /etc/mongod.conf on Secondary 1 (Node 2) and restart mongod. Wait for rs.status() to return SECONDARY and zero replication lag, then repeat on Secondary 2 (Node 3). If transitioning a live plaintext cluster to requireTLS, never flip directly to requireTLS on the first node—doing so causes the updated secondary to reject unencrypted replication connections from the still-plaintext primary. Instead, roll net.tls.mode: allowTLS or preferTLS across all three nodes first (so peers accept both plaintext and TLS), switch all application connection strings to tls=true, and only then roll requireTLS with disabledProtocols: TLS1_0,TLS1_1,TLS1_2 in a second pass. Rollback: restore previous mongod.conf and restart.
  3. Controlled Primary Stepdown: Run rs.stepDown(60, 10) on Node 1 so leadership passes cleanly to a caught-up secondary, then apply the updated mongod.conf to Node 1 and rejoin it as a secondary.
  4. Priority Alignment and Chaos Validation: Set priority = 1 on all members via rs.reconfig(conf). Verify TLS 1.3 with openssl s_client -connect mongo-node1.internal:27017 -tls1_3, then test single-AZ partition resilience by temporarily dropping port 27017 on one secondary (iptables -A INPUT -p tcp --dport 27017 -j DROP) and confirming a w: "majority" insert still commits across the remaining two nodes.

In Practice

The operational tradeoffs of this architecture follow directly from documented MongoDB consensus rules and AWS network behavior:

  • Quorum and electionTimeoutMillis: MongoDB’s election protocol documentation specifies that a 3-member replica set requires 2 votes to elect or retain a primary, and that electionTimeoutMillis defaults to 10000 ms. Lowering electionTimeoutMillis accelerates failure detection at the cost of higher sensitivity to transient VPC jitter; keeping priority: 1 symmetric across all members prevents unnecessary priorityTakeover elections when links recover.
  • Cross-AZ w: "majority" Latency Budget: A w: 1 write commits locally on the primary, whereas a w: "majority" write must replicate across the VPC to at least one secondary in another Availability Zone before acknowledging. Application SLAs must budget for that inter-AZ network round-trip rather than expecting w: "majority" to match local w: 1 latency, because w: 1 leaves acknowledged writes vulnerable to rollback if the primary fails before replication completes.
  • PSA Cache Pressure: MongoDB documentation explicitly warns that in 3-member PSA topologies, losing one data node prevents w: "majority" commits from advancing the majority commit point, which can cause WiredTiger cache pressure to build up on the surviving data node—another reason to standardize on 3 full data nodes (PSS).
  • Journal Durability (writeConcernMajorityJournalDefault): By default (true), w: "majority" waits for the write to be written to the on-disk journal of a calculated majority of voting data-bearing nodes, not merely applied in memory. That guarantees an acknowledged w: "majority" write survives a simultaneous power loss across the primary and one secondary without rolling back on restart.

I have not run multi-cluster cross-AZ r6g.2xlarge benchmarks personally; the latency and failover properties above are derived directly from MongoDB’s documented replication, write-concern, and election mechanics.

Where It Breaks

ConditionBreaks HowDetectMitigate
gp3 baseline IOPS saturationHeavy checkpoint flushes exceed gp3 baseline (3,000 IOPS / 125 MiB/s), stalling WiredTiger eviction.wiredTiger.cache dirty bytes > 20% and rising write-ticket wait counts.Provision higher gp3 IOPS/throughput explicitly or use io2 volumes for heavy write workloads.
Network partition with w: 1Isolated primary accepts w: 1 writes, steps down, and rolls back unreplicated writes on rejoin.Rollback files written under dbPath/rollback/ and w:1 client data loss.Mandate w: "majority" and retryWrites=true in all transactional driver strings.
Post-failover TLS reconnect stormHundreds of app pods reconnect simultaneously to the new primary, saturating CPU with TLS 1.3 handshakes.Spike in connections.current and CPU saturation during elections.Configure driver connection pool jitter/backoff and set maxIncomingConnections: 10000.
Asymmetric priority thrashingSkewed priorities (10, 5, 1) trigger repeated priorityTakeover elections on flapping links.Frequent electionReason: priorityTakeover entries in mongod.log.Enforce priority: 1 across all three voting members in rs.conf().
Direct requireTLS cutover on live plaintextEnabling requireTLS on one node before drivers or peers use TLS breaks intra-cluster replication.network error / TLS handshake failures in mongod.log during rolling restart.Stage preferTLS across all nodes and drivers first, then roll requireTLS + disabledProtocols.

Failure-path overlay showing w:1 split-brain rollback, TLS reconnect storms, priority takeover thrashing, and gp3 IOPS saturation

Key Takeaways

  • Never deploy a 3-node replica set across 2 AZs: A 2 + 1 layout puts 2 of 3 votes in one failure domain; losing that zone drops the cluster below floor(N/2) + 1 = 2 and forces it read-only.
  • Keep priority: 1 symmetric across all voting members: Asymmetric weights trigger priorityTakeover elections during transient network blips, turning minor jitter into repeated write pauses.
  • Avoid PSA arbiters on write-heavy production clusters: A 3-data-node PSS layout preserves both majority quorum and w: "majority" commit-point advancement when any single node is offline.
  • Migrate net.ssl to net.tls with explicit disabledProtocols: net.ssl was deprecated in 4.2 and removed in 8.0; enforce mode: requireTLS and disabledProtocols: TLS1_0,TLS1_1,TLS1_2 via a staged preferTLS rollout.
  • Budget application SLAs for cross-AZ w: "majority" RTT: Cross-zone replication adds one inter-AZ network round-trip per majority write, which is the physical cost of preventing w: 1 split-brain rollbacks.

What to Do Next

  • Problem: Unstandardized EC2 MongoDB clusters risk total write outages in 2-AZ layouts, priorityTakeover flapping from skewed weights, and TLS handshake failures from legacy net.ssl settings.
  • Solution: Standardize on an immutable 3-AZ symmetric PSS topology (priority: 1, votes: 1 on all nodes), gp3 storage with provisioned IOPS, net.tls.mode: requireTLS (TLS 1.3), and w: "majority" with retryWrites=true.
  • Proof: Run an iptables port-27017 partition test against one secondary in staging and verify that rs.status() retains 2/3 quorum and w: "majority" writes continue committing without error.
  • Action: Audit rs.conf().members and /etc/mongod.conf across your EC2 clusters this week to flag any 2-AZ placement, asymmetric priorities, or net.ssl directives for rolling remediation.