Skip to content

Next.js high memory usage: how I cut my server from 1 GB to 0.29 GB

From the work/ 19 min read

The Next.js image optimizer kept my Railway server near 1 GB. With images.unoptimized it read 0.29 GB: how I found it, how I measured it, and when not to do it.

  • Next.js
  • Performance
In this article (8)
  1. The symptom: memory near 1 GB and a bill that did not add up
  2. How I found the culprit: the Next.js image optimizer
  3. The change: images.unoptimized, and why it only works with images already optimized
  4. How I measured it (a sitemap crawl and Railway metrics)
  5. When NOT to do this
  6. Common mistakes
  7. Frequently asked questions
  8. Checklist

If your Next.js server shows high memory usage and every image already ships optimized from /public, the image optimizer may be the cause. On ecomlabs.dev, on Railway, the web service still averaged 0.99 GB after tuning. I set images.unoptimized: true, and after crawling all 276 sitemap pages, memory sat at 0.29 GB.

I first told this fix as a side example in the Ponytail post about the smallest change that works. This is the full, measured version: the symptom, how I found the cause, the one setting I changed in next.config.ts, the two scripts I measured with, and the cases where you should not copy it.

The symptom: memory near 1 GB and a bill that did not add up

ecomlabs.dev is a Next.js 15.5 app running next start on Railway, with a small Postgres database for the blog. It is a content site that does very little work per request. Even so, the web service's memory graph never sat still.

Until September 28, 2026, the service averaged 1.25 GB. After each deploy it started at about 0.5 GB and climbed to 1.5–2.2 GB before the next one. That day I tuned it (details below) and the average dropped, but not by much: 0.99 GB over seven days, with CPU near zero. Postgres averaged 54 MB the whole time.

The bill made it obvious. Railway charges memory at "$10 / GB / month ($0.000231 / GB / minute)", so 0.99 GB is about $10 a month in memory alone. In October, project usage stood at $5.28 so far in the billing period, and $5.12 of that was memory. A site that barely touched the CPU was paying almost entirely for RAM it held on to.

PeriodImage setupWeb service memoryWhat kind of number
Until Sep 28, 2026Optimizer with the default cache, AVIF and WebP1.25 GB; 0.5 up to 1.5–2.2 GB between deploysRailway average
Sep 28 – Oct 2030-day cache, one libvips thread, MALLOC_ARENA_MAX=2, heap cap0.99 GB7-day Railway average
From Oct 21, 02:10 UTCimages.unoptimized: true0.29 GBLive reading right after crawling all 276 sitemap pages

Mind the last column: 1.25 and 0.99 are averages; 0.29 is a point reading from the metrics tab. They are not the same kind of number, and I do not compare them as if they were.

web service memory on Railway, in GB00.511.52 GBuntil Sep 28average1.25 GBSep 28 tuning7-day average0.99 GBunoptimizedlive, 276 pages0.29 GBbetween deploys: 0.5 up to 1.5–2.2 GBtuning: 1.25 → 0.99 · no optimizer: 0.29Railway averages; 0.29 GB is a live reading, not an average

Scroll the figure sideways to see all of it

How I found the culprit: the Next.js image optimizer

Memory that grows while CPU stays at zero does not look like traffic or rendering. It looks like something allocating native memory and keeping it. On a self-hosted Next.js server, the first suspect is the next/image optimizer, which runs inside the same process. The Next.js 15 self-hosting guide says it "works self-hosted with zero configuration when deploying using next start", and that images are optimized at runtime, not during the build.

Here is what it does with each image. The component does not point at your file. It points at /_next/image?url=...&w=...&q=..., one URL per candidate in the srcset. When that request arrives, the server looks for a fresh copy in .next/cache/images. If there is none, it reads the original, resizes and re-encodes it with sharp (built on libvips), stores the copy and responds.

"Fresh" is the key word. In Next.js 15 the default is minimumCacheTTL: 60, // 1 minute, and the docs define the optimized image's expiry as "either the minimumCacheTTL or the upstream image Cache-Control header, whichever is larger". Files in /public are served with Cache-Control: public, max-age=0. The larger of 60 and 0 is 60, so every variant expired after a minute and was re-encoded on the first request after that. That was my September diagnosis.

It was not an edge case. Next.js 16 raised the default to 4 hours, and the version 16 upgrade guide explains why: "This caused revalidation to happen every 60 seconds, which increased CPU usage and cost."

The other half is native memory. The self-hosting guide warns: "On glibc-based Linux systems, Image Optimization may require additional configuration to prevent excessive memory usage." It links to sharp's section on the Linux memory allocator, which says glibc's default allocator "is unsuitable for long-running, multi-threaded processes that involve lots of small memory allocations". A Next.js server that processes images for days is exactly that kind of process.

The September 28 tuning went after both halves:

  • A 30-day minimumCacheTTL, so each variant was encoded once per deploy instead of once a minute.
  • experimental.imgOptConcurrency: 1, a single libvips thread. Next.js 15.5's own source says so where it sets sharp's concurrency: "Reducing concurrency should reduce the memory usage too."
  • MALLOC_ARENA_MAX=2 in the start command. The glibc manual describes its equivalent tunable, glibc.malloc.arena_max, which sets the number of malloc arenas a process uses "regardless of the number of cores in the system".
  • --max-old-space-size=384, a cap in MiB on V8's heap (Node.js docs).

The average went from 1.25 to 0.99 GB. But each of those lines was code added to keep alive a component I had never questioned. So I counted what it was optimizing. Every image on the site comes from /public: 47 WebP files, none wider than 1440 pixels, 2.2 MB in total, plus six PNGs that were actually in use. There was nothing the server needed to resize.

the same image, with and without the optimizerwith the optimizer (next/image default)GET /_next/image?url=%2Fshot.webp&w=640&q=751 · fresh copyin the cache?yes: send it, done2 · no: read /publicsharp (libvips)resizes, re-encodes3 · stores the copy.next/cache/imagesand respondsNext 15: the copy expires after 60 s = max(minimumCacheTTL 60, max-age=0)images.unoptimized: trueGET /shot.webpreads the file from /public and sends it as-is: no sharp, no srcsetthe same WebP, no work on the serveronly safe when the file in /public is already at its final size and format

Scroll the figure sideways to see all of it

The change: images.unoptimized, and why it only works with images already optimized

On October 20, in commit 0b18567, I removed the tuning and left a single setting. This is the images block of my next.config.ts, exactly as it is in the repository:

images: {
  // No runtime optimizer. Every image comes from /public and is already a
  // small WebP (≤1440 px, ~2 MB in total), so sharp only bought memory: even
  // with a 30-day cache and one libvips thread, its native allocations kept
  // the Railway container near 1 GB, which was nearly the whole bill.
  // Add new images to /public as WebP sized for their largest display.
  // shortcut: no srcset, so phones get the desktop-sized file; turn the
  // optimizer back on if /public gains large photos.
  unoptimized: true,
},
  1. unoptimized: true applies to every image on the site. The next/image docs describe it as: "The source image will be served as-is from the src instead of changing quality, size, or format." It has been a next.config.js option since Next.js 12.3.0.
  2. The first comments say why: everything comes from /public and is already a small WebP, so sharp only bought memory, even with the 30-day cache and one thread.
  3. The rule from now on: new images go into /public as WebP, sized for their largest display.
  4. The shortcut: line records the price (no srcset, so a phone downloads the same file as a desktop) and when to undo it: if /public gains large photos.

The same diff deleted formats: ["image/avif", "image/webp"], the 30-day minimumCacheTTL and experimental.imgOptConcurrency: with no optimizer there is nothing left to configure. What did not change is the start command in railway.json, which still sets MALLOC_ARENA_MAX=2 and --max-old-space-size=384 from September (plus --expose-gc, which I added a week later for another part of the site). The 0.29 GB reading was taken with those two September settings in place.

I checked in the Next.js 15.5 source what the component does with the option on: it returns the src untouched and leaves srcSet and sizes empty. The <img> keeps its width and height, but points straight at /shot.webp instead of going through /_next/image.

This only works because the images were already optimized. The 47 WebP files were already at their final size. I converted the six PNGs to WebP once, on my laptop, with the sharp the project already had installed. The logo was a 6345-pixel-wide PNG of 164 KB drawn at 30 pixels high; as a 96-pixel-high WebP it is 10 KB. The app icon went from 281 KB to 6 KB, and the four screenshots from about 180 KB each to about 40 KB. Doing that work once, before the deploy, is what lets you switch the optimizer off without making the page heavier. If your originals are 3 MB photos, unoptimized ships them at 3 MB, and your LCP will show it, as I explain in how to make your hero image load first.

How I measured it (a sitemap crawl and Railway metrics)

I measured in two places, and each measurement says something different.

Locally, I built the site, started it in production mode and crawled all 274 pages in its sitemap. The server process sat at 173 MB idle and 197 MB after the crawl, against a 344 MB peak in the same test with the tuned optimizer. That test does not reproduce the problem: it runs on my computer, not on Railway's glibc Linux. It is good for comparing two setups under the same conditions, not for predicting production.

In production, the change shipped on October 21, 2026 at 02:10 UTC. Right after, I crawled the 276 pages the sitemap listed by then, and the service's memory on Railway read 0.29 GB. You read that number in the service's Metrics tab. Per Railway's metrics docs, you get there "by clicking on a service in the project canvas, and going to the 'Metrics' tab", and there are "Up to 30 days of data" per project. If you run replicas, the Sum view combines them and the Replica view splits them out.

To repeat the test on your own app I wrote crawl-sitemap.mjs, with no dependencies. It fetches the sitemap, requests every <loc> and, with --images, every image on every page as well, which is what actually puts the optimizer to work:

// Requests every <loc> in a sitemap, on the sitemap's own host, and prints a summary.
// usage: node crawl-sitemap.mjs <sitemap-url> [--concurrency 1-4] [--images]
import { pathToFileURL } from "node:url";

const decode = (s) => s.replaceAll("&amp;", "&");

export function pageUrls(xml, sitemapUrl) {
  const host = new URL(sitemapUrl);
  // A local build's sitemap still lists the production domain: keep the path, swap the host.
  return [...xml.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((m) => {
    const u = new URL(decode(m[1]), host);
    return new URL(u.pathname + u.search, host.origin).href;
  });
}

export function imageUrls(html, pageUrl) {
  const found = [];
  for (const [tag] of html.matchAll(/<img\b[^>]*>/gi)) {
    for (const [, name, value] of tag.matchAll(/\s(src|srcset)="([^"]*)"/gi)) {
      const list = name.toLowerCase() === "srcset" ? value.split(",").map((c) => c.trim().split(/\s+/)[0]) : [value];
      for (const v of list) if (v && !v.startsWith("data:")) found.push(new URL(decode(v), pageUrl).href);
    }
  }
  // Same host only: the crawl measures your server, never someone else's CDN.
  return found.filter((u) => new URL(u).origin === new URL(pageUrl).origin);
}

export async function crawl(sitemapUrl, { concurrency = 1, images = false, log = () => {} } = {}) {
  const started = performance.now();
  const res = await fetch(sitemapUrl);
  if (!res.ok) throw new Error(`sitemap: HTTP ${res.status}`);
  const pages = pageUrls(await res.text(), sitemapUrl);
  if (pages.length === 0) throw new Error("no <loc> found (a sitemap index is not supported)");

  const statuses = {};
  const seen = new Set();
  let bytes = 0;
  const get = async (url) => {
    try {
      const r = await fetch(url, { signal: AbortSignal.timeout(30_000) });
      const body = Buffer.from(await r.arrayBuffer());
      bytes += body.length;
      statuses[r.status] = (statuses[r.status] ?? 0) + 1;
      if (r.status >= 400) log(`${r.status} ${url}`);
      return { r, body };
    } catch (err) {
      statuses.error = (statuses.error ?? 0) + 1;
      log(`error ${url}: ${err.message}`);
      return null;
    }
  };

  let next = 0;
  const worker = async () => {
    while (next < pages.length) {
      const url = pages[next++];
      const got = await get(url);
      if (!images || !got?.r.headers.get("content-type")?.includes("text/html")) continue;
      for (const img of imageUrls(got.body.toString("utf8"), url)) {
        if (seen.has(img)) continue;
        seen.add(img);
        await get(img);
      }
    }
  };
  await Promise.all(Array.from({ length: Math.min(concurrency, pages.length) }, worker));
  return { pages: pages.length, images: seen.size, statuses, bytes, ms: Math.round(performance.now() - started) };
}

if (import.meta.url === pathToFileURL(process.argv[1]).href) {
  const args = process.argv.slice(2);
  const url = args.find((a) => /^https?:\/\//.test(a));
  const i = args.indexOf("--concurrency");
  const concurrency = Math.min(4, Math.max(1, Number(i >= 0 ? args[i + 1] : 1) || 1));
  if (!url) {
    console.error("usage: node crawl-sitemap.mjs <sitemap-url> [--concurrency 1-4] [--images]");
    process.exit(2);
  }
  const s = await crawl(url, { concurrency, images: args.includes("--images"), log: console.log });
  const codes = Object.entries(s.statuses).map(([code, n]) => `${code} x ${n}`).join(", ");
  console.log(`pages:     ${s.pages}`);
  console.log(`images:    ${s.images}`);
  console.log(`responses: ${codes}`);
  console.log(`received:  ${(s.bytes / 1024 / 1024).toFixed(1)} MB`);
  console.log(`time:      ${(s.ms / 1000).toFixed(1)} s (concurrency ${concurrency})`);
  process.exitCode = Object.keys(s.statuses).some((c) => c === "error" || Number(c) >= 400) ? 1 : 0;
}
  1. pageUrls pulls out each <loc> and gives it the sitemap's host. You need this: a local build's sitemap lists the production domain (mine builds every URL from https://ecomlabs.dev), and without the swap a "local" crawl would hit production.
  2. imageUrls reads the src and every srcset candidate of each <img>, drops data: URIs and keeps only same-host URLs, so you never measure somebody else's CDN.
  3. get downloads each response in full, counts status codes and logs errors without stopping the crawl. Each request has a 30-second limit.
  4. The worker functions pull URLs from one shared list. --concurrency (1 to 4) sets how many requests run at once; the default is 1, one after another.
  5. seen makes sure each image is requested only once per crawl.
  6. At the end it prints pages, images, status codes, megabytes and time, and exits with code 1 if there was an error or a 4xx or 5xx response.

I tested it against a fake server built with node:http (test-server.mjs): a 13-URL sitemap on the example.com domain, 12 pages with images and one that returns 404. Never against the live site. This is the real output of node crawl-sitemap.mjs http://localhost:4321/sitemap.xml --concurrency 2 --images:

404 http://localhost:4321/gone
pages:     13
images:    10
responses: 200 x 22, 404 x 1
received:  0.4 MB
time:      0.1 s (concurrency 2)
  1. The first line is the 404 from /gone, which I put there on purpose. Even though the sitemap said example.com, every request went to localhost:4321.
  2. 13 pages and 10 unique images: the logo, three screenshots and the two srcset widths of each screenshot. The remote image and the data: URI were skipped.
  3. 22 responses with 200 (12 pages and 10 images) and one 404. Because of that 404, the script exited with code 1.

My five tests with node --test passed: the host swap, srcset parsing, the counts at concurrency 1 and 3, and the error on a sitemap with no <loc>.

While the crawl runs, measure the server process's memory. sample-rss.mjs prints it every N seconds:

// Prints a process's resident memory every N seconds until it exits (or Ctrl+C).
// usage: node sample-rss.mjs <pid> [seconds=2]
import { execFileSync } from "node:child_process";

const [pid, every = "2"] = process.argv.slice(2);
if (!/^\d+$/.test(pid ?? "")) {
  console.error("usage: node sample-rss.mjs <pid> [seconds]");
  process.exit(2);
}

const quiet = { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] };

function residentBytes() {
  if (process.platform === "win32") {
    // Windows has no ps -o rss; the working set is the closest number.
    const out = execFileSync("powershell", ["-NoProfile", "-Command", `(Get-Process -Id ${pid}).WorkingSet64`], quiet);
    return Number(out.trim());
  }
  return Number(execFileSync("ps", ["-o", "rss=", "-p", pid], quiet).trim()) * 1024; // ps prints KiB
}

const mb = (b) => (b / 1024 / 1024).toFixed(0);
let peak = 0;
const tick = () => {
  let bytes = 0;
  try {
    bytes = residentBytes();
  } catch {}
  if (!bytes) {
    console.log(`pid ${pid} is gone, peak ${mb(peak)} MB`);
    process.exit(0);
  }
  peak = Math.max(peak, bytes);
  console.log(`${new Date().toISOString().slice(11, 19)}  ${mb(bytes)} MB  (peak ${mb(peak)} MB)`);
};
tick();
setInterval(tick, Number(every) * 1000);
  1. It takes the server's PID and an interval in seconds (2 by default).
  2. On Linux and macOS it calls ps -o rss= -p <pid>, which prints resident memory in KiB.
  3. Windows has no ps with -o rss, so it asks PowerShell for the process's WorkingSet64, in bytes, which is the closest number.
  4. It keeps the peak and, when the process exits, prints it and stops.

Against my test server it printed 61 and 62 MB during the crawl, with slightly uneven samples because on Windows each reading starts a PowerShell process. If you would rather skip the script, this PowerShell loop is enough (the PID is the one my test server printed):

$id = 95172
1..3 | ForEach-Object { "{0:N0} MB" -f ((Get-Process -Id $id).WorkingSet64 / 1MB); Start-Sleep 2 }
  1. $id is the PID of the process you want to measure.
  2. WorkingSet64 is in bytes; dividing by 1MB turns it into megabytes, and {0:N0} rounds it.
  3. Three readings, one every 2 seconds. My test server read 62, 62 and 61 MB.

On Linux or macOS the same thing is a loop around ps -o rss= -p <pid> and sleep 2. A Windows working set and a Linux RSS are not identical, so always compare on the same machine. And the number that decides it in production is the one in Railway's Metrics tab: crawl production and watch the memory graph at that moment and over the following week.

When NOT to do this

images.unoptimized trades work on the server for work you do before the deploy. It applies to self-hosted Next.js on next start (Railway, a VPS, Docker), where the optimizer runs inside your process. Before you copy it, find your case:

Your caseunoptimized?Why
Every image in /public, already WebP or AVIF at its final sizeYesThere is nothing left for the server to optimize
Large photos in /public, such as camera originalsNo, or convert them firstThey would be served as-is, at full weight
Remote images from a CMS or a bucketNo, unless they already arrive at their final sizeThey are served from the original src, with no change in size or format
Images your users uploadNoYou do not control their size or format
Large photos that need a srcset on phonesNo, or write the srcset by handNo optimizer, no generated srcset
A separate service already optimizes your imagesUse a loader insteadThe self-hosting guide suggests you "configure an image loader"
Memory grows just the same on a crawl without --imagesNot yetThe optimizer only works when images are requested: look elsewhere

That last row is the cheapest test there is: crawl your sitemap without --images first, then with it, and watch memory. If it only climbs on the second crawl, the optimizer is your suspect. If it climbs on both, the problem is somewhere else and switching the optimizer off will not fix it.

what the memory costs on Railway$0.000231 / GB / min × 43,200 min = $9.98 per GB per 30 daysperiodmemorymath, 30 daysmemory / moSep 28 tuning0.99 GB avg0.99 × $9.98$9.88unoptimized0.29 GB0.29 × $9.98$2.89the billOctober, before the change: $5.28 so far, $5.12 of it memoryafter: about $3–3.5 a month in totalmemory was nearly the whole billRailway's rate: $10 / GB / month ($0.000231 / GB / minute)

Scroll the figure sideways to see all of it

Common mistakes

  • Switching the optimizer off with heavy originals in /public. Server memory goes down and page weight goes up. Convert once first, then switch it off.
  • Crawling only the HTML. Requesting a page does not download its images; the browser does that. If your crawl never requests /_next/image, it is not measuring the optimizer. That is what --images is for.
  • Crawling production by accident. A local build's sitemap lists your real domain. If your script uses each <loc> as-is, your "local" test loads production.
  • Trusting the local number. My 197 MB locally is not a Railway number: my computer does not reproduce glibc's allocator. The production number is the one that counts.
  • Comparing an average with a point reading. 0.99 GB is a seven-day average; 0.29 GB is a reading right after the crawl. To close the comparison, check the following week's average.
  • Forgetting that the rule is now for people. A 2 MB PNG that someone adds next month will be served at 2 MB. Check the weight of every new image when you review the change.

Frequently asked questions

Does images.unoptimized mean I stop using next/image?

No. You keep using the component; only the URL it points at changes. The Next.js 15 self-hosting guide says you can "disable Image Optimization and still retain other benefits of using next/image", for example if you optimize your images separately, which is what I did.

Can I turn optimization off for some images only?

Yes, with the unoptimized prop on each Image. The docs suggest it for images that gain nothing from optimization: "small images (less than 1KB), vector images (SVG), or animated images (GIF)". On my site no image gained anything, so I set it globally in next.config.ts.

Does Next.js 16 fix this with its new minimumCacheTTL default?

It fixes the once-a-minute re-encoding: the default went from 60 seconds to 4 hours. I cannot tell you whether that is enough for sharp's native memory on glibc, because I have not tested it: my site is still on Next.js 15.5. If you keep the optimizer on Next.js 15, raise minimumCacheTTL yourself.

How do I roll back if something goes wrong?

Remove unoptimized: true from next.config.ts, or revert the commit, and deploy again. On Next.js 15.5, sharp ships as an optional dependency of next, so there is nothing to install. If you go back to the optimizer on Next.js 15, add a long minimumCacheTTL again, or you are back to re-encoding every minute.

Checklist

  • You read the service's memory in Railway's Metrics tab for at least a week.
  • Every image comes from /public: no remote images and no user uploads.
  • Every image is already WebP or AVIF, sized for its largest display.
  • You accept having no srcset, or you write it by hand for large images.
  • You crawled the sitemap without and with --images while measuring the process's memory.
  • You set images: { unoptimized: true } and removed the settings that only served the optimizer.
  • After the deploy, you crawled production and read memory in Metrics.
  • A week later, you compared an average with an average.
  • You left a comment saying when to turn the optimizer back on.

This fix came from one question: does this component need to exist? I tell it with more context in Ponytail: teaching an AI coding agent to write less code. And before you convert your images by hand, read the post on the hero image that holds back LCP, where I cover size, format and srcset. And while you are looking at the server, check its runtime too: how to update Node in Docker.

Saw this on Instagram? Comment RAM on the Reel and I'll send you the guide.

Written by

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published November 2, 2026 · updated November 3, 2026

← Blog