Skip to content
rusthacks.dev

Cargo Lock Explained and Whether to Commit It for New Code

Commit Cargo.lock for applications and, per current Cargo guidance, for libraries too. See what the file records, how cargo update changes it and what --locked does in CI.

6 min read
Summarize in AI
Flat illustration for the post “Cargo Lock Explained and Whether to Commit It for New Code”, composed around cargo.

The old advice was "commit Cargo.lock for binaries, ignore it for libraries". Cargo's own FAQ dropped that line, and the reason it changed is worth understanding, because the lockfile decides whether the build you tested is the build you ship. This post shows what the file contains, what happens to a project without it, and when leaving it out is still defensible.

The examples ran on Cargo 1.99 with edition 2024; the lockfile excerpts come from a crate depending on rand 0.9.

What the file records

Cargo.toml states what you will accept: rand = "0.9" means any 0.9.x. Cargo.lock records what Cargo actually chose the last time it resolved, down to a checksum. Generate one and read it:

Cargo.tomlTOML
[package]
name = "dice"
version = "0.1.0"
edition = "2024"

[dependencies]
rand = "0.9"
src/main.rsrust
use rand::Rng;

fn main() {
    let roll: u8 = rand::rng().random_range(1..=6);
    println!("rolled {roll}");
}
Shell
cargo build
grep -A3 'name = "rand"' Cargo.lock
Text
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"

Each entry has the exact version, where it came from, and a SHA-256 of the downloaded archive. Cargo refuses to build if the archive on the registry no longer matches, which is a cheap defence against a tampered download. The file also lists, for every package, which other packages it depends on, so the whole graph is reproducible without consulting the registry again.

The failure the lockfile prevents

Without a committed lockfile, two builds of the same commit can differ. A transitive dependency publishes a patch release on Tuesday; your CI, resolving fresh, picks it up; your laptop, with a stale local lockfile, does not. When the patch is correct, nobody notices. When it is not, the symptom is a build that is red on one machine and green on another, with no change in your code to blame.

You can see Cargo's willingness to move by deleting the lock and re-resolving:

Shell
cp Cargo.lock Cargo.lock.before
rm Cargo.lock
cargo generate-lockfile
diff Cargo.lock.before Cargo.lock

An empty diff means nothing newer was available. A non-empty one lists every crate that would have changed under you if the lockfile had not existed. Run it on a project that has been idle for six months and the diff is usually long.

Why the library advice went away

The argument for ignoring the lock in a library was that downstream users do not use your lockfile: when someone depends on your crate, Cargo resolves from their lockfile and ignores yours. That is true, and it is the only thing the argument got right. It overlooked who else builds your library: you, your CI and your contributors. If none of you share a lockfile, each one tests a slightly different dependency set, and a regression in a dependency is reported by a stranger rather than caught in your pipeline.

The current guidance in the Cargo documentation is to commit it for new code whichever kind of crate it is, and to treat the question as one of tradeoffs for older projects. The one real cost is churn in the diff when dependencies update, which a scheduled update job turns into a reviewable pull request rather than noise.

Using the lock in CI

A lockfile only protects you if the build is not allowed to rewrite it. --locked makes Cargo fail when the lock and the manifest disagree, instead of quietly fixing it:

Shell
cargo build --locked
cargo test --locked

Edit Cargo.toml to require rand = "0.10", forget to update the lock, and the CI command stops:

Text
error: the lock file /work/dice/Cargo.lock needs to be updated but --locked was passed to prevent this
If you want to try to generate the lock file without accessing the network, remove the --locked flag and use --offline instead.

That error is the feature working. It means someone changed a requirement without committing the resolution that goes with it. --frozen goes further and also forbids network access, which suits air-gapped builds that use vendored sources.

Updating on purpose

With the lock committed, upgrades become deliberate acts you can review:

Shell
cargo update                  # every dependency, within its requirements
cargo update -p rand          # only rand and what it forces
cargo update -p rand --precise 0.9.1   # pin to an exact version
cargo update --dry-run        # show the plan, change nothing

Cargo prints each change as Updating rand v0.9.4 -> v0.9.5, so the pull request description writes itself. Updates are limited by the requirements in Cargo.toml: to cross a major version you edit the manifest first.

Reading a lockfile diff in review

A dependency update pull request is only worth merging if a reviewer can read it. The lockfile diff is the evidence, and most of it is mechanical, so look for three things. A changed version line is the update itself. A changed checksum with no version change is suspicious: the registry content for a published version should never change, so that means a yanked-and-republished crate, a different source, or a bad merge. And a new [[package]] block that nobody asked for means a dependency gained a dependency, which is a supply chain change you should read about even if the code compiles.

An illustrative excerpt of that kind of diff:

Diff
 [[package]]
 name = "rand"
-version = "0.9.4"
+version = "0.9.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "..."
+checksum = "..."
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.27"

The added block in that diff is the one to chase. cargo tree -i zerocopy-derive prints who now pulls it in, and cargo tree -d lists any crate that now appears at two versions, which is the other common side effect of an update.

Workspaces share one lockfile

In a workspace there is a single Cargo.lock at the root, covering every member. That is why a library inside a workspace with a binary gets a lockfile whether or not it asked for one, and why changing a dependency in one member can move the version every other member builds against. If members really need independent resolutions, they belong in separate workspaces.

Merge conflicts in the file

Two branches that each add a dependency will conflict in Cargo.lock. Do not resolve it by hand. Take either side, or delete the markers, and let Cargo rebuild the file:

Shell
git checkout --theirs Cargo.lock
cargo metadata --format-version 1 > /dev/null
git add Cargo.lock

Cargo reconciles the file with both branches' manifests and keeps every version that is still valid, so the result is a minimal diff rather than a fresh resolution.

When leaving it out is reasonable

There are honest reasons to ignore the file. A library with a wide matrix test, one that deliberately builds against the newest of everything each night to catch breakage early, wants a fresh resolution every time; committing a lock would hide exactly the failures it is looking for. A workspace of many small crates inside a monorepo might keep one lock at the root, which Cargo does by default, and never commit per-crate ones. And a throwaway experiment does not need the ceremony.

The rule that survives all of this: whichever you choose, choose it for the whole project, write it in the contributing guide, and run one CI job that does the opposite. A project that commits the lock should have a nightly job that runs cargo update && cargo test; a project that ignores it should have a job with --locked against a known good copy. Without the second job you are not choosing a policy, you are leaving one to chance.

What a lockfile does not do

It does not protect you from a malicious version that was already published when you locked. It does not pin the compiler, so pair it with a declared MSRV or a rust-toolchain.toml. And it does not replace auditing: a lockfile makes a vulnerable version reproducible just as faithfully as a safe one.

Also inTooling
Share

Keep reading

Flat illustration for the post “Incident Response for Rust Services a Short Runbook”, composed around deploy.
DevOps

Incident Response for Rust Services a Short Runbook

A one-page runbook for when a Rust service misbehaves: stabilize first, check recent changes, read the four golden signals, find the failing dependency, and use the Rust-specific evidence: panics, memory, executor stalls.

4 min read
Flat illustration for the post “Debugging Async Backtraces and Task Dumps in Tokio”, composed around async.
Tooling

Debugging Async Backtraces and Task Dumps in Tokio

A hung async service has no useful thread backtrace. Tokio task dumps capture the await stack of every task. Enable tokio_unstable and taskdump, trigger a dump from a signal or endpoint, and read where each task is parked.

4 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.