Repository navigation
feat: implement lazy CDC chunking for faster TTFB - #1081
Conversation
This implements lazy CDC chunking where NAR files are stored compressed without chunking initially, then chunked in the background. This significantly reduces TTFB on cache miss by avoiding the expensive decompression and chunking operations during download. Changes: - Add --cache-cdc-lazy-chunking-enabled flag (default: true) - Add --cache-cdc-background-workers flag (default: CPU count) - Store compressed NAR directly without chunking when lazy is enabled - Serve raw compressed NAR when total_chunks=0 - Add ScanAndMigratePendingNars for batch background migration - MigrateNarToChunks now handles compressed NARs via decompression The existing migrate-nar-to-chunks CLI command can still be used for manual chunking, and setting --cache-cdc-lazy-chunking-enabled=false restores the original immediate chunking behavior.
|
This change is part of the following stack: Change managed by git-spice. |
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a significant optimization to the cache's Content-Defined Chunking (CDC) process by implementing 'lazy chunking'. This change prioritizes faster initial data availability by storing compressed NARs directly upon ingestion, deferring the computationally intensive chunking operation to a background process. This approach is designed to improve the Time To First Byte (TTFB) for cache misses, enhancing user experience without compromising the benefits of CDC for subsequent requests. Highlights
Changelog
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
|
Documentation Updates 2 document(s) were updated by changes in this PR: Cache and Storage Configuration FlagsView Changes@@ -169,6 +169,77 @@
avg: 65536
max: 262144
```
+
+### Lazy Chunking
+
+Lazy chunking is a performance optimization that stores compressed NAR files without immediate chunking, then chunks them in the background. This significantly reduces Time To First Byte (TTFB) on cache miss by avoiding expensive decompression and chunking operations during download. When enabled, NAR files are stored compressed and served immediately while background workers chunk them asynchronously.
+
+**Flags:**
+
+- `--cache-cdc-lazy-chunking-enabled` (boolean): Enable lazy chunking. Default: `true`
+ - Environment variable: `CACHE_CDC_LAZY_CHUNKING_ENABLED`
+ - YAML key: `cache.cdc.lazy-chunking-enabled`
+
+- `--cache-cdc-background-workers` (integer): Number of background workers for lazy chunking. Default: number of CPUs (`runtime.NumCPU()`)
+ - Environment variable: `CACHE_CDC_BACKGROUND_WORKERS`
+ - YAML key: `cache.cdc.background-workers`
+
+**Behavior:**
+
+When lazy chunking is enabled (the default), NAR files are:
+1. Stored compressed without chunking (with `total_chunks=0` in the database)
+2. Served immediately from storage when requested
+3. Chunked asynchronously in the background by worker processes
+
+When lazy chunking is disabled (`--cache-cdc-lazy-chunking-enabled=false`), the original immediate chunking behavior is restored, where NAR files are chunked during the download/storage process.
+
+**CLI Example (using defaults):**
+```bash
+ncps serve --cache-cdc-enabled
+# Lazy chunking is enabled by default with CPU-count workers
+```
+
+**CLI Example (disabling lazy chunking):**
+```bash
+ncps serve \
+ --cache-cdc-enabled \
+ --cache-cdc-lazy-chunking-enabled=false
+```
+
+**CLI Example (custom worker count):**
+```bash
+ncps serve \
+ --cache-cdc-enabled \
+ --cache-cdc-background-workers 4
+```
+
+**YAML Example (using defaults):**
+```yaml
+cache:
+ cdc:
+ enabled: true
+ # lazy-chunking-enabled defaults to true
+ # background-workers defaults to CPU count
+```
+
+**YAML Example (disabling lazy chunking):**
+```yaml
+cache:
+ cdc:
+ enabled: true
+ lazy-chunking-enabled: false
+```
+
+**YAML Example (custom configuration):**
+```yaml
+cache:
+ cdc:
+ enabled: true
+ lazy-chunking-enabled: true
+ background-workers: 4
+```
+
+**Note:** The existing `migrate-nar-to-chunks` CLI command can still be used for manual chunking of stored NAR files.
### Immutable CDC Settings
NAR File Download and StreamingView Changes@@ -83,6 +83,8 @@
When CDC is enabled and a compressed NAR needs to be decompressed, the system implements a single-decompression mechanism that prevents multiple concurrent decompression operations. This mechanism ensures that only the first request performs the decompression, while subsequent concurrent requests share the same decompressed stream.
+**Note:** This mechanism applies only when lazy chunking is disabled (via `--cache-cdc-lazy-chunking-enabled=false`). With lazy chunking enabled (the default), compressed NAR files are stored directly without decompression or chunking, and background workers perform chunking asynchronously after storage completes.
+
The system uses an `io.Pipe` and a single temporary file when handling a compressed NAR that requires decompression:
- **io.Pipe**: Connects the HTTP response body to the decompressor without writing compressed data to disk
@@ -108,13 +110,14 @@
#### NAR File Record States
-When CDC is enabled, `nar_file` records in the database can exist in three distinct states:
+When CDC is enabled, `nar_file` records in the database can exist in multiple distinct states:
- **Fully chunked**: Records with `total_chunks > 0` and `chunking_started_at` set. These records represent NAR files that have been successfully chunked and are ready for CDC streaming.
-- **Actively chunking**: Records with `chunking_started_at` set but `total_chunks = 0`. These records indicate that chunking is in progress. With concurrent CDC chunking, the `chunking_started_at` timestamp is set within milliseconds of download start (before decompression completes), allowing other HA instances to immediately detect active chunking operations and use progressive streaming. The system uses progressive streaming to serve these NARs while chunking completes.
-- **Placeholder/Failed**: Records with `total_chunks = 0` and `chunking_started_at = NULL`. These are placeholder records created during narinfo storage (via `storeInDatabase`) to link the narinfo to its eventual NAR file. If the subsequent background NAR download fails (e.g., temporary directory missing), or if a chunking operation fails partway through (e.g., "no space left on device"), these placeholder records persist in the database without actual chunked data. When chunking fails, the system automatically clears the `chunking_started_at` lock via the `ClearNarFileChunkingStarted` database operation to prevent subsequent requests from waiting indefinitely for chunks that will never arrive.
-
-When determining whether to use CDC streaming for `GetNar` requests, the system first checks for active local download jobs using `hasActiveLocalJob`. If a local download is active, it uses the faster temp-file streaming path rather than progressive CDC streaming. Otherwise, the system checks both `total_chunks > 0` AND `chunking_started_at IS NOT NULL` to ensure the record represents actual chunked data rather than a placeholder. The `prePullNar` function distinguishes these three states to decide whether to serve from existing chunks, wait for progressive streaming, or trigger a fresh download from upstream.
+- **Actively chunking**: Records with `chunking_started_at` set but `total_chunks = 0`. These records indicate that chunking is in progress. When lazy chunking is disabled, the `chunking_started_at` timestamp is set within milliseconds of download start (before decompression completes), allowing other HA instances to immediately detect active chunking operations and use progressive streaming. The system uses progressive streaming to serve these NARs while chunking completes.
+- **Pending migration (lazy chunking)**: Records with `total_chunks = 0` and `chunking_started_at = NULL`. When lazy chunking is enabled (the default), these records represent compressed NAR files stored without chunking that are awaiting background migration. Background workers asynchronously chunk these files using the `migrate-nar-to-chunks` infrastructure.
+- **Placeholder/Failed**: Records with `total_chunks = 0` and `chunking_started_at = NULL` can also represent placeholder records created during narinfo storage (via `storeInDatabase`) to link the narinfo to its eventual NAR file. If the subsequent background NAR download fails (e.g., temporary directory missing), or if a chunking operation fails partway through (e.g., "no space left on device"), these placeholder records persist in the database without actual chunked data. When chunking fails, the system automatically clears the `chunking_started_at` lock via the `ClearNarFileChunkingStarted` database operation to prevent subsequent requests from waiting indefinitely for chunks that will never arrive.
+
+When determining whether to use CDC streaming for `GetNar` requests, the system first checks for active local download jobs using `hasActiveLocalJob`. If a local download is active, it uses the faster temp-file streaming path rather than progressive CDC streaming. Otherwise, the system checks both `total_chunks > 0` AND `chunking_started_at IS NOT NULL` to ensure the record represents actual chunked data rather than a placeholder or pending migration. The `prePullNar` function distinguishes these states to decide whether to serve from existing chunks, wait for progressive streaming, or trigger a fresh download from upstream.
Placeholder records with `chunking_started_at = NULL` do not cause the system to attempt serving from non-existent chunks. The progressive streaming mechanism in `streamProgressiveChunks` detects aborted chunking (when `total_chunks = 0` and `chunking_started_at = NULL`) and immediately fails fast with a "chunking was aborted" error instead of waiting for the 30-second timeout. This prevents clients from receiving truncated streams and ensures the cache recovers gracefully from failed NAR downloads. This behavior improvement ensures reliability when background downloads or chunking operations fail partway through the caching process.
@@ -123,6 +126,8 @@
The `migrate-nar-to-chunks` command requires CDC to be configured in the database before running the migration. CDC must be enabled by running `ncps serve` with CDC enabled first, which persists the CDC configuration to the database. The `migrate-nar-to-chunks` command reads this configuration from the database automatically.
If CDC is not enabled in the database, the command will return an error: "migrate-nar-to-chunks command requires CDC to be enabled in the database; please run 'ncps serve' with CDC enabled first". This ensures that the migration infrastructure is properly configured before attempting to migrate existing NAR files to the chunked storage format.
+
+When lazy chunking is enabled (the default via `--cache-cdc-lazy-chunking-enabled=true`), compressed NAR files are stored without immediate chunking, and background workers automatically perform migration using the same infrastructure as the `migrate-nar-to-chunks` command. The background workers can be configured via `--cache-cdc-background-workers` (defaults to CPU count).
> **⚠️ CDC Configuration Enforcement**
>
@@ -235,11 +240,71 @@
### Performance Improvements from Streaming
Streaming allows clients to start receiving and processing data immediately as it downloads, rather than waiting for the entire file to be present locally. This reduces perceived latency and improves throughput, especially for large NAR files or slow upstreams. The shared download mechanism also reduces redundant upstream requests and disk usage when multiple clients request the same file concurrently.
-When CDC is enabled, the chunking process runs concurrently with decompression. As soon as the download starts, a CDC goroutine begins reading from the temporary file using a `fileAvailableReader` that blocks until bytes become available (written by the decompression stream). This concurrent execution ensures the `nar_file` database record with `chunking_started_at` is created within milliseconds of download start, allowing other high-availability (HA) instances to immediately detect the active chunking operation instead of polling for up to 30 seconds. The HTTP response completes as soon as the download finishes, without waiting for CDC chunking to complete. This concurrent design significantly reduces Time-To-First-Byte (TTFB) in HA deployments by approximately 30 seconds for large compressed NARs.
+#### Lazy Chunking and TTFB Optimization
+
+When CDC is enabled with lazy chunking (the default via `--cache-cdc-lazy-chunking-enabled=true`), the system optimizes Time-To-First-Byte (TTFB) by storing compressed NAR files directly without immediate decompression or chunking. This approach provides significant performance benefits:
+
+**Benefits:**
+- **Faster cache miss TTFB**: Avoids expensive decompression and chunking operations during download, allowing the HTTP response to complete as soon as the compressed file is stored
+- **Background deduplication**: Background workers asynchronously chunk the stored compressed NAR files, providing the same storage deduplication benefits as immediate chunking but without blocking the client response
+- **Seamless serving**: The system intelligently serves from chunks when available (`total_chunks > 0`) or falls back to the raw compressed NAR from storage when not yet chunked (`total_chunks = 0`)
+
+**Configuration:**
+- `--cache-cdc-lazy-chunking-enabled` (default: `true`): Enable lazy chunking for optimal TTFB
+- `--cache-cdc-background-workers` (default: CPU count): Number of background workers for asynchronous chunking
+
+**Serving Logic:**
+
+When CDC is enabled and a NAR is requested, the system checks the `nar_file` record:
+- If `total_chunks > 0`: Serve from CDC chunks for optimal performance and deduplication
+- If `total_chunks = 0`: Serve the raw compressed NAR from storage while background workers perform chunking
+
+This dual-path serving ensures clients receive data immediately while chunking happens asynchronously, maintaining the deduplication benefits of CDC without impacting TTFB.
+
+To restore the previous behavior where chunking happens synchronously during download, set `--cache-cdc-lazy-chunking-enabled=false`.
+
+#### Concurrent CDC Chunking (Lazy Chunking Disabled)
+
+When lazy chunking is disabled, the chunking process runs concurrently with decompression during download. As soon as the download starts, a CDC goroutine begins reading from the temporary file using a `fileAvailableReader` that blocks until bytes become available (written by the decompression stream). This concurrent execution ensures the `nar_file` database record with `chunking_started_at` is created within milliseconds of download start, allowing other high-availability (HA) instances to immediately detect the active chunking operation instead of polling for up to 30 seconds. The HTTP response completes as soon as the download finishes, without waiting for CDC chunking to complete. This concurrent design significantly reduces TTFB in HA deployments by approximately 30 seconds for large compressed NARs.
For CDC-enabled first pulls where no local download is active, the system optimizes TTFB by preferring the original compressed NAR URL from upstream (e.g., xz) rather than requesting an uncompressed version. When a client requests `compression=none`, the server looks up the narinfo hash in the database and fetches the narinfo from upstream to find the original compressed URL. The `lookupPreferredUpstreamURL` function returns both the preferred compressed `*nar.URL` and the `*narinfo.NarInfo`, which is passed through to `pullNarIntoStore` for use in the single-decompression flow. The compressed file is downloaded and decompressed once using the single-decompression mechanism, with the decompressed data written to a temporary file that all concurrent clients share. This approach reduces TTFB significantly because upstream serves pre-compressed files directly from disk rather than decompressing on-the-fly [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/cache/cache.go#L94-L677).
-### Diagram: Streaming Download Flow with Concurrent CDC
+### Diagram: Streaming Download Flow with CDC
+
+#### Lazy Chunking Enabled (Default)
+```mermaid
+sequenceDiagram
+ participant Client
+ participant CacheServer
+ participant Upstream
+ participant Storage
+ participant BackgroundWorker
+
+ Client->>CacheServer: Request NAR file
+ CacheServer->>Storage: Check local store
+ alt Not found (CDC enabled, lazy chunking)
+ CacheServer->>Upstream: Download compressed NAR
+ Upstream-->>CacheServer: Stream compressed data
+ CacheServer->>Storage: Write compressed NAR directly
+ CacheServer->>Client: Stream compressed NAR
+ Note over CacheServer,Client: HTTP response completes immediately after storage
+ CacheServer->>BackgroundWorker: Trigger background migration (async)
+ BackgroundWorker->>Storage: Read compressed NAR
+ BackgroundWorker->>BackgroundWorker: Decompress and chunk
+ BackgroundWorker->>Storage: Store chunks in DB
+ else Found (nar_file record exists)
+ alt Chunked (total_chunks > 0)
+ CacheServer->>Storage: Serve from CDC chunks
+ CacheServer->>Client: Stream from chunks (deduplication active)
+ else Not chunked yet (total_chunks = 0)
+ CacheServer->>Storage: Serve raw compressed NAR
+ CacheServer->>Client: Stream compressed NAR
+ Note over BackgroundWorker: Background worker will chunk later
+ end
+ end
+```
+
+#### Lazy Chunking Disabled
```mermaid
sequenceDiagram
participant Client
@@ -250,7 +315,7 @@
Client->>CacheServer: Request NAR file
CacheServer->>TempFile: Check local store
- alt Not found (CDC enabled)
+ alt Not found (CDC enabled, lazy chunking disabled)
CacheServer->>Upstream: Download compressed NAR
CacheServer->>CDCGoroutine: Start CDC goroutine (immediately)
Upstream-->>CacheServer: Stream compressed data via io.Pipe |
There was a problem hiding this comment.
Code Review
This pull request introduces lazy CDC chunking to improve TTFB for cache misses. The changes look solid and correctly implement the described feature by deferring the chunking process to background workers. The logic for storing, serving, and triggering background migration of NARs seems correct. I have one suggestion regarding the handling of the new --cache-cdc-background-workers flag to ensure user-provided values are respected, aligning with best practices for parameter defaults.
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1081 +/- ##
=====================================
Coverage 5.04% 5.04%
=====================================
Files 6 6
Lines 436 436
=====================================
Hits 22 22
Misses 410 410
Partials 4 4 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
This implements lazy CDC chunking where NAR files are stored compressed
without chunking initially, then chunked in the background. This
significantly reduces TTFB on cache miss by avoiding the expensive
decompression and chunking operations during download.
Changes:
The existing migrate-nar-to-chunks CLI command can still be used for
manual chunking, and setting --cache-cdc-lazy-chunking-enabled=false
restores the original immediate chunking behavior.