How to Optimize RAM on a 4GB VPS: Real Numbers from Production

How I keep a production SaaS (Node.js + self-hosted Supabase/Postgres) inside 4GB of RAM: Postgres caps, Docker mem_limits, heap limits, zswap, earlyoom, and a free monitoring cron, with before/after measurements.

Last Updated: November 2026

This whole website and the database behind it runs comfortable on a 4GB VPS. We run Postgres, auth, object storage, and a reverse proxy comfortably. That said, there was some optimization necessary. On traffic spikes, the system would slow down. If enough users and requests come in, the system would crash. This article will be fairly technical, but I'll try to be methodical and explain what's happening.

A Linux Memory Primer

Left alone, the Linux kernel lets every process grow indefinitely. Postgres allocates memory for queries, caches, and connections. The web server allocates memory to serve requests. If the system tries to allocate more memory, it will move memory pages to swap, usually an alternative storage device like a hard drive or SSD. As more and more memory pages are moved to swap, the system will spend more and more time moving memory between RAM and the disk instead of doing the actual work. This process of moving back and forth nonstop instead of working is called "thrashing".

When a system starts thrashing, applications become unresponsive as the CPU spends its cycles managing memory instead of the application work.


Where the RAM Went

The baseline looked fine on paper, with about 1.2GB used of 3.7GB total:

Process RSS
node build/index.js (web app) ~142 MB
dockerd + containerd ~136 MB
postgres + workers ~140 MB
caddy ~61 MB
envoy (API gateway) ~68 MB
postgrest ~27 MB
OS baseline (systemd, journald, etc.) ~300–400 MB

Everything was manageable for now. But it was also uncapped, and we've had spikes of traffic before that would push us over the limit. Back when we were serverless, this wasn't a problem. We could scale up to meet traffic, then scale down when it passed. But that was more expensive than a 4GB VPS, and generally less performant too, since we ended up with latency moving data between different managed services.


The Real Risk: Postgres Math

There are two Postgres settings that cause most of the trouble:

  • work_mem is allocated per sort/hash node per connection. At the default 4MB with max_connections=100, a busy moment could (in theory) burn 4MB × 100 × several nodes ≈ 1GB+ on sorts alone, on top of shared_buffers.
  • shared_buffers defaults to 128MB, which is fine for a laptop but wastes the real upside of having RAM. The classic rule is ~25% of total memory.

Postgres Tuning for 4GB

Inside the database container:

docker exec supabase-db psql -U supabase_admin -d postgres -c "ALTER SYSTEM SET shared_buffers = '512MB'"
# ... repeat for each setting (ALTER SYSTEM can't run multi-statement in one -c)
Setting Before After Why
shared_buffers 128MB 512MB ~25% of RAM is the ceiling on small boxes
effective_cache_size 128MB 2GB Planner hint only, not allocated. It tells Postgres to expect a bigger OS cache
work_mem 4MB 4MB Already sane; raising it is how boxes fall over
maintenance_work_mem 64MB 256MB Headroom for VACUUM / index builds
max_connections 100 60 Each connection can burn work_mem × nodes

ALTER SYSTEM writes to postgresql.auto.conf inside the PGDATA volume, so restarting doesn't lose the settings. shared_buffers and max_connections require a Postgres restart; the rest are reloadable.

Before touching anything, I recorded the actual values so I could compare them afterward:

docker exec supabase-db psql -U supabase_admin -d postgres -c "SHOW shared_buffers; SHOW work_mem; SHOW max_connections;"

Postgres memory settings before and after tuning on a 4GB VPS


Hard Caps: Docker mem_limit + Node Heap

I added mem_limit to every compose service:

services:
  api-gw:  { mem_limit: 256m }
  rest:    { mem_limit: 128m }
  storage: { mem_limit: 384m }
  # ...same pattern for every other service
  db:      { mem_limit: 1g }   # guard rail, not a target

Each container now has a hard limit of the memory it can consume. So, why is this useful?

  1. It prevents any individual service from eating up all the RAM
  2. It provides a safety net if a service leaks memory
  3. It makes resource usage predictable and auditable

Note that the postgres cap is much higher than the other servives. This is because Postres is the most important service as well as the most resource-intensive. More memory for Postres means higher performance and more reliability. If Postres ever hits the cap, we need to increase the size-- this is a clear indicator that the VPS size is insufficient for the workload it handles.


Removing Unnecessary Services

The self-hosted Supabase docker setup ships optional compose overrides, and every one of them costs RAM. On a 4GB box, "available" features are a budget decision:

  • Log aggregation (.logs.yml, fluent-bit/vector): docker logs + journald are enough at this scale.
  • S3/rustfs backend: the app stores user-uploaded files on the local filesystem backend.
  • pgbouncer/supavisor: with only internal services connecting, 60 direct Postgres connections is plenty. While on hosted Supabase, I never saw it break 35.
  • Studio: it's a separate heavy Next.js app. We're in the agentic era-- psql and the CLI cover everything I need.

The rule: every optional service is a line item in the RAM budget. Add it back only when a metric says you need it. It's the same discipline as right-sizing cloud infrastructure at a bigger scale. Even if it's free, every new service consumes RAM and clutters up the environment. Only take what you need.


OS-Level: swappiness, zswap, earlyoom

Three cheap sysctl/package changes round out the safety net:

  1. swappiness: influences when Linux swaps out memory pages.
  • sysctl -w vm.swappiness=10
  • echo "vm.swappiness=10" > /etc/sysctl.d/99-cloudjobs.conf
  • vm.swappiness=10 # the default on most systems is 60, which is too high for such a small VPS
  1. zswap: compresses memory pages before writing them to swap. At a high level, you can think of turning CPU cycles into reduced memory usage.
  • echo Y > /sys/module/zswap/parameters/enabled
  1. earlyoom: proactively kills memory hogs before the kernel OOM killer panics the whole system.
  • apt install earlyoom
  • EARLYOOM_ARGS="--avoid 'postgres|dockerd|containerd|sshd'"

Note that the second command for earlyoom prevents it from killing the database or docker.


Monitoring for Free (No Netdata)

Netdata costs 150–200MB RSS itself, totally unacceptable on a VPS with only 4GB of RAM. Instead, I run a simple five-line cron that logs the metrics I care about:

  1. free -m - shows available and used memory
  2. docker stats --no-stream - shows container resource usage

These run a few times per hour and are stored locally for a couple weeks. When available memory or swap usage crosses a threshold, it emails an alert via SMTP. This could probably be more sophisticated, but it should be functional. It's the same "monitor what matters" instinct behind SRE practices, sized for one server instead of a fleet.


Before vs. After

Committed memory ceiling vs physical RAM on a 4GB VPS

The committed ceiling, the sum of all caps plus the OS baseline, is ~2.9GB against 3.8GB physical. Everything else is headroom.

Metric Before After
Postgres shared_buffers 128MB 512MB
max_connections 100 60
Container memory limits none 128m–1g per service
Node heap cap none (grows to available RAM) 384MB old-space
vm.swappiness 60 10
zswap disabled enabled (zstd)
OOM protection none earlyoom
Memory logging none cron job + email alerts

Container memory caps vs actual usage measured on the VPS

Post-change snapshot: ~1.0Gi used, 2.6Gi available, swap ~0. supabase-db RSS is still climbing toward ~600MB as shared_buffers demand-pages in. That's the intended trade: a bigger database cache, while staying under its 1GB guard rail.


When Does An Upgrade Become Necessary?

Setting caps and graceful failures give breathing room, but it is possible that the demand will grow to exceed the capacity. Horizontal scaling would be a nightmare considering the database lives on the VPS and we'd need a load balancer and a way to distribute connections. So, if the VPS can't handle the load, I'll scale it up. These are roughly what I'm monitoring:

  • Swap stays in use during normal traffic
  • MemAvailable stays low even at idle-ish load
  • shared_buffers can't be raised enough that queries stay fast
  • You want the heavy extras back: Studio, Realtime, image proxy, connection poolers

If this happens and is sustained for long enough, it's time to upgrade. Fortunately, that'll only move the cost of the website from ~$6 to ~$10. We should be able to afford that!


Conclusion

On a small VPS, we can't minimize memory consumption at all costs. Instead, we try to understand how much memory every component could consume under stress and constrain it to that. We have baselines, averages, and worst-case scenarios for the memory usage of each component. If we set a hard cap for each component that lets them handle any realistic workload, we can avoid memory exhaustion without sacrificing performance.

Without the cap, a memory leak could push Node.js from 142MB to 1GB or higher. With the cap, it stays just as performant but stays within its 384MB limit. To some extent, we moved off Supabase because of noisy neighbors. This approach us helps us ensure we don't become our own noisy neighbor. Barring an attack or a horrible code push, our 4GB box should stay a reliable production server for the foreseeable future. Knock on wood.


All figures are measured on the production VPS, as of 2026-11-08.

John Mehler

Written by John Mehler

Founder & Lead Engineer at CloudJobs.

John is a senior DevOps engineer with more than a decade of experience at Google, Microsoft, Deloitte, and a boutique private equity fund. He currently holds the CISSP, AWS Solutions Architect, Microsoft DevOps Engineer Expert, Security+, and Terraform Associate credentials. He previously held the Google Cloud Professional Cloud Architect and Azure Solutions Architect Expert.

← Back to Insights