When MongoDB runs on Linux, its latency and throughput guarantees are co-authored by the kernel—default OS settings designed for sequential batch workloads cause compaction stalls and 32x EBS read amplification under WiredTiger.

TL;DR

  • Problem: General-purpose Linux defaults—Transparent Huge Pages (always) on MongoDB 4.4–7.0, 256-sector (128 KB) block readahead, high dirty memory ratios, and ext4—cause thread stalls, gp3 bandwidth exhaustion, and OOM kills.
  • Answer: On MongoDB 4.4–7.0, disable THP (never) via a systemd unit, set NVMe readahead to 32 sectors (16 KB) via udev, mount XFS with noatime, set vm.swappiness=1 with a 1–2 GB swap file, and cap WiredTiger’s cache at max(0.5 * (RAM - 1 GB), 256 MB).
  • Watch out: MongoDB 8.0 reverses the THP rule—its upgraded per-CPU TCMalloc allocator on x86_64 and ARM64 requires THP enabled (always / defer+madvise), so AMI tuning must branch on MongoDB major version.

Comparison of general-purpose Linux defaults against a tuned EC2 baseline for MongoDB 4.4 to 7.0

Situation

Self-managed MongoDB deployments on AWS EC2 (r5 Intel or r6g Graviton2/3) backed by gp3 EBS volumes rely on WiredTiger’s dual-cache architecture: an uncompressed internal cache paired with the Linux OS page cache. Out of the box, however, enterprise Linux distributions (Amazon Linux, RHEL, Ubuntu) ship with defaults tuned for sequential file I/O and desktop responsiveness rather than random 4 KB B-tree lookups and multi-threaded memory churn.

When working sets exceed physical RAM under high concurrency, these OS defaults interact destructively with WiredTiger. Instead of degrading smoothly, clusters suffer periodic thread freezes, exhausted EBS throughput, and sudden SIGKILL terminations from the Linux Out-Of-Memory (OOM) killer.

The Problem

Three documented Linux kernel and block-layer behaviors explain why un-tuned EC2 instances stall under WiredTiger workloads:

  1. Transparent Huge Pages (THP) Compaction Stalls (MongoDB 4.4–7.0): Linux manages standard virtual memory in 4 KB pages, while THP allocates contiguous 2 MB pages to reduce TLB misses. Under MongoDB 4.4 through 7.0 (which use legacy per-thread TCMalloc), mongod threads continuously allocate and free variable-sized BSON documents, hazard pointers, and cache descriptors, fragmenting physical RAM. When a 2 MB contiguous allocation fails, khugepaged and direct memory compaction freeze threads in uninterruptible sleep (D state) while relocating 4 KB pages, driving up kernel system CPU (sy) and stalling WiredTiger read/write tickets.
  2. Block Device Readahead Amplification (32x on 4 KB Reads): Linux NVMe EBS devices default to 256 sectors (128 KB) of readahead. When an OLTP index lookup misses WiredTiger’s cache and requests a single 4 KB page, the kernel prefetches the target 4 KB plus 124 KB of adjacent blocks. For random B-tree leaf lookups, those adjacent blocks are rarely read—consuming 32x the EBS bandwidth (128 KB / 4 KB = 32) and evicting hot compressed blocks from the OS page cache. The arithmetic is stark on a baseline gp3 volume (125 MiB/s throughput): just 1,000 random 4 KB cache misses per second represent only ~3.9 MiB/s of logical data, yet with 128 KB readahead they demand 125 MiB/s of physical EBS read bandwidth, saturating the disk ceiling completely.
  3. Dirty Memory Flush Spikes and swapoff -a OOM Kills: Default vm.dirty_background_ratio (10%) and vm.dirty_ratio (20%–30%) scale poorly on large-RAM database instances. On a 128 GB r6g.4xlarge, 10% dirty memory equals 12.8 GB of buffered writes—if flushed in a burst against a 125 MiB/s gp3 volume, draining that backlog takes over 100 seconds of sustained disk saturation, stalling WiredTiger’s 60-second checkpoints. Conversely, running swapoff -a removes the kernel’s last-resort paging margin so any transient memory spike triggers an immediate OOM SIGKILL against mongod.

Three Linux kernel constraints: THP 2 MB compaction stalls, 32x block readahead amplification, and zero-swap OOM exposure

Inspect active kernel state on an EC2 host before applying changes:

cat /sys/kernel/mm/transparent_hugepage/enabled
cat /sys/kernel/mm/transparent_hugepage/defrag
grep -E "compact_stall|compact_fail|compact_success" /proc/vmstat
sudo blockdev --getra /dev/nvme1n1
vmstat 1 10

How should platform teams configure Linux memory management, swap, block readahead, and filesystems on AWS EC2 so the kernel accelerates WiredTiger instead of generating tail-latency spikes?

Options Considered

Platform teams typically choose among three approaches when managing Linux parameters for EC2 MongoDB fleets.

ApproachPersistence & Memory ModelProsWhere It BreaksDecision
Ad-hoc Runtime Shell Commandsecho never + blockdev --setra via SSHImmediate effect on live hostSilently resets to OS defaults on EC2 instance rebootRejected
90% WT Cache + swapoff -aOver-allocates cacheSizeGB, disables swapSlightly larger uncompressed B-tree cacheStarves OS compressed page cache; OOM killer targets mongodRejected
Immutable AMI (systemd + udev + XFS)Persistent unit files, sysctl, 1–2 GB swap, ~50% WT cacheReboot-safe, balanced dual-cache, eliminates 32x read ampRequires version-branching THP rules for MongoDB 8.0+Chosen

Running echo never > /sys/kernel/mm/transparent_hugepage/enabled or blockdev --setra 32 interactively fixes a host only until the next AWS maintenance reboot or autoscaling replacement. Similarly, setting cacheSizeGB to 90% of host RAM starves the Linux page cache, forcing every WiredTiger cache miss to hit physical EBS storage rather than decompressing from RAM. Baking systemd, udev, sysctl, and XFS mount options into an immutable Packer AMI eliminates configuration drift across the fleet.

Comparison of ad-hoc shell tuning, 90% cache with zero swap, and immutable Packer AMI with systemd and udev

The Dual-Cache Architecture

Unlike engines that manage a single monolithic buffer pool, WiredTiger relies on two cooperating memory tiers:

Dual-cache memory hierarchy on a 64 GB r6g.2xlarge splitting 28 GB WiredTiger cache and Linux OS page cache over XFS gp3

  1. WiredTiger Internal Cache: Governed by storage.wiredTiger.engineConfig.cacheSizeGB (defaulting to max(0.5 * (RAM - 1 GB), 256 MB)—for example, ~28–31 GB on a 64 GB r6g.2xlarge). It stores uncompressed BSON documents and B-tree pages for direct CPU pointer traversal. Keeping cacheSizeGB at or slightly below 50% of (RAM - 1 GB) also leaves headroom for connection thread stacks and observability agents (node_exporter, CloudWatch, Datadog) without encroaching on OS page cache.
  2. Linux OS Page Cache: The remaining host RAM holds raw filesystem blocks read from or written to EBS. Because WiredTiger compresses collection blocks with Snappy or zstd before writing to disk, the OS page cache stores compressed blocks, giving it higher effective data density per gigabyte of RAM.

When a query misses WiredTiger’s internal cache, WiredTiger reads from the filesystem. If the compressed block resides in the Linux page cache, WiredTiger decompresses it in memory without issuing an EBS I/O operation. Preserving roughly 40%–45% of RAM for the OS page cache is therefore essential for read throughput.

Production OS Configuration Baseline

1. Disable THP via systemd (MongoDB 4.4–7.0 Only)

For MongoDB 4.4 through 7.0, deploy /etc/systemd/system/disable-transparent-huge-pages.service with Before=mongod.service so THP is disabled before mongod allocates memory:

[Unit]
Description=Disable Transparent Hugepages (THP)
DefaultDependencies=no
After=sysinit.target local-fs.target
Before=mongod.service

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled && echo never > /sys/kernel/mm/transparent_hugepage/defrag'

[Install]
WantedBy=basic.target

2. Virtual Memory (sysctl), systemd Limits, and Swap Safety Valve

Deploy /etc/sysctl.d/99-mongodb.conf to keep a 1–2 GB swap file available as an OOM emergency valve while instructing the kernel to reclaim page cache aggressively before touching swap (vm.swappiness = 1), and to flush dirty pages smoothly (5% background, 15% synchronous cap). On instances with 128 GB or more of RAM, consider replacing percentage ratios with fixed byte thresholds (vm.dirty_background_bytes and vm.dirty_bytes) so background flushing starts after a predictable megabyte ceiling rather than waiting for gigabytes of dirty pages to accumulate.

Also note that systemd-managed services ignore /etc/security/limits.conf; set LimitNOFILE=64000 and LimitNPROC=64000 directly inside mongod.service (or a drop-in override) so high connection counts plus WiredTiger’s per-collection and per-index .wt file descriptors never hit EMFILE errors.

# /etc/sysctl.d/99-mongodb.conf
vm.swappiness = 1
vm.dirty_background_ratio = 5
vm.dirty_ratio = 15
vm.vfs_cache_pressure = 50
net.core.somaxconn = 65535
fs.file-max = 64000

3. NVMe Readahead (udev) and XFS noatime

MongoDB Production Notes recommend XFS over ext4 (to avoid ext4 extent-allocation latency spikes) mounted with noatime, and a low block readahead between 8 and 32 sectors (4 KB to 16 KB) on random-I/O OLTP volumes. Without noatime, every read against a .wt file that misses the OS page cache can trigger an inode access-time metadata update, turning pure read traffic into background metadata writes on the EBS volume. Similarly, ext4 serializes concurrent file growth and journal commits during WiredTiger’s 60-second checkpoints, whereas XFS supports parallel allocation groups across multi-core EC2 instances. Persist 16 KB readahead via /etc/udev/rules.d/85-mongodb-readahead.rules and configure /etc/fstab for XFS:

ACTION=="add|change", KERNEL=="nvme[0-9]*n[0-9]*", ATTR{bdi/read_ahead_kb}="16"
UUID=xxxx-xxxx-xxxx  /var/lib/mongodb  xfs  noatime,nodiratime  0 2

For multi-socket hosts, wrap mongod startup in numactl --interleave=all so memory pages distribute evenly across NUMA nodes instead of exhausting one socket’s local memory while another sits idle. In addition, check /proc/$(pgrep mongod)/limits after every service restart to verify that Max open files and Max user processes reflect 64000 rather than the Linux default of 1024 or 4096, because each WiredTiger collection and index opens dedicated file descriptors concurrently with client TCP sockets.

When tuning vm.vfs_cache_pressure = 50 (down from the Linux default of 100), the kernel retains filesystem dentry and inode metadata in RAM longer under memory pressure, preventing repeated metadata lookups across thousands of .wt files when directoryForIndexes: true is enabled.

How It Rolls Out

Roll OS tuning through Packer AMI builds and rolling secondary replacement rather than mutating live primaries in place.

Four-step Packer AMI and Ansible rollout with systemd, sysctl, XFS, and gate verification checks

  1. Bake systemd and udev Rules into the AMI: Include disable-transparent-huge-pages.service (for 4.4–7.0 images) and 85-mongodb-readahead.rules in the Packer/Ansible pipeline. Validation gate: boot a test EC2 instance and verify cat /sys/kernel/mm/transparent_hugepage/enabled prints [never] and blockdev --getra returns 32.
  2. Apply sysctl and Provision 1–2 GB Swap: Roll /etc/sysctl.d/99-mongodb.conf via sysctl --system and verify swapon --show reports the emergency swap file. Rollback: revert 99-mongodb.conf and reload sysctl --system.
  3. Format XFS Volumes and Replace Secondaries: On new or replacement replica set members, format /var/lib/mongodb with mkfs.xfs, mount with noatime, and sync each node as a secondary before stepping down the primary. Validation gate: inspect /proc/$(pgrep mongod)/limits to confirm Max open files and Max user processes are at least 64000.
  4. Verify Post-Rollout Kernel Telemetry: Under production traffic, confirm compact_stall counters in /proc/vmstat remain flat, si/so in vmstat 1 10 remain 0, and EBS read throughput aligns with logical WiredTiger cache-miss rates. On multi-socket hosts, inspect /proc/$(pgrep mongod)/numa_maps to confirm interleaved page allocation across sockets (interleave), and check journalctl -k for any XFS mount warnings or OOM-killer invocations before promoting the node to primary.

In Practice

The tuning baseline above rests on documented MongoDB Production Notes and Linux kernel mechanics:

  • MongoDB Production Notes (Linux): MongoDB’s official Linux production documentation explicitly mandates XFS with noatime over ext4, recommends blockdev --setra between 8 and 32 sectors (4 KB–16 KB) for WiredTiger OLTP volumes, and specifies vm.swappiness = 1 (or 0 on older kernels) plus numactl --interleave=all on NUMA hardware.
  • The MongoDB 8.0 THP Reversal: In MongoDB 8.0, MongoDB upgraded its vendored TCMalloc allocator on Linux x86_64 and ARM64 to use per-CPU caches instead of per-thread caches. Because per-CPU TCMalloc reduces fragmentation and benefits from 2 MB page lookups, MongoDB 8.0 documentation reverses the legacy rule and requires THP to be enabled (always / defrag: defer+madvise) on supported architectures—while also warning against Linux kernels 6.19 through 7.0.13 due to a known TCMalloc crash bug fixed in 7.0.14+.
  • Linux 6.x Multi-Gen LRU (MGLRU): Modern kernels in Amazon Linux 2023 and Ubuntu 24.04 LTS support MGLRU for lower-overhead page cache eviction, but they do not alter the gp3 32x readahead amplification math or the need to preserve OS page cache headroom. Operators can verify the impact of readahead and dirty-ratio changes directly via iostat -xz 1 (r/s, rkB/s, r_await, w_await, and aqu-sz), confirming that average read request sizes (rareq-sz) drop from ~128 KB toward 16 KB–32 KB on random OLTP workloads.

I have not run controlled r6g.4xlarge A/B benchmarks on these kernel parameters personally; every rule above is derived directly from MongoDB’s documented Production Notes, MongoDB 8.0 release notes, and Linux virtual memory behavior.

Where It Breaks

ConditionBreaks HowDetectMitigate
THP disabled on MongoDB 8.0+Upgraded per-CPU TCMalloc expects THP (always / defer+madvise); disabling THP hurts 8.0 allocation efficiency.mongod 8.0 startup warnings or elevated TLB/allocator overhead on x86_64/ARM64.Branch Packer/Ansible roles by version: THP never for 4.4–7.0, THP always for 8.0+.
cacheSizeGB set to 90% RAMStarves Linux OS page cache; every WiredTiger cache miss forces a physical EBS read.iostat read IOPS spike despite high RAM utilization.Cap cacheSizeGB at max(0.5 * (RAM - 1 GB), 256 MB).
swapoff -a under memory spikeZero paging headroom leaves the OOM killer no option except SIGKILL on mongod.dmesg shows Out of memory: Killed process (mongod).Provision 1–2 GB swap file with vm.swappiness = 1.
32-sector readahead on analytical nodesDedicated COLLSCAN / batch aggregation nodes lose sequential prefetching.Slower sequential scan throughput on reporting secondaries.Keep 32 sectors for OLTP primaries; use 128–256 on dedicated analytics secondaries.
ext4 data volume on multi-core EC2Single-lock extent allocation in ext4 serializes concurrent WiredTiger file growth.Periodic write freezes in mongod.log during checkpointing.Format /var/lib/mongodb with XFS (mkfs.xfs) and mount with noatime.

Failure-path overlay showing oversized WiredTiger cache, zero-swap OOM SIGKILL, ext4 inode locks, and NUMA skew

Key Takeaways

  • Match THP policy to MongoDB major version: Disable THP (never) via systemd for MongoDB 4.4 through 7.0, but enable THP (always / defer+madvise) for MongoDB 8.0+ on x86_64 and ARM64 where per-CPU TCMalloc is active.
  • Cut NVMe readahead from 256 to 32 sectors (16 KB) via udev: Eliminates the 32x EBS read amplification on random 4 KB B-tree lookups and stops unneeded blocks from poisoning the OS page cache.
  • Protect the dual-cache split (~50% WT / ~40% OS page cache): Over-allocating cacheSizeGB starves compressed block caching in Linux RAM and forces physical EBS reads on every miss.
  • Never run swapoff -a in production: Pair a 1–2 GB emergency swap file with vm.swappiness = 1 so minor memory spikes page idle daemons instead of triggering SIGKILL on mongod.
  • Always use XFS with noatime and numactl --interleave=all: Avoids ext4 extent-allocation lock contention and prevents single-socket memory exhaustion on multi-socket hosts.

What to Do Next

  • Problem: General-purpose Linux defaults (THP always on 4.4–7.0, 128 KB readahead, ext4, and swapoff -a) cause compaction stalls, 32x EBS read amplification, and OOM crashes under WiredTiger.
  • Solution: Bake version-aware THP units, 32-sector NVMe udev rules, sysctl (vm.swappiness=1, dirty_background_ratio=5, dirty_ratio=15), 1–2 GB swap, and XFS noatime into your Packer/Ansible EC2 AMIs.
  • Proof: Verify cat /sys/kernel/mm/transparent_hugepage/enabled, blockdev --getra, swapon --show, and /proc/$(pgrep mongod)/limits (>= 64000 open files) on every host before joining it to a replica set.
  • Action: Audit your running EC2 MongoDB nodes today for THP state, readahead sector size, and filesystem type, and update your golden AMI pipeline before your next rolling replacement.