Programming Search⌘K

Conceptcore

Package registries

Also called package registry, package index, package repository, artifact repository, private registry, registry mirror, PyPI, crates.io, Maven Central, nuget.org.

A package registry is a server that stores published packages and an index of their versions. Package managers download from it. Mirrors copy it; private registries hold internal packages.

Applies to
core-languages

Idea

A package manager needs a place to get packages from. A package registry is that place: a server that stores the packages that people publish, with the metadata of each version, and that answers the questions of the package manager. npm describes its public registry as "a database of JavaScript packages, each comprised of software and metadata".1 Other names are a package index (PyPI, the Python Package Index), a repository (Maven Central) and a host or feed (NuGet).234

Each tier 1 language has one main public registry:

Language Registry Default client
Python PyPI, pypi.org pip, uv
JavaScript and TypeScript the npm registry, registry.npmjs.org npm
Rust crates.io Cargo
Java and Kotlin Maven Central, repo.maven.apache.org/maven2 Maven
C# nuget.org NuGet, dotnet
Go the module mirror proxy.golang.org, with the site pkg.go.dev the go command

PyPI is "the official package repository for Python".2 pip is the standard client, and tools such as uv also use PyPI as their default source.5 For Rust, "The default registry is crates.io".6 npm "is configured to use the npm public registry at https://registry.npmjs.org by default".7 The official Maven repository is at https://repo.maven.apache.org/maven2.8 NuGet "maintains the central repository of over 100,000 unique packages at nuget.org".4 Go is different: a module lives in its own version control repository, and the default value of GOPROXY is https://proxy.golang.org,direct, so the go command first asks a public module proxy that Google operates.9 The site pkg.go.dev shows documentation for the modules, and its data "is downloaded from proxy.golang.org".10

How it works

A registry has three parts:

  1. Names and versions. A package has a name that is unique on the registry, and each version is a separate release. On PyPI, a project is "a collection of releases and files", and a release has one or more files, for example a source archive and a binary wheel.5 Maven Central uses three coordinates, groupId, artifactId and version, and the groupId starts with a reverse domain name.3
  2. An index. The package manager reads the index to find the versions of a name and their dependencies, without a download of each package. A Cargo registry contains an index, a searchable list of the crates that it has.6 pip reads indexes that comply with "PEP 503 (the simple repository API)".11
  3. A publish API. An author uploads a new version, usually with a token. Cargo uses cargo publish, and a registry "may also provide a web API to support publishing new crates directly from Cargo".6

The main rule of a public registry is that a published version does not change. Then a version number always means the same bytes, and a lock file can record a hash of them. Cargo warns that "a publish is generally permanent. The version can never be overwritten, and the code cannot be deleted".12 Maven Central says: "we do not remove or modify components once they are publicly available".13 On the Go side, "published versions cannot be reused or modified, and this includes retracted versions".10

A broken version is yanked or retracted, not deleted. "The semantics of a yanked version are that no new dependencies can be created against that version, but all existing dependencies continue to work."12 On PyPI, a yanked release "is always ignored by an installer, unless it is the only release that matches a version specifier", with == or ===.14 Go uses a retract directive in go.mod, and a new version that carries it.10

The examples below build a registry in memory. It refuses a second publish of the same version, it yanks a version, and it shows that a new install skips the yanked version while an exact pin still gets it. Then two registries, one internal and one public, have a package with the same name, and the example compares two ways to choose between them.

In languages

LanguageVerdictNote
PythonIdiom
C++IdiomA std::map of std::map and std::optional for the found version. Alternative: The Java example.
JavaIdiom
CIdiomAn array of structs with a name, a version and a yanked flag, and a compare function for versions. Alternative: The Go example.
C#Idiom
JavaScriptIdiomA Map from a name to a Map from a version to a yanked flag, as in Python; npm reads the public registry at registry.npmjs.org. Alternative: The Python example.
TypeScriptIdiomAs in JavaScript, with a type for the map of versions. Alternative: The Go example.
GoIdiom
RustIdiomA HashMap of HashMaps and an Option for the found version; Cargo reads crates.io by default. Alternative: The Go example.
KotlinIdiomA MutableMap of MutableMap and maxWithOrNull with a version comparator; Gradle and Maven read Maven Central. Alternative: The Java example.
SQLIdiomA table of (package, version, yanked) with a primary key on (package, version) refuses a second publish, and a query with ORDER BY finds the newest version. Alternative: The Python example.
BashIdiomAn associative array keyed by package and version, and sort -V for the newest version. Alternative: The Python example.
PowerShellIdiomA hashtable of hashtables and [version] casts to compare versions. Alternative: The C# example.
HTMLDoes not applyMarkup does not store packages.
CSSDoes not applyStyle rules do not store packages.
Regular expressionsDoes not applyA pattern can match a version string, but it does not store or compare versions.

Each example keeps a map from a package name to a map from a version to a yanked flag. Python uses dicts and max with a key function, Go uses maps and slices.Compare on the parts of a version, Java uses HashMap with a Comparator and Optional, and C# uses Dictionary, System.Version.Parse and LINQ MaxBy. The four programs print the same output.

PythonGitHub
# A registry keeps each published version for ever. A yank hides a version from new resolutions only.


def key(version):
    return tuple(int(part) for part in version.split("."))


class Registry:
    def __init__(self, name):
        self.name = name
        self.packages = {}  # package -> version -> yanked

    def publish(self, package, version):
        versions = self.packages.setdefault(package, {})
        if version in versions:
            print(f"publish {self.name}: {package} {version} error: the version exists")
            return
        versions[version] = False
        print(f"publish {self.name}: {package} {version} ok")

    def yank(self, package, version):
        self.packages[package][version] = True
        print(f"yank {self.name}: {package} {version}")

    def index(self, package):
        versions = self.packages.get(package, {})
        parts = [v + (" (yanked)" if versions[v] else "") for v in sorted(versions, key=key)]
        print(f"index of {package}: {', '.join(parts)}")

    def find(self, package, pin=None):
        versions = self.packages.get(package, {})
        if pin is not None:  # an exact pin can still get a yanked version
            return pin if pin in versions else None
        live = [v for v, yanked in versions.items() if not yanked]
        return max(live, key=key, default=None)


def best_match(registries, package):
    found = [(r.find(package), r.name) for r in registries if r.find(package)]
    version, name = max(found, key=lambda pair: key(pair[0]))
    print(f"best match over all indexes: {package} {version} from {name}")


def first_index(registries, package):
    for r in registries:
        version = r.find(package)
        if version is not None:
            print(f"first index with the package: {package} {version} from {r.name}")
            return


public = Registry("public")
public.publish("log", "1.0.0")
public.publish("log", "1.1.0")
public.publish("log", "1.1.0")
public.yank("log", "1.1.0")
public.index("log")
print(f"install log: {public.find('log')}")
print(f"install log ==1.1.0: {public.find('log', '1.1.0')}")

internal = Registry("internal")
internal.publish("billing", "1.0.0")
public.publish("billing", "99.0.0")  # someone takes the same name on the public registry
best_match([internal, public], "billing")
first_index([internal, public], "billing")
Output
publish public: log 1.0.0 ok
publish public: log 1.1.0 ok
publish public: log 1.1.0 error: the version exists
yank public: log 1.1.0
index of log: 1.0.0, 1.1.0 (yanked)
install log: 1.0.0
install log ==1.1.0: 1.1.0
publish internal: billing 1.0.0 ok
publish public: billing 99.0.0 ok
best match over all indexes: billing 99.0.0 from public
first index with the package: billing 1.0.0 from internal
  • Verdict: idiom. A dict of dicts holds the registry, and max with key=key compares versions as tuples of integers, so 1.10.0 sorts after 1.9.0.
  • publish checks for the version first and refuses to overwrite it, as crates.io and Maven Central do.
  • find with a pin returns the pinned version even when it is yanked. Without a pin, it skips yanked versions.
JavaGitHub
// A registry keeps each published version for ever. A yank hides a version from new resolutions only.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class Main {
    static final Comparator<String> BY_VERSION = Comparator.comparing(
            (String v) -> Arrays.stream(v.split("\\.")).mapToInt(Integer::parseInt).toArray(), Arrays::compare);

    static class Registry {
        final String name;
        final Map<String, Map<String, Boolean>> packages = new HashMap<>(); // package -> version -> yanked

        Registry(String name) {
            this.name = name;
        }

        void publish(String pkg, String version) {
            Map<String, Boolean> versions = packages.computeIfAbsent(pkg, k -> new HashMap<>());
            if (versions.containsKey(version)) {
                System.out.printf("publish %s: %s %s error: the version exists%n", name, pkg, version);
                return;
            }
            versions.put(version, false);
            System.out.printf("publish %s: %s %s ok%n", name, pkg, version);
        }

        void yank(String pkg, String version) {
            packages.get(pkg).put(version, true);
            System.out.printf("yank %s: %s %s%n", name, pkg, version);
        }

        void index(String pkg) {
            Map<String, Boolean> versions = packages.getOrDefault(pkg, Map.of());
            List<String> parts = new ArrayList<>();
            versions.keySet().stream().sorted(BY_VERSION)
                    .forEach(v -> parts.add(versions.get(v) ? v + " (yanked)" : v));
            System.out.printf("index of %s: %s%n", pkg, String.join(", ", parts));
        }

        // The newest version that is not yanked.
        Optional<String> find(String pkg) {
            return packages.getOrDefault(pkg, Map.of()).entrySet().stream()
                    .filter(e -> !e.getValue()).map(Map.Entry::getKey).max(BY_VERSION);
        }

        // An exact pin can still get a yanked version.
        Optional<String> find(String pkg, String pin) {
            return packages.getOrDefault(pkg, Map.of()).containsKey(pin) ? Optional.of(pin) : Optional.empty();
        }
    }

    static void bestMatch(List<Registry> registries, String pkg) {
        String version = null, from = null;
        for (Registry r : registries) {
            Optional<String> v = r.find(pkg);
            if (v.isPresent() && (version == null || BY_VERSION.compare(v.get(), version) > 0)) {
                version = v.get();
                from = r.name;
            }
        }
        System.out.printf("best match over all indexes: %s %s from %s%n", pkg, version, from);
    }

    static void firstIndex(List<Registry> registries, String pkg) {
        for (Registry r : registries) {
            Optional<String> v = r.find(pkg);
            if (v.isPresent()) {
                System.out.printf("first index with the package: %s %s from %s%n", pkg, v.get(), r.name);
                return;
            }
        }
    }

    public static void main(String[] args) {
        Registry pub = new Registry("public");
        pub.publish("log", "1.0.0");
        pub.publish("log", "1.1.0");
        pub.publish("log", "1.1.0");
        pub.yank("log", "1.1.0");
        pub.index("log");
        System.out.println("install log: " + pub.find("log").orElse("none"));
        System.out.println("install log ==1.1.0: " + pub.find("log", "1.1.0").orElse("none"));

        Registry internal = new Registry("internal");
        internal.publish("billing", "1.0.0");
        pub.publish("billing", "99.0.0"); // someone takes the same name on the public registry
        List<Registry> registries = List.of(internal, pub);
        bestMatch(registries, "billing");
        firstIndex(registries, "billing");
    }
}
Output
publish public: log 1.0.0 ok
publish public: log 1.1.0 ok
publish public: log 1.1.0 error: the version exists
yank public: log 1.1.0
index of log: 1.0.0, 1.1.0 (yanked)
install log: 1.0.0
install log ==1.1.0: 1.1.0
publish internal: billing 1.0.0 ok
publish public: billing 99.0.0 ok
best match over all indexes: billing 99.0.0 from public
first index with the package: billing 1.0.0 from internal
  • Verdict: idiom. Comparator.comparing with Arrays::compare orders versions by their integer parts, and Stream.max returns an Optional.
  • computeIfAbsent makes the inner map for a new package name, and containsKey refuses a second publish of the same version.
  • Two overloads of find give the newest version that is not yanked, and the pinned version.
// A registry keeps each published version for ever. A yank hides a version from new resolutions only.
var pub = new Registry("public");
pub.Publish("log", "1.0.0");
pub.Publish("log", "1.1.0");
pub.Publish("log", "1.1.0");
pub.Yank("log", "1.1.0");
pub.Index("log");
Console.WriteLine($"install log: {pub.Find("log")}");
Console.WriteLine($"install log ==1.1.0: {pub.Find("log", "1.1.0")}");

var internalRegistry = new Registry("internal");
internalRegistry.Publish("billing", "1.0.0");
pub.Publish("billing", "99.0.0"); // someone takes the same name on the public registry
Registry[] registries = [internalRegistry, pub];
BestMatch(registries, "billing");
FirstIndex(registries, "billing");

static void BestMatch(Registry[] registries, string pkg)
{
    var best = registries
        .Select(r => (Version: r.Find(pkg), r.Name))
        .Where(p => p.Version is not null)
        .MaxBy(p => System.Version.Parse(p.Version!));
    Console.WriteLine($"best match over all indexes: {pkg} {best.Version} from {best.Name}");
}

static void FirstIndex(Registry[] registries, string pkg)
{
    foreach (var r in registries)
    {
        if (r.Find(pkg) is string v)
        {
            Console.WriteLine($"first index with the package: {pkg} {v} from {r.Name}");
            return;
        }
    }
}

class Registry(string name)
{
    public string Name { get; } = name;
    readonly Dictionary<string, Dictionary<string, bool>> packages = []; // package -> version -> yanked

    public void Publish(string pkg, string version)
    {
        if (!packages.TryGetValue(pkg, out var versions))
        {
            versions = [];
            packages[pkg] = versions;
        }
        if (!versions.TryAdd(version, false))
        {
            Console.WriteLine($"publish {Name}: {pkg} {version} error: the version exists");
            return;
        }
        Console.WriteLine($"publish {Name}: {pkg} {version} ok");
    }

    public void Yank(string pkg, string version)
    {
        packages[pkg][version] = true;
        Console.WriteLine($"yank {Name}: {pkg} {version}");
    }

    public void Index(string pkg)
    {
        var versions = packages.GetValueOrDefault(pkg) ?? [];
        var parts = versions.Keys.OrderBy(System.Version.Parse)
            .Select(v => versions[v] ? v + " (yanked)" : v);
        Console.WriteLine($"index of {pkg}: {string.Join(", ", parts)}");
    }

    // The newest version that is not yanked, or the pinned version: an exact pin can still get a yanked version.
    public string? Find(string pkg, string? pin = null)
    {
        var versions = packages.GetValueOrDefault(pkg) ?? [];
        if (pin is not null)
        {
            return versions.ContainsKey(pin) ? pin : null;
        }
        return versions.Where(e => !e.Value).Select(e => e.Key).MaxBy(System.Version.Parse);
    }
}
Output
publish public: log 1.0.0 ok
publish public: log 1.1.0 ok
publish public: log 1.1.0 error: the version exists
yank public: log 1.1.0
index of log: 1.0.0, 1.1.0 (yanked)
install log: 1.0.0
install log ==1.1.0: 1.1.0
publish internal: billing 1.0.0 ok
publish public: billing 99.0.0 ok
best match over all indexes: billing 99.0.0 from public
first index with the package: billing 1.0.0 from internal
  • Verdict: idiom. System.Version.Parse reads a version such as 1.10.0, and LINQ MaxBy and OrderBy compare Version values, not strings.
  • TryAdd returns false when the version exists, so one call both checks and publishes.
  • Find has an optional parameter pin; a pinned version is returned even when it is yanked.
// A registry keeps each published version for ever. A yank hides a version from new resolutions only.
package main

import (
	"fmt"
	"slices"
	"strconv"
	"strings"
)

func key(version string) []int {
	var parts []int
	for _, p := range strings.Split(version, ".") {
		n, _ := strconv.Atoi(p)
		parts = append(parts, n)
	}
	return parts
}

func compare(a, b string) int { return slices.Compare(key(a), key(b)) }

type Registry struct {
	name     string
	packages map[string]map[string]bool // package -> version -> yanked
}

func NewRegistry(name string) *Registry {
	return &Registry{name: name, packages: map[string]map[string]bool{}}
}

func (r *Registry) Publish(pkg, version string) {
	versions, ok := r.packages[pkg]
	if !ok {
		versions = map[string]bool{}
		r.packages[pkg] = versions
	}
	if _, exists := versions[version]; exists {
		fmt.Printf("publish %s: %s %s error: the version exists\n", r.name, pkg, version)
		return
	}
	versions[version] = false
	fmt.Printf("publish %s: %s %s ok\n", r.name, pkg, version)
}

func (r *Registry) Yank(pkg, version string) {
	r.packages[pkg][version] = true
	fmt.Printf("yank %s: %s %s\n", r.name, pkg, version)
}

func (r *Registry) Index(pkg string) {
	versions := r.packages[pkg]
	var all []string
	for v := range versions {
		all = append(all, v)
	}
	slices.SortFunc(all, compare)
	var parts []string
	for _, v := range all {
		if versions[v] {
			v += " (yanked)"
		}
		parts = append(parts, v)
	}
	fmt.Printf("index of %s: %s\n", pkg, strings.Join(parts, ", "))
}

// Find returns the newest version that is not yanked, or the pinned version if pin is not empty.
func (r *Registry) Find(pkg, pin string) string {
	versions := r.packages[pkg]
	if pin != "" { // an exact pin can still get a yanked version
		if _, ok := versions[pin]; ok {
			return pin
		}
		return ""
	}
	best := ""
	for v, yanked := range versions {
		if !yanked && (best == "" || compare(v, best) > 0) {
			best = v
		}
	}
	return best
}

func bestMatch(registries []*Registry, pkg string) {
	version, name := "", ""
	for _, r := range registries {
		if v := r.Find(pkg, ""); v != "" && (version == "" || compare(v, version) > 0) {
			version, name = v, r.name
		}
	}
	fmt.Printf("best match over all indexes: %s %s from %s\n", pkg, version, name)
}

func firstIndex(registries []*Registry, pkg string) {
	for _, r := range registries {
		if v := r.Find(pkg, ""); v != "" {
			fmt.Printf("first index with the package: %s %s from %s\n", pkg, v, r.name)
			return
		}
	}
}

func main() {
	public := NewRegistry("public")
	public.Publish("log", "1.0.0")
	public.Publish("log", "1.1.0")
	public.Publish("log", "1.1.0")
	public.Yank("log", "1.1.0")
	public.Index("log")
	fmt.Printf("install log: %s\n", public.Find("log", ""))
	fmt.Printf("install log ==1.1.0: %s\n", public.Find("log", "1.1.0"))

	internal := NewRegistry("internal")
	internal.Publish("billing", "1.0.0")
	public.Publish("billing", "99.0.0") // someone takes the same name on the public registry
	registries := []*Registry{internal, public}
	bestMatch(registries, "billing")
	firstIndex(registries, "billing")
}
Output
publish public: log 1.0.0 ok
publish public: log 1.1.0 ok
publish public: log 1.1.0 error: the version exists
yank public: log 1.1.0
index of log: 1.0.0, 1.1.0 (yanked)
install log: 1.0.0
install log ==1.1.0: 1.1.0
publish internal: billing 1.0.0 ok
publish public: billing 99.0.0 ok
best match over all indexes: billing 99.0.0 from public
first index with the package: billing 1.0.0 from internal
  • Verdict: idiom. A map from a name to a map from a version to a bool holds the registry, and slices.Compare compares the integer parts of two versions.
  • Go map order is random, so Index sorts the versions with slices.SortFunc before it prints them, and Find keeps the largest version in a loop.
  • Find takes an empty string for no pin, because Go has no optional parameters.
  • Private registries. A company can run its own registry for internal packages. NuGet supports "private hosts alongside the public nuget.org host", in the cloud, on a private network, or "on just your local file system".4 Cargo reads other registries from the table [registries] in .cargo/config.toml, and a dependency selects one with the key registry. But "crates.io does not accept packages that depend on crates from other registries".6
  • Scopes and namespaces. An npm scope groups packages under a name such as @myorg/mypackage. "Each npm user/organization has their own scope, and only you can add packages in your scope."15 A scope can point to a private registry, and "a scope only ever points to one registry".15
  • Mirrors and proxies. A mirror is a copy of a registry, nearer or under your control. Maven gives these reasons for a mirror: a closer and faster server, an internal repository "which you have greater control over", or a repository manager that gives a local cache.8 Cargo can replace crates.io with a mirror or with a local directory, on the assumption that "the source code is exactly the same from both sources".16 With GOPROXY=https://corp.example.com,https://proxy.golang.org, the go command asks the company proxy first and goes to the next entry after a 404 or 410 response.9
  • Unpublish windows. Some registries let you remove a mistake for a short time. On the npm public registry, if no other package depends on it, "you can unpublish anytime within the first 72 hours after publishing".17

Pitfalls

  • Dependency confusion. When a tool reads more than one index, an attacker can publish a public package with the name of your private package and a higher version. pip searches all its locations with "no priority", and its documentation says that the use of --extra-index-url for private packages is unsafe.11 uv by default stops "at the first index on which a given package is available", to prevent dependency confusion.18 NuGet gives Package Source Mapping, which can "filter, per package, which source(s) NuGet will search".19 The example shows both rules: the best match over all indexes takes the attacker's billing 99.0.0, and the first index rule takes the internal billing 1.0.0.
  • Typosquatting. "An attacker publishes a malicious project with a name that is a common misspelling of a popular, legitimate project".20 Check the name before you add a package, and install from a pinned requirements file or a lock file.20
  • Deleted and yanked versions. Do not plan to delete a bad release. Publish a new version with the fix; Maven Central suggests a patch release.13 Yank or retract the bad one, so that new resolutions skip it.1210
  • Mirrors that differ. A mirror that is not exact breaks reproducible builds. Maven warns that the known mirrors of Maven Central "may not have the same contents".8 Hashes in a lock file find such a difference.

Cost

A request to a registry costs a network round trip, and a resolution can need the index entry of each package in the tree. Package managers keep a local cache for this reason, and a mirror near the build machines cuts the time of each install. A private registry costs the work to run it, to back it up and to control its tokens.

History

The Comprehensive Perl Archive Network (CPAN) "has been online since October 1995".21 npm added scoped packages in npm 2, and the primary npm registry has supported them since 2015-04-19.15 Today each tier 1 language has a main registry, and Go downloads modules through a module proxy and checks them with the checksum database sum.golang.org.263497

References

  1. npm Docs, About the public npm registry, the first paragraph
  2. PyPI User Documentation, Welcome to PyPI's user documentation, the first paragraph
  3. Maven Central Documentation, Requirements, Correct Coordinates
  4. Microsoft Learn, An introduction to NuGet, the introduction; The flow of packages between creators, hosts, and consumers
  5. PyPI User Documentation, PyPI Basics, Projects, releases and files (packages) on PyPI
  6. The Cargo Book, Registries, the introduction; Using an Alternate Registry
  7. npm Docs (v11), registry, Description
  8. Maven, Using Mirrors for Repositories, the introduction; the note on the official Maven repository
  9. Go Modules Reference, Module proxies; Environment variables
  10. pkg.go.dev, About, Adding a package; Removing a package
  11. pip documentation, pip install, Package Index Options; Examples
  12. The Cargo Book, Publishing on crates.io, the introduction; cargo yank
  13. Maven Central Documentation, Immutability of Published Components, the first paragraphs
  14. PyPI User Documentation, Yanking, the first paragraphs
  15. npm Docs (v11), scope, Description; Publishing scoped packages; Associating a scope with a registry
  16. The Cargo Book, Source Replacement, the introduction
  17. npm Docs, npm Unpublish Policy, Packages published less than 72 hours ago
  18. uv documentation, Package indexes, Searching across multiple indexes
  19. Microsoft Learn, Package Source Mapping, the introduction; Package Pattern precedence
  20. PyPI User Documentation, Common attacks, Typosquatting; Dependency confusion
  21. The Comprehensive Perl Archive Network (CPAN), Welcome to CPAN

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/E4S2X3/text.yaml