Design CI/CD Build Caching System
System DesignModel answerLast updated
Design a distributed build caching system for CI/CD pipelines, covering cache key generation, concurrent upload coordination, and tiered storage architecture.
Design a distributed build caching platform for an enterprise CI/CD service executing tens of thousands of pipeline jobs daily across diverse runtimes (Node.js, Rust, Go, Python, and C++).
The system aims to accelerate pipeline execution by storing and retrieving intermediate compilation and dependency artifacts (such as package manager directories, object files, and pre-built container layers) between worker runs.
Core Requirements
Functional Requirements
- Artifact Transfer: CI worker agents must download existing cache bundles before executing build steps and upload newly generated bundles after successful steps.
- Deterministic Keying: Compute unique, collision-free cache keys based on input states (e.g., source tree hashes, toolchain versions, OS/architecture, lockfiles). Support fallback prefix matching for partial restores.
- Lifecycle & Eviction: Define clean-up policies (e.g., TTLs, LRU) to constrain total storage consumption across projects.
Non-Functional & Resilience Requirements
- Fail-Open Operational Model: Caching is an optimization. Cache failures, high latency, or total service outages must never fail a CI pipeline; agents must safely fall back to clean builds.
- High Read Throughput: Downloading cached archives must be orders of magnitude faster than building from source, even for multi-gigabyte payloads.
- Concurrency Control: Gracefully handle duplicate writes when concurrent pipelines finish identical steps at the same time ("thundering herd" / cache stampede).
Requirements for your Design
- API Design: Define RESTful endpoints for cache checking, lease reservation, streaming transfers, and committing artifacts.
- Storage Layer: Propose a scalable architecture separating control plane metadata from bulk object storage.
- Keying & Match Logic: Detail how deterministic keys are generated and how partial prefix fallbacks operate.
- Concurrency & Failures: Explain the state machine and leasing mechanisms used to resolve race conditions between concurrent pipeline steps.
Hints
Hint 1
Decouple control plane metadata from data plane bytes: return presigned storage URLs so workers download directly from object storage without bottlenecking API servers.
Hint 2
Make final payload storage immutable and content-addressable (keyed by payload SHA-256) to enable implicit deduplication across different projects.
Hint 3
Coordinate concurrent writes with a short-lived lease state machine (PENDING -> COMMITTED) using atomic conditional updates (CAS).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture Overview
A production CI/CD cache separates the control plane (metadata lookups, authentication, key matching, and upload coordination) from the data plane (high-throughput blob storage and delivery).
+---------------------------------------+
| CI Worker Runner |
+---+-------------------------------+---+
| |
1. Check/Reserve (JSON) 3. Upload/Download
| Blobs
v v
+-----------------------+ +-----------------------+
| Cache API Service | | Edge / S3 Payload Store|
| (Control Plane) | | (Data Plane) |
+-----------+-----------+ +-----------------------+
|
Metadata Lookup/Lease
v
+-----------------------+
| Metadata DB / Redis |
+-----------------------+
1. Capacity Estimation & Scale
To size the system, consider an enterprise deployment:
- Build Volume: 100,000 builds/day ($\approx 1.16$ builds/sec average, peaking at $\approx 10$ builds/sec during peak working hours).
- Cache Invocations: Each build executes an average of 4 cache steps (e.g., base tooling, package dependencies, intermediate object files, test snapshots).
- Read QPS: Peak of $\approx 40$ lookup requests/sec.
- Payload Sizes: Median 150 MB (ranging from 5 MB dependency manifests to 3 GB compiler outputs).
- Network Bandwidth:
- With an 80% cache hit rate: $$\text{Read Bandwidth} = 40 \text{ req/s} \times 0.80 \times 150 \text{ MB} = 4.8 \text{ GB/s} \ (\approx 38.4 \text{ Gbps})$$
- Upload bandwidth for the 20% miss rate: $$\text{Write Bandwidth} = 40 \text{ req/s} \times 0.20 \times 150 \text{ MB} = 1.2 \text{ GB/s} \ (\approx 9.6 \text{ Gbps})$$
- Storage Footprint:
- Daily uncompressed uploads: $100,000 \text{ builds} \times 4 \text{ steps} \times 0.20 \text{ misses} \times 150 \text{ MB} = 12 \text{ TB/day}$.
- With a 14-day sliding TTL and content deduplication, steady-state storage settles around 80 TB – 120 TB.
2. API Design
Workers interact with the control plane to receive presigned object storage URLs, shifting binary bandwidth directly to storage infrastructure.
Endpoint: Restore Cache Bundle
POST /v1/projects/{project_id}/cache/restore
Request:
{
"primary_key": "deps-node-v2-ubuntu22-x86_64-f9b871c3...",
"fallback_prefixes": [
"deps-node-v2-ubuntu22-x86_64-",
"deps-node-v2-"
]
}
Response (Hit - 200 OK):
{
"status": "HIT",
"matched_key": "deps-node-v2-ubuntu22-x86_64-f9b871c3...",
"exact_match": true,
"download_url": "https://storage.internal.net/blobs/sha256/a8f3b...?sig=...",
"archive_format": "tar.zst",
"sha256": "a8f3b20721869e9e1c45688b7782..."
}
Response (Miss - 200 OK):
{
"status": "MISS",
"matched_key": null,
"download_url": null
}
Endpoint: Reserve Upload Lease
POST /v1/projects/{project_id}/cache/reserve
Request:
{
"key": "deps-node-v2-ubuntu22-x86_64-f9b871c3...",
"expected_bytes": 145892012,
"sha256": "a8f3b20721869e9e1c45688b7782..."
}
Response (Lease Granted - 201 Created):
{
"reservation_status": "GRANTED",
"upload_id": "upl_89af310a",
"upload_urls": [
"https://storage.internal.net/staging/upl_89af310a/part1?sig=..."
],
"lease_expires_at": 1718005400
}
Response (Conflict / Exists - 409 Conflict):
{
"reservation_status": "ALREADY_COMMITTED",
"message": "Artifact matching digest already exists. Upload skipped."
}
Endpoint: Commit Cache Bundle
POST /v1/projects/{project_id}/cache/commit
Request:
{
"key": "deps-node-v2-ubuntu22-x86_64-f9b871c3...",
"upload_id": "upl_89af310a",
"sha256": "a8f3b20721869e9e1c45688b7782..."
}
Response (200 OK):
{
"status": "COMMITTED"
}
3. Storage Layer Architecture
┌─────────────────────────────────────────┐
│ Control Plane │
│ (Stateless API) │
└────────────────────┬────────────────────┘
│
┌──────────────────┴──────────────────┐
▼ ▼
┌───────────────────────────┐ ┌───────────────────────────┐
│ Metadata Store (NoSQL) │ │ Object Storage (S3/GCS) │
├───────────────────────────┤ ├───────────────────────────┤
│ Key -> Blob Mapping │ │ /staging/<upload_id>/... │
│ Key Index for Prefixes │ │ /blobs/sha256/<hash> │
└───────────────────────────┘ └───────────────────────────┘
The system uses a two-tier storage layout:
Metadata Store (DynamoDB or PostgreSQL)
Stores high-QPS relational mappings between logic keys and content digests.
Table Schema (cache_entries):
project_id(Partition Key)cache_key(Sort Key)status(PENDING,COMMITTED)blob_digest(SHA-256 string)size_bytes(Int64)lease_holder_id(UUID)lease_expires_at(Timestamp)last_accessed_at(Timestamp)created_at(Timestamp)
Global Secondary Index (GSI): (project_id, key_prefix, created_at DESC) supports rapid prefix queries on exact matches.
Payload Object Store (S3 / GCS / Ceph)
Stores binary archives structured by payload content hash:
s3://build-cache-bucket/staging/{upload_id}/...(Temporary chunk area with a 24-hour lifecycle deletion rule)s3://build-cache-bucket/blobs/sha256/{digest}(Immutable production payloads)
Content Deduplication: Identical dependencies across different branches or repositories share the exact same physical payload path under blobs/sha256/{digest}, minimizing overall storage overhead.
4. Key Strategy & Fallback Logic
A cache entry is valid only if all execution dependencies match exactly. Cache keys are generated deterministically by hashing a structured manifest:
$$\text{Cache Key} = \text{SHA256}(\text{CanonicalJSON}(\text{Key Manifest}))$$
Manifest Structure
{
"schema_version": "v2",
"project_id": "proj_99812",
"step_id": "compile_binaries",
"os": "ubuntu-22.04",
"arch": "x86_64",
"toolchain": {
"gcc": "11.4.0",
"go": "1.22.0"
},
"lockfile_hashes": {
"Cargo.lock": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"env_vars": {
"CGO_ENABLED": "1",
"GOOS": "linux"
}
}
Keying Guidelines
- Canonical Formatting: Keys in JSON manifests must be lexically sorted to ensure deterministic output.
- Allowlisted Environment Variables: Hash only build-relevant environment variables to maintain high cache hit rates.
- Prefix Restoration: When an exact match misses, fallback prefixes (e.g.,
deps-node-v2-ubuntu22-x86_64-) fetch the most recent partial cache bundle. The package manager then performs an incremental download rather than starting from scratch.
5. Concurrency Control & State Machine
When multiple parallel jobs finish simultaneously, they may try to write identical artifacts. The system uses an Atomic Write Lease state machine to prevent race conditions and redundant work.
┌────────────────────────┐
│ UNCLAIMED │
└───────────┬────────────┘
│
POST /reserve (CAS Success)
│
v
┌────────────────────────┐
┌──────────┤ PENDING ├──────────┐
│ │ (Lease Active) │ │
│ └───────────┬────────────┘ │
│ │ │
Lease Expired POST /commit Upload Error
│ │ │
v v v
┌──────────────┐ ┌────────────────────┐ ┌─────────────────┐
│ Lease Reset │ │ COMMITTED │ │ Lease Cancelled │
└──────────────┘ └────────────────────┘ └─────────────────┘
Protocol Steps
-
Lease Reservation: When a worker attempts to save a cache entry, it calls
POST /reserve. The server executes an atomic Compare-And-Swap (CAS) update:INSERT INTO cache_entries (project_id, cache_key, status, lease_expires_at) VALUES ('proj_1', 'key_abc', 'PENDING', NOW() + INTERVAL '10 minutes') ON CONFLICT (project_id, cache_key) DO UPDATE SET status = 'PENDING' WHERE cache_entries.lease_expires_at < NOW();- Winner: Receives a 201 status and presigned upload URLs.
- Loser: Receives a 409 status indicating the payload already exists or is being uploaded by another worker, and safely skips the upload.
-
Upload & Staging: The winning worker uploads chunks directly to
/staging/{upload_id}/. -
Atomic Commit: Upon completion, the worker calls
POST /commit. The API verifies the SHA-256 digest, moves the staged data to/blobs/sha256/{digest}using an object store copy operation, and updates the state toCOMMITTED. -
Crash Recovery: If a worker crashes during upload, its lease expires after 10 minutes. Subsequent requests can re-claim the key, and background lifecycle policies clean up uncommitted staging objects.
6. Eviction & Operational Resilience
Fail-Open Guarantees
- Client Timeouts: Runner agents use aggressive connection timeouts (e.g., 2-second API lookup timeout).
- Circuit Breakers: If the cache service reports elevated error rates or degraded latency, workers automatically skip cache steps and execute clean builds.
- Asynchronous Writes: Uploads run after main build steps complete and operate in a background, non-blocking mode.
Storage Eviction
- Sliding Window TTL: Each cache read refreshes the entry's
last_accessed_attimestamp. - Asynchronous Batch Updates: Access times are buffered in Redis and flushed to the database periodically (e.g., hourly) to prevent database write bottlenecks.
- LRU Eviction Sweeper: Background jobs purge entries that have not been accessed within 14 days or when storage quotas are exceeded.