Linux Server Admin with Fexingo: Sysadmin, Bash, and Server Engineering · Fexingo
Most sysadmins think Linux memory management is simple: the kernel takes what it needs and gives it back. But that intuition fails when dealing with page cache pressure, slab allocations, and reclaim stalls. This episode dissects how the Linux kernel actually balances dirty pages, anonymous memory, and buffer heads under load. We look at the specific mechanics of kswapd, direct reclaim paths, and why servers stall during high-pressure memory compaction. For anyone managing production infrastructure, understanding these internal rhythms prevents the mysterious latency spikes that happen when RAM hits one hundred percent. #LinuxKernel #MemoryManagement #SysadminTips #ServerEngineering #PageCache #SlabAllocator #Kswapd #DirectReclaim #LatencyOptimization #ProductionInfra #BashScripting #TechOps #FexingoBusiness #BusinessPodcast #SystemPerformance #CloudInfrastructure #DevOpsDaily #LucasAndLuna Keep every episode free: buymeacoffee.com/fexingo
Lucas: We have a habit in this industry of treating Linux memory like a bucket. You pour data in, you take data out, and if it overflows, the system swaps or crashes. It is a dangerously simple mental model for anyone running production workloads. Luna: It feels intuitive until you see a server sitting at ninety-nine percent memory usage with zero swap activity, yet every query just hangs for three seconds. That is not an overflow problem; that is a pacing problem. Lucas: Exactly. Today we are drilling into the kernel's internal memory reclamation strategies, specifically looking at how the balance between page cache, slab allocations, and anonymous memory determines whether your application stays responsive or enters a deadlock state. Luna: So we are talking about the invisible tug of war inside the kernel when physical RAM becomes scarce? Lucas: Precisely. The kernel does not just delete files from RAM to make space. It has to decide what is safe to drop, what must be written to disk first, and how to prioritize incoming requests against outgoing cleanup tasks. If those decisions are misaligned, you get what we call reclaim stalls. Luna: I saw a cluster last week where database writes stalled completely because the kernel was busy trying to compress memory instead of flushing logs. Lucas: That is a classic symptom of aggressive background reclaim fighting against foreground I/O. To understand why that happens, we need to look at the two main actors in this drama: kswapd and the direct reclaim path. Luna: Kswapd is that background daemon, right? The one that runs quietly until things get tight? Lucas: Right. Kswapd is the gentle gardener. It wakes up periodically and tries to free up a small percentage of memory by moving dirty pages to disk or dropping clean cache entries. It operates on a low priority so it does not interfere with active processes. Luna: But if the system is under heavy load, the gardener gets overwhelmed and someone else has to step in? Lucas: Exactly. When kswapd cannot keep up, the kernel triggers direct reclaim. This is where the process requesting memory stops, waits, and helps free up pages itself. It is immediate, but it introduces latency spikes because your application thread is now doing housekeeping instead of processing data. Luna: So the hang I mentioned earlier was likely threads stuck in direct reclaim, waiting for disk I/O to complete while the CPU is idle? Lucas: Spot on. And here is the tricky part: the kernel prioritizes different types of memory differently. Page cache, which holds file data, is usually the first to go. Slab allocations, which hold kernel structures, are harder to touch. Anonymous memory, which is your application’s actual runtime data, is the most painful to evict because it often requires swapping to disk. Luna: Which means if you have a huge database caching many small files, the kernel might aggressively drop that cache, causing random I/O spikes as the app has to read those files from disk again. Lucas: Yes, and that creates a feedback loop. The app reads from disk, fills the cache again, the cache gets full, the kernel drops it again. Your effective throughput plummets even though you have plenty of RAM available, it is just being managed poorly. Luna: This sounds like a configuration issue rather than a hardware limitation. Are there knobs we can turn to smooth this out? Lucas: There are several, but they require nuance. The most common lever is the vm.dirty_ratio and vm.dirty_background_ratio settings. These control how much dirty data the kernel allows to sit in memory before forcing a write to disk. Luna: If we lower those ratios, won't that increase write latency for the applications generating the data? Lucas: It can, if the disks are slow. But if you have fast NVMe storage, lowering the dirty ratio forces more frequent, smaller flushes. This prevents the kernel from having to flush gigabytes of data all at once during a reclaim event, which stabilizes latency. Luna: So we trade bursty, massive I/O events for steady, manageable streams. That makes sense for consistency. Lucas: Another critical area is the watermark levels. The kernel uses high, low, and min watermarks to determine when to wake kswapd or trigger direct reclaim. If these thresholds are too close together, you get thrashing. Luna: Thrashing in this context means the kernel starts reclaiming and then immediately needs to allocate again because it freed too little? Lucas: Correct. It is a ping-pong effect. By widening the gap between the low and high watermarks, you give kswapd more room to operate efficiently without constantly waking up and going back to sleep. Luna: Have you seen cases where disabling transparent huge pages helped with this kind of pressure? Lucas: Absolutely. Transparent huge pages reduce TLB misses but increase memory fragmentation and reclaim complexity. For databases and high-frequency trading systems, disabling them often reduces tail latency significantly because the kernel does not have to perform expensive memory compaction. Luna: Compaction is another beast. That is when the kernel tries to merge free pages to create larger contiguous blocks for huge pages. Lucas: It is. And compaction can block processes for hundreds of milliseconds. If you are running a latency-sensitive service, that single block can look like a total crash to the user. Monitoring compaction stalls is essential. Luna: Where do you look to catch those stalls? Is it in dmesg or something more granular? Lucas: You want to watch /proc/vmstat for events like compact_stall and compact_success. A rising compact_stall count without a corresponding rise in compact_success indicates the system is struggling to find contiguous memory. Luna: That is a very specific metric. Most people just look at free memory and miss the signal entirely. Lucas: They do. And they wonder why their server feels sluggish despite having five gigabytes of free RAM. The issue is not volume; it is contiguity and access patterns. Luna: So the takeaway is that memory health is about flow and structure, not just quantity. Lucas: Precisely. You need to treat memory like a pipeline, not a warehouse. If the pipe gets clogged with dirty pages or fragmented blocks, the flow stops regardless of how much inventory you have stored. Luna: I think we should pause briefly here to acknowledge that keeping these technical deep dives accurate and ad-free takes real effort from our team. Lucas: If today's breakdown of reclaim strategies gave you a clearer picture of your own server behavior, the way we sustain this network is through listener support. You can help us keep producing these detailed engineering analyses by visiting buy me a coffee dot com slash fexingo. Luna: It really does make a difference in allowing us to dig into these niche topics without relying on sponsorships that might skew the technical advice. Lucas: Thank you for that consideration. Now, let's circle back to one final practical tip for diagnosing these issues in real-time. Luna: What tool do you recommend for seeing exactly what the kernel is discarding? Lucas: Use smem or pidstat with memory flags, but specifically look at the pss column. PSS, or proportional set size, shows the actual physical memory consumed by a process, accounting for shared libraries. It cuts through the noise of virtual memory figures. Luna: Virtual memory is deceptive because it includes mapped files that might never be touched. PSS tells you what is actually pinned in RAM. Lucas: Exactly. And if you combine that with iostat to see if those pss heavy processes are causing disk bottlenecks, you get a complete picture of the memory-I/O interaction. Luna: It turns abstract resource contention into concrete process-level actions. Lucas: It does. The next time your server hovers near full capacity, check the reclaim stats before you start adding more RAM. You might find that a simple tweak to the dirty ratios or a disablement of huge pages solves the latency spike instantly. Luna: A reminder that sometimes the best optimization is just letting the kernel breathe better rather than throwing hardware at the problem. Lucas: Right. Efficiency is rarely about capacity; it is about rhythm. We will see what other internal mechanisms we can unpack next time.
More Linux Server Admin with Fexingo: Sysadmin, Bash, and Server Engineering episodes →