Skip to content

fix(s3_v2): bound concurrent S3 uploads per flush and add opt-in JSONL batch files - #41258

Merged
yucheng-berri merged 11 commits into
mainfrom
litellm_s3_v2_bounded_uploads
Sep 24, 2026
Merged

yucheng-berri merged 11 commits into
mainfrom
litellm_s3_v2_bounded_uploads

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • s3_v2 fires one unbounded PUT task per queued log on every flush
  • A 512 entry flush means hundreds of simultaneous PUTs; eight workers doing that at once measured at about 4,500 PUT/s into one fresh prefix, and AWS answered 503 SlowDown on 11 to 18 percent of them (real bucket run below)
  • Entries that exhaust the 3 retries are dropped and never retried
  • Customers asked for one batch file per flush instead of one object per request (Pylon [Bug]: [Nit] max_completion_tokens not supported on Azure when api_version is not specified #8638)

How it solves it:

  • async_send_batch awaits uploads through an asyncio.Semaphore sized s3_max_concurrent_uploads (default 16)
  • Failed uploads stay in the queue and go out with the next flush
  • New opt-in s3_batch_file_upload: true writes each flush as one NDJSON .jsonl object per key prefix (team and API key prefixes kept)
  • A batch file that failed to upload is retried under the same key and body, so a PUT that committed but timed out is overwritten, not duplicated
  • Batch mode is ignored with a warning when s3_v2 is also the cold storage logger, since spend log lookups need per request objects
  • "false", "0", "abc", negatives and empty strings in s3_callback_params resolve safely instead of enabling batching or hanging the flush
  • Logs appended while a flush is in progress are kept for the next flush

User Flow

Before: a proxy admin logging to S3 with s3_v2 sees bursts of 503s in the proxy log and missing objects in the bucket

  1. They set litellm_settings.callbacks: ["s3_v2"] with their bucket in s3_callback_params and fire 64 concurrent requests at POST https://litellm-domain/v1/chat/completions, all return 200
  2. Ten seconds later the proxy opens 25 uploads to S3 at once for those 64 requests, and with a 512 entry flush the count climbs into the hundreds
  3. When S3 throttles, the proxy log shows S3 upload returned 503, retrying in 1s (attempt 1/3) and attempt 2/3, and any entry throttled a third time ends in Error uploading to s3: ... 503 Slow Down
  4. Listing s3://bucket/path/2026-09-23/ shows fewer objects than requests served (79,993 of 80,000 in the real bucket run); the missing ones are gone for good

After: the same setup uploads at a bounded rate and every request ends up in the bucket

  1. Same config, same 64 concurrent requests against POST https://litellm-domain/v1/chat/completions, all return 200
  2. Ten seconds later at most 16 uploads are in flight at a time (tunable with s3_max_concurrent_uploads)
  3. When S3 throttles, the proxy log shows async_send_batch raised; preserving 32 events in queue for retry and the same objects are uploaded on the next flush once S3 recovers
  4. Listing s3://bucket/path/2026-09-23/ shows exactly one object per request
  5. Optionally the admin sets s3_batch_file_upload: true; the same listing now shows one batch_<HH-MM-SS>_<id>.jsonl file per flush with one request payload per line, and with s3_use_team_prefix: true the file sits under path/<team_alias>/2026-09-23/ like the per request objects did

Relevant issues

Affected release

Linear ticket

Resolves LIT-7800

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Setup for every run: a real proxy started from the tree under test (litellm --config config.yaml, import path checked with python -c "import litellm; print(litellm.__file__)"), model openai/gpt-5-mini with a real OpenAI key, callbacks: ["s3_v2"], DEFAULT_S3_FLUSH_INTERVAL_SECONDS=5. The burst is 64 concurrent curls:

seq 1 64 | xargs -P 64 -I{} curl -s -o /dev/null -w '%{http_code}\n' \
  -X POST http://127.0.0.1:$PORT/v1/chat/completions -H 'Authorization: Bearer sk-lit7800' \
  -H 'Content-Type: application/json' \
  -d '{"model":"gpt-5-mini","messages":[{"role":"user","content":"reply with the single word ok"}],"max_tokens":16}'

Concurrency is measured with s3_endpoint_url pointed at a local HTTP server that accepts the signed PUTs, holds each one for 0.5s and prints the peak number of in flight PUTs. Object creation is verified against the real bucket litellm-e2e-suite-logs with aws s3 ls --recursive.

Before (e26a645)

Upload fan out, 64 requests

  1. HTTP 200 count: 64
  2. Local S3 endpoint: sink: peak=25 total=64
  3. Direct flush of a 512 entry queue against the same endpoint: queued=512 delivered=512 peak=81

S3 throttling for 25s (endpoint answers 503 SlowDown for the first 25s, then 200)

  1. HTTP 200 count: 32
  2. Proxy log: 96 lines of Error uploading to s3: ... 503 (3 retries per entry, all inside the window), then nothing
  3. Endpoint after 90s: total=0 accepted PUTs, all 32 logs lost

After (4b48743; all six live legs re-ran at this head, verdict PASS 6/6, F1 sink peak 9 within the bound of 16)

Upload fan out, 64 requests, default settings

  1. HTTP 200 count: 64
  2. Local S3 endpoint: sink: peak=16 total=64, keys final/f1-default/<date>/time-*.json
  3. Direct flush of a 512 entry queue against the same endpoint: queued=512 delivered=512 peak=16

Real bucket, default settings

  1. HTTP 200 count: 64
  2. aws s3 ls --recursive s3://litellm-e2e-suite-logs/lit7800-qa/final-4b48743/ | wc -l -> 64
  3. Proxy log: zero Error uploading to s3 lines

S3 throttling for 25s, batch mode, same fault shape as Before

  1. HTTP 200 count: 8 across two flushes
  2. Proxy log: S3BatchUploadError: 1 of 1 S3 uploads failed then 2 of 2, with preserving 4 events in queue for retry twice
  3. Endpoint after the window: each batch key retried with an identical body (attempts 10 and 7, one distinct body per key), every event delivered exactly once

s3_batch_file_upload: true with s3_use_team_prefix: true, base vs head

  1. Base: 8 PUTs final/f2/alpha/<date>/time-*.json
  2. Head: final/f2/alpha/<date>/batch_09-01-33_d669164e....jsonl lines=5 and batch_09-01-38_9c5a5b09....jsonl lines=3, same alpha parent as base
  3. Head with a key that has no team: final/f2/<date>/batch_09-02-*_a2d0bb3c....jsonl lines=4 at the path root

cold_storage_custom_logger: s3_v2 with the batch flag on

  1. Per request object written: final/f4/<date>/time-09-04-45-465090_chatcmpl-ERDC9P9CZukmzxqck7ZYaQPHIj7vg.json
  2. Proxy log: s3 logging: s3_batch_file_upload is ignored because s3_v2 is the cold storage logger; per-request objects are required for spend log lookups
  3. GET /spend/logs/ui/chatcmpl-ERDC9P9CZukmzxqck7ZYaQPHIj7vg returns populated messages and response
  4. Admin UI at http://127.0.0.1:24810/ui/?page=logs lists the 8 requests and the Request ID drawer shows request and response payloads (screenshots in the PR comment thread)

Real AWS 503 SlowDown, base vs head, no fault injection

Eight processes, each an S3Logger from the tree under test with 10,000 small s3BatchLoggingElements appended to log_queue and one flush_queue() call, all started in the same second against fresh prefixes under lit7800-qa/flood503/<run>/p1..p8 in the real bucket (the shape of eight uvicorn workers ticking at once). httpx event hooks count status codes and in flight PUTs; objects are counted afterwards with aws s3 ls --recursive. One unfixed process alone never got throttled (512, 2,000 and 5,000 entries at 480 to 1,104 PUT/s, peak 291 to 316 in flight, all 200). Eight at once did

  1. Base, per process: queued=10000 codes={200: 10000, 503: 1429..1783} peak_inflight=321..393 wall=21s put_rate=~575/s, about 4,500 PUT/s aggregate into one not yet partitioned prefix. AWS body: <Code>SlowDown</Code><Message>Please reduce your request rate.</Message>
  2. Base, retries: 11087 x "returned 503, retrying in 1s (attempt 1/3)", 1926 x "attempt 2/3", then 7 x "Error uploading to s3" for entries that got 503 three times in a row. Bucket listing: 79993 of 80000 objects, the 7 keys never land and nothing requeues them
  3. Head, same load: queued=10000 codes={200: 10000, 503: 4..13} peak_inflight=16 wall=60s put_rate=~168/s per process, 68 503s total across eight processes, every one recovered on the first retry, 80000 of 80000 objects, left_in_queue=0 after a single flush round
  4. Head, one process alone, 5,000 entries, bound 16 / 32 / 64: 165 / 333 / 611 PUT/s, so the PUT round trip from the test box to us-east-1 is about 97ms and one worker at the default drains a full 512 queue in about 3s

Untouched neighbours

  1. callbacks: ["s3"] (the legacy logger) on base and head: 8 PUTs each, identical header key set, Content-Type: application/json
  2. s3_v2 per request PUT headers on base and head: identical key set, Content-Type, Content-Disposition and Content-Language
  3. store_audit_logs: true with batch mode: one .jsonl carrying 2 audit lines and 1 request line
  4. Two uvicorn workers: each worker holds its own semaphore, so the process wide peak is 2 x 16

Audit matrix (tests/integration, base e26a645 vs head 4b48743, head runs 9 and 10 both 20 passed with identical 20 collected and 20 passed, zero skips)

Every cell boots a real proxy from the leg under test with real Postgres and Redis; the provider and the S3 endpoint are local wire servers

cell node base head
mixed chat, messages, responses burst (sync, async, streaming), per request objects, peak <= 16 test_s3_v2_mixed_surface_burst_bounds_puts_one_object_per_response_id FAIL (peak 25) pass x2
same burst in batch mode, one NDJSON line per response id test_s3_v2_mixed_surface_batch_writes_ndjson_lines_per_response_id FAIL pass x2
sink 503 for the first 30 PUTs mid burst, every id lands once test_s3_v2_sink_outage_mid_mixed_burst_recovers_every_response_id pass pass x2
upstream 401 failure events land next to successes test_s3_v2_upstream_failure_events_land_alongside_successes pass pass x2
s3_max_concurrent_uploads "abc", 0, "" fall back to 16 test_s3_v2_invalid_or_empty_bound_falls_back_to_sixteen[...] FAIL x3 pass x3, x2
sink 403 for 10s, requeue and deliver every id once test_s3_v2_sink_rejection_requeues_and_delivers_every_id_once FAIL pass x2
batch retry reuses identical key and body test_s3_v2_batch_retry_resends_identical_key_and_body FAIL pass x2
unknown model 400 while a burst on another key keeps logging test_s3_v2_unknown_model_rejection_keeps_other_requests_logging pass pass x2
batch flag ignored when s3_v2 is the cold storage logger, spend log readback populated test_s3_v2_batch_flag_ignored_when_s3_v2_is_cold_storage_logger FAIL (no warning on base) pass x2
16 identical requests land 16 objects test_s3_v2_identical_requests_land_distinct_objects pass pass x2
two workers, peak <= 32, every id lands test_s3_v2_two_workers_bound_and_deliver_every_id FAIL (peak 42) pass x2
1.5s per PUT with a 1s flush interval, no duplicates, readiness stays 200 test_s3_v2_slow_sink_never_duplicates_or_stalls_readiness pass pass x2
SIGKILL one of two workers mid burst test_s3_v2_worker_kill_mid_burst_keeps_surviving_deliveries pass pass x2
SIGTERM the proxy mid burst, no duplicates, only in flight ids lost test_s3_v2_sigterm_mid_burst_loses_only_inflight_without_duplicates pass pass x2

The original four cells (default bound, configured bound with env backed false, batch mode, team prefix) are red on base and green on head in the same runs. The sink outage and unknown model cells are green on base as well: they are isolation invariants rather than fix discriminators, and 30 rejected attempts are absorbed by the per upload retries the base already has, while the 10s 403 window in the rejection cell outlasts them and shows the base dropping the events

Mutation checks on the unit tests, each killed by the mapped tests in tests/test_litellm/integrations/test_s3_v2.py: dropping the bound < 1 check, replacing the boolean resolver with bool(), dropping the failed event requeue, not raising on failed uploads, removing the semaphore, joining batch lines with commas, writing .json instead of .jsonl, grouping every key under the root, requeueing raw elements instead of built batch files, removing the cold storage check

Type

🐛 Bug Fix
🆕 New Feature

Caveats (if any)

Medium

  • With cold_storage_custom_logger: s3_v2 the batch flag is ignored and a warning is logged on every flush, so an admin who wants both gets per request objects

Low

  • Audit log entries keep their own audit_logs/... prefix, so in batch mode they land in their own .jsonl file next to the request log batch

  • The cold storage check runs at flush time rather than at startup because general_settings may be applied after the callback is built

  • The bound is per worker; with N uvicorn workers the process wide peak is N x s3_max_concurrent_uploads

  • A flush now holds the flush lock for the duration of the uploads, so a very slow S3 endpoint delays the next periodic flush rather than piling up tasks

  • DEFAULT_S3_MAX_CONCURRENT_UPLOADS is parsed with int() at import like its neighbours, so a non numeric value fails at startup

  • In per request mode only the elements whose PUT failed are re-sent; in batch mode the built file is re-sent under its original key

QA runbook

  • tests/integration/observability/test_s3_v2_upload_fanout.py::test_s3_v2_flush_bounds_concurrent_puts_to_the_default_of_sixteen - 64 concurrent chat requests produce 64 per request objects with at most 16 PUTs in flight

    • Start the proxy with callbacks: ["s3_v2"] and s3_endpoint_url pointing at a local server that delays each PUT by 0.5s and counts in flight requests
    • Fire 64 concurrent POST /v1/chat/completions, expect 64 x 200
    • Expect 64 PUTs with keys <path>/<date>/*.json and a peak in flight count of at most 16
    • Sanity check: this test makes sense to add and is not hand-wavey (e.g., assert actual expected spend instead of just spend > 0) or potentially flaky
  • tests/integration/observability/test_s3_v2_upload_fanout.py::test_s3_v2_honors_configured_bound_and_env_backed_false_batch_flag - s3_max_concurrent_uploads: 4 and s3_batch_file_upload: "false" give a peak of 4 and per request objects

    • Same setup with those two params added under s3_callback_params
    • Fire 64 requests, expect 64 PUTs of .json objects and a peak in flight count of at most 4
    • Sanity check: this test makes sense to add and is not hand-wavey (e.g., assert actual expected spend instead of just spend > 0) or potentially flaky
  • tests/integration/observability/test_s3_v2_upload_fanout.py::test_s3_v2_batch_file_upload_writes_one_jsonl_object_per_flush - s3_batch_file_upload: true writes NDJSON batch files

    • Same setup with s3_batch_file_upload: true
    • Fire 64 requests, expect at most 2 PUTs (one per flush) with keys <path>/<date>/batch_HH-MM-SS_<32 hex>.jsonl, Content-Type: application/x-ndjson, and 64 JSON lines in total whose id fields match the 64 responses
    • Sanity check: this test makes sense to add and is not hand-wavey (e.g., assert actual expected spend instead of just spend > 0) or potentially flaky
  • tests/integration/observability/test_s3_v2_upload_fanout.py::test_s3_v2_batch_file_upload_keeps_team_alias_prefix - batch files land under the team alias prefix

    • Same setup with s3_batch_file_upload: true and s3_use_team_prefix: true, create a team with alias alpha and a key on it
    • Fire 64 requests with that key, expect every .jsonl key to match <path>/alpha/<date>/batch_HH-MM-SS_<32 hex>.jsonl and the 64 lines to match the responses
    • Sanity check: this test makes sense to add and is not hand-wavey (e.g., assert actual expected spend instead of just spend > 0) or potentially flaky
  • tests/integration/observability/test_s3_v2_flush_surfaces.py and the audit cells in test_s3_v2_upload_fanout.py - the matrix above: chat, messages and responses surfaces, invalid bounds, sink 403/500/503 faults, cold storage guard, two workers, worker kill and proxy SIGTERM

    • Run uv run --no-sync pytest tests/integration/observability/test_s3_v2_flush_surfaces.py tests/integration/observability/test_s3_v2_upload_fanout.py against the rig twice, expect 20 passed both times with no skips
    • Sanity check: this test makes sense to add and is not hand-wavey (e.g., assert actual expected spend instead of just spend > 0) or potentially flaky

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/cf92245d91a5424faa91369ee0d975d6
Open in Devin Desktop: https://app.devin.ai/desktop/session/cf92245d91a5424faa91369ee0d975d6?variant=devin
Requested by: @yucheng-berri

@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 15, 2026 16:42
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

CLAassistant commented Sep 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ yucheng-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

@codspeed

codspeed Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_s3_v2_bounded_uploads (4b48743) with main (2dccc0d)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (e26a645) during the generation of this report, so 2dccc0d was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@greptile-apps

greptile-apps Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge, with no outstanding previous findings or accepted new issues

Summary

The PR bounds concurrent S3 v2 uploads, preserves failed events for later flushes, and adds opt-in JSONL batching while retaining per-request objects for cold-storage lookups

  • Adds validated concurrency and batch-mode configuration
  • Groups JSONL files by existing S3 key prefix and retries failed batch objects unchanged
  • Adds unit and integration coverage for throttling, retry behavior, configuration edge cases, queue preservation, and multi-worker operation

Reviews (8) · Last reviewed commit: "test(s3_v2): keep fake upload state on t..."

Comment thread litellm/integrations/s3_v2.py Resolved
Comment thread litellm/integrations/s3_v2.py Resolved
Comment thread litellm/integrations/s3_v2.py Resolved
@codecov

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.59459% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/integrations/s3.py 82.60% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_s3_v2_bounded_uploads branch from ab47e11 to e8b0f97 Compare September 23, 2026 07:11

@devin-ai-integration devin-ai-integration Bot left a comment

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.

Devin Review found 3 potential issues.

2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment thread litellm/integrations/s3_v2.py Resolved
Comment thread litellm/integrations/s3_v2.py Resolved
Comment thread litellm/integrations/s3_v2.py Resolved
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

1 similar comment
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

Admin UI evidence at 38c941c: proxy booted from this branch with cold_storage_custom_logger: s3_v2 plus s3_batch_file_upload: true, 8 curl requests to openai/gpt-5-mini, 8 per-request .json objects landed in the real bucket under lit7800-qa/ui-final/, zero upload errors, and the batch-mode ignore warning logged. Repro: http://127.0.0.1:24810/ui/?page=logs, then click a Request ID row

Logs page

Log detail with request payload

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/integrations/s3_v2.py Resolved
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

devin-ai-integration Bot and others added 10 commits September 23, 2026 14:51
…L batch files

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ntegration coverage

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…onfig value is null

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ety in batch file mode

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…s with sink faults

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…local counters

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_s3_v2_bounded_uploads branch from d8f318b to 4b48743 Compare September 23, 2026 14:52
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor 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.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 4b48743. Configure here.

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.

2 participants