iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐠

Speed up Nix-based CI/CD with Caching - How to Use Cachix -

に公開

Introduction

When using Nix for CI/CD with GitHub Actions, you can reduce build times by utilizing binary caches.

This article explains how to use the highly popular and free-for-personal-use cachix-action.

https://github.com/cachix/cachix-action

https://nix.dev/guides/recipes/continuous-integration-github-actions

Cachix Registration

Access the official site and register from Sign up.

I used Sign up with GitHub.
It was easy since it was completed in a few clicks.

https://www.cachix.org/

Create a Cache Destination

After logging in, open the Caches page from the top menu.
Click New Cache.

Creating a Cache

Enter an arbitrary name in the Unique name field.
The value set here will be the name of the cache storage location.

Visibility will be paid if set to private, so leave it as public.

If you are not particular about security measures, I think leaving Signing as Managed by Cachix is fine.

Cache Creation Screen

Issuing an Access Token

Select the cache you just created from Caches.

Cache List Screen

Click Settings in the upper right corner.

Screen After Cache Creation

Open the Auth Tokens tab.
Generate an access token with Write + Read permissions.

Token Creation Screen

Setting GitHub Actions Secrets

https://docs.github.com/ja/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets

Open the repository where you want to use Cachix, and select Settings > Security > Secrets and variables > Actions.

Click New repository secrets.

Secrets Setting Screen

Register the previously generated access token as CACHIX_AUTH_TOKEN.

Secrets Creation

GitHub Actions Workflow Example

Using my flake.nix and workflow as an example.

Assuming a flow where marp-cli, a tool for statically generating slides from Markdown, and necessary tools are built, and then nix run is used to create slides with the marp command.

In the example, we only run marp --version after building.

Folder Structure
your_repo
 ├─ .github
 │     └ workflows
 │         └ build.yml
 └─ flake.nix
flake.nix
{
  description = "Marp environment";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
    flake-utils.url = "github:numtide/flake-utils";
  };

  outputs =
    { nixpkgs, flake-utils, ... }:
    flake-utils.lib.eachDefaultSystem (
      system:
      let
        pkgs = nixpkgs.legacyPackages.${system};
      in
      rec {
        packages = {
          marp_build = pkgs.buildEnv {
            name = "marp_build_tools";
            paths = with pkgs; [
              marp-cli
              chromium
              noto-fonts-cjk-sans
            ];
          };
          default = packages.marp_build;
        };

        devShells = {
          default = pkgs.mkShell {
            nativeBuildInputs = with pkgs; [
              packages.marp_build
              gh
            ];
          };
        };

        apps = {
          marp = {
            type = "app";
            program = "${pkgs.marp-cli}/bin/marp";
          };
          default = apps.marp;
        };
      }
  );
}
build.yml
name: "build"

on:
  pull_request:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  marp_build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: cachix/install-nix-action@v31
      - uses: cachix/cachix-action@v16
        with:
          name: ryuryu333
          authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
      - run: nix build
      - run: nix run .#marp -- --version

Supplementary Note

For the cachix/cachix-action, enter the name of the Cache you created in Cachix for the name field.

build.yml
- uses: cachix/install-nix-action@v31
- uses: cachix/cachix-action@v16
  with:
    name: ryuryu333
    authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'

For available options for each action, refer to the following:

https://github.com/marketplace/actions/install-nix

https://github.com/marketplace/actions/cachix

(Miscellaneous) Observing Workflow Execution Behavior

Let's look at the Actions execution results.

GitHub Actions execution result screen

It was confirmed that at Run cachix/cachix-action@v16, it accesses the created Cachix cache (ryuryu333).

Run cachix/cachix-action@v16
Run cachix/cachix-action@v16
Cachix: installing
Cachix: checking version
/home/runner/.nix-profile/bin/cachix authtoken ***
Written to /home/runner/.config/cachix/cachix.dhall
Cachix: using cache ryuryu333
  /home/runner/.nix-profile/bin/cachix use ryuryu333
  No config at /home/runner/.config/nix/nix.conf:
  
  /home/runner/.config/nix/nix.conf: openFile: does not exist (No such file or directory)
  
  Configured https://ryuryu333.cachix.org binary cache in /home/runner/.config/nix/nix.conf

At Run nix build, after building, all packages were copied from cache.nixos.org (details later).

In Post Run cachix/cachix-action@v16, almost everything is Skipping.

Post Run cachix/cachix-action@v16
Post job cleanup.
Cachix: push
  [2025-10-21 13:26:31][Info] Starting Cachix Daemon
  [2025-10-21 13:26:31][Info] Configuration:
  PID: 2816
  Socket: /home/runner/work/_temp/cachix-daemon-Vt58U4/daemon.sock
  Workers: 8
  Cache name: ryuryu333
  Cache URI: https://ryuryu333.cachix.org
  Cache public keys: ["ryuryu333.cachix.org-1:okrrlMq6VWGKbDx1hhDcJ/u+lkOBJohOy6m1ANoHz5c="]
  Cache is public: True
  Compression: ZSTD
  /home/runner/.nix-profile/bin/cachix daemon stop --socket /home/runner/work/_temp/cachix-daemon-Vt58U4/daemon.sock
  [2025-10-21 13:27:00][Info] Shutting down daemon...
  [2025-10-21 13:27:02][Info] Skipping /nix/store/zzjjkknlijh0dh695b8lh63sjn7gx2hl-json-glib-1.10.8
  [2025-10-21 13:27:02][Info] Skipping /nix/store/zz7vx2a97vyi8r1ap6znzdkq5mr9bvrw-libpng-apng-1.6.50

  # Omitted
  
  [2025-10-21 13:27:02][Info] Skipping /nix/store/00sgbhwr125slpyvnbnm6xfwd5q546iq-libvpx-1.15.2
  [2025-10-21 13:27:02][Info] Skipping /nix/store/00bc157nm93q5fjz551fwk60ihlbilvj-coreutils-9.7
  [2025-10-21 13:27:02][Info][retry:0] Pushing /nix/store/mdm9ya8550c5d40b5a81lcvyfyzrav5b-marp_build_tools
  [2025-10-21 13:27:06][Info] Pushed /nix/store/mdm9ya8550c5d40b5a81lcvyfyzrav5b-marp_build_tools
  [2025-10-21 13:27:06][Info] Daemon shut down. Exiting.

Cachix's Cache Strategy

Let's verify why items were skipped.

In this example, packages like pkgs.marp are used directly from Nixpkgs.
In other words, the official binary cache (cache.nixos.org) is used during build.

According to Cachix documentation, if the path already exists in the official binary cache, the upload process is skipped.

When pushing Nix store paths to Cachix, they are first checked for existence in upstream NixOS cache (to avoid wasting storage) and if not, they are compressed and uploaded.

https://docs.cachix.org/garbage-collection

Smart.

This time, the only path that was cached was /nix/store/mdm9ya8550c5d40b5a81lcvyfyzrav5b-marp_build_tools.

This file is a collection of paths to the tools defined in the packages of flake.nix. Since it only exists in my environment, it seems this was the only one uploaded.

$ ls -l /nix/store/mdm9ya8550c5d40b5a81lcvyfyzrav5b-marp_build_tools
total 12
dr-xr-xr-x 2 root root 4096 Jan  1  1970 bin
lrwxrwxrwx 1 root root   62 Jan  1  1970 lib -> /nix/store/5b625p55ssjcayg8wf31f736d3l2r6s9-marp-cli-4.2.3/lib
dr-xr-xr-x 2 root root 4096 Jan  1  1970 share

$ ls -l /nix/store/mdm9ya8550c5d40b5a81lcvyfyzrav5b-marp_build_tools/bin
total 12
lrwxrwxrwx 1 root root 80 Jan  1  1970 chromium -> /nix/store/0rmxq6cn9kxpz9raqmrs1z25jw2wiz7j-chromium-141.0.7390.107/bin/chromium
lrwxrwxrwx 1 root root 88 Jan  1  1970 chromium-browser -> /nix/store/0rmxq6cn9kxpz9raqmrs1z25jw2wiz7j-chromium-141.0.7390.107/bin/chromium-browser
lrwxrwxrwx 1 root root 67 Jan  1  1970 marp -> /nix/store/5b625p55ssjcayg8wf31f736d3l2r6s9-marp-cli-4.2.3/bin/marp

When Does Cachix Shine?

With the flake.nix example workflow shown here, I couldn't feel the effect of caching.
(46s -> 41s: 10% reduction)

On the other hand, when building node_modules with Nix, caching significantly sped up the build.
(2m 10s -> 51s: 60% reduction)

※ zenn_build is the one that built node_modules.

flake.nix and Workflow

The files used are as follows:

flake.nix
{
  description = "Zenn CLI environment";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
    flake-utils.url = "github:numtide/flake-utils";
  };

  outputs =
    { nixpkgs, flake-utils, ... }:
    flake-utils.lib.eachDefaultSystem (
      system:
      let
        pkgs = nixpkgs.legacyPackages.${system};
        npmRoot = ./node-pkgs;
        nodejs = pkgs.nodejs_24;
        inherit (pkgs) importNpmLock;
        npmDeps = importNpmLock.buildNodeModules {
          inherit nodejs npmRoot;
        };
      in
      rec {
        packages = {
          zenn_tools = pkgs.buildEnv {
            name = "zenn_tools";
            paths = with pkgs; [
              treefmt
              lychee
              npmDeps
            ];
          };
          default = packages.zenn_tools;
        };

        devShells = {
          zenn = pkgs.mkShell {
            nativeBuildInputs = [
              packages.zenn_tools
              pkgs.go-task
              importNpmLock.hooks.linkNodeModulesHook
            ];
            inherit npmDeps;
          };
          node = pkgs.mkShell {
            packages = [
              nodejs
              pkgs.npm-check-updates
            ];
          };
          default = devShells.zenn;
        };
      }
    );
}
build.yml
name: "build"

on:
  pull_request:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  zenn_build:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: zenn

    steps:
      - uses: actions/checkout@v5

      - uses: cachix/install-nix-action@v31

      - uses: cachix/cachix-action@v16
        with:
          name: ryuryu333
          authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'

      - run: nix build

      - run: nix develop -c zenn --version

  marp_build:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: marp

    steps:
      - uses: actions/checkout@v5

      - uses: cachix/install-nix-action@v31

      - uses: cachix/cachix-action@v16
        with:
          name: ryuryu333
          authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'

      - run: nix build

      - run: nix run .#marp -- --version

・First Build
First build

https://github.com/ryuryu333/nix_cache_ci_experiments/actions/runs/18685389246/job/53276514338

・Second Build
Second build

https://github.com/ryuryu333/nix_cache_ci_experiments/actions/runs/18685468935/job/53276790034

Differences in Build Behavior With and Without Cache

Let's look at the build for zenn_build, which builds node_modules, before and after caching.

Without cache, the build process shows these 269 derivations will be built:. After that, it starts downloading with these 464 paths will be fetched.

On the other hand, with cache, there is no build step; it starts with these 677 paths will be fetched.

First Build

copying path '/nix/store/cxm2pydim6pkc7nh5qkbl7q21ipp5bmz-source' from 'https://cache.nixos.org'...
these 269 derivations will be built:
  /nix/store/01a2vbg5i8gbrchg06y104fn5d937f0i-flat-cache-6.1.13.tgz.drv
# ...
these 464 paths will be fetched (265.13 MiB download, 1391.91 MiB unpacked):
  /nix/store/7fini49zkfwf439iqxvm7nzz2v6aclrn-acl-2.3.2
# ...
copying path '/nix/store/ii4q8jj7a9rf92vxdq64camx6d7bmiyr-builder.pl' from 'https://cache.nixos.org'...
# ...
building '/nix/store/zliiyj09fah0nkqahv9mwqyqhf79h5fy-zod-to-json-schema-3.24.6.tgz.drv'...
building '/nix/store/rfif1gkymmc1r3d7a2sx8l0p6695gr1r-zenn-cli-env-1.0.0-sources.drv'...
building '/nix/store/j2mdvv44jyslv0gwsig2wqxzgml9j069-zenn-cli-env-node-modules-1.0.0.drv'...
building '/nix/store/m1l63pbzj4sidc83hazk4rww5lx2yxyr-zenn_tools.drv'...
# Total 1480 lines

Second Build

copying path '/nix/store/cxm2pydim6pkc7nh5qkbl7q21ipp5bmz-source' from 'https://cache.nixos.org'...
these 677 paths will be fetched (166.06 MiB download, 509.45 MiB unpacked):
  /nix/store/gx7nm6qfh215c5c1p00x2b6sqwz1wr09-accepts-2.0.0.tgz
# ...
copying path '/nix/store/vba83965m65n7wglxi4sik53ix3na93h-icu4c-76.1-dev' from 'https://cache.nixos.org'...
copying path '/nix/store/357id3rjy9417k4dkvxxmpgd9bxrwc7l-nodejs-24.5.0' from 'https://cache.nixos.org'...
copying path '/nix/store/irybss8kj23zljz3aravjm0rc03ssf5l-zenn-cli-env-node-modules-1.0.0' from 'https://ryuryu333.cachix.org'...
copying path '/nix/store/26b5qk8dbms05h23wc6qn2vvl0n4fdkv-zenn_tools' from 'https://ryuryu333.cachix.org'...
# Total 1367 lines

Supplementary Note

As a comparison, let's also check marp_build, which uses packages directly from Nixpkgs like pkgs.marp.

Only the first build log is shown. Since only one item is built, it's understandable that caching doesn't provide much speedup.

this derivation will be built:
  /nix/store/xa5vqc5v7ingk0x556qiy38dd18fvbz0-marp_build_tools.drv
these 381 paths will be fetched (437.39 MiB download, 1937.79 MiB unpacked):
  /nix/store/4wzkp02pxxk8kkg3q3197il63pi65m3m-abseil-cpp-20250814.0
  /nix/store/jj3knbpiiwbwmplin208h775gzm86rc3-acl-2.3.2
# ...
copying path '/nix/store/plx9hmh9gbd8s7nbiaijz49501br2vvf-pipewire-1.4.8' from 'https://cache.nixos.org'...
copying path '/nix/store/9lvz6s89kalqzqdwp0d9vg86rf0435jc-openal-soft-1.24.3' from 'https://cache.nixos.org'...
copying path '/nix/store/7sdvkc58p9gfaf8dl4zqlhq1hrd5kqr6-gst-plugins-bad-1.26.5' from 'https://cache.nixos.org'...
copying path '/nix/store/2329310vfm5ivldbrnwp317ijcmzbfzi-gtk4-4.18.6' from 'https://cache.nixos.org'...
copying path '/nix/store/0rmxq6cn9kxpz9raqmrs1z25jw2wiz7j-chromium-141.0.7390.107' from 'https://cache.nixos.org'...
copying path '/nix/store/mdm9ya8550c5d40b5a81lcvyfyzrav5b-marp_build_tools' from 'https://ryuryu333.cachix.org'...
# Total 750 lines

References

https://nix.dev/guides/recipes/continuous-integration-github-actions

https://github.com/cachix/cachix-action

https://www.takeokunn.org/posts/fleeting/20250510192642-use_cachix_in_github_actions/

https://zenn.dev/asa1984/books/nix-introduction/viewer/07-binary-cache

Discussion