Caching

The mechanism whereby Nix uses already-built artifacts rather than building some artifacts unnecessarily

Concepts / Caching

By default, Nix uses caching to make building packages faster and more efficient. This in turn makes other Nix operations that involve building packages, like creating development environments and standing up NixOS environments, faster and more efficient as well.

Building vs. caching

Whenever Nix builds a package by realising the package's derivation, it needs to realise the entire closure of the derivation, which means that it needs to realise all of the derivations required to build the package's derivation, plus the derivations required to build those derivations, and so on. Some packages have tiny closures (dependency trees) while others have massive closures involving thousands of derivations, which makes build efficiency a primary concern in Nix.

Here's what Nix does whenever it realises a derivation:

  1. It computes a hash for the derivation and, using that hash, a Nix store path of this form (for a hypothetical Git package):

            
    /nix/store/ 1. Nix store prefix
    f8f72p3xxr20k111mpg4kk93i4cp74qb 2. Hash part
    -
    git-2.37.0 3. Package name
  2. With a store path in hand, Nix determines whether the derivation has already been built. First, Nix checks the configured Nix store to see if the path /nix/store/f8f72p3xxr20k111mpg4kk93i4cp74qb/git-2.37.0 already exists. If so, it uses that rather than building it. If not...

  3. It checks a if the store path exists in a configured binary cache.

  4. If the store path exists neither in a configured Nix store nor in a configured binary cache, Nix builds the derivation from scratch, recursively following all of the steps in this list, using already-realised packages whenever possible and building only what is necessary.

Nix without caching

Without caching, realisation would involve always building everything from scratch every single time, which would make Nix a much less efficient—and thereby much less compelling!—package manager and build tool.

Binary caches

In addition to the local Nix store, you can also cache Nix artifacts using remote Nix stores called binary caches that serve pre-built binaries via HTTP. For the most part, binary caches work just like the Nix store, enabling Nix to quickly determine whether something has already been built on the basis of a derivation's Nix store path.

By default, Nix uses cache.nixos.org as a binary cache, which is open to all and populated by continuous integration systems. In addition to this community cache, you can also run your own or use a third-party binary cache service like Cachix.


Was this page helpful?