Skip to content

feat: coalesce concurrent cache misses into one upstream fetch - #440

Merged
alecthomas merged 7 commits into
mainfrom
coalesce-cache-misses-design
Nov 9, 2026
Merged

alecthomas merged 7 commits into
mainfrom
coalesce-cache-misses-design

Conversation

@alecthomas

@alecthomas alecthomas commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

When many clients request the same uncached object at once, each one fetches it from upstream independently. That multiplies upstream load and bandwidth exactly when an object is most in demand, and makes upstream rate limits more likely. This matters most for large artefacts and the upcoming OCI strategy, where a fleet of CI machines often pulls the same blob at the same moment.

This change makes the first miss for a key start a single upstream fetch, and every concurrent request for that key streams the response while it is still downloading. It replaces the Git strategy's private spool with a shared internal/spool package used by every HTTP strategy, Git upload-pack and Git snapshot generation.

  • A spool.Registry owns every in-flight fetch. Fetches run detached from the requests that started them, so the cache still fills if every client disconnects. They end at fill-timeout (default 30m) or when the registry is closed after the server drains at shutdown.
  • Successful responses are shared with concurrent requests. Error responses are shared only where RFC 9111 allows a shared cache to reuse them, for at most error-window (default 5s) from when the error's headers arrive, so a burst of misses does not turn into a burst of upstream errors. Each waiting request is checked against its own credentials, no-cache directives and the response's Vary headers, so an anonymous 404 cannot block an authorized download and a forced retry always reaches upstream.
  • Caches that can be read while they are written implement the new optional cache.PendingReader interface on their Writer. Disk and tiered caches do, so readers follow the cache write directly and the response is stored once. Other backends fall back to a temporary file in the spool directory.
  • Each fill commits its cache write with Writer.Commit, which returns cache failures to the strategy that owns the fill rather than logging them inside the spool. A cache failure never fails an otherwise complete response. Shared handler fills keep the handler's body verification and revalidation timestamps, so a body that fails verification is still served but never cached.
  • HEAD misses are still forwarded upstream without caching. Range and conditional misses are not coalesced, because they need a different response from the shared one, and keep the existing miss path.
  • If a shared response fails after its headers were sent, the connection is aborted so clients cannot mistake a truncated body for a complete one. Fills run outside the HTTP server's panic recovery, so an http.ErrAbortHandler panic from reused handler code such as httputil.ReverseProxy becomes a fill error instead of crashing the process. This also fixes a Git bug where a failed spooled upload-pack response was followed by a second, upstream response after headers had been sent.
  • Git snapshots are now generated once, directly into the cache, while every waiting request streams them. The fill holds the repository's snapshot lock from clone to commit, so it cannot overwrite a newer periodic snapshot. If another snapshot job holds the lock, the fill streams without caching.

Configuration is a new optional global block, documented in the README. Leaving it out applies the defaults shown:

spool {
  dir          = "${CACHEW_STATE}/spools"
  fill-timeout = "30m"
  error-window = "5s"
}

This overlaps with #430, which also coalesces HTTP misses. This PR covers that part more broadly, but it does not include #430's backoff after upstream 429 responses, which would need to land separately.

🤖 Generated with Claude Code

alecthomas and others added 2 commits November 9, 2026 12:54
When many clients request the same uncached object, each one used to fetch
it from upstream independently. That multiplies upstream load, risks rate
limits, and wastes bandwidth exactly when an object is most in demand.

A shared spool now lets the first miss start a single fetch that every
concurrent request streams while it downloads. The fetch runs detached
from its clients, so the cache still fills if they all disconnect, and is
bounded by a configurable timeout and cancelled at shutdown. Error
responses are shared only where RFC 9111 permits reuse, for at most a
configurable window.

Caches that can be read while writing (disk, tiered) expose an optional
PendingReader so readers follow the cache write directly instead of
writing the response twice.

Git upload-pack and snapshot generation move onto the same spool. This
also fixes a bug where a failed spooled response was followed by an
upstream response after headers had been sent; truncated responses now
abort the connection instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The pre-push hook rejected the coalescing change. Lint flagged an
over-long main, test packaging and an always-nil return, and the race
detector caught a handler test closing its cache under in-flight
requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alecthomas
alecthomas marked this pull request as ready for review November 9, 2026 02:11
@alecthomas
alecthomas requested a review from a team as a code owner November 9, 2026 02:11
@alecthomas
alecthomas requested review from stuartwdouglas and removed request for a team November 9, 2026 02:11
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T03:20:24.981269Z b970aef New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e2be8b3793

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/strategy/git/git.go Resolved
Comment thread internal/spool/group.go Resolved
Fills run in the registry's goroutine, outside the HTTP server's panic
recovery, but they reuse handler code. httputil.ReverseProxy panics with
http.ErrAbortHandler on a truncated upstream body, so a failed Git
upload-pack fill could crash cachewd. Fills now convert that panic into
a fill error, so only the affected responses are aborted.

The spool also logged cache commit failures itself, leaving strategies
no say in how they are reported. Writer.Commit now returns them to the
fill, which outlives its readers and so is the one caller guaranteed to
see the outcome. A fill that stores a cache write but never commits it
fails with ErrUncommitted rather than silently losing the entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 171a331a7d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/spool/group.go Resolved
Comment thread internal/spool/group.go Resolved
Comment thread internal/strategy/git/snapshot.go Resolved
Spool cleanup failures were logged inside the package, so owners could
not report or act on them. The registry now takes an owner callback,
because cleanup runs on whichever goroutine drops the last reference.

A shared error response was checked only against the request that
fetched it, so an anonymous 404 could suppress an authorized download
of the same key. Followers are now checked against their own
credentials and the response's Vary headers.

On-demand snapshot fills could publish an older clone over a newer
periodic snapshot. Fills now hold the snapshot mutex from clone to
commit, and stream without caching when another publisher holds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 929e408295

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/spool/group.go Resolved
A shared error's reuse lifetime only started counting when its fill
finished, so a slowly streaming error stayed joinable for its whole
download and then for its full lifetime again. Stale failures could
keep reaching clients after upstream recovered, beyond error-window.

Expiry is now fixed when the headers arrive. Requests arriving later
start a fresh fill instead of joining, and a completed entry is kept
only for the time remaining.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a121447dd0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/httputil/reuse.go Resolved
alecthomas and others added 2 commits November 9, 2026 14:15
A client retrying a failed download with Cache-Control: no-cache could
still receive a retained 404 or 503 without upstream being contacted,
even after the resource became available. Before coalescing, non-200
responses were always fetched independently, so this was a regression.

Followers that request no-cache, or Pragma: no-cache without
Cache-Control, now fetch upstream themselves. A leader's no-cache does
not stop others reusing its response, so the reuse rules are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A bare panic(http.ErrAbortHandler) reads as a mistake. Note that the
abort stops the server from ending the chunked body cleanly, which
would let git treat a truncated pack as complete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alecthomas
alecthomas merged commit 125c6ea into main Nov 9, 2026
7 checks passed
@alecthomas
alecthomas deleted the coalesce-cache-misses-design branch November 9, 2026 04:17
worstell added a commit that referenced this pull request Nov 9, 2026
Image pulls from CI and workstations fetch the same layers from Docker
Hub and other registries over and over. That is slow, and it runs into
pull rate limits. This adds an `oci` strategy that serves the OCI
Distribution API from cachew, so those pulls hit the local and tiered
caches instead. It builds on the handler groundwork from #438 and the
request coalescing from #440.

The changes, one commit each:

- The `oci` strategy, configured with one block per registry.
- Routes: clients reach a registry at `/oci/<registry>/v2/`, which suits
containerd with `override_path`, or on a dedicated hostname at `/v2/`,
which Docker and Podman need because they cannot use a path prefix.
`/v2/` is answered locally. Pushes and any other write method get a 405.
- Paths are parsed from the end, because repository names can contain
slashes. Configured rewrites, such as Docker Hub's implicit `library/`
namespace, are applied before the name and reference are validated.
- Blobs are keyed on registry plus digest, verified against their digest
before caching, and never revalidated. Large blob fills use
`ParallelFetch`, with configurable chunk size and concurrency (32 MB × 4
by default). Registry redirects to a CDN are followed on the server
side.
- Digest-addressed manifests are verified and treated as immutable. Tag
manifests are keyed on a normalised `Accept` header. After `tag-ttl`
(default 5m) they are revalidated with a HEAD request on
`Docker-Content-Digest`, since the cache replaces upstream ETags. Docker
Hub does not count HEADs against rate limits. A stale tag is served when
the upstream is unavailable or rate limiting.
  - Tag lists and referrers pass through uncached.
- Upstream auth uses go-containerregistry's token transport with the
strategy's own `username`/`password`, or anonymous access when they are
unset. One transport is kept per repository scope. Client
`Authorization` and `Cookie` headers are removed and never forwarded.
- The README has an `oci` section with a Docker Hub example and setup
notes for containerd and Docker.
- An integration test against the reference registry (`registry:3`,
Distribution 3.1.2) running in Docker. It pulls through cachew with
go-containerregistry's client and checks every blob digest. It covers
anonymous and htpasswd upstreams, tag updates, and serving from cache
after the registry container is removed. It runs under the `integration`
tag in CI and fails rather than skips when Docker is missing.

New dependencies:

- go-containerregistry v0.22.1 provides the token exchange. It also
brings in docker/cli's config code, docker-credential-helpers and
logrus.
- go-digest checks digests.
- `golang.org/x/crypto` was already an indirect dependency and is now
direct, because the integration test uses bcrypt to create the htpasswd
file.
- Module version selection also raised klauspost/compress, x/mod, x/sync
and x/sys.

Known limitations:

- A manifest fetched only by tag is not also cached under its digest. A
later pull by digest misses the cache, and fails if the upstream is
down.
- In `tags/list` responses, the `Link` header for the next page still
uses the upstream path. A path-prefixed client that follows it will go
around cachew.
- Blob keys do not include the repository. A cached blob can therefore
be fetched under any repository name on the same registry. That is
consistent with every client sharing the upstream credentials.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Elizabeth Worstell <worstell@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Elizabeth Worstell <worstell@squareup.com>
Co-authored-by: Chain <492cad42391b4a5c84d831885f468e6f1699c0a8c39241f1c002235ece37ee69@buzz>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant