Is it possible to garbage collect a store based on time?

I know that you can use nix-collect-garbage —older-than x days.
However this always removes artifacts that aren’t linked.
For a host that acts as a cache this isn’t optimal.
Is there a way to remove only derivations that are older than X days even if they aren’t linked?


It’s not an answer to your question (which I share), but as a substitute I generally use the --max-freed parameter when GCing to free up just enough space to get me to a certain threshold of free disk. Either I’m lucky, or the garbage collector is somewhat smart about removing old things first.

1 Like

Ah that’s actually a very good input.
I can let it clean up to 10% free disk space every day or something similar.

The --max-freed parameter tells the amount of data to GC. But you can enable autoGC (nix.gc.automatic), If you want to specify thresholds for free space (e.g. 10 gigs), you can set options for Nix itself to run a GC at invocation time if the thresholds are met:

From Storage optimization - NixOS Wiki

nix.extraOptions = ''
  min-free = ${toString (100 * 1024 * 1024)}
  max-free = ${toString (1024 * 1024 * 1024)}

Note that this might lead to a GC-redownload-loop if something fails due to low disk space and there is not enough stuff in the store that can be GC’d.

FWIW, it should in principle be possible to GC based on time. The DB records the “registration time” of a store path. I guess there’s just not a CLI for using it right now.

$ nix path-info /run/current-system --json | jq '.[].registrationTime'
1 Like

Thank you for your replies.
I probably should’ve mentioned that the server isn’t a NixOS system but your information is still valid.

You can set min-free and max-free directly in nix.conf (nix.conf - Nix Reference Manual), so this is not bound to NixOS.

1 Like