Physical and swapfile memory run out when running `sudo nixos-rebuild switch`

I have two devices: i5 6200u and an i5 8350u. Both devices have 8GBs of DDR3 or DDR4 ram, and have a zswap file of 8GBs.

Whenever I run sudo nixos-rebuild switch with or without --upgrade, my system ends up maxing out my physical and swapfile ram, causing my terminal to crash. I’m unable to switch or upgrade.

I have nothing else open but terminal.

What can I do to have this process finish so that terminal wouldn’t crash in the middle of running switch or switch --upgrade?

Swap is irrelevant.
You have 8 gigs of ram which is in many cases, insufficient for nix (eval is memory hungry) and of course can be insufficient for whatever build systems the packages use themselves (for any uncached packages).

Eval and build on another machine, or get more RAM.
(You can try reducing the number of jobs/cores, see Tuning Cores and Jobs - Nix Reference Manual, but this only matters for building; if it’s OOMing during eval… you have to make changes.)

FWIW, most of my systems only take about 4G to evaluate. But yes, a particularly complex system could go over 8G. I have one system that takes 15G to eval, but that’s because it has 3 declarative nixos containers, which are each their own nixos evals. And yea, memory use during build time is pretty easy to keep under control with --max-jobs and --cores.

Yeah, true, the third option is to just do less in the config.
Overuse of overlays, too many inputs, etc will bloat eval.

FWIW overlays don’t really increase memory usage meaningfully. It’s a common misconception that each overlay re-instantiates nixpkgs, but that’s only if you use pkgs.extend. If you just instantiate it once with an overlays argument (which is what NixOS does), it’s not very costly.

{ n }:

with import <nixpkgs> {
  overlays = builtins.genList (_idx: _self: super: {
    systemd = super.systemd.overrideAttrs (old: {
      i = old.i or 0 + 1;
    });
  }) n;
};

systemd.outPath

Evaluating this with \time nix-instantiate . --eval --arg n $N gives me 220K max resident for N=1 and 365K for N=40.

Too many inputs probably isn’t that bad either. I wager the big use of memory comes from a combination of just how monstrously complex the NixOS module system is, and the many many packages it evaluates.

Side note: Code search results · GitHub - some of these are lib.extend, but nevertheless… people do wild stuff when they are copypasting from other beginners.

They are if they’re using their own instance of nixpkgs.