Skip to content

registry: enable sendfile for filesystem blob GETs - #5052

Merged
milosgajdos merged 3 commits into
distribution:mainfrom
jgehrcke:jp/linux-sendfile-submit
Nov 28, 2026
Merged

milosgajdos merged 3 commits into
distribution:mainfrom
jgehrcke:jp/linux-sendfile-submit

Conversation

@jgehrcke

@jgehrcke jgehrcke commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

This PR enables the registry to use sendfile(2) when serving blobs from a local filesystem.

#5081 is part of this patch (edit: merged).

Compared with main before #5081, this approach reduces registry total CPU time per whole-blob GET by ~78 % (4 MiB) and ~90 % (32 MiB) over plain HTTP.

The ~90 % reduction / ~10x improvement was measured for a warm page cache. With a cold page cache I measured a CPU time reduction of ~72 % (see below for more raw-ish data).

How? Without this patch, two wrappers keep Go's net/http from using sendfile(2): fileReader hides the *os.File, and instrumentedResponseWriter hides io.ReaderFrom. I've addressed this in two parts:

  • PR 5081 passes the *os.File directly to http.ServeContent.
  • This PR forwards ReadFrom through the response wrappers (and deals with the fallout).

Note: Go cannot use sendfile(2) when it itself does TLS termination. However, even when we do TLS termination directly in Go (in the registry process), #5081 typically yields some significant CPU utilization reduction (cf. 5081's PR description).

Making metrics/logging instrumentation play along

This was a bit rough, actually the hardest part of this patch series I'd say.

The challenge: the access log machinery, otelhttp, and the Prometheus metrics machinery each wrap the response writer, and they all need to comply with forwarding ReadFrom, i.e. these wrappers no longer see the body! This is no problem per se, but seemingly this wasn't really tried much before. So, I needed to crunch through all these dependencies and help to make them do the right thing.

#5075 and #5076 were split out of this PR earlier and are already merged.

This PR branch contains three more commits to deal with the remaining challenges:

Restore otelhttp body byte counting

Pin otelhttp to an unreleased commit that counts the body bytes (this contains my patch #9998). Should this PR here wait for a release?

Repair response size logging

For a body copied through ReadFrom, Gorilla's access log handler logs a size of zero. I reported that here. I think it is unlikely that we see a new Gorilla release for that. So, I took a deep breath and opted for a pragmatic solution: registry/accesslog.go is a new handler of ~100 lines. It counts bytes with httpsnoop hooks and builds the log line itself, in Gorilla's format (quite heavily reviewed/tested by an agent).

Not beautiful, but not all too ugly. I think it's a workable solution.

Edit: this part of the patch was now broken out to #5103. (update: merged)

Work around a Prometheus wrapper issue in the pull-through proxy

Keep the pull-through proxy copying through Write: the Prometheus wrapper that we use here has a defect: it sends status 200 before it reads the body. I reported it here and worked around that here in this PR. I'll also propose a proper upstream patch. (update: proposed a patch here: prometheus/client_golang#2223)

Measurement summary

Registry total CPU time per whole-blob GET in ms (mean ± sample SD), warm page cache, linux/arm64:

Transport Blob main (n=15) #5081 (n=15) This PR (n=15) Change, main to this PR
plain HTTP 4 MiB 1.983 ± 0.028 1.176 ± 0.014 0.433 ± 0.013 -78.2%
plain HTTP 32 MiB 9.51 ± 0.12 6.981 ± 0.026 0.960 ± 0.020 -89.9%
TLS 4 MiB 3.393 ± 0.032 2.405 ± 0.012 2.349 ± 0.019 -30.8%
TLS 32 MiB 20.263 ± 0.079 17.608 ± 0.066 17.429 ± 0.031 -14.0%

With a cold page cache (8 GETs of 1 GiB blobs from a local NVMe drive, one at a time), registry total CPU time in s (mean ± sample SD):

Transport main (n=15) #5081 (n=15) This PR (n=15) Change, main to this PR
plain HTTP 2.750 ± 0.040 2.821 ± 0.021 0.781 ± 0.013 -71.6%
TLS 5.278 ± 0.044 5.595 ± 0.050 5.521 ± 0.069 +4.6%

Cold page cache, wall time change: the client waited 49 % less over plain HTTP and 7 % less over TLS.

Update: I've published the exact code used for measuring here: https://github.com/jgehrcke/sendfile-perf-repro/tree/main/distribution (on a beefy machine with 144 cores, harness currently assumes two NUMA nodes, tests were run with client and server processes pinned to one of the NUMA nodes)

@github-actions github-actions Bot added area/storage area/proxy Related to registry as a pull-through cache dependencies Pull requests that update a dependency file labels Oct 27, 2026
@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from 6b00397 to 0426171 Compare November 11, 2026 16:03
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 11, 2026
Update golang.org/x/sys from v0.48.0 to v0.49.0. No other module
changes version.

full diff: golang/sys@v0.48.0...v0.49.0

distribution#5052 needs this: the otelhttp revision it pins lists x/sys v0.49.0
in its go.mod.

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 11, 2026
Update go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp
from v0.67.0 to v0.72.0, the latest tagged release.

otelhttp v0.72.0 requires these module versions, which move with it:

  go.opentelemetry.io/otel             v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/trace       v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/metric      v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/sdk         v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/sdk/metric  v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/log         v0.21.0 -> v1.47.0
  github.com/felixge/httpsnoop         v1.0.4  -> v1.1.0

No other module changes version; autoexport and the exporter modules
stay as they are. go.mod, go.sum and vendor are the output of go get,
go mod tidy and go mod vendor. No registry code changes.

Server spans keep their names and attribute keys. Two values change:
http.request.method is _OTHER instead of GET for an unknown request
method, and the instrumentation scope version becomes 0.72.0. otelhttp
now takes its attribute definitions from semconv v1.43.0 instead of
v1.40.0.

This is split out of distribution#5052 to keep its dependency change small.

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from 0426171 to f1426a8 Compare November 11, 2026 17:02
milosgajdos pushed a commit that referenced this pull request Nov 11, 2026
Update golang.org/x/sys from v0.48.0 to v0.49.0. No other module
changes version.

full diff: golang/sys@v0.48.0...v0.49.0

#5052 needs this: the otelhttp revision it pins lists x/sys v0.49.0
in its go.mod.

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
milosgajdos pushed a commit that referenced this pull request Nov 11, 2026
Update go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp
from v0.67.0 to v0.72.0, the latest tagged release.

otelhttp v0.72.0 requires these module versions, which move with it:

  go.opentelemetry.io/otel             v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/trace       v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/metric      v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/sdk         v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/sdk/metric  v1.45.0 -> v1.47.0
  go.opentelemetry.io/otel/log         v0.21.0 -> v1.47.0
  github.com/felixge/httpsnoop         v1.0.4  -> v1.1.0

No other module changes version; autoexport and the exporter modules
stay as they are. go.mod, go.sum and vendor are the output of go get,
go mod tidy and go mod vendor. No registry code changes.

Server spans keep their names and attribute keys. Two values change:
http.request.method is _OTHER instead of GET for an unknown request
method, and the instrumentation scope version becomes 0.72.0. otelhttp
now takes its attribute definitions from semconv v1.43.0 instead of
v1.40.0.

This is split out of #5052 to keep its dependency change small.

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from f1426a8 to b7d5b12 Compare November 11, 2026 19:14
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 12, 2026
This patch fixes two defects in blob GET requests on the filesystem
driver and significantly reduces the CPU time that the registry consumes
for serving them. It passes the blob file directly to http.ServeContent.

This patch was extracted from distribution#5052. That PR builds on this patch to
enable sendfile(2), which requires passing an *os.File to
http.ServeContent.

Performance impact
------------------

With a warm page cache, this patch reduces registry total CPU time by
13% to 42% per whole-blob GET (100 KiB to 32 MiB) and by 9% to 58% per
range GET.

Before this patch, fileReader allocated a buffer of up to 4 MiB per GET
and copied blobs larger than 32 KiB a second time. Now ServeBlob passes
the *os.File to http.ServeContent.

Registry total CPU time per GET in ms (mean +/- sample SD), warm page
cache, linux/arm64:

    Transport   Blob    Before (n=15)      Now (n=15)         Change
    plain HTTP   4 MiB   1.994 +/- 0.026    1.160 +/- 0.009   -41.8%
    plain HTTP  32 MiB   9.423 +/- 0.061    6.851 +/- 0.021   -27.3%
    TLS          4 MiB   3.401 +/- 0.027    2.404 +/- 0.018   -29.3%
    TLS         32 MiB  20.159 +/- 0.063   17.528 +/- 0.113   -13.0%

The 4 MiB buffer dates from February 2015 (0270bec). That commit
message records no measurement or specific reasoning. Does removing this
buffer hurt? Would a smaller buffer be better? With a warm page cache,
no: buffers from 32 KiB to 1 MiB (tested on d14ff2f) used the same or
more registry total CPU time than this patch. With a cold page cache,
removing the buffer has a cost that is small compared to the 13% to 42%
gain with a warm page cache: registry total CPU time was 2% to 7% higher
(1 GiB blobs, local NVMe drive).

Fixed
-----

The registry now opens the blob file before it sets the response
status, and sets Content-Length from the file size instead of the blob
descriptor. Passing the file to http.ServeContent requires both
changes. Each change fixes one defect (distribution#5080):

- The blob file is missing or cannot be opened.
  Before: The registry sent status 200, a Content-Length header and no
  body (missing file: issues distribution#5010 and distribution#2966).
  Now: The registry sends status 404 with error code BLOB_UNKNOWN for a
  missing file. It sends status 500 for other open errors.
- The blob file size is less than the size in the blob descriptor.
  Before: The registry set Content-Length from the size in the blob
  descriptor and sent a truncated body (curl, for example, reports
  error 18).
  Now: The registry sets Content-Length from the file size.

Before this patch, skopeo logged "unexpected EOF" and retried in both
cases.

Remarks
-------

This patch applies only to the filesystem driver, when its Reader
returns an *os.File. For S3, Azure, GCS and all other storage drivers,
the registry still uses fileReader and its buffer (capped at blob size
since distribution#5070). HEAD responses are unchanged.

If the blob file is missing, the registry now answers every GET with
status 404. Previously, it answered some conditional GETs with status
304 or 412. The blob file is authoritative.

The registry still sets Docker-Content-Digest and ETag from the blob
descriptor. When the blob file is smaller than the size in the blob
descriptor, the transfer now completes. Only a client that checks size
or digest detects the mismatch.

net/http can use sendfile(2) for plain HTTP only. For TLS, distribution#5052
reduces CPU time no further.

Related issues: distribution#2367, distribution#5010, distribution#2966, distribution#2778. Related PR: distribution#5008.

Fixes distribution#5080

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 12, 2026
This patch fixes two defects in blob GET requests on the filesystem
driver and significantly reduces the CPU time that the registry consumes
for serving them. It passes the blob file directly to http.ServeContent.

This patch was extracted from distribution#5052. That PR builds on this patch to
enable sendfile(2), which requires passing an *os.File to
http.ServeContent.

Performance impact
------------------

With a warm page cache, this patch reduces registry total CPU time by
13% to 42% per whole-blob GET (100 KiB to 32 MiB) and by 9% to 58% per
range GET.

Before this patch, fileReader allocated a buffer of up to 4 MiB per GET
and copied blobs larger than 32 KiB a second time. Now ServeBlob passes
the *os.File to http.ServeContent.

Registry total CPU time per GET in ms (mean +/- sample SD), warm page
cache, linux/arm64:

    Transport   Blob    Before (n=15)      Now (n=15)         Change
    plain HTTP   4 MiB   1.994 +/- 0.026    1.160 +/- 0.009   -41.8%
    plain HTTP  32 MiB   9.423 +/- 0.061    6.851 +/- 0.021   -27.3%
    TLS          4 MiB   3.401 +/- 0.027    2.404 +/- 0.018   -29.3%
    TLS         32 MiB  20.159 +/- 0.063   17.528 +/- 0.113   -13.0%

The 4 MiB buffer dates from February 2015 (0270bec). That commit
message records no measurement or specific reasoning. Does removing this
buffer hurt? Would a smaller buffer be better? With a warm page cache,
no: buffers from 32 KiB to 1 MiB (tested on d14ff2f) used the same or
more registry total CPU time than this patch. With a cold page cache,
removing the buffer has a cost that is small compared to the 13% to 42%
gain with a warm page cache: registry total CPU time was 2% to 7% higher
(1 GiB blobs, local NVMe drive).

Fixed
-----

The registry now opens the blob file before it sets the response
status, and sets Content-Length from the file size instead of the blob
descriptor. Passing the file to http.ServeContent requires both
changes. Each change fixes one defect (distribution#5080):

- The blob file is missing or cannot be opened.
  Before: The registry sent status 200, a Content-Length header and no
  body (missing file: issues distribution#5010 and distribution#2966).
  Now: The registry sends status 404 with error code BLOB_UNKNOWN for a
  missing file. It sends status 500 for other open errors.
- The blob file size is less than the size in the blob descriptor.
  Before: The registry set Content-Length from the size in the blob
  descriptor and sent a truncated body (curl, for example, reports
  error 18).
  Now: The registry sets Content-Length from the file size.

Before this patch, skopeo logged "unexpected EOF" and retried in both
cases.

Remarks
-------

This patch applies only to the filesystem driver, when its Reader
returns an *os.File. For S3, Azure, GCS and all other storage drivers,
the registry still uses fileReader and its buffer (capped at blob size
since distribution#5070). HEAD responses are unchanged.

If the blob file is missing, the registry now answers every GET with
status 404. Previously, it answered some conditional GETs with status
304 or 412. The blob file is authoritative.

In a pull-through cache, the registry now answers a GET with status 404
when the local blob file is missing and its blob descriptor is still
cached. The registry does not fetch the blob from the upstream again.
Fetching it again is what distribution#5010 prefers, and is left for a follow-up.

The registry still sets Docker-Content-Digest and ETag from the blob
descriptor. When the blob file is smaller than the size in the blob
descriptor, the transfer now completes. Only a client that checks size
or digest detects the mismatch.

net/http can use sendfile(2) for plain HTTP only. For TLS, distribution#5052
reduces CPU time no further.

Related issues: distribution#2367, distribution#5010, distribution#2966, distribution#2778. Related PR: distribution#5008.

Fixes distribution#5080

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 12, 2026
This patch fixes two defects in blob GET requests on the filesystem
driver and significantly reduces the CPU time that the registry consumes
for serving them. It passes the blob file directly to http.ServeContent.

This patch was extracted from distribution#5052. That PR builds on this patch to
enable sendfile(2), which requires passing an *os.File to
http.ServeContent.

Performance impact
------------------

With a warm page cache, this patch reduces registry total CPU time by
13% to 42% per whole-blob GET (100 KiB to 32 MiB) and by 9% to 58% per
range GET.

Before this patch, fileReader allocated a buffer of up to 4 MiB per GET
and copied blobs larger than 32 KiB a second time. Now ServeBlob passes
the *os.File to http.ServeContent.

Registry total CPU time per GET in ms (mean +/- sample SD), warm page
cache, linux/arm64:

    Transport   Blob    Before (n=15)      Now (n=15)         Change
    plain HTTP   4 MiB   1.994 +/- 0.026    1.160 +/- 0.009   -41.8%
    plain HTTP  32 MiB   9.423 +/- 0.061    6.851 +/- 0.021   -27.3%
    TLS          4 MiB   3.401 +/- 0.027    2.404 +/- 0.018   -29.3%
    TLS         32 MiB  20.159 +/- 0.063   17.528 +/- 0.113   -13.0%

The 4 MiB buffer dates from February 2015 (0270bec). That commit
message records no measurement or specific reasoning. Does removing this
buffer hurt? Would a smaller buffer be better? With a warm page cache,
no: buffers from 32 KiB to 1 MiB (tested on d14ff2f) used the same or
more registry total CPU time than this patch. With a cold page cache,
removing the buffer has a cost that is small compared to the 13% to 42%
gain with a warm page cache: registry total CPU time was 2% to 7% higher
(1 GiB blobs, local NVMe drive).

Fixed
-----

The registry now opens the blob file before it sets the response
status, and sets Content-Length from the file size instead of the blob
descriptor. Passing the file to http.ServeContent requires both
changes. Each change fixes one defect (distribution#5080):

- The blob file is missing or cannot be opened.
  Before: The registry sent status 200, a Content-Length header and no
  body (missing file: issues distribution#5010 and distribution#2966).
  Now: The registry sends status 404 with error code BLOB_UNKNOWN for a
  missing file. It sends status 500 for other open errors.
- The blob file size is less than the size in the blob descriptor.
  Before: The registry set Content-Length from the size in the blob
  descriptor and sent a truncated body (curl, for example, reports
  error 18).
  Now: The registry sets Content-Length from the file size.

Before this patch, skopeo logged "unexpected EOF" and retried in both
cases.

Remarks
-------

This patch applies only to the filesystem driver, when its Reader
returns an *os.File. For S3, Azure, GCS and all other storage drivers,
the registry still uses fileReader and its buffer (capped at blob size
since distribution#5070). HEAD responses are unchanged.

If the blob file is missing, the registry now answers every GET with
status 404. Previously, it answered some conditional GETs with status
304 or 412. The blob file is authoritative, not the blob descriptor,
which can be a stale entry in the blob descriptor cache.

In a pull-through cache, the registry now answers a GET with status 404
when the local blob file is missing and its blob descriptor is still
cached. The registry does not fetch the blob from the upstream again.
Fetching it again is what distribution#5010 prefers, and is left for a follow-up.

The registry still sets Docker-Content-Digest and ETag from the blob
descriptor. When the size of the blob file differs from the size in the
blob descriptor, the registry now sends the whole file, and the transfer
completes. Only a client that checks size or digest detects the
mismatch.

net/http can use sendfile(2) for plain HTTP only. For TLS, distribution#5052 reduced
registry total CPU time by at most 7% more (measured for range GETs).

Related issues: distribution#2367, distribution#5010, distribution#2966, distribution#2778. Related PR: distribution#5008.

Fixes distribution#5080

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 12, 2026
This patch fixes two defects in blob GET requests on the filesystem
driver and significantly reduces the CPU time that the registry consumes
for serving them. It passes the blob file directly to
`http.ServeContent`.

This patch was extracted from distribution#5052. That PR builds on this patch to
enable sendfile(2), which requires passing an `*os.File` to
`http.ServeContent`.

Performance impact
------------------

With a warm page cache, this patch reduces registry total CPU time by
13% to 42% per whole-blob GET (100 KiB to 32 MiB) and by 9% to 58% per
range GET.

Before this patch, `fileReader` allocated a buffer of up to 4 MiB per
GET and copied blobs larger than 32 KiB a second time. Now `ServeBlob`
passes `*os.File` directly to `http.ServeContent`.

Registry total CPU time per GET in ms (mean +/- sample SD), warm page
cache, linux/arm64:

    Transport   Blob    Before (n=15)      Now (n=15)         Change
    plain HTTP   4 MiB   1.994 +/- 0.026    1.160 +/- 0.009   -41.8%
    plain HTTP  32 MiB   9.423 +/- 0.061    6.851 +/- 0.021   -27.3%
    TLS          4 MiB   3.401 +/- 0.027    2.404 +/- 0.018   -29.3%
    TLS         32 MiB  20.159 +/- 0.063   17.528 +/- 0.113   -13.0%

The 4 MiB buffer dates from February 2015 (0270bec). That commit
message records no measurement or specific reasoning.

Does removing this buffer hurt? Would a smaller buffer be better? With a
warm page cache, no: buffers from 32 KiB to 1 MiB (tested on d14ff2f)
used the same or more registry total CPU time than this patch. With a
cold page cache, removing the buffer has a cost that is small compared
to the aforementioned gains (registry total CPU time was 2% to 7% higher
for 1 GiB blobs, local NVMe drive).

Fixed
-----

The registry now opens the blob file before it sets the response
status, and sets Content-Length from the file size instead of the blob
descriptor. Passing the file to `http.ServeContent` requires both
changes. Each change fixes one defect (distribution#5080):

- The blob file is missing or cannot be opened.
  Before: The registry sent status 200, a Content-Length header and no
  body (missing file: issues distribution#5010 and distribution#2966).
  Now: The registry sends status 404 with error code BLOB_UNKNOWN for a
  missing file. It sends status 500 for other open errors.
- The blob file size is smaller than the size stored in the blob
  descriptor.
  Before: The registry set Content-Length from the size in the blob
  descriptor and sent a truncated body (curl, for example, reports
  error 18).
  Now: The registry sets Content-Length from the file size.

Before this patch, skopeo for example would log "unexpected EOF" and
retry in both cases.

Remarks
-------

This patch applies only to the filesystem driver, when its `Reader`
returns an `*os.File`. For S3, Azure, GCS and all other storage drivers,
the registry still uses `fileReader` and its buffer (capped at blob size
since distribution#5070). HEAD responses are unchanged.

If the blob file is missing, the registry now answers every GET with
status 404. Previously, it answered some conditional GETs with status
304 or 412. The blob file is authoritative, not the blob descriptor,
which can be a stale entry in the blob descriptor cache.

In a pull-through cache, the registry now answers a GET with status 404
when the local blob file is missing and its blob descriptor is still
cached. The registry does not fetch the blob from the upstream again.
Fetching it again is what distribution#5010 prefers, and is left for a follow-up.

The registry still sets Docker-Content-Digest and ETag from the blob
descriptor. When the blob file is smaller or larger than the size in the
blob descriptor, the registry now sends the whole file, and the transfer
completes. Only a client that checks size or digest detects the
mismatch.

Tests
-----

The new tests fail without the changes to `blobserver.go` and `blob.go`,
except `TestBlobServerOtherDriverReaderCalls`, which covers what this
patch does not change: one `Reader` call per GET on other drivers.

Related issues: distribution#2367, distribution#5010, distribution#2966, distribution#2778. Related PR: distribution#5008.

Fixes distribution#5080

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from 2ff3b53 to 0eb9d57 Compare November 12, 2026 04:07
@jgehrcke jgehrcke changed the title storage: enable sendfile for filesystem blob downloads registry: enable sendfile for filesystem blob GETs Nov 12, 2026
@jgehrcke
jgehrcke marked this pull request as ready for review November 12, 2026 05:07
@jgehrcke

Copy link
Copy Markdown
Contributor Author

Quick note: this patch is not affecting Linux only. Go uses what the underlying platform offers:

  • Linux, macOS, FreeBSD, ...: sendfile, via Golang's sendFileChunk.
  • Windows Server: TransmitFile.
  • NetBSD, OpenBSD, ...: a plain user-space copy, as today.

I measured on linux/arm64 only. CI runs the new tests on Linux and Windows. They check that the file pointer arrives at ReadFrom, not which syscalls Go then makes.

@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch 2 times, most recently from 83d0f6a to d84d17c Compare November 13, 2026 02:48
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 17, 2026
This patch fixes two defects in blob GET requests on the filesystem
driver and significantly reduces the CPU time that the registry consumes
for serving them. It passes the blob file directly to
`http.ServeContent`.

This patch was extracted from distribution#5052. That PR builds on this patch to
enable sendfile(2), which requires passing an `*os.File` to
`http.ServeContent`.

Performance impact
------------------

With a warm page cache, this patch reduces registry total CPU time by
13% to 42% per whole-blob GET (100 KiB to 32 MiB) and by 9% to 58% per
range GET.

Before this patch, `fileReader` allocated a buffer of up to 4 MiB per
GET and copied blobs larger than 32 KiB a second time. Now `ServeBlob`
passes `*os.File` directly to `http.ServeContent`.

Registry total CPU time per GET in ms (mean +/- sample SD), warm page
cache, linux/arm64:

    Transport   Blob    Before (n=15)      Now (n=15)         Change
    plain HTTP   4 MiB   1.994 +/- 0.026    1.160 +/- 0.009   -41.8%
    plain HTTP  32 MiB   9.423 +/- 0.061    6.851 +/- 0.021   -27.3%
    TLS          4 MiB   3.401 +/- 0.027    2.404 +/- 0.018   -29.3%
    TLS         32 MiB  20.159 +/- 0.063   17.528 +/- 0.113   -13.0%

The 4 MiB buffer dates from February 2015 (0270bec). That commit
message records no measurement or specific reasoning.

Does removing this buffer hurt? Would a smaller buffer be better? With a
warm page cache, no: buffers from 32 KiB to 1 MiB (tested on d14ff2f)
used the same or more registry total CPU time than this patch. With a
cold page cache, removing the buffer has a cost that is small compared
to the aforementioned gains (registry total CPU time was 2% to 7% higher
for 1 GiB blobs, local NVMe drive).

Fixed
-----

The registry now opens the blob file before it sets the response
status, and sets Content-Length from the file size instead of the blob
descriptor. Passing the file to `http.ServeContent` requires both
changes. Each change fixes one defect (distribution#5080):

- The blob file is missing or cannot be opened.
  Before: The registry sent status 200, a Content-Length header and no
  body (missing file: issues distribution#5010 and distribution#2966).
  Now: The registry sends status 404 with error code BLOB_UNKNOWN for a
  missing file. It sends status 500 for other open errors.
- The blob file size is smaller than the size stored in the blob
  descriptor.
  Before: The registry set Content-Length from the size in the blob
  descriptor and sent a truncated body (curl, for example, reports
  error 18).
  Now: The registry sets Content-Length from the file size.

Before this patch, skopeo for example would log "unexpected EOF" and
retry in both cases.

Remarks
-------

For blob GETs, the filesystem driver opts in through `ReadSeeker`
and returns the original `*os.File`. Drivers and middleware without
`ReadSeeker` use `fileReader` and its buffer (capped at blob size
since distribution#5070).

If the blob file is missing, the registry now answers every GET with
status 404. Previously, it answered some conditional GETs with status
304 or 412. The blob file is authoritative, not the blob descriptor,
which can be a stale entry in the blob descriptor cache.

In a pull-through cache, the registry now answers a GET with status 404
when the local blob file is missing and its blob descriptor is still
cached. The registry does not fetch the blob from the upstream again.
Fetching it again is what distribution#5010 prefers, and is left for a follow-up.

The registry still sets Docker-Content-Digest and ETag from the blob
descriptor. When the blob file is smaller or larger than the size in the
blob descriptor, the registry now sends the whole file, and the transfer
completes. Only a client that checks size or digest detects the
mismatch.

Tests
-----

The stale-size and missing-file tests cover the two GET fixes.
`TestBlobServerDriverWithoutReadSeeker` checks that a range GET through
a filesystem wrapper makes one `Reader` call at the requested offset.

Related issues: distribution#2367, distribution#5010, distribution#2966, distribution#2778. Related PR: distribution#5008.

Fixes distribution#5080

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from d84d17c to 6c07128 Compare November 18, 2026 12:42
@jgehrcke

Copy link
Copy Markdown
Contributor Author

I updated #5081 and also now updated this branch here to include the changes.

@milosgajdos

Copy link
Copy Markdown
Member

Can you rebase on main, please, so I have the full context here

@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from 6c07128 to 790a263 Compare November 19, 2026 10:47
@jgehrcke

jgehrcke commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased on current HEAD of main. I can imagine that one of the bigger questions for this PR now is: must we wait for a proper release of https://github.com/open-telemetry/opentelemetry-go-contrib/releases -- or is the pinned commit good enough? What's our feeling about this? We could merge with the pinned commit, to get the changes in and hence rolled out to other devs. We could then pay attention to doing another bump PR to include the next go-otel release before the next distribution release.

Comment thread registry/accesslog.go
"github.com/felixge/httpsnoop"
)

// accessLogHandler logs requests to out in Apache Combined Log Format, like

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I dont understand how this change relates to the filesystem driver changes. We should split this out to a separate PR

@jgehrcke jgehrcke Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hey @milosgajdos.

Without this access log treatment, this PR would introduce a regression in the access log. The root cause is a bug in Gorilla. I had reported that here: gorilla/handlers#284. gorilla/handlers#207 is a sad story (this could have fixed the problem back in 2020).

Which regression in the access log? Some HTTP responses would wrongly be logged with response body size 0.

I had to address that, right? :) Gorilla is ~unmaintained, releases are unlikely. I needed to find a bit of a creative solution for that. Which is the one you just commented on.

I had tried to prepare for this 'surprise' in the PR description, which says:

For a body copied through ReadFrom, Gorilla's access log handler logs a size of zero. I reported that gorilla/handlers#284. I think it is unlikely that we see a new Gorilla release for that. So, I took a deep breath and opted for a pragmatic solution: registry/accesslog.go is a new handler of ~100 lines. It counts bytes with httpsnoop hooks and builds the log line itself, in Gorilla's format (quite heavily reviewed/tested by an agent). Not beautiful, but not all too ugly. I think it's a workable solution.

@jgehrcke jgehrcke Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I can of course also extract the access log change to another PR which we then review independently. Let me know if you prefer that. I would however argue that it kinda belongs into this PR here, as an atomic unit :).

Another high-level perspective: we want to use ReadFrom() (for sendfile). That is, we sadly have to work around this access log bug in Gorilla. My proposed way of doing that is certainly not the only way. But I put some thought into it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I dont understand how this change relates to the filesystem driver changes.

This is here to ensure that we do not change access log output behavior.

The sendfile stuff should obviously not result in anything about access log output changing. Getting there was a little complicated.

(I fear I wrote too much :) Sorry. So I just felt included to share another perspective that is easy to reason about.)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The thing is the Gorilla project is more or less dead at this point; I think we need to start thinking about how to rip it out of this repo because it's basically a liability;

I still think we should rip out the access log into a dedicated PR, now that I understand what the problem is.... seems to me 2nd commit (f7c599f) in the PR is already more or less self-contained and passes its tests without instrumentedResponseWriter.ReadFrom, so extracting shouldnt be hard.

I dont disagree that it may belong to this change, though, I'd also argue, this change merely surfaced the broken behaviour - any other similar change would've. done the same

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I still think we should rip out the access log into a dedicated PR

ok :) Preparing that now!

start thinking about how to rip [Gorilla] out of this repo because it's basically a liability

Yeees. Came to the same conclusion.

Made me sad because at first I thought that this is going to be the reason for why I can't propose a reasonable sendfile patch.

Now we talk about this topic, as we have to. That's a win I guess. Thank you for taking the time to wade through this.

@jgehrcke jgehrcke Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

okay, here is the access log PR: #5103

Normally I would have taken a little more time to polish the commit message. Now I focused just on manually editing the PR description and worked rather quickly.

Edit: I'll update this PR soon, correspondingly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this change merely surfaced the broken behaviour

Yes. In general, I found it somewhat surprising to see (through observations like this) that the critical importance of 'sendfile' has been somewhat under the radar in the golang ecosystem all these years.

jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 26, 2026
…ribution#5052)

Gorilla's combined logging handler counts response bytes in `Write`
only. For a body copied through `ReadFrom` it logs size 0
(gorilla/handlers#284).

On main no registry response is copied through `ReadFrom`. With distribution#5052,
filesystem blob GETs are.

Replace Gorilla's handler with a local one that writes the same log
line and counts the bytes of `Write` and `ReadFrom` with httpsnoop
hooks. The tests compare its log line with Gorilla's and cover copies
through `ReadFrom`.

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 26, 2026
…ribution#5052)

Gorilla's combined logging handler counts response bytes in `Write`
only. For a body copied through `ReadFrom` it logs size 0
(gorilla/handlers#284).

This only happens from distribution#5052 on, which copies filesystem blob GET
bodies through `ReadFrom`.

Replace Gorilla's handler with a local one that writes the same log
line and counts the bytes of `Write` and `ReadFrom` with httpsnoop
hooks. The tests compare its log line with Gorilla's and cover copies
through `ReadFrom`.

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 27, 2026
Messages of squashed commits:

--------------------

registry: fix access log size 0 for ReadFrom bodies (coming with distribution#5052)

Gorilla's combined logging handler counts response bytes in `Write`
only. For a body copied through `ReadFrom` it logs size 0
(gorilla/handlers#284).

This only happens from distribution#5052 on, which copies filesystem blob GET
bodies through `ReadFrom`.

Replace Gorilla's handler with a local one that writes the same log
line and counts the bytes of `Write` and `ReadFrom` with httpsnoop
hooks. The tests compare its log line with Gorilla's and cover copies
through `ReadFrom`.

--------------------

registry: fix access log status after a flush

When a handler flushes and then calls `WriteHeader(503)`, the client
gets 200 but the access log shows 503. Flushing commits the response
status before the handler sets 503.

Track the committed header in the `Flush` and `FlushError` hooks.
The client-status test flushes with both `http.Flusher` and
`http.ResponseController`. Both cases fail without the hooks.

--------------------

registry: restore multipart file cleanup in the access logger

Middleware can pass a copy of the request to the access logger. If the
handler parses a multipart upload on that copy, the server's original
request has no form to clean up. Any upload spilled to disk remains
after the request.

Restore Gorilla's call to `MultipartForm.RemoveAll` after the handler
returns. As in Gorilla, skip the log line if cleanup fails.

The test parses a file on a request copy and checks that the file is
gone when the logger returns. Without the fix the file still opens.

--------------------

registry: avoid quoting plain ASCII access log fields

`quoteLogField` splits and quotes even an empty Referer or a user agent
like `docker/29.0.0`. Both already contain exactly what the log needs.

Return the input string for printable ASCII without quotes or
backslashes. Keep the existing escaping for all other fields, including
Gorilla's special spelling for DEL.

--------------------

registry: clean up multipart files on dispatched request copies

A blob upload request can leave a temporary file behind even when
authentication fails. Authorization reads the source repository with
`FormValue`, which can parse a multipart body on a request copy.
The server cannot clean up a form it never sees.

Remove the form on return from the dispatcher if it was parsed there
or on the copy passed to the upload handler. A form already present
on entry remains the caller's responsibility.

The regression test checks the temporary directory after both a 401
and a 202. Both cases leave a file behind without the fix.

Fixes distribution#5106.

--------------------

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
jgehrcke added a commit to jgehrcke/distribution that referenced this pull request Nov 27, 2026
Messages of squashed commits:

registry: fix access log size 0 for ReadFrom bodies (coming with distribution#5052)

Gorilla's combined logging handler counts response bytes in `Write`
only. For a body copied through `ReadFrom` it logs size 0
(gorilla/handlers#284).

This only happens from distribution#5052 on, which copies filesystem blob GET
bodies through `ReadFrom`.

Replace Gorilla's handler with a local one that writes the same log
line and counts the bytes of `Write` and `ReadFrom` with httpsnoop
hooks. The tests compare its log line with Gorilla's and cover copies
through `ReadFrom`.

--------------------

registry: fix access log status after a flush

When a handler flushes and then calls `WriteHeader(503)`, the client
gets 200 but the access log shows 503. Flushing commits the response
status before the handler sets 503.

Track the committed header in the `Flush` and `FlushError` hooks.
The client-status test flushes with both `http.Flusher` and
`http.ResponseController`. Both cases fail without the hooks.

--------------------

registry: restore multipart file cleanup in the access logger

Middleware can pass a copy of the request to the access logger. If the
handler parses a multipart upload on that copy, the server's original
request has no form to clean up. Any upload spilled to disk remains
after the request.

Restore Gorilla's call to `MultipartForm.RemoveAll` after the handler
returns. As in Gorilla, skip the log line if cleanup fails.

The test parses a file on a request copy and checks that the file is
gone when the logger returns. Without the fix the file still opens.

--------------------

registry: avoid quoting plain ASCII access log fields

`quoteLogField` splits and quotes even an empty Referer or a user agent
like `docker/29.0.0`. Both already contain exactly what the log needs.

Return the input string for printable ASCII without quotes or
backslashes. Keep the existing escaping for all other fields, including
Gorilla's special spelling for DEL.

--------------------

registry: clean up multipart files on dispatched request copies

A blob upload request can leave a temporary file behind even when
authentication fails. Authorization reads the source repository with
`FormValue`, which can parse a multipart body on a request copy.
The server cannot clean up a form it never sees.

Remove the form on return from the dispatcher if it was parsed there
or on the copy passed to the upload handler. A form already present
on entry remains the caller's responsibility.

The regression test checks the temporary directory after both a 401
and a 202. Both cases leave a file behind without the fix.

Fixes distribution#5106.

--------------------

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
@jgehrcke

Copy link
Copy Markdown
Contributor Author

I'll update this PR after #5103 lands.

@milosgajdos

Copy link
Copy Markdown
Member

I'll update this PR after #5103 lands.

yah, this needs a rebase now

@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from 790a263 to 908d29d Compare November 27, 2026 20:15

@milosgajdos milosgajdos left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok this looks very good now; Im ok with our temporarily pinning otel to a commit until they sort themselves out.

One thing I think we should do though is maybe adding a simple integration test...which would test one filesystem blob GET through the assembled handler chain.

I think itd be helpfu; once that's in lets merge. Nice!

@jgehrcke

Copy link
Copy Markdown
Contributor Author

One thing I think we should do though is maybe adding a simple integration test...which would test one filesystem blob GET through the assembled handler chain.

I've added a commit, see commit message. After review we can fold it into the sendfile commit then :)

@milosgajdos

Copy link
Copy Markdown
Member

ok,LGTM; can you squash the commits, please @jgehrcke

@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from 664d920 to db693c3 Compare November 28, 2026 02:43
@jgehrcke

Copy link
Copy Markdown
Contributor Author

Thanks @milosgajdos -- doing that now

@milosgajdos

milosgajdos commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

I merged a PR into proxy and hmm, there are some merge conflicts now

@jgehrcke

Copy link
Copy Markdown
Contributor Author

there are some merge conflicts now

ack, looking into that now

otelhttp v0.72.0 does not count response bytes that a handler copies
through ReadFrom. The server span of such a response has no
http.response.body.size attribute. Upstream commit ec3c636e3541 fixes
that (open-telemetry/opentelemetry-go-contrib#9998). No tagged release
contains the commit yet.

Require otelhttp at the pseudo-version of that commit,
v0.72.1-0.20261023153556-ec3c636e3541, and regenerate vendor. No other
module changes version.

The registry needs the fix from the commit that makes its response
writer forward ReadFrom (later in this series).

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
Comment thread registry/proxy/proxyblobstore.go Outdated
_, err = io.CopyN(writer, remoteReader, desc.Size)
// Hide ReadFrom: promhttp commits 200 before reading, masking early upstream errors.
// See https://github.com/prometheus/client_golang/issues/2155.
_, err = io.CopyN(struct{ io.Writer }{writer}, remoteReader, desc.Size)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

For the record, #5115 (which was merged earlier today) achieves this in a tidier fashion; so I am happy for this hunk to be dropped from this PR :)

Here, our goal was to hide ReadFrom, @milosgajdos' blobResponseWriter from #5115 exposes only Write and hence achieves the same protection.

I'll keep the corresponding test on this PR branch though.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

makes sense

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Okay, resolved the conflict. This is the commit that contains the test only: 62a0069

I took forever writing this following commit message to remind myself and hopefully others what we're even doing, things got slightly convoluted :)

proxy: test that an in-flight blob copy uses Write

This test confirms that the proxy uses the response writer's Write
method when a request misses the cache for a blob already being fetched.

In #5052 the registry's response writer forwards ReadFrom to enable
sendfile. Without blobResponseWriter from #5115, io.CopyN would use
ReadFrom here. With Prometheus instrumentation enabled, promhttp's
ReadFrom would commit status 200 before reading the upstream body,
even if the first read failed (prometheus/client_golang#2155).

Using Write here costs us no sendfile opportunity. ReadFrom would still
read the upstream HTTP response body through an HTTPReadSeeker.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This test confirms that the proxy uses the response writer's Write
method when a request misses the cache for a blob already being fetched.

In distribution#5052 the registry's response writer forwards ReadFrom to enable
sendfile. Without blobResponseWriter from distribution#5115, io.CopyN would use
ReadFrom here. With Prometheus instrumentation enabled, promhttp's
ReadFrom would commit status 200 before reading the upstream body,
even if the first read failed (prometheus/client_golang#2155).

Using Write here costs us no sendfile opportunity. ReadFrom would still
read the upstream HTTP response body through an HTTPReadSeeker.

Keep blobResponseWriter and this test after upgrading to a client_golang
release that fixes distribution#2155. The wrapper sets blob headers on the first
write of blob data, so early error responses keep their own headers.

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
For a GET on the filesystem driver, ServeBlob passes the blob file to
http.ServeContent. ServeContent copies the file with io.CopyN, which
calls the ReadFrom method of the response writer when the writer has
one. The registry's response writer (instrumentedResponseWriter) had
none, so io.CopyN read the file into a buffer and passed each chunk to
Write.

Add ReadFrom to the registry's response writer. It passes the reader
unchanged to the ReadFrom of the writer it wraps, and it counts the
copied bytes as Write does. The blob file now reaches
net.TCPConn.ReadFrom, where Go calls sendfile(2) on Linux. A TLS
connection has no ReadFrom, so TLS responses do not use sendfile(2).

ReadFrom records status 200 when it copies bytes and the handler has
set no status. When it copies no bytes, it records no status. When the
wrapped writer has no ReadFrom, it copies through Write.

The integration test uploads a filesystem blob and fetches it over TCP
through the handler built by NewRegistry, with access logging,
OpenTelemetry and Prometheus enabled. It checks the status, the body
and that the *os.File reaches net.TCPConn.ReadFrom. Without ReadFrom
on the registry's response writer, only the last check fails.

Signed-off-by: Dr. Jan-Philip Gehrcke <[email protected]>
@jgehrcke
jgehrcke force-pushed the jp/linux-sendfile-submit branch from db693c3 to 995ace1 Compare November 28, 2026 17:28

@milosgajdos milosgajdos left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@milosgajdos
milosgajdos merged commit a1c7439 into distribution:main Nov 28, 2026
25 checks passed
@jgehrcke

Copy link
Copy Markdown
Contributor Author

Thanks @milosgajdos for your support and time investment here! Happy that this is in now. I'll watch out for follow-up work if it becomes obvious.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/api area/proxy Related to registry as a pull-through cache area/storage dependencies Pull requests that update a dependency file

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants