The user wants to design a content-addressed storage (CAS) system specifically for build artifacts, with a focus on retention (keeping or deleting artifacts based on policies).
1. Deconstruct the Request:
- Core Concept: Content-Addressed Storage (CAS). This means the key to retrieve data is derived from the content itself (usually a hash like SHA-256).
- Domain: Build Artifacts. This implies large binary files, potentially hierarchical structures (directories), metadata (who built it, when, dependency graph), and access patterns (write-once, read-many).
- Key Feature: Retention. This is the tricky part. CAS makes deduplication easy, but makes "deletion" hard because if multiple artifacts share a chunk of data, you can't delete that chunk just because one artifact expired. This requires a reference counting or garbage collection mechanism.
2. High-Level Architecture:
- Client: The build system (e.g., Bazel, Gradle, custom CI/CD).
- API Layer: REST/gRPC interface to put/get blobs.
- Storage Engine: The actual disk/object store.
- Index/Metadata Database: Tracks references, tags, and retention policies.
- Garbage Collector (GC): The process handling retention and cleanup.
3. Detailed Component Design:
4. Workflow Scenarios:
5. Optimizations & Edge Cases:
- Race Conditions: A build is uploading while GC is running. Need locking or "in-progress" flags.
- Performance: Walking the tree to update ref counts can be slow. It's better to do ref counting on the Tree nodes, not just leaf blobs, or do a mark-and-sweep batch job instead of real-time reference counting.
- Correction: Real-time ref counting is dangerous for high write throughput. A periodic "Mark and Sweep" is often better for distributed systems.
- Revised GC Strategy:
- Retention policy deletes the logical pointer (the "tag").
- A background crawler walks the graph starting from active tags.
- Everything reached is "alive". Everything else is "dead".
- Delete dead blobs.
6. Structuring the Design Document:
I will structure the response logically:
- Core Concepts: Define CAS, Merkle Trees, and the challenge of retention.
- System Architecture: Diagram description (API, DB, Storage).
- Data Model: How we store blobs and metadata.
- The Workflow (Lifecycle): Upload, Download, GC.
- The Retention Strategy (Deep Dive): This is the specific answer to the prompt's nuance. I'll focus on the Mark-and-Sweep vs. Ref Counting trade-off.
- API Design: Quick look at endpoints.
- Scaling & Reliability: Sharding, consistency.
Refining the Retention Strategy:
The "Build Artifact" is usually a folder. In CAS, a folder is a hash of a list of (Name, Hash) pairs.
If I want to delete "Build 100":
- I remove the pointer to "Build 100" from my SQL DB.
- I need to clean up the storage.
Method A: Ref Counting on Write.
When "Build 100" is uploaded, traverse its Merkle tree. For every node,
ref_count++.
When "Build 100" expires, traverse its Merkle tree. For every node, ref_count--. If 0, delete.
Pros: Immediate cleanup. Cons: Write amplification. Slow uploads.
Method B: Mark & Sweep (Lazy).
- Sweep: Identify expired logical artifacts. Remove their entries from the SQL DB.
- Mark: Periodically, iterate through all remaining logical artifacts in the SQL DB. Traverse their Merkle trees. Mark every hash found as "keep" (e.g., update a
last_accessed timestamp or set a bit in Redis).
- Delete: Scan the CAS storage. If a blob's hash hasn't been marked recently (or doesn't exist in the 'keep' set), delete it.
Decision: I will recommend a hybrid or Mark-and-Sweep approach because it handles "Build 100" and "Build 101" sharing 99% of code (deduplication) much more gracefully without locking the DB on every upload.
7. Drafting the Content:
- Introduction: Define the goals (Deduplication, Integrity, Cost optimization).
- Data Structures:
Blob: The raw bytes.
TreeNode: The directory structure (Merkle DAG).
ArtifactRecord: The logical entry (Project, Version, Timestamp).
- The Retention Logic:
- Policy Engine (TTL, Max Builds).
- Garbage Collector implementation details.
- Tech Stack: S3/MinIO for storage, Postgres for logic.
Let's write it out. I will ensure I distinguish between the Logical layer (what the user sees: "v1.0.0") and the Physical layer (what the disk sees: sha256:abc...).
(Self-Correction during drafting):
Make sure to mention Integrity. CAS guarantees integrity by definition. If the hash doesn't match the content, it's corrupt.
Make sure to mention Deduplication. This is the main selling point.
Final check on "Retention":
How do we handle Pinning? Just a boolean flag on the ArtifactRecord that the GC ignores.
Okay, ready to generate the response. I'll structure it as a System Design Proposal.
Designing a Content-Addressed Storage (CAS) system for build artifacts requires balancing three competing goals: Immutability (data integrity), Deduplication (storage efficiency), and RetentionPolicy (cost management).
Below is a comprehensive design for a distributed CAS system tailored for CI/CD artifacts.
1. High-Level Architecture
The system separates the Control Plane (metadata and retention logic) from the Data Plane (raw blob storage).
- Client: The CI/CD runner or developer machine (e.g., Bazel, Gradle, custom scripts).
- API Gateway: Authentication, rate limiting, and routing.
- Metadata Store (The "Index"): A database tracking ownership, references, and retention policies.
- Blob Store (The "Vault"): The underlying storage engine (S3, MinIO, Azure Blob) where raw bytes live.
- Garbage Collector (GC): The background worker enforcing retention.
2. The Data Model
In a CAS, we do not store files by name. We store them by hash.
A. The Blob (Physical Storage)
- Key:
SHA-256 Hash of the content.
- Value: The raw compressed bytes (e.g., Zstandard compressed).
- Location:
s3://bucket/cas/sha256/{hash_prefix}/{hash}.
B. The Manifest (Logical Storage)
Since raw blobs are anonymous, we need a structure to define a "Build Artifact" (like a .tar.gz or a Docker Image). We use a Merkle Tree structure (similar to Git or OCI Images).
- Entry: A JSON/Lightweight record pointing to a Root Hash.
- Fields:
ArtifactID: UUID.
ProjectID: Which project owns this.
CommitSHA: The source code version.
RootHash: The hash of the top-level manifest file pointing to all other blobs.
Timestamp: When it was uploaded.
Tags: (e.g., master, v1.0, latest).
Status: Pinning status (e.g., permanent, standard, cache).
3. The Retention Strategy (The Hard Part)
The core challenge in CAS retention is that multiple artifacts often share the same underlying blobs (deduplication). You cannot simply delete a blob when an artifact expires, because a newer artifact might still need that blob (e.g., a common library like libc or lodash).
We solve this using Reference Counting in the Metadata Store.
The Reference Lifecycle
- Upload (CAS Hit): When a client uploads an artifact, they calculate hashes locally. If the server already has a blob, the client does not upload it. The server simply increments the Ref Count for that existing blob hash and links it to the new Artifact ID.
- Upload (CAS Miss): Client uploads bytes. Server writes to Blob Store, creates a Metadata entry with
Ref Count = 1.
Retention Policies
Policies act on the Artifact (the logical grouping), not individual blobs.
- Time-to-Live (TTL):
- Rule: Delete artifacts older than 90 days.
- Scope: Only applies to artifacts with tag
cache or branch-build.
- Max Count:
- Rule: Keep only the last 10 artifacts for
feature/* branches.
- Pinned / Release:
- Rule: Artifacts tagged with a semantic version (e.g.,
v1.0.0) have Retention: Infinite.
4. Garbage Collection (GC) Mechanism
Because deleting logical artifacts affects shared physical blobs, deletion is a two-phase process handled by a background Garbage Collector.
Phase 1: Logical Expiration (The Sweep)
The GC worker queries the Metadata Store for artifacts matching expiration criteria (e.g., created_at < NOW - 90 days AND policy = standard).
- It identifies the
RootHash of the expired artifact.
- It traverses the Merkle Tree of that artifact.
- For every blob hash encountered in the tree, it decrements the Reference Count.
- It deletes the Artifact Record from the Metadata Store.
Phase 2: Physical Reclamation (The Purge)
Eventually, the Reference Count for specific blobs will hit Zero. This means no existing artifact uses this data anymore.
- The GC scans the Metadata Store for blob entries where
ref_count == 0.
- It issues a
DELETE command to the Blob Store (S3) for those hashes.
- It removes the blob entry from the Metadata Store.
5. API Design
PUT /artifacts/{project_id}/{commit_sha}
- Action: Establishes a new logical artifact.
- Body: The Root Hash + Manifest metadata.
- Logic: Server traverses the provided graph, ensuring all referenced blobs exist, and updates Ref Counts.
POST /cas/blobs/{sha256}/{size}
- Action: Upload a raw chunk of data.
- Protocol: Often gRPC (Remote Execution API / REAPI) for streaming.
- Deduplication: If hash exists, return
ALREADY_EXISTS immediately (Zero-byte upload optimization).
GET /artifacts/{project_id}?tags=latest
- Action: Retrieve the manifest for a specific build.
- Response: Returns the Root Hash. The client then requests specific blobs from
/cas/blobs/{hash}.
6. Optimizations for Scale
- Directory-Level Hashing:
Instead of hashing every file individually, hash directory structures. This reduces the number of metadata entries and API calls required to reconstruct a complex artifact.
- Tombstoning (Lazy Deletion):
In high-throughput systems, decrementing reference counts synchronously is slow. Instead, write "Tombstone" events to a queue (Kafka/SQS). A worker processes these asynchronously to update Ref Counts.
- Reachability-Based GC (Alternative to Ref Counting):
If the Metadata Store is a graph database (like Neo4j), you can run a traversal query starting from all "Live" artifacts. Any blob not visited in the traversal is "Garbage." This avoids the overhead of maintaining atomic ref counters but requires heavy computation during GC cycles.
- Storage Tiers:
- Hot: Recent artifacts (last 7 days) on SSD/NVMe.
- Cold: Older artifacts automatically transition to S3 Glacier or cheaper object storage classes via lifecycle policies on the underlying bucket.
7. Technology Stack Recommendation
- API: Go or Rust (high concurrency handling for streaming blobs).
- Metadata Store:
- Option A (SQL): PostgreSQL (reliable, strict ACID for ref counting).
- Option B (KV): Redis (speed) + SQLite (persistence) or DynamoDB.
- Blob Store: MinIO (on-prem) or AWS S3 (cloud).
Summary Flow
- Upload: Client sends hashes -> Server checks existence -> Client sends missing bytes -> Server stores blobs + updates Metadata (Ref Count +1).
- Storage: Deduplicated automatically.
- Retention: GC identifies an old "Build 101" -> Removes its metadata -> Decrements Ref Counts for its blobs.
- Cleanup: "Build 101" used
lib.so (Ref Count drops to 0). "Build 105" used a different lib.so. The GC permanently deletes the lib.so from Build 101 from S3.