Skip to content

feat: implement lazy CDC chunking for faster TTFB - #1081

Merged
kalbasit merged 2 commits into
mainfrom
feat-implement-lazy-cdc-chunking
Mar 13, 2026
Merged

kalbasit merged 2 commits into
mainfrom
feat-implement-lazy-cdc-chunking

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

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 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.
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Mar 13, 2026
@dosubot dosubot Bot added enhancement New feature or request go Pull requests that update go code labels Mar 13, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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

  • Lazy CDC Chunking Implementation: Implemented a new lazy CDC chunking mechanism where NAR files are initially stored compressed without chunking, and then chunked in the background. This aims to significantly reduce Time To First Byte (TTFB) on cache misses by deferring expensive decompression and chunking operations.
  • New Configuration Flags: Added --cache-cdc-lazy-chunking-enabled (default: true) to control the lazy chunking behavior and --cache-cdc-background-workers (default: CPU count) to specify the number of workers for background chunking.
  • Conditional NAR Storage: Modified the NAR storage process to store compressed NARs directly without immediate chunking when lazy chunking is enabled, marking them with total_chunks=0 for later background migration.
  • Intelligent NAR Serving: Updated the NAR serving logic to serve raw compressed NARs directly from storage if they have not yet been chunked (i.e., total_chunks=0), otherwise serving from pre-chunked data for optimized performance.
  • Background Migration Trigger: Integrated a mechanism to trigger background migration for NARs that were stored lazily, ensuring they are eventually chunked for optimal long-term performance.
Changelog
  • pkg/cache/cache.go
    • Added cdcLazyChunkingEnabled and cdcBackgroundWorkers fields to the Cache struct for lazy chunking configuration.
    • Implemented SetCDCLazyChunking, GetCDCLazyChunkingEnabled, and GetCDCBackgroundWorkers methods to manage lazy chunking settings.
    • Modified storeNarFromTempFile to store compressed NARs directly without immediate chunking if lazy CDC is enabled.
    • Refactored pullNarIntoStore to explicitly check for lazy chunking status before processing NARs through the CDC pipeline.
    • Introduced a background migration trigger in pullNarIntoStore for NARs stored with lazy chunking.
    • Enhanced serveNarFromStorageViaPipe to serve raw compressed NARs if they haven't been chunked yet due to lazy chunking.
  • pkg/ncps/serve.go
    • Imported the runtime package to determine the number of CPU cores.
    • Added --cache-cdc-lazy-chunking-enabled and --cache-cdc-background-workers CLI flags for configuring lazy chunking.
    • Configured the cache's lazy chunking with defaults for cdcLazyChunkingEnabled (true) and cdcBackgroundWorkers (CPU count) based on CLI flags.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@dosubot

dosubot Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

Documentation Updates

2 document(s) were updated by changes in this PR:

Cache and Storage Configuration Flags
View 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 Streaming
View 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

How did I do? Any feedback?  Join Discord

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/ncps/serve.go Resolved
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@codecov

codecov Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (4ea3739) to head (08661d7).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@kalbasit
kalbasit enabled auto-merge (squash) March 13, 2026 00:36
@kalbasit
kalbasit merged commit 405ce06 into main Mar 13, 2026
16 checks passed
@kalbasit
kalbasit deleted the feat-implement-lazy-cdc-chunking branch March 13, 2026 00:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant