Running Self-Managed MongoDB on AWS EC2: The Standardized Production Architecture
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
priorityTakeoverelection flapping, and legacynet.ssldirectives permit downgraded TLS handshakes.- Answer: Deploy a symmetric 3-AZ Primary-Secondary-Secondary (PSS) replica set with
priority: 1andvotes: 1on every node,net.tls.mode: requireTLSwithdisabledProtocols: TLS1_0,TLS1_1,TLS1_2, andw: "majority"plusretryWrites=true.- Watch out: Cross-AZ
w: "majority"writes incur an inescapable inter-AZ network round-trip compared tow: 1, andreplication.enableMajorityReadConcernwas removed from user configurability (permanentlytrue) starting in MongoDB 5.0.
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:
- 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.
- Asymmetric Priority Flapping: Assigning skewed priorities (such as
10,5,1) to pin the primary to a preferred AZ triggerspriorityTakeoverelections whenever a transient link recovers, causing repeated write pauses. - Transport Layer Drift: Mixing deprecated
net.ssl.modesettings (deprecated in MongoDB 4.2, removed in 8.0) with modernnet.tls.modedirectives 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 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 runsrs.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 defaultselectionTimeoutMillisto10000ms (10 seconds), with nodes exchanging heartbeats every 2 seconds. When a primary becomes unreachable for theelectionTimeoutMilliswindow, eligible secondaries call an election. If priorities are skewed, a recovering higher-priority secondary within 10 seconds of the primary’s latest optime initiates apriorityTakeoverelection even when the active primary is healthy—turning minor packet loss into election thrashing. Furthermore, while apriorityTakeoverelection 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.sslin favor ofnet.tls, and MongoDB 8.0 removednet.sslentirely. LeavingpreferSSLor omittingdisabledProtocolsallows 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 sharedsecurity.keyFileorx509client 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.
| Topology | Placement | Durability & Quorum | Where It Breaks | Decision |
|---|---|---|---|---|
2-AZ PSS (2 + 1) | 2 data nodes in AZ-A, 1 in AZ-B | 3 data copies, 3 votes | Losing AZ-A drops 2/3 votes and halts all writes | Rejected |
| 3-AZ PSA (Arbiter) | 2 data nodes + 1 vote-only arbiter | 2 data copies, 3 votes | Losing 1 data node leaves 1 data copy; w:majority stalls or triggers cache pressure | Rejected |
| 3-AZ Symmetric PSS | 1 data node per AZ (priority: 1 each) | 3 data copies, 3 votes | Cross-AZ w: "majority" incurs 1 inter-AZ network RTT per write | Chosen |
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.
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.
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.
- Certificate Deployment: Distribute the CA bundle and node
.pemcertificates across all three hosts (chmod 400,chown mongodb:mongodb). Validation gate: verify certificate SANs match each node’s private DNS hostname withopenssl x509 -noout -text. Rollback: remove unused cert files;mongodis untouched. - Rolling Secondary Reload: Update
/etc/mongod.confon Secondary 1 (Node 2) and restartmongod. Wait forrs.status()to returnSECONDARYand zero replication lag, then repeat on Secondary 2 (Node 3). If transitioning a live plaintext cluster torequireTLS, never flip directly torequireTLSon the first node—doing so causes the updated secondary to reject unencrypted replication connections from the still-plaintext primary. Instead, rollnet.tls.mode: allowTLSorpreferTLSacross all three nodes first (so peers accept both plaintext and TLS), switch all application connection strings totls=true, and only then rollrequireTLSwithdisabledProtocols: TLS1_0,TLS1_1,TLS1_2in a second pass. Rollback: restore previousmongod.confand restart. - Controlled Primary Stepdown: Run
rs.stepDown(60, 10)onNode 1so leadership passes cleanly to a caught-up secondary, then apply the updatedmongod.conftoNode 1and rejoin it as a secondary. - Priority Alignment and Chaos Validation: Set
priority = 1on all members viars.reconfig(conf). Verify TLS 1.3 withopenssl s_client -connect mongo-node1.internal:27017 -tls1_3, then test single-AZ partition resilience by temporarily dropping port27017on one secondary (iptables -A INPUT -p tcp --dport 27017 -j DROP) and confirming aw: "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 thatelectionTimeoutMillisdefaults to10000ms. LoweringelectionTimeoutMillisaccelerates failure detection at the cost of higher sensitivity to transient VPC jitter; keepingpriority: 1symmetric across all members prevents unnecessarypriorityTakeoverelections when links recover. - Cross-AZ
w: "majority"Latency Budget: Aw: 1write commits locally on the primary, whereas aw: "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 expectingw: "majority"to match localw: 1latency, becausew: 1leaves 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 acknowledgedw: "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
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
gp3 baseline IOPS saturation | Heavy 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: 1 | Isolated 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 storm | Hundreds 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 thrashing | Skewed 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 plaintext | Enabling 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. |
Key Takeaways
- Never deploy a 3-node replica set across 2 AZs: A
2 + 1layout puts 2 of 3 votes in one failure domain; losing that zone drops the cluster belowfloor(N/2) + 1 = 2and forces it read-only. - Keep
priority: 1symmetric across all voting members: Asymmetric weights triggerpriorityTakeoverelections 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.ssltonet.tlswith explicitdisabledProtocols:net.sslwas deprecated in 4.2 and removed in 8.0; enforcemode: requireTLSanddisabledProtocols: TLS1_0,TLS1_1,TLS1_2via a stagedpreferTLSrollout. - 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 preventingw: 1split-brain rollbacks.
What to Do Next
- Problem: Unstandardized EC2 MongoDB clusters risk total write outages in 2-AZ layouts,
priorityTakeoverflapping from skewed weights, and TLS handshake failures from legacynet.sslsettings. - Solution: Standardize on an immutable 3-AZ symmetric PSS topology (
priority: 1,votes: 1on all nodes),gp3storage with provisioned IOPS,net.tls.mode: requireTLS(TLS 1.3), andw: "majority"withretryWrites=true. - Proof: Run an
iptablesport-27017partition test against one secondary in staging and verify thatrs.status()retains 2/3 quorum andw: "majority"writes continue committing without error. - Action: Audit
rs.conf().membersand/etc/mongod.confacross your EC2 clusters this week to flag any 2-AZ placement, asymmetric priorities, ornet.ssldirectives for rolling remediation.