Skip to content

fix: prevent duplicate budget alert emails on concurrent threshold crossings - #32011

Merged
yucheng-berri merged 2 commits into
litellm_internal_stagingfrom
litellm_lit_4172_dup_budget_alert
Jul 3, 2026
Merged

yucheng-berri merged 2 commits into
litellm_internal_stagingfrom
litellm_lit_4172_dup_budget_alert

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Resolves LIT-4172

Pre-Submission checklist

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

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / Proof of Fix

Budget alert emails were being delivered more than once for a single threshold crossing. Reproduced live against a proxy with Postgres, Redis (shared dedup cache, as in a multi-replica deployment), and an SMTP server, hitting real openai/gpt-4.1-mini. A local SMTP catcher counts delivered alert emails; it holds each connection open briefly to model a real mail server and widen the send window.

Config (config.yaml) matches the reported setup:

litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: os.environ/REDIS_HOST
    port: os.environ/REDIS_PORT
  default_key_max_budget_alert_emails:
    "50": ["budget-alerts@litellm.test"]
general_settings:
  master_key: sk-1234
  alerting: ["email"]

Launched with SMTP_HOST/SMTP_PORT pointed at the catcher and SMTP_TLS=False.

Steps (identical against unfixed and fixed code):

# 1. create a key and drive it just past the 50% threshold, then fire a
#    burst of concurrent requests that all observe the crossed spend before
#    any alert marker is written (the production race under bursty traffic)
KEY=$(curl -sS $BASE/key/generate -H "Authorization: Bearer sk-1234" \
  -H "Content-Type: application/json" \
  -d '{"max_budget":0.003,"models":["gpt-3.5-turbo"]}' | jq -r .key)
HASH=$(python3 -c "import hashlib,sys;print(hashlib.sha256(sys.argv[1].encode()).hexdigest())" "$KEY")
psql "$DATABASE_URL" -c "UPDATE \"LiteLLM_VerificationToken\" SET spend=0.00175 WHERE token='$HASH';"

# 2. fire 8 concurrent requests (real gpt-4.1-mini calls) for the same crossing
for i in $(seq 1 8); do
  curl -sS $BASE/v1/chat/completions -H "Authorization: Bearer $KEY" \
    -H "Content-Type: application/json" \
    -d '{"model":"gpt-3.5-turbo","messages":[{"role":"user","content":"hi"}],"max_tokens":5}' >/dev/null &
done; wait

Before (unfixed) - three duplicate emails for one 50% crossing, seconds apart:

1783042598.328	to=['budget-alerts@litellm.test']
1783042599.842	to=['budget-alerts@litellm.test']
1783042601.358	to=['budget-alerts@litellm.test']
TOTAL alert emails delivered = 3

After (fixed) - exactly one email for the same burst:

1783042663.605	to=['budget-alerts@litellm.test']
TOTAL alert emails delivered = 1

The shared Redis marker after the fixed run confirms all eight concurrent requests reached the dedup guard, yet only the one that atomically claimed the slot sent:

redis-cli GET email_budget_alerts:max_budget_alert:50:<hash>
# -> "8"   (8 concurrent claims, 1 send)

A repeat burst within the alert TTL still delivers no further emails, so dedup persists as before.

Type

🐛 Bug Fix

Changes

EmailBaseCallback.budget_alerts guarded against duplicate sends by reading an "already sent" cache marker, awaiting the email send, then writing the marker. Because the marker was written only after the await, two requests that crossed the same threshold within the send window both read no marker and both sent. The same shape existed in all three branches of the method: the multi-threshold path (default_key_max_budget_alert_emails), the legacy single-threshold path (EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE), and the soft budget path. Redis narrowed but did not close the window because the write still landed after the send.

All three branches now claim the send slot atomically before sending with async_increment_cache, the same primitive the alerting code already uses for its counters. The increment is atomic per event loop for the in-memory cache and across workers via Redis INCR, so only the caller that observes a count of 1 proceeds to send; concurrent callers observe a higher count and return. The refresh_ttl=False default preserves the 24h window, keyed per entity and threshold exactly as before. On send failure the marker is released with async_delete_cache so a transient email backend error does not suppress the alert for the full TTL, matching the previous behavior where a failed send left no marker.

The live proof above exercises the multi-threshold path end to end. The single-threshold and soft budget paths share the identical mechanism and are each covered by concurrent-crossing and failed-send regression tests (parametrized over all three branches) that fail when the fix is reverted.

The Slack alert channel (SlackAlerting.budget_alerts) has an analogous get-send-set guard for its own dedup. That is a separate subsystem from the reported email symptom and is tracked as a follow-up on LIT-4172 rather than changed here, to keep this PR scoped to the one bug


Note

Medium Risk
Touches enterprise alerting dedup semantics under Redis/multi-replica concurrency; behavior change is intentional but mis-increment or release logic could suppress or duplicate alerts.

Overview
Fixes duplicate budget alert emails when many requests cross the same spend threshold at once (LIT-4172).

BaseEmailLogger.budget_alerts no longer uses read-cache → send → write "SENT". Soft budget, legacy max-budget, and multi-threshold max-budget paths now async_increment_cache on the same TTL keys before sending; only the caller that sees count ≤ 1 sends. Failed sends call new _release_budget_alert_claim (async_delete_cache) so a transient SMTP error does not block retries for the full TTL.

Unit tests mock async_increment_cache instead of get/set; new parametrized tests cover concurrent crossing (exactly one send) and failed-send retry across all three branches.

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

@greptile-apps

greptile-apps Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes duplicate budget alert emails under concurrent threshold crossings by replacing the read-check-send-write dedup with an atomic async_increment_cache claim before the send in all three budget_alerts branches (soft budget, single-threshold max budget, multi-threshold max budget). A new _release_budget_alert_claim helper handles send failures cleanly by deleting the counter in a guarded try/except so a transient email-backend error does not permanently suppress future alerts within the TTL.

  • Atomic dedup: async_increment_cache (Redis INCR / single-event-loop increment) replaces the non-atomic get → send → set sequence; only the coroutine that receives count == 1 proceeds.
  • Failure recovery: _release_budget_alert_claim deletes the counter on send failure and swallows its own exception with a debug-level log, so a secondary cache error neither propagates nor leaves logs silent about the original send error.
  • Test coverage: Three new parametrised tests (concurrent_crossing, failed_send_retry, release_failure_does_not_propagate) exercise all three branches with a real DualCache instance.

Confidence Score: 5/5

Safe to merge; the atomic increment correctly prevents duplicate sends across all three alert branches, and the new _release_budget_alert_claim helper addresses the previously reported unguarded delete path.

All three previously identified blocking issues (unguarded async_delete_cache in each of the soft-budget, single-threshold, and multi-threshold exception handlers) are resolved by the shared _release_budget_alert_claim helper. The core dedup mechanism — async_increment_cache returning the post-increment count with INCR atomicity on Redis and cooperative-scheduling atomicity in the in-memory path — is sound. New parametrised tests verify concurrent dedup, failed-send retry, and cascaded-cache-error resilience across all three branches using a real DualCache instance.

No files require special attention.

Important Files Changed

Filename Overview
enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py Replaces the check-then-send-then-mark dedup pattern with atomic async_increment_cache across all three budget-alert branches; adds _release_budget_alert_claim helper that wraps async_delete_cache in its own try/except, eliminating the previously reported unguarded delete path.
tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py All existing mock setups updated from async_get_cache/async_set_cache to async_increment_cache; adds three new parametrised tests covering concurrent-crossing dedup, failed-send claim release, and cache-delete failure propagation across all three alert branches.

Reviews (4): Last reviewed commit: "fix: harden budget alert claim release a..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…ossings

Budget alert emails were sent more than once for a single threshold crossing. The email dedup guard read the "already sent" marker, awaited the send, then wrote the marker, so concurrent requests crossing the same threshold within the send window all saw no marker and each sent. This affected the multi-threshold path (default_key_max_budget_alert_emails), the legacy single-threshold path (EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE), and the soft budget path, all in EmailBaseCallback.budget_alerts

All three branches now claim the send slot atomically before sending via async_increment_cache, which is atomic per event loop for the in-memory cache and across workers via Redis INCR; only the caller that observes a count of 1 sends. On send failure the marker is released with async_delete_cache so a transient failure does not suppress the alert for the full 24h TTL
@yucheng-berri
yucheng-berri force-pushed the litellm_lit_4172_dup_budget_alert branch from d3f1ebc to 850d26f Compare July 3, 2026 01:58
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

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 850d26f. Configure here.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

1 similar comment
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Addresses review feedback on the claim-before-send change. The claim release in each send-failure handler now logs the send error first and releases the claim best-effort through a shared helper, so a transient cache error during async_delete_cache cannot propagate out of the fire-and-forget budget_alerts task, drop the send-failure log, and leave the claim stuck for the full 24h TTL. In the multi-threshold branch the increment claim now runs before the WebhookEvent is built, so skipped concurrent crossings no longer construct and discard the event, matching the single-threshold and soft budget branches
@yucheng-berri
yucheng-berri force-pushed the litellm_lit_4172_dup_budget_alert branch from 639e183 to 4d7cffc Compare July 3, 2026 19:20
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

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 4d7cffc. Configure here.

@yucheng-berri
yucheng-berri requested a review from tin-berri July 3, 2026 21:55
@yucheng-berri
yucheng-berri merged commit 099bc97 into litellm_internal_staging Jul 3, 2026
76 checks passed
@yucheng-berri
yucheng-berri deleted the litellm_lit_4172_dup_budget_alert branch July 3, 2026 21:59
yucheng-berri added a commit that referenced this pull request Aug 4, 2026
The dedup claim added in #32011 lives in DualCache, which is memory-only
when Redis is not configured, so each replica wins its own claim and sends
its own copy of the same alert. It is also lost on restart and expires with
EMAIL_BUDGET_ALERT_TTL, so a long-crossed threshold keeps re-alerting.

Record the claim in a new LiteLLM_BudgetAlertSent table instead. The unique
constraint makes the insert an atomic cross-replica claim, and the stored
budget window re-arms the alert when the budget period resets or max_budget
changes rather than on a timer. Falls open when the claim cannot be recorded.

Resolves LIT-4172
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