解决 GitHub Actions 报错 Failed to save cache reserve already exists 缓存冲突修复
排查 actions/cache 在工作流结束尝试保存缓存时报错 Failed to save: ReserveCacheError: Another job has reserved this cache key,分析 并发矩阵构建(Matrix)共享相同 cache-key 导致的竞争锁。
问题现象
配置了多平台矩阵构建(Matrix Build)的工作流在执行完成后,部分任务报错警告:
Post job cleanup.
Warning: Failed to save: ReserveCacheError: Another job has reserved this cache key: npm-cache-Linux-package-lock.hash44120
Cache not saved.
触发根因
- 矩阵中的多个并行 Job(如不同的 Node 版本或不同系统)使用了完全相同的静态
key字符串计算缓存; - 先完成的 Job 已经成功向 GitHub 缓存服务器申请并预留了该 Key 的写入锁(Reserve Cache);
- 后完成的并行 Job 尝试提交时被判定冲突拒绝覆盖。
解决步骤
在 actions/cache 的 key 计算表达式中嵌入矩阵变量保持唯一性
确保各个并发 Job 的缓存键绝对隔离:
- name: Cache Node modules
uses: actions/cache@v4
with:
path: ~/.npm
# 关键:将 runner.os 与 matrix.node-version 融入 key 中
key: ${{ runner.os }}-node-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-${{ matrix.node-version }}-
${{ runner.os }}-node-
确保 restore-keys 提供优雅降级匹配
即便具体依赖哈希未命中也能重用基础包依赖,大幅提升下载速度。
验证确认
重新触发矩阵流水线:
各个维度的并行构建各自拥有专属缓存插槽,缓存保存 100% 成功,后续流水线命中率稳定在 95% 以上。


