Thrashing

On this page 6

Thrashing is a condition in which an operating system spends most of its time servicing page faults and moving pages between physical memory and secondary storage, so that very little useful computation takes place. In memory management, it occurs when the combined working sets of active processes exceed available RAM, causing pages to be evicted shortly before they are needed again.

Thrashing is a collapse of throughput rather than a simple slowdown: CPU utilization falls, disk or SSD activity saturates and response times grow by orders of magnitude. Understanding it requires the concepts of demand paging, page replacement and the working set, which together explain why adding one more process can turn a busy system into an almost unusable one.

How thrashing develops in virtual memory

Thrashing develops when the page fault rate rises faster than the system can service faults. Under demand paging, a process loads a page only when it touches it. If the page is not resident, the memory management unit raises a page fault, the kernel selects a victim page frame, writes it out if it is dirty and reads the requested page from storage. A single major fault costs thousands to millions of times more than a normal memory access, depending on the storage device.

As long as each process keeps its working set, the pages it actively uses in a recent time window, resident in RAM, faults remain rare. When too many processes compete for too few frames, the replacement algorithm must evict pages that belong to someone’s working set. Those pages are referenced again almost immediately, which causes a new fault that evicts another needed page, and the cycle feeds itself.

Classic analyses also describe a harmful scheduler feedback loop. Low CPU utilization, caused by processes waiting on paging I/O, looked like spare capacity, so older batch schedulers admitted more processes, which further reduced the frames per process and deepened the thrashing. Modern kernels avoid this specific mistake, but the underlying mechanism remains.

The table below shows how the system moves from normal operation into thrashing as memory pressure grows.

StagePage fault rateCPU utilizationUser experience
Normal operationLow, mostly minor faultsHigh and productiveResponsive
Moderate pressureRising major faultsSlightly reducedOccasional pauses
Onset of thrashingSteep rise, storage busyFalling sharplyLong freezes
Full thrashingSaturated paging deviceLow, mostly I/O waitSystem appears hung
Stages of memory pressure

Thrashing is best understood as the failure mode of virtual memory overcommitment, and it is easily confused with several neighboring concepts. Each of the related terms describes a mechanism or a measurement, whereas thrashing describes a pathological system state.

ConceptWhat it describesRelation to thrashing
Page faultA single access to a non-resident pageThrashing is an extreme, sustained fault rate
Working setPages a process actively usesThrashing begins when working sets exceed RAM
Page replacement algorithmPolicy for choosing a victim pageA poor policy can hasten thrashing
SwappingMoving whole processes or pages to diskHeavy swapping is the visible symptom
Out of memoryMemory and swap fully exhaustedThrashing often precedes an out-of-memory event
Cache thrashingRepeated eviction in CPU caches or the TLBSame pattern at a smaller hardware scale
How thrashing relates to neighboring concepts

The term is also used for the same pattern at other levels of the memory hierarchy. Cache thrashing and TLB thrashing describe CPU caches or the translation lookaside buffer repeatedly evicting entries that are needed again, but in operating systems the unqualified word usually means paging-level thrashing.

Detecting thrashing on a running system

Thrashing is detected by combining paging activity, I/O wait and memory pressure metrics, because no single counter proves it. A high page-in and page-out rate together with low useful CPU time and a saturated swap device is the characteristic signature.

The following indicators are available on mainstream desktop and server platforms.

IndicatorWhere to observe itWarning sign
Major page faults per secondPerformance counters or process statisticsSustained high rate across many processes
Swap-in and swap-out ratesMemory statistics toolsContinuous traffic in both directions
I/O wait timeCPU usage breakdownLarge share of time waiting on storage
Memory pressure stall informationLinux pressure metricsTasks stalled on memory most of the time
Resident set size versus demandPer-process memory viewsResident size far below working set
Practical indicators of thrashing

A useful rule of thumb is that swap usage alone is not a problem: pages that are swapped out and never touched cost nothing. The danger sign is continuous traffic in both directions, which means needed pages are being evicted and reloaded.

How operating systems prevent and resolve thrashing

The fundamental remedy is to reduce demand for frames or increase their supply, so that active working sets fit in RAM again. Operating systems and administrators use several complementary techniques.

  • Working set model: the kernel tracks each process’s working set and suspends processes whose working sets cannot all fit.
  • Page fault frequency control: the kernel allocates more frames to processes with high fault rates and reclaims frames from processes with low rates.
  • Load control: the scheduler reduces the degree of multiprogramming by suspending or swapping out entire processes.
  • Memory compression: compressing rarely used pages in RAM delays the point at which storage paging becomes necessary.
  • Out-of-memory handling: user-space daemons or the kernel terminate a process before the system thrashes for minutes.

The right response depends on the situation, as the decision table below summarizes.

SituationRecommended responseReason
One process with a runaway allocationTerminate or limit that processRestores memory for all others
Too many concurrent jobsReduce parallelismFewer working sets compete for RAM
Steady workload larger than RAMAdd physical memoryOnly lasting fix for genuine demand
Containers on a shared hostSet memory limits per containerConfines pressure to the offender
Poor access locality in codeRestructure data accessShrinks the effective working set
Choosing a response to thrashing

A common misconception is that a faster SSD eliminates thrashing. Solid-state storage shortens each fault considerably compared with a hard disk, but it remains far slower than RAM, so a system with a chronic shortfall of memory still thrashes, only less dramatically.

In simple terms

Imagine working at a tiny desk with a filing cabinet across the room. Normally you keep the papers you need on the desk and fetch something from the cabinet now and then. Thrashing is what happens when the job needs more papers than the desk can hold. You put one folder away to make room, and a moment later you need it again, so you walk back to the cabinet.

Soon you spend almost all your time walking back and forth and almost none actually working. A computer in this state looks frozen. The fix is to work on fewer things at once or get a bigger desk, which for a computer means more memory.

A practical example

A data analyst runs a statistics workload on a laptop with 16 GB of RAM. Alone, the job uses about 10 GB and finishes in twenty minutes. One afternoon the analyst starts the same job twice with different parameters while a browser with many tabs uses another 4 GB. Combined demand reaches about 24 GB, well beyond physical memory.

Within a minute the laptop becomes almost unresponsive. The system monitor shows the SSD constantly reading and writing, CPU time dominated by I/O wait and the page-in and page-out rates both high. Neither job is making real progress, and the estimated completion time stretches to hours.

The analyst closes the browser and cancels the second job. Memory demand drops below RAM, paging traffic stops within seconds and the remaining job finishes in its usual twenty minutes. Running the two jobs one after another proves far faster than running them together, which is the defining lesson of thrashing.