Dependency-Aware Software Package Manager: Resolve, Install, Roll Back
System DesignModel answerLast updated
Design a client-side package manager that resolves versioned dependencies, rejects cycles and conflicts, and applies installs transactionally with recovery after failure.
Problem
You are asked to design a tool in the spirit of apt, npm or pip. It installs, upgrades and removes software packages, and it must leave the machine in a healthy, consistent state after every operation, including when an operation fails midway.
What the tool must do
- Transitive resolution. Given a package name and version, work out every package it needs, directly or indirectly.
- Version constraints. Understand requirements such as
A >= 1.2.0orB < 2.0.0. - Conflict detection. Refuse an installation when two requirements demand incompatible versions of the same package.
- Cycle detection. Reject circular dependencies (A needs B, B needs A) and report them clearly.
- Atomicity. If an install breaks partway, there must be a way to return to the last known good state.
Quality targets
- Scale: thousands of packages in play and deep dependency chains.
- Speed: keep the time between the user's command and the first download as short as possible.
What to cover in your answer
- How package metadata and versions are stored.
- The in-memory graph model and how it supports cycle and conflict detection.
- The algorithm that picks a valid set of versions (backtracking, SAT, or something else), and its trade-offs.
- How you handle partially applied installs and protect system integrity.
State your assumptions (single machine vs. fleet, one version per package vs. several, and so on) before you start.
Hints
Hint 1
Separate the work into a pure planning phase (compute the final set and ordered actions) and an execution phase (download, verify, apply). Planning should touch nothing on disk.
Hint 2
Version selection with conflicting constraints is NP-complete in general. Think about a backtracking search with good heuristics, then about how conflict-driven learning (as in PubGrub or SAT solvers) avoids repeating doomed branches.
Hint 3
For atomicity, think like a database: take a lock, write a journal entry first, stage everything off to the side, then switch it into place with atomic renames, and use the journal to finish or undo after a crash.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
Three ideas matter most: dependency resolution is a hard search problem, planning must be separated from execution, and a multi-file filesystem change must behave like a database transaction. I would state these early and spend most of the time on the resolver and on atomicity.
1. Assumptions and scale
- A single-machine client talks to a remote registry, and the hard parts are client-side.
- The registry holds about 10^5 to 10^6 packages with roughly 10 to 100 versions each. A typical install touches 50 to 2,000 transitive packages, with depth up to about 30.
- Resolution should finish in 1 to 2 seconds for typical installs. Downloads are I/O-bound and parallel.
- Semantic versioning with range operators (
>=,<,^,~). - One version per package per environment (apt/pip style). This is what makes conflicts possible; a nested model like npm's sidesteps many of them at the cost of duplication.
- Each install is marked explicit (user asked) or automatic (pulled in), so removal can clean up orphans.
2. Interface
install(specs) remove(names) upgrade(names)
plan(specs) -> Plan # dry run
rollback(generation)
Every mutating command is plan() then execute(plan). The dry run is a useful feature in itself and keeps the resolver pure and easy to test.
3. Data model
Registry (immutable once published):
Package(name, owners)
Version(name, semver, deps[(name, constraint)], artifact_url, sha256, size, signature, yanked)
Serve metadata per package (for example /index/<name>.json) so the client fetches only what it needs, lazily and in parallel, instead of a monolithic index. Artifacts sit behind a CDN.
Local state (SQLite plus a file lock):
installed(name, version, explicit, generation)files(name, path, hash)for clean removal and integrity checksreverse_deps(name -> dependents)to block unsafe removalsjournal(txn_id, state, actions)as a write-ahead log
4. Graph model and cycle detection
- Nodes are concrete
(name, version)pairs; edges go from dependent to dependency. During search, constraints live on edges; after resolution the result is a plain DAG. - Cycle detection: DFS with three colors (a gray-to-gray edge is a cycle) or Kahn's algorithm (fewer than V nodes emitted means a cycle). Kahn's also yields the install order, dependencies first. Removal uses the reverse order.
- Always report the actual path (
A -> B -> A), not just "cycle found". - Nodes at the same topological level are independent and can be unpacked in parallel.
5. Resolution algorithm
Choosing versions under conflicting constraints reduces to SAT, so there is no fast worst-case algorithm. The job is choosing good heuristics.
Baseline backtracking:
- Keep the current assignment and the set of constraints per package.
- Pick the most constrained unresolved package (fewest candidate versions).
- Try candidates newest-first, but prefer the already-installed version to minimize churn.
- On choosing a version, merge its dependency constraints into the existing ones. An empty intersection is a conflict, so backtrack.
def resolve(assign, constraints):
pending = [n for n in constraints if n not in assign]
if not pending:
return assign
name = min(pending, key=lambda n: len(candidates(n, constraints[n])))
for v in candidates(name, constraints[name]): # newest first
merged = merge(constraints, deps_of(name, v))
if merged is not None:
r = resolve({**assign, name: v}, merged)
if r:
return r
return None
Production upgrade: conflict-driven clause learning. Naive backtracking can thrash, retrying the same bad combination in many branches. PubGrub (Dart, Poetry, uv) and SAT solvers such as libsolv record why a conflict occurred (for example "web 1.x needs db < 2, but app needs db >= 2") and backjump past irrelevant decisions. PubGrub also generates readable explanations, which makes conflict detection a user-facing feature.
Performance levers:
- Prefetch metadata for candidate dependencies concurrently with the solver.
- Cache metadata locally and revalidate with ETags.
- Use lockfiles: if a lockfile pins an exact set with hashes, skip solving and just verify.
- Ignore yanked versions unless pinned.
6. Atomicity and failure handling
Goal: after any failure, even power loss, the system is in the old state or the new state, never in between.
- Lock the state DB so only one mutator runs.
- Journal the full plan as
txn=N PENDING. - Download and verify all artifacts (hash and signature) into a staging directory. Nothing live is touched, and most failures (network, bad hash, full disk) happen here and cost nothing to abort. Check free disk space up front.
- Stage: unpack into the staging area and back up every file that will be overwritten or deleted.
- Commit: move staged files into place with
rename()(atomic within a filesystem), update the state DB in one DB transaction, and mark the journalCOMMITTED. - Cleanup: delete backups and staging only after commit.
Recovery: on the next start, inspect the journal. A PENDING transaction with no commit marker is rolled back from the backups; a transaction marked committed but not cleaned up is simply finished. Every step must be idempotent.
Stronger option: an immutable, generation-based layout (Nix or ostree style). Each generation is a directory tree, and a single atomic symlink swap activates it. Rollback is then swapping the symlink back, and rollback(generation) is trivial. The cost is more disk space and some dedup machinery.
Maintenance scripts (post-install hooks) are the hard case because they can have side effects outside the managed files. Run them last, keep them idempotent, and treat failure as a reason to roll back where possible.
7. Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Single version per package | Simple, small footprint | Real conflicts possible |
| Nested versions | Few conflicts | Duplication, harder security patching |
| Simple backtracking | Easy to build | Exponential on bad inputs |
| CDCL / PubGrub | Robust, good errors | Complex to implement |
| Journal + rename | Works on any filesystem | Backup space, careful recovery code |
| Generation symlinks | Instant rollback | More disk use |
8. Common mistakes
- Resolving and downloading in an interleaved fashion, so a conflict is found after gigabytes are fetched.
- Reporting "conflict" with no explanation of which requirements clash.
- Forgetting reverse dependencies on removal, which breaks other packages.
- Not verifying hashes or signatures before unpacking.
- Treating rollback as an afterthought rather than designing the journal first.
- Ignoring concurrent invocations (no lock).
- Failing to handle the same package reached through several paths with different constraints (diamond dependencies).
9. Likely follow-ups
- Optional and platform-specific dependencies, and virtual packages ("provides").
- Pre-release versions and how ranges treat them.
- Supply-chain defenses: signed metadata, transparency logs, pinned hashes.
- Making resolution reproducible and deterministic across machines.