Distributed Container Image Registry
Medium · System Design · Software Engineer · Technical Screen
Prompt
Architect a distributed container registry service where developers, CI runners, and cluster nodes publish and download container images at global scale. Every container image consists of a lightweight JSON manifest alongside an ordered list of compressed filesystem layer archives.
Functional Requirements
- Image Publishing (
push): Clients upload any missing binary layer archives and register a JSON manifest linking those layers together. - Tag & Digest Retrieval (
pull): Clients fetch images either by a mutable tag (such asbilling/worker:2.4orbilling/worker:stable) or by an immutableSHA-256content digest. - Cross-Image Deduplication: Whenever two images or repositories incorporate identical layer bytes, the storage backend must persist a single physical copy.
Non-Functional & Scale Requirements
- Read Availability: Image pulls sit on the critical path of production autoscaling and rollouts and must remain highly available.
- Multi-Gigabyte Layer Resilience: Individual machine-learning or OS layers can span multiple gigabytes; transfers must tolerate network drops without restarting from scratch.
- Metadata Integrity: Metadata updates must be strongly consistent so published manifests never point to incomplete, corrupted, or deleted layers.
- Target Scale: Tens of millions of manifests and several petabytes of binary layers, with steep traffic spikes during business-hour CI/CD waves and fleet-wide deployments.
Illustrative Workflow (billing/worker:2.4)
- Publishing: The CLI checks which layer digests already exist -> skips an existing
750 MBbase runtime layer -> uploads a new18 MBapplication archive -> commits the2.4manifest linking both digests. - Fetching: A cluster node resolves
billing/worker:2.4-> receives the signed/verified manifest JSON -> downloads only the layer digests not already cached on disk.
Scope & Expectations
- Metadata & Blob Data Model: Define how repositories, mutable tags, manifests, and content-addressed binary blobs are represented and separated across storage tiers.
- Upload & Download APIs: Specify the core HTTP endpoints for existence checks, resumable chunked layer uploads, manifest registration, and tag/digest pulls.
- Read-Path Scaling & Geo-Distribution: Explain how the architecture absorbs massive concurrent read bursts and minimizes cross-region egress bandwidth.
- Consistency & Storage Reclamation: Detail how concurrent pushes, tag mutations, and background cleanup of unreferenced blobs stay race-free.
Step-by-step walkthrough
Clarify requirements and scope
Before drawing servers, let us make sure the building blocks of a container image are crystal clear:
- Layer blob: a compressed archive file (such as
.tar.gzor.tar.zst) containing the filesystem changes from one build step — for example, installing Linux packages or copying compiled application code. - Config blob: a small JSON file storing runtime settings such as environment variables, working directory, and startup command.
- Manifest: a small JSON "table of contents" (typically 1–10 KB) that lists one config blob and an ordered list of layer blobs that make up an image. A multi-architecture index manifest (also called a manifest list) is a parent JSON document pointing to platform-specific manifests (
linux/amd64,linux/arm64) so one image name works on both Intel servers and ARM machines. - Digest: the cryptographic SHA-256 hash (
sha256:9f86d08..., a 256-bit fingerprint computed over exact bytes) that names every blob and every manifest. Changing even a single bit produces a completely different digest. - Tag: a human-readable, movable pointer such as
billing/worker:stableorbilling/worker:2.4that points to one manifest digest inside a repository.
Almost the entire architecture follows from one observation: blobs and manifests are completely immutable (never edited once written), while tags are the only mutable pointers.
Functional requirements
- Push images: upload missing layer and config blobs, upload the manifest, and optionally move or create a tag pointing to that manifest.
- Pull images by tag or by digest: resolve the tag (if given) to a manifest digest, fetch the manifest JSON, and download any layer blobs the client machine does not already have locally.
- Cross-repository deduplication: if two images or two teams use the exact same layer bytes, store those bytes once globally while keeping repository permissions isolated.
- Resumable large uploads, listing tags, and deleting tags/manifests: support interrupted multi-gigabyte uploads, paginated tag listings, and safe cleanup of unreferenced data.
Non-functional requirements and scope assumptions
- High pull availability (
99.99%): a failed pull breaks production autoscaling and CI/CD pipelines, so reads must degrade gracefully even during control-plane hiccups. - Large binary resilience: individual ML/CUDA layers can reach
5–20 GB, so uploads and downloads must resume cleanly across dropped connections. - Strong metadata consistency: a manifest must never become visible before every blob it references is durably stored, and garbage collection must never delete a blob that a concurrent push is linking.
- End-to-end byte integrity: every byte stored and served must match its SHA-256 digest.
- Assumed scope: clients speak the standard OCI Distribution Specification (the open HTTP protocol used by
docker,containerd, and Kubernetes), both public and private repositories exist with RBAC (Role-Based Access Control — granting read/write permissions based on user or robot roles), and traffic spans multiple geographic regions. Image building and vulnerability scanning run asynchronously off push events and are outside core registry storage.
- Layer blob: a compressed archive file (such as
Back-of-the-envelope numbers
Let us convert our target scale — multi-petabyte blob storage, tens of millions of manifests, and bursty CI/CD build waves — into concrete traffic and storage numbers so the bottlenecks jump out.
Scale assumptions repositories 5M manifests 60M tags: 100M unique blobs 150M, average ~30 MB compressed -> 150M x 30 MB = ~4.5 PB stored once daily pushes 2M manifest PUTs/day, averaging ~1 brand-new layer (~20 MB) per push (the other ~7-9 base layers already exist and are deduplicated) daily pulls 300M manifest GETs/day, 100M blob downloads/day (local node caches skip repeats) peak-to-average ratio 5x during business-hour CI/CD build storms Metadata storage (rough row sizes) blobs 150M x 200 B = 30 GB manifests (raw JSON) 60M x 4 KB = 240 GB manifest -> child edges 60M x 8 x 80 B = 38.4 GB tags 100M x 150 B = 15 GB repository -> blob links 600M x 60 B = 36 GB total metadata ~360 GB + indexes = < 0.8 TB -> fits comfortably in a small SQL cluster Throughput and bandwidth manifest GETs 300M / 86,400 s = ~3,500/s average, ~17,500/s peak blob GETs 100M / 86,400 s = ~1,200/s average, ~6,000/s peak blob egress bandwidth 100M x 30 MB = 3 PB/day; peak 6,000/s x 30 MB = 180 GB/s (~1.44 Tbps!) manifest PUTs 2M / 86,400 s = ~23/s average, ~120/s peak HEAD blob checks on push ~10 layers/push = ~1,200/s peak daily new blob bytes 2M x 20 MB = 40 TB/day -> ~14.6 PB/year if never garbage-collected Single large layer upload time 5 GB at 100 MB/s ~50 seconds; at 10 MB/s Wi-Fi: ~8.3 minutes -> mid-upload drops are routineFour design decisions fall straight out of this math:
- Blob bytes must never flow through the API servers on pulls. Serving
1.44 Tbpsthrough application servers would require hundreds of bandwidth-bound machines. Instead, API servers check permissions and return an HTTP redirect to a CDN (Content Delivery Network — edge cache servers distributed close to users) backed by regional object storage. - Metadata is tiny (
< 1 TB) and write-light (~120 manifest PUTs/speak). We do not need to sacrifice ACID transactions for eventual consistency; a strongly consistent SQL database handles this write rate effortlessly. - Almost all reads are immutable. Manifests and blobs fetched by
sha256:...never change and can be cached aggressively without staleness bugs; onlytag -> digestlookups can go stale. - Garbage collection is mandatory. At
40 TB/dayof newly built CI layers, unreferenced layers would add~15 PB/yearof wasted storage cost.
- Blob bytes must never flow through the API servers on pulls. Serving
API design
Following the standard OCI
/v2/HTTP protocol ensures standarddockerand Kubernetes clients work out of the box. Here<name>is a repository path likebilling/worker, and<digest>issha256:<64 hex chars>.Authentication handshake GET /v2/ 200 if token valid; else 401 + WWW-Authenticate challenge Blob existence, download, and resumable upload HEAD /v2/<name>/blobs/<digest> 200 + Content-Length if linked to <name>, else 404 GET /v2/<name>/blobs/<digest> 307 Temporary Redirect -> short-lived signed CDN URL POST /v2/<name>/blobs/uploads/ Start upload session -> 202 Accepted, Location: /v2/<name>/blobs/uploads/<upload_id>, OCI-Chunk-Min-Length: 5242880 POST /v2/<name>/blobs/uploads/?mount=<digest>&from=<other-repo> Cross-repo deduplication -> 201 Created (linked, 0 bytes sent) or 202 Accepted (not found / unauthorized -> fall back to upload) PATCH /v2/<name>/blobs/uploads/<upload_id> Upload byte chunk with Content-Range: 0-67108863 -> 202 Accepted, Range: 0-67108863 (inclusive last durable byte) GET /v2/<name>/blobs/uploads/<upload_id> Query progress after disconnect -> 204, Range: 0-<end_byte> PUT /v2/<name>/blobs/uploads/<upload_id>?digest=<digest> Finalize (optionally carrying final chunk) -> 201 Created, Docker-Content-Digest: <digest> DELETE /v2/<name>/blobs/uploads/<upload_id> Cancel and discard in-progress upload Manifest and tag endpoints PUT /v2/<name>/manifests/<tag-or-digest> Verify child blobs exist, store manifest, update tag -> 201 GET /v2/<name>/manifests/<tag-or-digest> Return raw manifest JSON + Docker-Content-Digest header HEAD /v2/<name>/manifests/<tag-or-digest> Return digest + size headers without body GET /v2/<name>/tags/list?n=100&last=<tag> Cursor-paginated tag list (sorted lexicographically) DELETE /v2/<name>/manifests/<digest> Unlink manifest (and tags pointing to it) from <name>Here is how a concrete two-layer
docker push billing/worker:2.4flows over those endpoints when the750 MBbase runtime layer already exists inlibrary/python:Client Registry API |--- HEAD /v2/billing/worker/blobs/sha256:base -->| 404 Not Found (billing/worker doesn't link it yet) |--- POST .../uploads/?mount=sha256:base | | &from=library/python ------------------>| Caller can pull library/python & push billing/worker: |<-- 201 Created ---------------------------------| Inserts repo_blobs(billing/worker, sha256:base); 0 bytes uploaded! |--- HEAD /v2/billing/worker/blobs/sha256:app24 ->| 404 Not Found (brand-new 18 MB layer) |--- POST /v2/billing/worker/blobs/uploads/ ----->| 202 Accepted, Location: .../uploads/u-99 |--- PATCH .../uploads/u-99 (18 MiB) ------------>| 202 Accepted, Range: 0-18874367 |--- PUT .../uploads/u-99?digest=sha256:app24 --->| Verifies SHA-256 == app24 -> 201 Created |--- PUT /v2/billing/worker/manifests/2.4 ------->| Checks base & app24 active, writes manifest + tag '2.4' -> 201Data model and storage strategy
Separating small, strongly consistent metadata from massive immutable blobs calls for a split storage architecture: small, relational metadata lives in a horizontally scalable distributed SQL database (such as CockroachDB or Google Spanner, which provides ACID transactions across shards), while large binary layers live in regional object storage (such as Amazon S3 or GCS).
Both blobs and manifests use content-addressable storage (CAS) — a storage pattern where every item's primary key is the cryptographic SHA-256 hash of its own bytes rather than a user-chosen file path.
Distributed SQL metadata tables repositories repo_id PK, name UNIQUE, namespace_id, visibility (public | private), immutable_tags BOOL, retention_days INT, created_at blobs digest PK, size_bytes, media_type, state ('active' | 'pending_delete' | 'deleting'), created_at, last_linked_at, pending_since blob_locations (digest, region) PK, storage_key, verified_at repo_blobs (repo_id, digest) PK, created_at -- authorization link proving <repo_id> is allowed to read <digest> manifests digest PK, media_type, size_bytes, raw_body BYTES (<= 4 MiB), created_at manifest_refs (manifest_digest, child_digest) PK, child_kind ('config' | 'layer' | 'manifest') INDEX idx_child (child_digest) repo_manifests (repo_id, manifest_digest) PK, pushed_at, pushed_by, last_pulled_at tags (repo_id, tag_name) PK, manifest_digest, version BIGINT, updated_at uploads upload_id PK, repo_id, region, storage_key, multipart_id, bytes_stored BIGINT, parts JSONB, sha256_state BYTES, expires_at Regional object storage (one bucket per region) uploads/<upload_id> raw layer bytes uploaded during session <upload_id>; kept in place once verifiedEvery table solves a specific correctness or performance trap:
- Global deduplication with per-repository isolation (
blobs+repo_blobs):blobsstores one global record perdigest, giving instant deduplication across all 5 million repositories. However, simply checking whetherdigestexists inblobson aGETwould let an attacker who guesses or leaks a SHA-256 hash download a private layer! Checkingrepo_blobs(repo_id, digest)enforces that a blob is readable through<name>only after someone legitimately uploaded or mounted it into<name>. - Zero-copy upload commit via
blob_locations: Object stores like S3 have no cheaprename()— changing a key fromuploads/u-99toblobs/sha256:abcrequires copying all5 GBand deleting the original. Storingstorage_key = 'uploads/u-99'inblob_locations(digest, region)turns upload finalization into a 1-millisecond SQLINSERTwith zero byte copying. - Exact
raw_bodyfor manifests: A manifest's SHA-256 digest is computed over the exact UTF-8 bytes uploaded by the client. Parsing JSON into columns and re-serializing it onGETwould alter whitespace or key order and break every client's digest verification. - Edge table (
manifest_refs) instead of aref_countinteger onblobs: Ifblobskept aref_countcolumn, every concurrent push building onubuntu:24.04would executeUPDATE blobs SET ref_count = ref_count + 1on the exact same base-layer row, queuing behind an exclusive row lock. Inserting(new_manifest_digest, base_layer_digest)intomanifest_refsinserts a brand-new row with only a shared read lock onblobs, and never suffers from permanent counter drift if a bug occurs.
- Global deduplication with per-repository isolation (
High-level architecture
Clients (docker CLI, CI runners, Kubernetes kubelets) | ^ | Small HTTP metadata & upload chunks | Heavy blob GETs (Range-capable) v | [ Geo-DNS / Anycast -> nearest region ] [ Global CDN Edge ] | (validates URL signature; v caches by digest, ignoring token) +--------------|-- Region (e.g. us-east, eu-west, ap-northeast) --^----------------+ | v | | | [ L7 Load Balancer ] (consistent-hash affinity on upload_id) | | | | | | | v [ Regional Origin Shield ] | | [ Stateless Registry API ] <--> [ Auth / Token Service ] | | | | | | (issues 5-min RBAC JWTs) | | | | | +-----> [ Redis Cache ] | | | | | - manifest by digest | | | | | - tag -> digest (5-30s TTL) | | | | | - repo_blobs existence | | | | v v | | | [ Distributed SQL Metadata ] [ Regional Blob Origin ] | | | (multi-region leaders + | | | | local read replicas) v | | +-----------------------------------> [ Regional Object Store ] | | ^ | | [ GC Workers ] [ Upload Reaper ] +-- [ Cross-Region Replicator ] | | [ Event Outbox -> Webhooks / Vulnerability Scanners ] | +----------------------------------------------------------------------------------+- Write path summary: Upload missing layers via chunked
PATCHinto the regional object store -> verify SHA-256 onPUTand link in SQL ->PUTmanifest in one SQL transaction that verifies all child blobs areactiveand updates the tag. - Read path summary:
GETmanifest resolvestag -> digest(short-TTL Redis cache) and fetches the immutable manifest JSON (long-lived cache) -> for each layer missing on the node,GET /blobs/<digest>verifies permissions and returns307to a signed CDN URL -> client pulls bytes straight from the nearest CDN edge.
- Write path summary: Upload missing layers via chunked
Deep dive 1: resumable, deduplicated uploads of multi-gigabyte layers
Let us examine how a
5–20 GBlayer survives flaky Wi-Fi or preemptible CI runners without restarting from byte zero or accepting corrupted data.1. Skip uploading whenever possible. Before sending a byte, the client sends
HEAD /v2/<name>/blobs/<digest>(answered from Redis + SQL without touching object storage). If the layer exists in another repository the user can read,POST .../uploads/?mount=<digest>&from=<source>verifies pull permission on<source>and push permission on<name>, then insertsrepo_blobsin milliseconds.2. Stream chunks into object-store multipart uploads.
POST .../uploads/creates anuploadsrow (expires_at = now() + 24h), opens an object-store multipart upload (an S3/GCS feature that accepts numbered byte parts independently and stitches them into one object at the end) atuploads/<upload_id>, and returnsOCI-Chunk-Min-Length: 5242880(5 MiB, S3's minimum non-final part size). - As aPATCHstreams in, the API server cuts the stream into64 MiBS3 parts (10,000max parts ×64 MiBsupports layers up to625 GiB). - What if an older client sends a2 MiBPATCHbefore the end of the file? S3 rejects non-final parts smaller than5 MiB, so the API server writes sub-5 MiBleftovers to a temporary scratch objectscratch/<upload_id>and flushes a real S3 part as soon as>= 5 MiBaccumulates (or flushes it as the final part onPUT, where S3 allows any size).3. Advance
bytes_storedonly after bytes are durable. If an API pod crashes mid-chunk,GET <upload URL>readsuploads.bytes_storedfrom SQL and returnsRange: 0-<bytes_stored - 1>. The client resumes frombytes_stored, losing at most the single in-flight chunk. Load-balancer affinity routes anupload_idto the same pod in the happy path, while storingpartsandbytes_storedin SQL lets any healthy pod take over seamlessly after a crash.4. Incremental SHA-256 hashing. Re-reading a
10 GBobject from S3 at the end of an upload just to compute its SHA-256 adds10–20 secondsof tail latency. Instead, the API server feeds bytes into a streaming SHA-256 hasher as they arrive and serializes the hasher's internal 108-byte state (sha256_state) into theuploadsSQL row alongside each durable part. If an upload finishes on a different runtime that cannot restore the hash state, re-reading the completed object from regional S3 remains a safe fallback.5. Atomic verification and deduplicating commit.
PUT /v2/billing/worker/blobs/uploads/u-99?digest=sha256:abc... 1. Flush trailing bytes as the final S3 part; complete multipart upload at 'uploads/u-99'. 2. Finalize SHA-256. If computed_digest != sha256:abc...: Delete 'uploads/u-99' in object store, delete uploads row -> return 400 DIGEST_INVALID. 3. Run serializable SQL transaction: BEGIN INSERT INTO blobs (digest, size_bytes, state, last_linked_at) VALUES ('sha256:abc...', size, 'active', now()) ON CONFLICT (digest) DO UPDATE SET state = 'active', last_linked_at = now() WHERE blobs.state <> 'deleting'; -- If 0 rows affected, GC sweep is actively deleting old copies right now: -- ROLLBACK, back off briefly until sweep finishes, and retry step 3. INSERT INTO blob_locations (digest, region, storage_key, verified_at) VALUES ('sha256:abc...', current_region, 'uploads/u-99', now()) ON CONFLICT (digest, region) DO NOTHING; INSERT INTO repo_blobs (repo_id, digest) VALUES (billing_worker_id, 'sha256:abc...') ON CONFLICT DO NOTHING; COMMIT 4. If blob_locations kept an earlier storage_key (two clients uploaded identical bytes concurrently), enqueue 'uploads/u-99' for background object deletion. 5. Delete uploads row -> return 201 Created + Docker-Content-Digest: sha256:abc...Notice how cleanly concurrent identical uploads resolve: both clients get
201 Created, the first transaction'suploads/<id>becomes the canonical regional object, and the second duplicate object is quietly cleaned up without either user seeing an error.6. Abandoned upload cleanup. A background upload reaper scans
uploads WHERE expires_at < now(), aborts the S3 multipart upload (freeing hidden part storage), and deletes the SQL row. A bucket-level S3 lifecycle rule aborting incomplete multipart uploads after 3 days acts as an independent safety net.Deep dive 2: high-throughput pulls and global distribution
During a deployment or CI morning rush,
5,000Kubernetes nodes across three continents may pull the exact same newly released image within 60 seconds.1. Separate immutable digest reads from mutable tag reads. - Manifest by digest (
GET /manifests/sha256:...): Completely immutable. Cached in local pod RAM and regional Redis indefinitely. One subtle trap in multi-region setups: if CI pushes an image inus-eastand immediately triggers a deploy ineu-west200 mslater,eu-west's local SQL read replica might lag by300 ms. Therefore, a local replica404on a digest lookup retries once as a strong leader read before returningMANIFEST_UNKNOWN. - Manifest by tag (GET /manifests/stable): Mutable pointer. Cached in Redis with a short TTL (Time-To-Live — automatic cache expiration, say5–15 seconds), and proactively invalidated in the local region onPUT. Production deployment pipelines that require zero staleness pin image digests (billing/worker@sha256:...).2. Signed CDN redirects with shared cache keys. When a client calls
GET /v2/billing/worker/blobs/sha256:abc..., the API server verifies the client's JWT (JSON Web Token — a cryptographically signed permission ticket) locally in microseconds, checksrepo_blobsin Redis, and returns307 Temporary Redirectto:https://cdn.registry.example/blobs/sha256:abc...?exp=1764520000&sig=hmac_sha256(...)- The CDN edge validatesexpandsigat the perimeter with zero callback to our API. - Crucially, the CDN configures its cache key as/blobs/sha256:abc...alone (strippingexpandsig). That way,5,000different authenticated pods with5,000different signatures all hit the exact same cached layer at the edge! - Request coalescing (collapsing concurrent misses for the same cache key so only one request goes upstream while the other4,999wait on the same stream) at both the CDN edge and a regional origin shield (a shared parent cache per region) reduces5,000simultaneous cold pulls to 1 object-store read per region.3. Minimizing cross-region WAN transfer. - Lazy pull-through for most repositories: Each blob starts with one
blob_locationsrow in the region where it was pushed (its home region). On the first CDN miss inap-northeast, the regional blob origin acquires a short Redis lockpull_lock:<digest>, streams the blob once from the home region intoap-northeast's object store, verifies its SHA-256, inserts(digest, 'ap-northeast')intoblob_locations, and serves all waiting edge shields. Every blob crosses an ocean at most once per region where it is actually pulled. - Eager async replication for hot multi-region repositories: Repositories flagged as global base images publish push events that copy new layers to all active regions immediately, making even the very first pull in every continent local. - In-cluster mirrors and P2P: Inside a customer's2,000-node Kubernetes cluster, a local pull-through registry mirror or peer-to-peer distributor (such as Dragonfly or Kraken) shares downloaded chunks across cluster LAN links so the cluster's NAT gateway downloads each layer once.Deep dive 3: consistent metadata and safe garbage collection
The deadliest bug in a container registry is a push-vs-GC race condition:
Time Client pushing billing/worker:2.5 Naive Garbage Collector t=1 HEAD /blobs/sha256:layerX -> 200 OK! (Client skips uploading layerX) t=2 Sees 0 manifests referencing layerX -> DELETES layerX from S3 and SQL! t=3 PUT /manifests/2.5 (references layerX) -> 201! --> CORRUPTION: billing/worker:2.5 is live, but pulling layerX returns 404 forever!We eliminate this entire class of bugs by combining row-level SQL locking on manifest writes with two-stage mark-and-sweep garbage collection and a 24-hour grace period.
Atomic manifest
PUTtransaction:PUT /v2/billing/worker/manifests/2.4 (body = raw_bytes) 1. Compute digest = sha256(raw_bytes); validate JSON schema and size <= 4 MiB. 2. BEGIN -- Shared lock (FOR SHARE) lets 1,000 concurrent pushes share a base layer without blocking -- each other, while blocking GC from taking an exclusive FOR UPDATE delete lock! For each referenced blob child_d (config + layers): SELECT state FROM blobs WHERE digest = child_d FOR SHARE; Require state = 'active' AND EXISTS (SELECT 1 FROM repo_blobs WHERE repo_id = :repo AND digest = child_d); -- For multi-arch index manifests, verify platform manifests exist in this repo: For each referenced child manifest child_m: SELECT 1 FROM repo_manifests WHERE repo_id = :repo AND manifest_digest = child_m FOR SHARE; If any check fails -> ROLLBACK and return 400 MANIFEST_BLOB_UNKNOWN. INSERT INTO manifests (digest, media_type, size_bytes, raw_body) VALUES (...) ON CONFLICT DO NOTHING; INSERT INTO manifest_refs (manifest_digest, child_digest, child_kind) VALUES (...) ON CONFLICT DO NOTHING; INSERT INTO repo_manifests (repo_id, manifest_digest, pushed_at) VALUES (...) ON CONFLICT DO NOTHING; INSERT INTO tags (repo_id, tag_name, manifest_digest, version) VALUES (:repo, '2.4', :digest, 1) ON CONFLICT (repo_id, tag_name) DO UPDATE SET manifest_digest = :digest, version = tags.version + 1, updated_at = now(); COMMITTwo-stage garbage collection:
-
Stage 1 — Opt-in manifest retention: Deleting unreferenced blobs is invisible to users, whereas deleting manifests removes old image versions, so Stage 1 runs per-repository retention rules. Two rules prevent breaking production:
- A platform manifest (
linux/amd64) rarely has its own tag — it is referenced by a tagged multi-arch index manifest! So a manifest is considered unreferenced in a repository only if zero tags point to it AND zero index manifests in that repository reference it inmanifest_refs. - Because production deploys pull by
@sha256:...without tags, Stage 1 only unlinks unreferenced manifests where bothpushed_atandlast_pulled_atare older thanNdays (for example, 30 days;last_pulled_atis updated lazily at most once per day to avoid write amplification on pulls). When norepo_manifestsrows remain for a manifest across any repo, itsmanifest_refsandmanifestsrows are deleted, and its child blob digests are pushed onto a GC candidate queue.
- A platform manifest (
-
Stage 2 — Mark-and-sweep blobs with a 24-hour grace period: Instead of scanning all 150 million rows every hour, GC workers consume the candidate queue (supplemented by a slow weekly full table scan to catch abandoned uploads):
- Mark (
active -> pending_delete): UnderSELECT ... FROM blobs WHERE digest = :d FOR UPDATE(which waits for any in-flightPUTmanifest'sFOR SHARElock!), verify that zeromanifest_refsrows havechild_digest = :d, zerorepo_blobslinks were created in the last 24 hours, andlast_linked_at < now() - interval '24 hours'(every200HEADresponse refresheslast_linked_atat most once per hour). If all hold, setstate = 'pending_delete', pending_since = now()and evict:dfrom Redis existence caches. - Quarantine behavior: While a blob is
pending_delete,HEADreturns404! That forces any new push to upload (or re-verify) the layer, which flipsstateright back to'active'. If a client already gotHEAD 200right before the mark, the manifestPUTchecksstate = 'active'and cleanly returns400 MANIFEST_BLOB_UNKNOWN(prompting the client to retry and upload the blob) instead of ever committing a broken image. - Sweep (
pending_delete -> deleting -> gone): After 24 hours inpending_delete, re-lock the rowFOR UPDATE, re-verify zero references andstate = 'pending_delete', setstate = 'deleting', commit, delete the object from every region listed inblob_locations, and finally delete theblob_locations,repo_blobs, andblobsrows.
- Mark (
-
Scaling, bottlenecks, and failure handling
Bottleneck / failure scenario Impact at peak Mitigation in this design ----------------------------------- --------------------------- ---------------------------------------------------- Blob egress (~1.44 Tbps) Saturates API NICs 307 redirects to signed CDN URLs; zero API proxy bytes CI release storm on 1 new layer 5,000 simultaneous misses CDN request coalescing + regional origin shield + Redis pull lock Tag lookup hot spots (:latest) ~17.5k GETs/s 5-15s Redis TTL + local invalidation on tag PUT API pod dies mid-5 GB upload Connection drops Client queries GET <upload_url>, resumes from durable bytes_stored Corrupted or tampered upload bytes Hash mismatch Streaming SHA-256 check rejects PUT with 400 DIGEST_INVALID SQL leader failover in push region ~5-10s write pause Digest pulls stay 100% up via caches + replicas; pushes retry Regional object store outage Origin misses fail locally Regional blob origin falls back to fetching from peer region CDN provider outage Edge URLs unreachable Feature flag switches 307 redirects directly to S3 pre-signed URLs Suspected bug in GC logic Risk of data loss 24h pending_delete quarantine + S3 object versioning (7-day undelete) Silent bit-rot in object storage Corrupted cold layer Background scrubber samples & re-hashes blobs; heals from peer regionSummary of the trade-offs
- Content-addressable storage (SHA-256 keys): Gives global deduplication, tamper-proof integrity, and infinite CDN cacheability for free, in exchange for sequential hashing on upload and asynchronous garbage collection on delete.
- Distributed transactional SQL vs. NoSQL for metadata: At
< 1 TBand~120 manifest PUTs/s, SQL transactions (FOR SHARE/FOR UPDATE) eliminate dangling-layer and GC race conditions cleanly; we willingly pay a few milliseconds of cross-AZ commit latency on rare writes to guarantee zero corrupt images. - HTTP
307redirects to CDN vs. proxying bytes: Removes terabits per second of load from API servers at the cost of one extra HTTP round trip and short-lived URL signing. - Indirection table (
blob_locations) vs. content-named S3 keys: Avoids copying multi-gigabyte objects on commit, trading away human-readable S3 keys for instant zero-copy finalization. - Hybrid lazy + eager cross-region replication: Pull-through avoids replicating petabytes of rarely used CI builds across continents, while eager replication for hot repositories removes first-pull latency where it matters.
Intuition & how it works
Think of a container image registry like a global warehouse for LEGO kits. Thousands of different kits reuse the exact same heavy sealed bags of standard bricks (like an ubuntu base OS or a python runtime). Instead of storing duplicate brick bags inside every kit's box, the warehouse stamps every sealed bag with a tamper-proof barcode computed from the exact bricks inside — a cryptographic digest (sha256:...). Each kit's thin instruction booklet — the manifest (a small JSON file) — simply lists which barcoded bags snap together in order, and a movable shelf sticker like billing/worker:stable — a tag — points to whichever instruction booklet is current. Because sealed bags and printed booklets never change once created (immutable), only the tiny shelf stickers ever move (mutable).
Why do the obvious designs fail? Storing each pushed image as one giant folder per repository wastes petabytes duplicating identical base layers across thousands of teams and forces every docker push to re-upload gigabytes over the network. Streaming blob downloads directly through your API servers collapses under 1.4+ Tbps of peak CI/CD bandwidth. Conversely, dumping manifests and blobs into plain object storage without a transactional metadata database invites race conditions where garbage collection deletes a shared layer milliseconds before a new push links to it, leaving a permanently broken image in production.
Let us trace a concrete mini-example where a team pushes billing/worker:2.3, then pushes billing/worker:2.4 after updating application code, and a cluster node pulls billing/worker:2.4:
1. Push billing/worker:2.3 (750 MB base layer sha256:aaa + 18 MB app layer sha256:bbb):
- HEAD /blobs/sha256:aaa -> 404; client uploads chunks -> verified & stored once at uploads/u-1.
- HEAD /blobs/sha256:bbb -> 404; client uploads chunks -> verified & stored once at uploads/u-2.
- PUT /manifests/2.3 -> SQL transaction locks aaa & bbb (FOR SHARE), saves manifest sha256:m1, sets tag 2.3 -> m1.
2. Push billing/worker:2.4 (same 750 MB sha256:aaa + new 18 MB app layer sha256:ccc):
- HEAD /blobs/sha256:aaa -> 200 OK! Client skips uploading 750 MB completely.
- HEAD /blobs/sha256:ccc -> 404; client uploads only the 18 MB diff -> stored at uploads/u-3.
- PUT /manifests/2.4 -> saves manifest sha256:m2 referencing [aaa, ccc], sets tag 2.4 -> m2.
3. Pull billing/worker:2.4 on a fresh node:
- GET /manifests/2.4 -> resolves tag 2.4 -> sha256:m2, returns JSON listing [sha256:aaa, sha256:ccc].
- GET /blobs/sha256:aaa -> API checks permission in Redis, returns 307 Redirect to signed CDN URL;
node downloads 750 MB straight from the nearest CDN edge without touching the API server!
Key trade-offs
- Transactional SQL vs. eventually consistent key-value store for metadata: Metadata totals under
1 TBand peaks around120 manifest PUTs/s, so a horizontally scalable SQL database (such as CockroachDB or Spanner) easily affords serializable ACID transactions (database operations guaranteed to succeed or fail as one isolated unit). Transactions make "no manifest points to a missing blob" and lock-coordinated garbage collection exact invariants rather than best-effort background repairs. - Global content-addressed deduplication vs. per-repository physical copies: Storing one global blob per SHA-256 digest saves petabytes of object storage and lets a CDN (Content Delivery Network — distributed edge caches) serve one cached copy across all authorized tenants. The trade-off is maintaining a
repo_blobsauthorization link table so knowing a digest never grants unauthorized access to a private repository's layer, plus running asynchronous garbage collection. - HTTP
307CDN redirects vs. proxying blob bytes through API servers: Returning a short-lived signed CDN URL offloads~1.44 Tbpsof peak egress to edge caches and regional object storage, keeping the API fleet small and CPU-focused. Proxying would simplify per-byte bandwidth billing and firewall allowlists, but would require a massive bandwidth-provisioned API tier. - Edge table (
manifest_refs) vs. reference-count column (ref_count) for garbage collection: Incrementing an integer counter on a popular base layer (ubuntu:24.04) forces every concurrent push to acquire an exclusive write lock on that single row, serializing pushes and risking permanent counter drift on bugs. An indexed edge table (manifest_digest -> child_digest) needs only shared read locks (FOR SHARE) during pushes and can always be audited, trading away single-row counter checks for a background mark-and-sweep pass (a two-phase cleanup that first flags unreachable items and deletes them after a safety delay). - Indirection row (
blob_locations) vs. renaming uploaded objects: Object stores like S3 copy every byte when "renaming" a key, which would double write I/O on a10 GBlayer. Recordingstorage_key = 'uploads/<upload_id>'in SQL commits a verified upload in milliseconds with zero byte copying, at the small cost that operators must look up object paths via SQL metadata. - Tag cache TTL vs. immediate freshness: Caching
tag -> digestin Redis for5–15 secondsabsorbs CI pull storms on:latest, trading a few seconds of cross-region tag staleness; workloads requiring instant exactness pull immutable digests (@sha256:...).
Common mistakes
- Streaming multi-gigabyte blob downloads through API servers: Forces your stateless API fleet to scale for terabits per second of network throughput instead of delegating byte delivery to a CDN and object storage.
- Re-serializing manifest JSON instead of storing raw bytes: Parsing a manifest into database columns and re-encoding JSON on
GETalters whitespace or key ordering, changing its SHA-256 hash and failing client integrity checks. - Checking global blob existence instead of per-repository links (
repo_blobs): IfHEADorGETreturns200whenever a digest exists anywhere in the registry, an attacker can probe SHA-256 hashes to confirm or download another tenant's private proprietary layers. - Trusting client-supplied digests or skipping resumable uploads: Making an upload visible before computing its server-side SHA-256 allows cache poisoning, and omitting chunked
PATCH+Rangeresumption makes10 GBML layer pushes unusable on real networks. - Running garbage collection without locking and a grace period: Deleting an unreferenced layer between a client's
HEAD 200check and itsPUT /manifests/...creates a live manifest whose layer returns404forever. - Deleting "untagged" manifests without checking multi-arch indexes or digest pulls: Platform-specific child manifests (
linux/amd64,linux/arm64) inside a multi-arch image have no tags of their own, and production clusters routinely pull untagged images by@sha256:...digest; ignoring either breaks live deployments. - Returning
404on a digest pull from a slightly lagging read replica: Right after CI pushes a manifest in one region, a deployment in another region may query a replica that is200 msbehind; always retry a digest miss against the SQL leader before returningMANIFEST_UNKNOWN.
Follow-up questions
- How do you reclaim unreferenced layer blobs without racing against in-flight image pushes or breaking digest-pinned deployments? Run cleanup in two lock-coordinated stages. First, per-repository retention rules unlink manifests that carry zero tags, are not referenced inside any multi-arch index manifest in
manifest_refs, and have bothpushed_atandlast_pulled_atolder thanNdays (protecting untagged@sha256:...production workloads). Second, a mark-and-sweep worker drains candidate digests that lost references (supplemented by a weekly safety scan), locks eachblobsrowFOR UPDATE(serializing cleanly against concurrent manifestPUTtransactions holdingFOR SHARE), and marks itpending_deleteonly when zeromanifest_refsrows point to it and no upload, mount, orHEADtouched it during the past24 hours. Throughout the subsequent24-hourquarantine window,HEADreturns404(forcing concurrent pushes to re-upload and revive the row toactive), after which the sweep re-locks the row, setsstate = 'deleting', removes the regional S3 objects, and deletes the metadata rows. - How should authentication and repository-level role permissions work across CLI users, CI pipelines, and signed blob download URLs? Implement the standard OCI bearer-token flow: unauthenticated
/v2/requests receive401 UnauthorizedwithWWW-Authenticate: Bearer realm="...",service="registry",scope="repository:billing/worker:pull,push". Clients exchange SSO user credentials, OIDC CI workload tokens, or scoped robot keys at the Auth Token Service, which evaluates RBAC (Role-Based Access Control — mapping users, teams, and service accounts to roles such asreader,writer, oradminon namespaces and repositories) and mints a short-lived (5-minute) signed JWT embedding only the permitted scopes. Stateless Registry API pods validate the JWT signature and scopes in local memory with zero database round trips, cross-repository mounts requirepullon the source repository pluspushon the destination repository, and307blob redirects return short-lived (10-minute) HMAC-signed CDN URLs scoped to that single digest so revoked access expires quickly. - How would you structure multi-region caching and blob replication so teams on different continents get fast pulls without copying every build everywhere? Direct clients via Anycast / Geo-DNS (network routing that sends requests to the nearest regional stack) backed by a global CDN with request coalescing and a regional origin shield (collapsing thousands of simultaneous cold pulls into one origin read), stripping URL query signatures from the CDN cache key so authorized pods share cached layer bytes. Replicate SQL metadata globally so immutable digest fetches read from local caches and read replicas (retrying against the SQL leader on a replica miss to preserve read-after-write consistency across oceans), while
tag -> digestlookups use a5–15 secondRedis TTL. For binary blobs, pair lazy pull-through replication (copying a layer from its home region on the first miss in another continent under a per-digest lock so each blob crosses WAN links at most once per active region) with eager async replication for hot shared base images, plus in-cluster pull-through mirrors or peer-to-peer distribution inside large node fleets.
Follow-up questions
- How do you reclaim unreferenced layer blobs without racing against in-flight image pushes or breaking digest-pinned deployments?
- How should authentication and repository-level role permissions work across CLI users, CI pipelines, and signed blob download URLs?
- How would you structure multi-region caching and blob replication so teams on different continents get fast pulls without copying every build everywhere?
Similar questions
- Evaluate Basic Arithmetic Strings
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency