Skip to content

perf: eliminate sequential blocking in non-lazy CDC download path - #1100

Closed
kalbasit wants to merge 1 commit into
mainfrom
perf-eliminate-sequential
Closed

kalbasit wants to merge 1 commit into
mainfrom
perf-eliminate-sequential

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

The non-lazy CDC path was slow because the CDC chunker used
fileAvailableReader which blocks on a condition variable waiting for
decompression to signal each write. This created a sequential
dependency: decompression writes bytes -> CDC reads bytes.

Changes:

  • Add directFileReader that reads directly from the growing file without
    blocking on condition variable. The OS handles blocking when reading
    past EOF, enabling true pipelining between decompression (writing to
    file) and CDC chunking.
  • Reduce batch delays: cdcFirstBatchDelay 100ms -> 10ms,
    cdcSubsequentBatchDelay 500ms -> 50ms for faster chunk recording.

The non-lazy CDC path was slow because the CDC chunker used
fileAvailableReader which blocks on a condition variable waiting for
decompression to signal each write. This created a sequential
dependency: decompression writes bytes -> CDC reads bytes.

Changes:
- Add directFileReader that reads directly from the growing file without
  blocking on condition variable. The OS handles blocking when reading
  past EOF, enabling true pipelining between decompression (writing to
  file) and CDC chunking.
- Reduce batch delays: cdcFirstBatchDelay 100ms -> 10ms,
  cdcSubsequentBatchDelay 500ms -> 50ms for faster chunk recording.
@kalbasit

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Mar 17, 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 significantly enhances the performance of the non-lazy Change Data Capture (CDC) download process by addressing a critical sequential dependency. By introducing a new file reading mechanism that allows the operating system to manage read blocking, it enables parallel execution of decompression and CDC chunking. Additionally, the adjustments to batch processing delays contribute to faster data ingestion and improved system responsiveness.

Highlights

  • Performance Improvement: Eliminated sequential blocking in the non-lazy Change Data Capture (CDC) download path, which previously caused a bottleneck where decompression had to complete writing before CDC could read.
  • New Reader Implementation: Introduced a new directFileReader that reads directly from a growing file, leveraging the operating system's blocking behavior when reading past EOF. This enables true pipelining between decompression and CDC chunking.
  • Batch Delay Reduction: Reduced cdcFirstBatchDelay from 100ms to 10ms and cdcSubsequentBatchDelay from 500ms to 50ms to accelerate CDC chunk recording and batch processing.
  • Reader Replacement: Replaced the blocking fileAvailableReader with the new directFileReader in the pullNarIntoStore function for improved concurrency.
Changelog
  • pkg/cache/cache.go
    • Reduced cdcFirstBatchDelay from 100ms to 10ms.
    • Reduced cdcSubsequentBatchDelay from 500ms to 50ms.
    • Added directFileReader struct and its associated newDirectFileReader constructor and Read and Close methods.
    • Replaced the instantiation of fileAvailableReader with newDirectFileReader in the pullNarIntoStore function.
Activity
  • No specific activity (comments, reviews, progress updates) has been recorded for this pull request yet.
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 added enhancement New feature or request go Pull requests that update go code labels Mar 17, 2026
@dosubot

dosubot Bot commented Mar 17, 2026

Copy link
Copy Markdown

Related Documentation

1 document(s) may need updating based on files changed in this PR:

kalbasit's Space

NAR File Download and Streaming
View Suggested Changes
@@ -93,8 +93,8 @@
 The download and CDC chunking processes work concurrently with two 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.
-3. Multiple concurrent clients requesting the uncompressed version share the same decompressed stream via `fileAvailableReader`, which blocks until bytes become available in `assetPath`.
+2. **CDC goroutine**: Starts immediately and reads from `assetPath` using a `directFileReader`, which reads directly from the growing file without blocking on a condition variable. The goroutine chunks the data concurrently and creates the `nar_file` database record within milliseconds. The `directFileReader` lets the OS handle blocking when reading past EOF, enabling true pipelining between decompression (writing to file) and CDC chunking (reading from file).
+3. Multiple concurrent clients requesting the uncompressed version share the same decompressed stream via `fileAvailableReader`, which blocks on a condition variable 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.
@@ -301,7 +301,15 @@
 
 #### 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.
+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 `directFileReader`, which reads directly from the growing file without blocking on a condition variable. Unlike the previous `fileAvailableReader` approach that blocked on a condition variable waiting for decompression to signal each write, the `directFileReader` lets the OS handle blocking when reading past EOF. This enables true pipelining between decompression (writing to file) and CDC chunking (reading from file), eliminating the sequential dependency that made the non-lazy CDC path slow.
+
+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. 
+
+Performance improvements include:
+- **Reduced batch delays**: The `cdcFirstBatchDelay` has been reduced from 100ms to 10ms, and `cdcSubsequentBatchDelay` from 500ms to 50ms, enabling faster chunk recording and batch processing.
+- **Eliminated sequential blocking**: The `directFileReader` eliminates the sequential blocking that occurred with `fileAvailableReader`, where CDC chunking had to wait for explicit signals from the decompression goroutine.
+
+This concurrent design with pipelined processing 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).
 
@@ -358,7 +366,7 @@
         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->>TempFile: Read from temp file (directFileReader)
             CDCGoroutine->>CDCGoroutine: Chunk data and store in DB
             and
             CacheServer->>Client: Stream decompressed data
@@ -367,9 +375,10 @@
             Upstream-->>CacheServer: Next compressed chunk via pipe
             CacheServer->>CacheServer: Decompress chunk
             CacheServer->>TempFile: Write decompressed chunk
-            CDCGoroutine->>TempFile: Read and chunk concurrently
+            CDCGoroutine->>TempFile: Read and chunk concurrently (pipelined)
             CacheServer->>Client: Stream chunk
         end
+        Note over CDCGoroutine: directFileReader enables pipelining without condition variable
         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

[Accept] [Decline]

Note: You must be authenticated to accept/decline updates.

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 improves the performance of the non-lazy CDC download path by replacing the fileAvailableReader, which uses a condition variable, with a new directFileReader that polls a growing file. This change aims to create a better pipeline between decompression and CDC chunking. The PR also reduces batch delays for faster chunk recording. My review focuses on the implementation of the new directFileReader. I've identified a potential infinite loop and an unused field.

Comment thread pkg/cache/cache.go
Comment on lines +486 to +519
func (r *directFileReader) Read(p []byte) (int, error) {
for {
// Try to read directly from the file
n, readErr := r.f.ReadAt(p, r.offset)

if n > 0 {
r.offset += int64(n)

return n, readErr
}

// No bytes read - check why
r.ds.mu.Lock()
finalSize := r.ds.finalSize
downloadErr := r.ds.downloadError
r.ds.mu.Unlock()

// Check for download error
if downloadErr != nil {
return 0, downloadErr
}

// Check if download is complete
if finalSize > 0 && r.offset >= finalSize {
return 0, io.EOF
}

// Download is still in progress but no bytes available yet
// Sleep briefly to avoid busy looping, then retry
// This is better than blocking on a condition variable because
// it allows the decompressor to write at its own pace
time.Sleep(10 * time.Millisecond)
}
}

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.

high

The Read method has a couple of areas for improvement:

  1. Unhandled Errors: If r.f.ReadAt returns n=0 and an error other than io.EOF (e.g., os.ErrClosed), the error is ignored. This can lead to an infinite loop where the code continuously retries a failing ReadAt call. You should check for and return unexpected errors.
  2. Magic Number: The sleep duration 10 * time.Millisecond is a magic number. It's better to define this as a constant (e.g., directFileReaderPollInterval) for readability and maintainability. You could add this to the const block at the top of the file, or define it locally within the function as shown in the suggestion.

The suggestion below addresses both points.

func (r *directFileReader) Read(p []byte) (int, error) {
	const directFileReaderPollInterval = 10 * time.Millisecond
	for {
		// Try to read directly from the file
		n, readErr := r.f.ReadAt(p, r.offset)

		if n > 0 {
			r.offset += int64(n)
			return n, readErr
		}

		// If we read no bytes, but there was an error other than EOF, return it.
		if readErr != nil && readErr != io.EOF {
			return 0, readErr
		}

		// No bytes read - check why
		r.ds.mu.Lock()
		finalSize := r.ds.finalSize
		downloadErr := r.ds.downloadError
		r.ds.mu.Unlock()

		// Check for download error
		if downloadErr != nil {
			return 0, downloadErr
		}

		// Check if download is complete
		if finalSize > 0 && r.offset >= finalSize {
			return 0, io.EOF
		}

		// Download is still in progress but no bytes available yet
		// Sleep briefly to avoid busy looping, then retry
		// This is better than blocking on a condition variable because
		// it allows the decompressor to write at its own pace
		time.Sleep(directFileReaderPollInterval)
	}
}

Comment thread pkg/cache/cache.go
Comment on lines +469 to +484
type directFileReader struct {
f *os.File
ds *downloadState
offset int64
readBufSize int
}

// newDirectFileReader creates a reader that reads directly from the growing file.
func newDirectFileReader(f *os.File, ds *downloadState) *directFileReader {
return &directFileReader{
f: f,
ds: ds,
offset: 0,
readBufSize: 64 * 1024, // 64KB read buffer for efficient chunking
}
}

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.

medium

The field readBufSize is initialized in newDirectFileReader but it's never used in the Read method or anywhere else in directFileReader. This field should be removed to avoid confusion and dead code.

type directFileReader struct {
	f           *os.File
	ds          *downloadState
	offset      int64
}

// newDirectFileReader creates a reader that reads directly from the growing file.
func newDirectFileReader(f *os.File, ds *downloadState) *directFileReader {
	return &directFileReader{
		f:           f,
		ds:          ds,
		offset:      0,
	}
}

@codecov

codecov Bot commented Mar 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (7924c85) to head (34fcf40).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1100   +/-   ##
=====================================
  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

Copy link
Copy Markdown
Owner Author

fixed in #1102 instead...

@kalbasit kalbasit closed this Mar 18, 2026
@kalbasit
kalbasit deleted the perf-eliminate-sequential branch March 18, 2026 03:29
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