---
name: low-memory-deployment
description: Guides memory-safe implementation patterns for the DWP Hours Tracker deployed on a 512MB DigitalOcean droplet.
title: low-memory-deployment
canonical_url: https://skilld.dev/gh/corey-alix/dwp-hours/low-memory-deployment
last_updated: 2026-10-07T01:30:59.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install corey-alix/dwp-hours/low-memory-deployment`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/low-memory-deployment`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/corey-alix/dwp-hours/low-memory-deployment) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/low-memory-deployment`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/low-memory-deployment --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/low-memory-deployment --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Low-Memory Deployment Skill

## Description

The DWP Hours Tracker production server runs on a DigitalOcean droplet with **457MB total RAM, no swap**. Node.js gets ~200MB usable after OS and PM2 overhead. This skill captures hard-won patterns for avoiding OOM kills.

## Trigger

Activate this skill when:

- Implementing features that process large files (Excel, CSV, images)
- Adding middleware or libraries that buffer request/response bodies
- Changing PM2 or server configuration
- Debugging SIGKILL crashes on the production server
- Working on bulk data operations (imports, exports, report generation)

## Server Environment

| Resource             | Value                                 |
| -------------------- | ------------------------------------- |
| Total RAM            | 457 MB                                |
| Swap                 | None                                  |
| Available to Node.js | ~200 MB                               |
| PM2 mode             | Cluster (single instance)             |
| OS                   | Ubuntu on DigitalOcean                |
| Node.js heap default | ~256 MB (V8 default for <2GB systems) |

## Response Pattern

### 1. Identify Memory Hotspots

Before implementing, estimate peak memory usage:

- **File uploads**: multer `memoryStorage()` holds entire file in RAM
- **Library parsing**: ExcelJS `readFile()` / `load(buffer)` expands compressed xlsx to full object model (~10–50x file size)
- **Database**: sql.js holds entire SQLite DB in memory
- **Accumulated objects**: Large result arrays, logging buffers

### 2. Apply Streaming Patterns

Process data incrementally instead of loading everything at once:

- Use `multer.diskStorage()` instead of `memoryStorage()` — write uploads to `/tmp`, clean up in `finally` block
- Use ExcelJS `WorkbookReader` streaming API instead of `readFile()` (see exceljs skill)
- Process items one at a time, releasing references between iterations
- For database bulk operations, disable autoSave and persist once at the end

### 3. Clean Up Aggressively

- Delete temp files in `finally` blocks
- Null out large objects after use
- Release worksheet references after processing each sheet
- Use `workbook.removeWorksheet(ws.id)` if using non-streaming ExcelJS

## Proven Patterns

### File Upload: Disk Instead of Memory

```typescript
// BAD — holds entire file in Node.js memory
const upload = multer({ storage: multer.memoryStorage() });

// GOOD — writes to disk, stays off the heap
const upload = multer({
  storage: multer.diskStorage({
    destination: "/tmp",
    filename: (_req, file, cb) => {
      cb(null, `upload-${Date.now()}-${file.originalname}`);
    },
  }),
  limits: { fileSize: 10 * 1024 * 1024 },
});

// Always clean up temp files
try {
  await processFile(req.file.path);
  res.json({ success: true });
} finally {
  fs.unlink(req.file.path, () => {});
}
```

### Excel: Stream One Sheet at a Time

```typescript
// BAD — loads all 68 sheets into memory at once (~200MB+)
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(filePath);

// GOOD — streams one sheet at a time (~5MB peak per sheet)
const reader = new ExcelJS.stream.xlsx.WorkbookReader(filePath, {
  worksheets: "emit",
  sharedStrings: "cache",
  styles: "cache",
  hyperlinks: "cache",
});

for await (const wsReader of reader) {
  const ws = await materialiseWorksheet(wsReader); // one sheet in memory
  processSheet(ws);
  // ws is GC'd on next iteration
}
```

### Bulk DB Operations: Single Save

```typescript
// BAD — sql.js autoSave writes entire DB to disk on every insert
for (const item of items) {
  await repo.save(item); // triggers disk write each time
}

// GOOD — disable autoSave, batch all writes, save once
const driver = dataSource.driver as any;
const originalAutoSave = driver.options?.autoSave;
driver.options.autoSave = false;

try {
  for (const item of items) {
    await repo.save(item); // in-memory only
  }
} finally {
  driver.options.autoSave = originalAutoSave;
  await driver.save(); // single disk write
}
```

## Debugging OOM on Production

### Symptoms

- PM2 shows increasing restart count (↺ column)
- Process exits with SIGKILL (not SIGINT or SIGTERM)
- No error in application logs — process killed mid-operation
- `dmesg` may show OOM killer messages (requires root access)

### Diagnosis Steps

1. `ssh deploy@server "pm2 status"` — check restart count and uptime
2. `ssh deploy@server "pm2 logs --nostream --lines 100"` — find last operation before crash
3. `ssh deploy@server "free -m"` — check available memory
4. Look for the pattern: operation starts → no completion log → server restarts

### Common Culprits

| Operation                    | Memory Risk               | Fix                              |
| ---------------------------- | ------------------------- | -------------------------------- |
| Excel import (68 sheets)     | ~200MB+ with `readFile()` | Use streaming `WorkbookReader`   |
| File upload                  | File size × 1             | Use `diskStorage()`              |
| Report generation            | Depends on data volume    | Stream output, limit batch sizes |
| Multiple concurrent requests | Additive                  | Queue heavy operations           |

## PM2 Configuration Notes

- The server runs in **cluster mode** with a single instance
- Each cluster worker is a full Node.js process
- On 512MB, never run more than 1 instance
- Consider `--max-memory-restart 200M` as a safety net

## Additional Context

- This skill complements the `exceljs` skill (streaming patterns) and `sql-js-database-assistant` skill (bulk operations)
- The production server has no swap partition — when memory is exhausted, the OOM killer acts immediately with SIGKILL
- Always test memory-intensive operations with realistic data volumes before deploying
