Swapfresh

Event-Driven Swap Cleanup Daemon for Linux

Challenge

Linux doesn't move pages from swap back to RAM when memory pressure drops. After a spike, swap remains full even with plenty of free RAM, reducing the system's ability to handle future spikes.

Solution

Built a single-file Python daemon that uses Linux PSI (Pressure Stall Information) triggers for reactive monitoring and periodic checks for proactive cleanup. Safety guards ensure flushes only happen when free RAM is at least 2x swap usage.

Result

A production-grade daemon running via systemd with watchdog integration, automatic zram detection, priority-ordered device flushing, and exponential backoff recovery. Zero external dependencies, fully testable, and security-hardened with systemd sandboxing.

Key Highlights

  • Hybrid Reactive/Proactive Architecture

    Combines Linux PSI triggers for instant reactive response with periodic proactive checks, ensuring swap is reclaimed both during and after memory pressure events.

  • Safety-First Design

    Multiple safety guards including a 2x free RAM requirement, exponential backoff on failures, and graceful degradation ensure the daemon never makes memory pressure worse.

  • Zero Dependencies

    A single-file Python daemon with no external dependencies, fully hardened via systemd sandboxing with capability-based security and watchdog integration.

Architecture diagram of the Swapfresh event-driven swap cleanup daemon

Technology Stack

Core
Python 3.10+
Linux PSI
systemd
Architecture
Event-Driven
State Machine
Zero Dependencies
Security
systemd Sandbox
Capability-Based
Hardened