How to fix VPS out of memory: Comparison and Best Practices
Compare immediate fixes, optimization strategies, and scaling solutions for VPS memory issues. Practical troubleshooting steps and recommendations.

On this page
TL;DR — Key takeaways
- Emergency fix: Add swap space immediately to prevent service crashes, then identify the memory-consuming process using top or htop for targeted action.
- Long-term optimization: Enable swap for burst protection, tune application memory limits, and implement monitoring alerts before reaching 80% RAM usage.
- Scaling decision: Upgrade RAM if baseline usage consistently exceeds 70%, optimize application configuration if spikes are process-specific, or migrate to dedicated resources for sustained high loads.
When your VPS runs out of memory, services crash, websites go offline, and the OOM (Out of Memory) killer terminates processes without warning. Memory exhaustion is one of the most common reasons for VPS instability, whether caused by traffic spikes, misconfigured applications, or undersized infrastructure.
This guide compares three approaches to fixing VPS memory issues: immediate emergency fixes, optimization strategies, and infrastructure scaling. Each approach has different trade-offs in cost, complexity, and long-term sustainability. We'll evaluate when to use each method and provide clear recommendations based on your situation.
Understanding VPS Memory Exhaustion
Memory exhaustion occurs when running processes consume all available RAM, forcing the Linux kernel to invoke the OOM killer. This mechanism terminates processes to free memory, often killing critical services like databases or web servers.
Common causes include memory leaks in applications, insufficient RAM allocation for workload demands, misconfigured caching systems that consume unbounded memory, sudden traffic surges, and missing or undersized swap space.
Before applying fixes, diagnose the current state. Use 'free -h' to check total memory and swap usage, 'top' or 'htop' to identify high-memory processes, and 'dmesg | grep -i oom' to check if the OOM killer has been triggered. Document baseline memory usage during normal operation for comparison.
Approach 1: Emergency Fixes (Immediate Relief)
Emergency fixes provide immediate relief when your VPS is experiencing active memory pressure. These are temporary measures that buy time for deeper analysis and permanent solutions.
Add swap space if none exists. Swap allows the kernel to move inactive memory pages to disk, preventing immediate crashes. Create a 2GB swap file with: 'sudo fallocate -l 2G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile'. Make it permanent by adding '/swapfile none swap sw 0 0' to /etc/fstab. Performance will degrade when swap is actively used, but services remain available.
Restart high-memory processes to clear accumulated memory. Identify the culprit with 'ps aux --sort=-%mem | head', then restart the specific service (e.g., 'systemctl restart apache2' or 'systemctl restart mysql'). Always verify the service restarts successfully and check logs for errors.
Clear system caches if they're consuming excessive memory. Run 'sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches' to free pagecache, dentries, and inodes. This is safe but temporary—memory will refill during normal operation.
- Trade-off: Fast implementation but degrades performance when swap is active
- Cost: Free, uses existing disk space
- Downtime: Seconds to minutes for service restarts
- Best for: Immediate crisis response while investigating root cause
Approach 2: Application and System Optimization
Optimization addresses the root causes of memory consumption without requiring infrastructure changes. This approach is cost-effective but requires technical knowledge of your application stack.
Tune web server memory limits. For Apache, reduce MaxRequestWorkers in /etc/apache2/mods-enabled/mpm_prefork.conf (typically 25-50 for 1-2GB RAM). For Nginx, adjust worker_processes and worker_connections in /etc/nginx/nginx.conf. Each Apache worker consumes 20-50MB; calculate max workers as (Total RAM - OS overhead - other services) / per-worker memory.
Optimize database memory settings. MySQL/MariaDB default configurations often assume 8GB+ servers. Edit /etc/mysql/my.cnf to set innodb_buffer_pool_size to 50-70% of available RAM if MySQL is the primary service, or 128-256MB on shared hosting. Set max_connections to realistic limits (50-100 for small sites). Restart MySQL after changes and monitor with 'mysqladmin status' and 'SHOW ENGINE INNODB STATUS'.
Configure application-level caching limits. PHP applications: reduce memory_limit in php.ini from 128M to 64M or 32M based on actual script needs. Redis/Memcached: set maxmemory limits with eviction policies (e.g., 'maxmemory 256mb' and 'maxmemory-policy allkeys-lru' in redis.conf). Node.js: use --max-old-space-size flag to cap heap size.
Enable and tune swappiness for better behavior. Set vm.swappiness to 10-20 (default is 60) to make the kernel prefer freeing cache over swapping: 'echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf && sudo sysctl -p'. This keeps active processes in RAM while allowing swap as a safety buffer.
- Trade-off: Requires configuration knowledge but no recurring costs
- Cost: Free, uses existing resources more efficiently
- Downtime: Brief service restarts for configuration changes
- Best for: VPS with sufficient RAM that's being used inefficiently
Approach 3: Infrastructure Scaling
Scaling upgrades the VPS hardware when optimization cannot meet demand. This is the simplest solution but has recurring cost implications.
Vertical scaling (RAM upgrade) is appropriate when baseline memory usage consistently exceeds 70-80% during normal load, optimization has been fully applied, and traffic growth is steady. Most providers allow RAM upgrades without full migration. Typical VPS tiers: 1GB → 2GB → 4GB → 8GB. A 2GB VPS costs $10-20/month, 4GB costs $20-40/month. Upgrade immediately if you're regularly hitting OOM conditions despite optimization.
Horizontal scaling (multiple servers) becomes necessary when a single VPS cannot handle peak loads or you need redundancy. Separate database and web servers to isolate memory usage. A 1GB database server + 2GB application server configuration costs $15-30/month and provides better resource isolation than a single 3GB server. Requires load balancing and session management.
Managed services offload memory management entirely. Managed database hosting (RDS, managed MySQL) removes database memory concerns. CDN and edge caching reduce application server load. Static site generation eliminates server memory for content delivery. Evaluate based on total cost of ownership including management time.
- Trade-off: Immediate relief but ongoing costs
- Cost: $5-40/month additional depending on tier
- Downtime: 0-30 minutes for resize, varies by provider
- Best for: Sustained high memory usage that cannot be optimized away
Side-by-Side Comparison and Recommendations
Choose emergency fixes when you need immediate relief during an active incident, services are crashing, and you need time to investigate. Implementation time is under 10 minutes. Continue with deeper analysis afterward.
Choose optimization when memory usage is high but not critical, your VPS has adequate RAM for the workload type, and you have configuration access to key services. This is the most cost-effective long-term solution. Expect 1-3 hours for analysis and tuning, with 20-40% memory reduction typical for default configurations.
Choose scaling when baseline usage exceeds 70% after optimization, your application is properly configured but legitimately memory-intensive, or you've experienced multiple OOM incidents. A 2GB to 4GB upgrade typically resolves issues for moderately busy WordPress or small application servers.
Recommended strategy: Implement emergency swap immediately if you don't have it, analyze memory usage patterns over 24-48 hours, optimize configuration based on findings, then scale only if optimization doesn't reduce usage below 70% baseline. Always implement monitoring before you reach crisis points.
- Emergency fix: Immediate relief, degrades under load, no cost
- Optimization: 20-40% reduction, requires expertise, no cost
- Scaling: Guaranteed capacity, recurring cost, simple implementation
- Hybrid approach: Swap + optimization + monitoring, scale only when necessary
Monitoring and Prevention
Implement monitoring to detect memory pressure before services crash. Set up alerts at 80% memory usage to trigger investigation. Use free tools like monit, netdata, or simple cron scripts that check 'free -m' and send email alerts.
Create a monitoring script that runs every 5 minutes: 'USED=$(free | awk "/Mem:/ {print int($3/$2 * 100)}"); if [ $USED -gt 80 ]; then echo "Memory at ${USED}%" | mail -s "VPS Memory Alert" [email protected]; fi'. Install with crontab.
Log memory-intensive processes daily to identify trends. A simple daily log: 'ps aux --sort=-%mem | head -n 10 > /var/log/memory-usage-$(date +%F).log' helps identify gradual memory leaks or usage pattern changes.
Test changes in a staging environment or during low-traffic periods. After configuration changes, monitor for 24-48 hours before considering them stable. Keep backups of configuration files before making changes: 'cp /etc/mysql/my.cnf /etc/mysql/my.cnf.backup-$(date +%F)'.
Quick troubleshooting checklist
- Check current memory status with 'free -h' and 'top' to establish baseline
- Verify swap space exists; if not, create 2GB swap file immediately
- Identify top memory-consuming processes with 'ps aux --sort=-%mem | head'
- Review and optimize web server MaxRequestWorkers or worker_processes settings
- Tune database innodb_buffer_pool_size and max_connections for available RAM
- Set vm.swappiness to 10-20 for better swap behavior
- Implement memory monitoring with alerts at 80% usage
- Document configuration changes and keep backups
- Monitor for 24-48 hours after changes to verify stability
- Plan RAM upgrade if baseline usage consistently exceeds 70% after optimization
FAQ
What is the OOM killer and why does it crash my services?
The OOM (Out of Memory) killer is a Linux kernel mechanism that terminates processes when the system runs out of memory to prevent complete system failure. It selects processes based on memory usage and priority, often killing databases or web servers because they consume significant RAM. The OOM killer activates when both RAM and swap space are exhausted and no memory can be freed through normal means.
How much swap space should I configure on a VPS?
Configure swap space equal to your RAM size for VPS with 2GB or less RAM (e.g., 2GB swap for 2GB RAM), or 2-4GB swap for VPS with 4GB+ RAM. Swap provides a safety buffer for memory spikes but significantly degrades performance when actively used because disk I/O is 100-1000x slower than RAM. Set vm.swappiness to 10-20 to use swap only when necessary rather than the default aggressive swapping behavior.
When should I upgrade my VPS RAM versus optimizing configuration?
Upgrade VPS RAM when baseline memory usage consistently exceeds 70-80% during normal operation after you've optimized application and system configurations, when you're experiencing regular OOM killer events, or when legitimate workload growth requires more resources. Optimize configuration first if you're running default settings, have high cache usage, or are using more than 50 Apache workers on a 1-2GB VPS, as misconfiguration often wastes 30-50% of available memory.
Is it safe to clear system caches to free memory?
Yes, clearing PageCache, dentries, and inodes with 'sync && echo 3 > /proc/sys/vm/drop_caches' is safe and does not cause data loss or corruption. The sync command flushes pending writes to disk first, and caches rebuild automatically during normal operation. However, this provides only temporary relief—memory will refill within minutes to hours. Cache clearing is useful for emergency situations but does not address the root cause of memory pressure.
How do I identify which process is consuming all my VPS memory?
Use 'ps aux --sort=-%mem | head -n 10' to list the top 10 memory-consuming processes with their memory percentage and command details, or run 'top' and press 'M' to sort by memory usage interactively. Check 'dmesg | grep -i oom' to see which processes the OOM killer has terminated recently. For detailed process memory breakdown, use 'pmap [PID]' where PID is the process ID from ps or top output. Monitor over several hours to distinguish between temporary spikes and sustained high usage.
Related articles
- Hosting OperationsSelf-Hosted App Deployment Fails? Check DNS, SSL, Reverse Proxy, and Logs FirstTroubleshoot failed self-hosted app deployments by checking DNS, SSL, reverse proxy routing, container status, logs, and ports.
- Hosting OperationsSelf-Hosted PaaS on a VPS: What to Check Before Installing Coolify, Dokploy, or CapRoverA hosting support checklist for preparing a VPS before installing self-hosted PaaS tools like Coolify, Dokploy, or CapRover.
- Hosting OperationsLinux Server Security Lessons from the Arch Linux Malware Package IncidentPractical Linux server security checklist for VPS admins after package malware concerns, with safe checks, rollback steps, and support guidance.
- Hosting OperationsAWS Lightsail Hong Kong VPS Latency: Practical Hosting Guide for IndonesiaLearn how to test AWS Lightsail Hong Kong VPS latency, compare regions, migrate safely, and troubleshoot hosting performance.
- Hosting OperationsCloudflare Tomorrow Watchlist: A Practical Hosting Operations GuidePractical Cloudflare troubleshooting checklist for DNS, SSL, caching, WAF, origin health, safe testing, and rollback planning.
- Hosting OperationsNetwork Safety Checklist for AI Agent Skills in Hosting OperationsAudit AI agent skills safely with network checks, secret protection, sandbox testing, rollback steps, and hosting support troubleshooting guidance.