Skip to content

S3: avoid full-object reads for GetObject ranges - #10564

Open
tonypottera24 wants to merge 1 commit into
getmoto:masterfrom
tonypottera24:fix/s3-ranged-get-read
Open

tonypottera24 wants to merge 1 commit into
getmoto:masterfrom
tonypottera24:fix/s3-ranged-get-read

Conversation

@tonypottera24

@tonypottera24 tonypottera24 commented Nov 16, 2026 •

Copy link
Copy Markdown

Ranged GetObject currently reads the entire stored object before _handle_range_header slices the requested bytes. Repeated small ranges over a large object therefore read the full object once per request.

Add a slice reader to FakeKey, using its existing SpooledTemporaryFile and per-key seek/read lock. The full value getter uses the same reader. Pass the selected key to the existing Range handler so it can resolve the range before reading its body. Authorization, version selection, conditional requests, Range parsing, checksum headers and byte responses retain their existing behavior.

The HTTP regression test covers memory-backed and disk-backed keys, with both unversioned objects and a non-current version. It checks actual bytes and headers as well as the underlying read size. All four variants fail on the original source because a 16-byte response performs an unbounded read.

Validation on Python 3.14.4, boto3/botocore 1.44.3:

  • Complete S3 decorator suite: 571 passed, 5 skipped, 2 xfailed.
  • S3 ServerMode suite with Docker Lambda cases deselected: 482 passed, 91 skipped, 4 deselected, 2 xfailed. Used the normal localhost:5000 endpoint required by an existing test.
  • ruff check moto/s3 tests/test_s3, ruff format --check moto/s3 tests/test_s3 with repository-pinned Ruff 0.14.10, and mypy moto/s3 passed.

A local decorator-mode comparison uses one disk-backed 128 MiB object and 32 requests for 1 MiB each. Each request verifies its returned bytes. Upload time is excluded; each source is sampled three times.

Source Stored bytes read per sample Median request-loop time
Base 980d15c304e72c384dfb6aa8cae9b4bf39c73100 4 GiB 2.0074 s
This change fd4fa84f3 32 MiB 0.03562 s

Base wall-time samples: 1.973463, 2.007409, 2.068236 s. Changed samples: 0.036211, 0.035621, 0.034498 s. Both perform 32 underlying reads; the read amplification drops from 128x to 1x. These are local SDK/mock measurements, not AWS or network throughput.

Reproduce the measurement

Run this script in the same environment on the base and PR commits:

import json
import platform
import time
from unittest.mock import patch

import boto3
from moto import mock_aws
from moto.s3.models import s3_backends

with mock_aws():
    client = boto3.client("s3", region_name="us-east-1")
    client.create_bucket(Bucket="range-benchmark")
    data = bytes(range(256)) * (512 * 1024)
    client.put_object(Bucket="range-benchmark", Key="key", Body=data)
    key = s3_backends["123456789012"]["aws"].get_object("range-benchmark", "key")
    native_read = key._value_buffer.read
    results = []
    for repeat in range(3):
        counts = {"calls": 0, "bytes": 0}

        def read(*args, **kwargs):
            result = native_read(*args, **kwargs)
            counts["calls"] += 1
            counts["bytes"] += len(result)
            return result

        with patch.object(key._value_buffer, "read", side_effect=read):
            start = time.perf_counter()
            cpu_start = time.process_time()
            for index in range(32):
                begin = index * 1024 * 1024 + 7
                end = begin + 1024 * 1024
                response = client.get_object(
                    Bucket="range-benchmark",
                    Key="key",
                    Range=f"bytes={begin}-{end - 1}",
                )
                assert response["Body"].read() == data[begin:end]
            results.append(
                {
                    "seconds": time.perf_counter() - start,
                    "cpu_seconds": time.process_time() - cpu_start,
                    **counts,
                }
            )
    print(
        json.dumps(
            {
                "python": platform.python_version(),
                "object_bytes": len(data),
                "requests": 32,
                "requested_bytes": 32 * 1024 * 1024,
                "samples": results,
            },
            indent=2,
        )
    )

The UploadPartCopy follow-up is #10565 and reuses this reader in a separate commit.

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