Repository navigation
perf: fix CDC eager mode performance — async chunking and batch progressive streaming - #1102
Conversation
…essive streaming Two separate bottlenecks caused slow NAR downloads when CDC eager mode (lazy chunking disabled) was active: **Bottleneck 1 — Server A: CDC blocked the HTTP response (Fix 1A)** In the simple download path, storeNarWithCDC was called synchronously after the download completed. The HTTP response stayed open until all CDC chunking finished, forcing the Nix client to wait for the full chunk pipeline before it could verify the NAR hash. Fix: after streamResponseToFile completes and CDC eager mode is active, spawn a background goroutine to run storeNarWithCDC asynchronously (same pattern as the existing CDC compressed path). The onNarFileReady callback closes ds.stored early — as soon as the nar_file DB record is created and before chunking starts — so the HTTP response completes at download+transfer speed. CDC chunking continues in the background. Removed the now-dead CDC eager-mode branch from storeNarFromTempFile. **Bottleneck 2 — Servers B/C: progressive chunk streaming was slow (Fixes 2A/2B)** streamProgressiveChunks polled one chunk at a time via GetChunkByNarFileIDAndIndex with a 200ms sleep between retries. For a large NAR (e.g. 370 chunks), the per-chunk polling overhead added several seconds. The prefetch buffer was also only 2 chunks. Fix 2A: added GetChunksByNarFileIDFromIndex batch query to all three database engines (SQLite, PostgreSQL, MySQL) and replaced the one-at-a- time poll loop with batch queries of up to 256 chunks per round-trip. When multiple chunks are already available (CDC goroutine has flushed a batch), they are fed into the pipeline immediately without any sleep. The 200ms sleep is only incurred when at the frontier (no new chunks yet). Re-added the abort/completion NarFile re-check inside the inner wait loop so fast-fail for aborted chunking is preserved. Fix 2B: increased prefetchBufferSize from 2 to 16, allowing more chunk I/O to overlap with data copying.
|
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 significantly enhances the performance of NAR downloads when Content-Defined Chunking (CDC) eager mode is active. It addresses two primary bottlenecks by decoupling the CDC chunking process from the HTTP response cycle and by optimizing the progressive streaming of chunks through batch database queries and increased prefetching. These changes aim to provide a faster and more responsive experience for clients downloading NARs. 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 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView Changes@@ -90,14 +90,14 @@
- **io.Pipe**: Connects the HTTP response body to the decompressor without writing compressed data to disk
- **Uncompressed file** (`assetPath`): Stores the decompressed data as it is written by the decompression stream
-The download and CDC chunking processes work concurrently with two goroutines:
+The download and CDC chunking processes work with asynchronous goroutines:
1. **Download goroutine**: The HTTP response body is piped through a decompressor (`nar.DecompressReader`), and the decompressed output is written to the temp file at `assetPath` using `streamReaderToFile`. This happens inline within the download goroutine.
-2. **CDC goroutine**: Starts immediately and reads from `assetPath` using a `fileAvailableReader`, which blocks until bytes become available. The goroutine chunks the data concurrently and creates the `nar_file` database record within milliseconds.
+2. **CDC goroutine**: Runs asynchronously in a background goroutine after the download completes. The goroutine reads from `assetPath` and chunks the data, creating the `nar_file` database record within milliseconds of starting. The HTTP response returns to the client immediately once the download finishes, without waiting for chunking to complete, allowing the Nix client to verify the NAR hash without blocking on CDC operations.
3. Multiple concurrent clients requesting the uncompressed version share the same decompressed stream via `fileAvailableReader`, which blocks until bytes become available in `assetPath`.
4. Clients begin receiving uncompressed data as soon as the decompressor produces bytes, without waiting for the full download to complete.
-This approach prevents the excessive memory usage and resource contention that would occur if multiple clients simultaneously attempted to decompress the same large NAR file. By eliminating the compressed temp file and using an `io.Pipe`, the system reduces disk I/O—only the decompressed data is written to disk, not the compressed data. The concurrent CDC chunking ensures that the database record with `chunking_started_at` is visible to other HA instances immediately, rather than waiting for full decompression to complete first. The single-decompression mechanism significantly reduces memory pressure and disk usage under concurrent load and improves system reliability for CDC-enabled deployments.
+This approach prevents the excessive memory usage and resource contention that would occur if multiple clients simultaneously attempted to decompress the same large NAR file. By eliminating the compressed temp file and using an `io.Pipe`, the system reduces disk I/O—only the decompressed data is written to disk, not the compressed data. The asynchronous CDC chunking ensures that the HTTP response completes at download speed, rather than waiting for CDC operations to finish. The single-decompression mechanism significantly reduces memory pressure and disk usage under concurrent load and improves system reliability for CDC-enabled deployments.
#### Background Job Context Isolation
@@ -119,7 +119,7 @@
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.
+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` uses batch queries to fetch multiple available chunks at once (up to 256 chunks per query via `GetChunksByNarFileIDFromIndex`), eliminating per-chunk poll latency when chunks are already created. This batch approach only polls with a 200ms sleep when no new chunks are available yet, providing fast streaming when chunks are already written. The mechanism 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.
#### CDC Requirements
@@ -240,6 +240,10 @@
### 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.
+**Progressive Streaming Performance:**
+
+The progressive streaming mechanism (`streamProgressiveChunks`) has been optimized for performance with a prefetch buffer of 16 chunks (allowing effective overlapping of I/O operations during chunk streaming) and batch queries that fetch up to 256 chunks at once via `GetChunksByNarFileIDFromIndex`. This batch approach eliminates per-chunk polling overhead when multiple chunks are already available, significantly improving streaming performance for large NAR files. The 200ms poll interval is only incurred when waiting at the frontier for new chunks to be written, rather than between every chunk.
+
#### 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:
@@ -299,9 +303,9 @@
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.
+#### Async CDC Chunking (Lazy Chunking Disabled)
+
+When lazy chunking is disabled, the chunking process runs asynchronously in a background goroutine after the download completes. The HTTP response returns to the client immediately once the download finishes, without waiting for CDC chunking to complete. This allows the Nix client to verify the NAR hash without blocking on CDC operations. The background CDC goroutine reads from the temporary file and chunks the data, creating the `nar_file` database record within milliseconds of starting. This asynchronous design significantly improves download performance by decoupling the HTTP response from CDC operations, which can take considerable time for large NAR files.
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).
@@ -353,25 +357,21 @@
CacheServer->>TempFile: Check local store
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
CacheServer->>CacheServer: Decompress inline in download goroutine
CacheServer->>TempFile: Write decompressed data to temp file
- par Concurrent Operations
- CDCGoroutine->>TempFile: Read from temp file (blocks until available)
- CDCGoroutine->>CDCGoroutine: Chunk data and store in DB
- and
- CacheServer->>Client: Stream decompressed data
- end
+ CacheServer->>Client: Stream decompressed data
loop Until download complete
Upstream-->>CacheServer: Next compressed chunk via pipe
CacheServer->>CacheServer: Decompress chunk
CacheServer->>TempFile: Write decompressed chunk
- CDCGoroutine->>TempFile: Read and chunk concurrently
CacheServer->>Client: Stream chunk
end
+ Note over CacheServer,Client: HTTP response completes when download finishes
+ CacheServer->>CDCGoroutine: Start CDC goroutine asynchronously (after download)
+ CDCGoroutine->>TempFile: Read from temp file
+ CDCGoroutine->>CDCGoroutine: Chunk data and store in DB
Note over CDCGoroutine: Creates nar_file DB record within milliseconds
- Note over CacheServer,Client: HTTP response completes when download finishes
Note over CDCGoroutine: Continues chunking in background
CacheServer->>TempFile: Cleanup temp file after all readers finish
else Found |
There was a problem hiding this comment.
Code Review
This pull request significantly optimizes chunk streaming performance, particularly for Content-Defined Chunking (CDC). It introduces a new batched database query (GetChunksByNarFileIDFromIndex) to fetch multiple chunks at once, replacing the previous single-chunk polling mechanism. The prefetchBufferSize for chunk streaming has been increased from 2 to 16, and a progressivePollBatchSize of 256 has been added to reduce database round-trips. Additionally, a "CDC eager mode" has been implemented to perform CDC chunking asynchronously in the background after a NAR download, improving client responsiveness. Minor changes include adding /.claude/plans/ to .gitignore.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1102 +/- ##
=====================================
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:
|
|
Backport failed for Please cherry-pick the changes locally and resolve any conflicts. git fetch origin release-0.9
git worktree add -d .worktree/backport-1102-to-release-0.9 origin/release-0.9
cd .worktree/backport-1102-to-release-0.9
git switch --create backport-1102-to-release-0.9
git cherry-pick -x a64b63fbc5e90596828640091d594378cd7f20ac |
…essive streaming [backport #1102] Two separate bottlenecks caused slow NAR downloads when CDC eager mode (lazy chunking disabled) was active: **Bottleneck 1 — Server A: CDC blocked the HTTP response (Fix 1A)** In the simple download path, storeNarWithCDC was called synchronously after the download completed. The HTTP response stayed open until all CDC chunking finished, forcing the Nix client to wait for the full chunk pipeline before it could verify the NAR hash. Fix: after streamResponseToFile completes and CDC eager mode is active, spawn a background goroutine to run storeNarWithCDC asynchronously (same pattern as the existing CDC compressed path). The onNarFileReady callback closes ds.stored early — as soon as the nar_file DB record is created and before chunking starts — so the HTTP response completes at download+transfer speed. CDC chunking continues in the background. Removed the now-dead CDC eager-mode branch from storeNarFromTempFile. **Bottleneck 2 — Servers B/C: progressive chunk streaming was slow (Fixes 2A/2B)** streamProgressiveChunks polled one chunk at a time via GetChunkByNarFileIDAndIndex with a 200ms sleep between retries. For a large NAR (e.g. 370 chunks), the per-chunk polling overhead added several seconds. The prefetch buffer was also only 2 chunks. Fix 2A: added GetChunksByNarFileIDFromIndex batch query to all three database engines (SQLite, PostgreSQL, MySQL) and replaced the one-at-a- time poll loop with batch queries of up to 256 chunks per round-trip. When multiple chunks are already available (CDC goroutine has flushed a batch), they are fed into the pipeline immediately without any sleep. The 200ms sleep is only incurred when at the frontier (no new chunks yet). Re-added the abort/completion NarFile re-check inside the inner wait loop so fast-fail for aborted chunking is preserved. Fix 2B: increased prefetchBufferSize from 2 to 16, allowing more chunk I/O to overlap with data copying. (cherry picked from commit a64b63f)
…essive streaming [backport #1102] (#1103) Two separate bottlenecks caused slow NAR downloads when CDC eager mode (lazy chunking disabled) was active: **Bottleneck 1 — Server A: CDC blocked the HTTP response (Fix 1A)** In the simple download path, storeNarWithCDC was called synchronously after the download completed. The HTTP response stayed open until all CDC chunking finished, forcing the Nix client to wait for the full chunk pipeline before it could verify the NAR hash. Fix: after streamResponseToFile completes and CDC eager mode is active, spawn a background goroutine to run storeNarWithCDC asynchronously (same pattern as the existing CDC compressed path). The onNarFileReady callback closes ds.stored early — as soon as the nar_file DB record is created and before chunking starts — so the HTTP response completes at download+transfer speed. CDC chunking continues in the background. Removed the now-dead CDC eager-mode branch from storeNarFromTempFile. **Bottleneck 2 — Servers B/C: progressive chunk streaming was slow (Fixes 2A/2B)** streamProgressiveChunks polled one chunk at a time via GetChunkByNarFileIDAndIndex with a 200ms sleep between retries. For a large NAR (e.g. 370 chunks), the per-chunk polling overhead added several seconds. The prefetch buffer was also only 2 chunks. Fix 2A: added GetChunksByNarFileIDFromIndex batch query to all three database engines (SQLite, PostgreSQL, MySQL) and replaced the one-at-a- time poll loop with batch queries of up to 256 chunks per round-trip. When multiple chunks are already available (CDC goroutine has flushed a batch), they are fed into the pipeline immediately without any sleep. The 200ms sleep is only incurred when at the frontier (no new chunks yet). Re-added the abort/completion NarFile re-check inside the inner wait loop so fast-fail for aborted chunking is preserved. Fix 2B: increased prefetchBufferSize from 2 to 16, allowing more chunk I/O to overlap with data copying. (cherry picked from commit a64b63f)
Two separate bottlenecks caused slow NAR downloads when CDC eager mode
(lazy chunking disabled) was active:
Bottleneck 1 — Server A: CDC blocked the HTTP response (Fix 1A)
In the simple download path, storeNarWithCDC was called synchronously
after the download completed. The HTTP response stayed open until all
CDC chunking finished, forcing the Nix client to wait for the full chunk
pipeline before it could verify the NAR hash.
Fix: after streamResponseToFile completes and CDC eager mode is active,
spawn a background goroutine to run storeNarWithCDC asynchronously (same
pattern as the existing CDC compressed path). The onNarFileReady
callback closes ds.stored early — as soon as the nar_file DB record is
created and before chunking starts — so the HTTP response completes at
download+transfer speed. CDC chunking continues in the background.
Removed the now-dead CDC eager-mode branch from storeNarFromTempFile.
Bottleneck 2 — Servers B/C: progressive chunk streaming was slow
(Fixes 2A/2B)
streamProgressiveChunks polled one chunk at a time via
GetChunkByNarFileIDAndIndex with a 200ms sleep between retries. For a
large NAR (e.g. 370 chunks), the per-chunk polling overhead added
several seconds. The prefetch buffer was also only 2 chunks.
Fix 2A: added GetChunksByNarFileIDFromIndex batch query to all three
database engines (SQLite, PostgreSQL, MySQL) and replaced the one-at-a-
time poll loop with batch queries of up to 256 chunks per round-trip.
When multiple chunks are already available (CDC goroutine has flushed a
batch), they are fed into the pipeline immediately without any sleep.
The 200ms sleep is only incurred when at the frontier (no new chunks
yet). Re-added the abort/completion NarFile re-check inside the inner
wait loop so fast-fail for aborted chunking is preserved.
Fix 2B: increased prefetchBufferSize from 2 to 16, allowing more chunk
I/O to overlap with data copying.