Skip to content

feat(proxy): add a surcharge on customer requests - #52406

Merged
moe-berri merged 28 commits into
mainfrom
litellm_team_cost_margin
Nov 18, 2026
Merged

moe-berri merged 28 commits into
mainfrom
litellm_team_cost_margin

Conversation

@ishaan-j-berri

@ishaan-j-berri ishaan-j-berri commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

add per-app and global surcharge option for customer portal

Details

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

TLDR

Problem this solves:

  • Customer-facing requests can't carry a chargeback surcharge
  • Existing margins hit every request, internal ones too
  • The earlier revision of this PR put the surcharge on teams

How it solves it:

  • New customer entry in cost_margin_config, e.g. 0.02 for 2%
  • Applies only to requests made for a customer organization
  • Customer, key, team and user spend include the surcharge
  • Budgets and budget reservations count the surcharge
  • Keys bound to a customer are surcharged without customer headers
  • Billed failures, such as a read timeout, are surcharged too
    • The key binding is read from litellm_metadata or metadata, as on success
    • A failure with no logging snapshot still records the surcharge on its spend row
  • Each request records customer_margin_percent and customer_margin_amount
  • Daily spend tables get a customer_margin_spend column
  • Customer usage pages show Spend with Base cost and Surcharge
  • Per-team cost_margin_percent from the earlier revision is removed

User Flow

Before: an admin who bills customers 2% on top of model cost has to compute it outside LiteLLM

  1. Admin sends PATCH https://litellm.example.com/config/cost_margin_config with {"customer": 0.02} and gets 400 Invalid provider(s): customer
  2. An app sends POST https://litellm.example.com/v1/chat/completions with x-litellm-customer-org-alias: acme-bank
  3. x-litellm-response-cost equals the model cost, and the customer organization's spend shows only the model cost

After: the customer is billed with the surcharge, and internal traffic is not

  1. Admin sends PATCH https://litellm.example.com/config/cost_margin_config with {"customer": 0.02}, or picks Customer requests on the Cost Tracking page, and gets 200
  2. An app sends the same POST https://litellm.example.com/v1/chat/completions with x-litellm-customer-org-alias: acme-bank
  3. x-litellm-response-cost is the model cost times 1.02, and x-litellm-response-cost-original is the model cost
  4. The customer usage page shows Spend with the surcharge included, and Base cost and Surcharge under it
  5. The same request without a customer header costs the model cost, with no surcharge

Customer usage page at /ui/customers/usage?org=. The first shot is a date range with no surcharged spend, which renders the same as before this PR. The second is the range with customer requests, where Base cost and Surcharge appear under Spend.

Usage with no surcharge

Usage with surcharge

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished

Screenshots / Proof of Fix

Real Postgres, one dedicated Redis on port 56379 for router and coordination state, 2 proxy workers (two Started server process PIDs in the log), and real anthropic/claude-haiku-4-5 calls.

python litellm/proxy/proxy_cli.py --config config.yaml --num_workers 2 --detailed_debug --reload --use_v2_migration_resolver 2>&1 | tee litellm.log

Env var names: DATABASE_URL, LITELLM_MASTER_KEY, ANTHROPIC_API_KEY. config.yaml is a copy of litellm/proxy/dev_config.yaml with these added.

general_settings:
  coordination_redis:
    host: 127.0.0.1
    port: 56379
router_settings:
  redis_host: 127.0.0.1
  redis_port: 56379

Shared setup, run against each proxy.

curl -X PATCH $BASE/config/cost_margin_config -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d '{"customer": 0.02}'
curl -X POST $BASE/management/v1/customer_organizations -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d '{"alias":"acme-bank","budget":{"max_budget":50,"budget_duration":"1mo"}}'
curl -X POST $BASE/key/generate -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d '{"key_alias":"coworker-app"}'
# the request, sent with and without the customer header
curl -i -X POST $BASE/v1/chat/completions -H "Authorization: Bearer $APP_KEY" -H "Content-Type: application/json" \
  -H "x-litellm-customer-org-alias: acme-bank" \
  -d '{"model":"anthropic-haiku-4-5","messages":[{"role":"user","content":"Say hi in three words."}],"max_tokens":20}'

Before (b81933c)

  1. The PATCH returns 400
{"detail":{"error":"Invalid provider(s): customer. Must be valid LiteLLM providers or 'global'. ..."}}
  1. The request with x-litellm-customer-org-alias: acme-bank returns 200
x-litellm-response-cost: 5.3e-05
x-litellm-response-cost-original: 5.3e-05
  1. After the spend flush, the spend log has no surcharge and the organization spend is the model cost
  spend  | has_surcharge
 5.3e-05 | f
   alias   |  spend
 acme-bank | 5.3e-05

After (6c4b67d)

  1. The PATCH returns 200
{"message":"Cost margin configuration updated successfully","status":"success","values":{"customer":0.02}}
  1. Three requests return 200. One has no customer header, one has x-litellm-customer-member-id: alice, one has x-litellm-customer-org-alias: acme-bank
no customer   x-litellm-response-cost: 4.8e-05    x-litellm-response-cost-original: 4.8e-05
member alice  x-litellm-response-cost: 5.916e-05  x-litellm-response-cost-original: 5.8e-05
org acme-bank x-litellm-response-cost: 5.406e-05  x-litellm-response-cost-original: 5.3e-05
  1. After the spend flush, the spend log records the surcharge only on the customer requests
   spend   | pct  |        surcharge         | has_org
   4.8e-05 |      |                          | f
 5.916e-05 | 0.02 | 0.0000011600000000000001 | t
 5.406e-05 | 0.02 | 0.00000106               | t
  1. Organization and member spend include the surcharge, and the daily rollups keep it separate
acme-bank spend = 0.00011322 (5.916e-05 + 5.406e-05)
alice spend     = 5.916e-05
LiteLLM_DailyCustomerMemberSpend  spend 0.00011322  customer_margin_spend 2.22e-06
LiteLLM_DailyTeamSpend            spend 0.00016122  customer_margin_spend 2.22e-06
LiteLLM_DailyUserSpend            spend 0.00016122  customer_margin_spend 2.22e-06
  1. GET /management/v1/customer_organizations/daily/activity/aggregated?customer_org_id=... returns "total_spend": 0.00011322 and "total_customer_margin_spend": 2.22e-06

UI, driven on the dashboard dev server against the same proxy. On the Cost Tracking page, Customer requests is saved at 2.0%, a fixed amount for it is refused, and its inline editor only takes a percentage. After eight more real requests for acme-bank, the usage page shows Spend $0.34, Base cost $0.331 and Surcharge $0.0066, matching the database (spend 0.33762612, surcharge 0.00662012). The Logs page shows customer_margin_amount: 0.00080092 and customer_margin_percent: 0.02 on a customer request.

Customer requests margin editor

Surcharge in the request log

Tests

tests/unit/proxy/spend_tracking/test_customer_cost_margin.py
tests/unit/proxy/spend_tracking/test_cost_finalization.py
tests/unit/proxy/spend_tracking/test_budget_reservation.py
tests/unit/proxy/management_endpoints/test_cost_tracking_settings.py
tests/unit/proxy/management_endpoints/test_common_daily_activity.py
tests/unit/accounting tests/unit/proxy/db tests/unit/repositories tests/unit/proxy/hooks
7600 passed

The five lint gates and check_migrations_no_data_rewrites.py pass locally.

Type

🆕 New Feature

Caveats (if any)

Severe

  • Boot migration adds one column to eight daily spend tables
    • ADD COLUMN IF NOT EXISTS ... NOT NULL DEFAULT 0.0, no row rewrite

Medium

  • A request counts as customer-facing only with a customer organization
  • The surcharge is a percentage only, no fixed amount
  • Rows written before this PR report a surcharge of 0
  • Per-application surcharge is follow-up work
  • Reload after a refused margin save was not exercised live

Low

  • Only the English locale has the new strings

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

Note

High Risk
Changes payment and budget paths (finalization, reservations, failure billing) plus a schema migration across all daily spend tables; mis-attribution or double-surcharging would directly affect customer charges.

Overview
Introduces a customer entry in cost_margin_config that applies a percentage surcharge only on customer-attributed requests (customer org headers, key binding, or usage metadata), leaving internal traffic at base cost.

The surcharge is woven through billing and enforcement: cost finalization and success callbacks adjust response_cost and cost_breakdown; budget reservations scale estimates the same way; billed failures get the surcharge too, including rows without a logging snapshot. customer_margin_spend is rolled up in daily spend tables (new DB column + migration), accounting, daily-activity APIs, and OpenAPI types.

The Cost Tracking UI can configure a customer-only percentage margin; customer usage pages show base cost vs surcharge under total spend.

Reviewed by Cursor Bugbot for commit 54e12b5. Bugbot is set up for automated code reviews on this repo. Configure here.

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

CLAassistant commented Nov 18, 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.

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

@veria-ai

veria-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Fixed/addressed: 3 · PR risk: 0/10

Reviews

Comment thread litellm/proxy/_types.py Resolved
@codspeed

codspeed Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing litellm_team_cost_margin (54e12b5) with main (da8c02b)

Open in CodSpeed

@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.94595% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/spend_tracking/cost_finalization.py 83.33% 2 Missing ⚠️
...tellm/proxy/spend_tracking/spend_tracking_utils.py 75.00% 2 Missing ⚠️
...oxy/management_endpoints/cost_tracking_settings.py 75.00% 1 Missing ⚠️
...tellm/proxy/spend_tracking/customer_cost_margin.py 98.93% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

devin-ai-integration Bot and others added 4 commits November 18, 2026 01:47
Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
moe-berri and others added 8 commits November 18, 2026 04:54
… requests

A cost_margin_config entry keyed customer adds a percentage to requests made for a customer organization. The surcharge is part of spend, so customer budgets count it, and each request records it in cost_breakdown and in a customer_margin_spend column on the daily spend tables so cost before the surcharge stays exact

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>
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>
moe-berri and others added 3 commits November 18, 2026 05:57
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…t for customer requests

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>
@devin-ai-integration devin-ai-integration Bot changed the title feat(proxy): add per-team chargeback cost margin feat(proxy): add a surcharge on customer requests Nov 18, 2026
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
moe-berri and others added 2 commits November 18, 2026 07:56
…s binding

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>

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

Stale Bugbot comment from a previous run.

moe-berri and others added 4 commits November 18, 2026 08:00
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>
…o fields for a zero surcharge

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>
moe-berri and others added 2 commits November 18, 2026 08:52
…ucket of any route

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>

Copy link
Copy Markdown
Contributor

@greptileai please review the current fixes at c1f4aef, including billed-failure surcharge and nonzero rollup coverage. Build and test checks now pass.

Copy link
Copy Markdown
Contributor

bugbot run

Please review the current surcharge changes at c1f4aef for correctness and regressions, including customer attribution and budget accounting. Build and test checks now pass.

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

Stale Bugbot comment from a previous run.

…rd the surcharge without a snapshot

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

Copy link
Copy Markdown
Contributor

@greptileai please verify the failure-path fixes at 4542eb6: trusted key binding from either metadata bucket and surcharge breakdown on rows without a logging snapshot. Regression tests were added and build/test CI passes. Please reassess the remaining failure-path thread.

Copy link
Copy Markdown
Contributor

bugbot run

Please verify both billed-failure fixes at 4542eb6, including key-bound customer attribution and surcharge breakdown without a logging snapshot. Regression tests were added and build/test CI passes.

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

Stale Bugbot comment from a previous run.

moe-berri and others added 2 commits November 18, 2026 11:28
…ide litellm_params

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

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

Copy link
Copy Markdown
Contributor

@greptileai please verify the Responses failure-metadata fix and callback-level regression at 54e12b5. Build/test CI passes; the test exercises the real failure callback and checks the spend-row surcharge.

Copy link
Copy Markdown
Contributor

bugbot run

Please verify the Responses failure-metadata fix and callback-level regression at 54e12b5. Build/test CI passes; the test exercises the real failure callback and checks the spend-row surcharge.

@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 54e12b5. Configure here.

@moe-berri
moe-berri merged commit dec8bc6 into main Nov 18, 2026
108 of 109 checks passed
@moe-berri
moe-berri deleted the litellm_team_cost_margin branch November 18, 2026 16:45
yuneng-berri added a commit that referenced this pull request Nov 23, 2026
…ges (#53940)

Brings nine tests in line with behavior that intentionally changed:

- SSO client removal: /sso/key/generate without SSO now redirects to /ui/login (#53205)
- budget partial update: /budget/info returns the app relation keys (#52477, #52787, #53232)
- performance alerts opt-out: /alerts/monitoring returns thresholds (#52139)
- cost margin rejection: the error names 'customer' as a valid key (#52406)
- regional two-image generation: Gemini gets n single-image requests (#52103)
- customer app budget key rotation: the rotated key's cleanup tolerates /key/regenerate
- DeepSeek 401: the upstream error type is relayed (#53217)
- vLLM rejected predicate: the plain upstream message is relayed (#53217). The case still
  fails on the non-OpenAI error type that #51809 fixes
- /callbacks/list e2e: the Rust spend logger is listed as spend_log (#52182)
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.

4 participants