# Next.js OOM (Out of Memory) on production

On small droplets (e.g. 2GB RAM), the Next.js process can be killed by the Linux OOM killer. You may see:

- `nextjs.service: Main process exited, code=killed, status=9/KILL`
- Or in `journalctl -u nextjs`: process exits repeatedly after a short run

## Current setup (4GB RAM, optimized)

- **Next.js**: Runs in **standalone** mode (`output: 'standalone'` in `next.config.ts`) for lower memory. Heap capped at **1536MB** via `NODE_OPTIONS=--max-old-space-size=1536` in `scripts/nextjs.service`.
- **FastAPI**: **3 Gunicorn workers** by default (`gunicorn.conf.py`). For 2GB RAM set `GUNICORN_WORKERS=2` in `.env` or the service.

### Deploy steps (after git pull)

1. Build Next.js (required for standalone):
   ```bash
   cd /var/www/boundary-fastapiandnextjs/plagis-nextjs
   npm ci
   npm run build
   ```
2. Copy `public` into standalone so static assets (e.g. favicons, images) are served:
   ```bash
   cp -r public .next/standalone/public 2>/dev/null || true
   ```
3. Install/update the systemd unit and restart:
   ```bash
   sudo cp /var/www/boundary-fastapiandnextjs/scripts/nextjs.service /etc/systemd/system/nextjs.service
   sudo systemctl daemon-reload
   sudo systemctl restart nextjs
   ```

### 2GB RAM droplets

- In `nextjs.service`: set `NODE_OPTIONS=--max-old-space-size=512` and either keep standalone (recommended) or switch back to `WorkingDirectory=.../plagis-nextjs` and `ExecStart=/usr/bin/npm start`.
- Set `GUNICORN_WORKERS=2` (or 1) for FastAPI so the backend doesn’t use too much RAM.

## Check memory and status

```bash
sudo bash /var/www/boundary-fastapiandnextjs/scripts/check_memory_nextjs.sh
```

Shows `free -h`, top processes by memory, and status of nextjs/fastapi.

## Other tips

- **Swap** (optional): `sudo fallocate -l 1G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile`
