Skip to content

Pause all accounts on a Spotify rate limit instead of sleeping in the executor - #69

Merged
Mincka merged 2 commits into
mainfrom
fix/shared-rate-limit-backoff
Aug 23, 2026
Merged

Mincka merged 2 commits into
mainfrom
fix/shared-rate-limit-backoff

Conversation

@Mincka

@Mincka Mincka commented Aug 23, 2026

Copy link
Copy Markdown
Owner

Fixes #68

Problem

Spotify() was built with spotipy's defaults, which retry a 429 through urllib3's Retry with respect_retry_after_header=True. That means time.sleep(Retry-After) (capped at 6 h by urllib3) inside the Home Assistant executor thread, up to 3 times, for every call that gets a 429. With the reporter's Retry-After values (2,484 s to 12,471 s) a single coordinator refresh or play_media call could hang for hours, once per account, and nothing in spotcast read Retry-After or told the other accounts (same client id, same rate limit) to stop.

Fix

  • spotify/client.py: remove 429 from spotipy's status_forcelist (5xx retries unchanged, the fake-429-on-5xx unmasking moved here as SERVER_ERROR_PATTERN / is_rate_limit()), and consult a shared RateLimitGuard before every request. A genuine 429 registers Retry-After (default 30 s when missing, never shortens an existing window) and raises RateLimitedError; until the window expires every client fails fast with no network call, then resumes on its own.
  • spotify/rate_limit.py (new): thread-safe guard, one WARNING per window then DEBUG.
  • spotify/exceptions.py: RateLimitedError(SpotifyException) with status 429, retry_at, seconds_remaining, resume_time, so existing except SpotifyException paths keep working.
  • coordinator.py: "Spotify rate limit active for this client id. Refresh of entry ... paused for N s (until HH:MM:SS)".
  • services/service_handler.py: HomeAssistantError("Spotify is rate limiting this client id. Try again in N s (after HH:MM:SS)") instead of a traceback.
  • spotify/account/playback.py: RateLimitedError passes through the PlaybackError wrappers (device-not-found retry extracted into _async_retry_when_device_appears).
  • system_health.py: Rate Limit row (ok / limited until HH:MM:SS).
  • Docs note on the per-client-id quota, changelog entry.

Tests

35 new tests (guard, client, coordinator, service handler, playback, system health). task test: 791 passed. pylint custom_components: 10.00/10.

🤖 Generated with Claude Code

… executor

spotipy retried a 429 by sleeping the full Retry-After (capped at 6 h by
urllib3) inside the Home Assistant executor thread, up to 3 times, once
per account and per action call. A rate limit therefore left coordinator
refreshes and play_media calls hanging for hours, and every waking thread
immediately re-hit an API that had already said no.

- Remove 429 from spotipy's retry codes (5xx retries unchanged).
- Add a shared RateLimitGuard consulted by every Spotify client before a
  request: a 429 registers Retry-After (default 30 s when missing) and
  raises RateLimitedError; every account fails fast with no network call
  until the window expires, then resumes on its own.
- RateLimitedError subclasses SpotifyException (429) so existing handlers
  keep working; the coordinator and service handler report the resume
  time, playback wrappers let it through, system health shows a Rate
  Limit row.

Fixes #68

Co-Authored-By: Claude Fable 5 <[email protected]>
urllib3 retries any 429/503 carrying a Retry-After header whenever
respect_retry_after_header is set, regardless of status_forcelist, and
spotipy's session builder gives no way to turn it off. Verified through
the real requests/urllib3 stack against a local server answering like
Spotify: a 429 now returns immediately with a single request, 5xx keep
their 3 retries. Adds real-stack tests for both.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Mincka

Mincka commented Aug 23, 2026

Copy link
Copy Markdown
Owner Author

Simulation of the reporter's condition (real HTTP stack)

Local server impersonating api.spotify.com (429 + Retry-After, Spotify's JSON body), two accounts = two real spotipy clients through requests/urllib3, driven through the real SpotifyAccount + SpotcastCoordinator + ServiceHandler.

=== BEFORE: stock spotipy client, Retry-After: 4 s, one call ===
raised SpotifyException http_status=429 reason=ResponseError('too many 429 error responses')
elapsed: 12.0 s (thread blocked), server hits: {'account-a': 4}
-> with the reporter's Retry-After: 12471 this single call would block an executor thread for 10.4 h

=== AFTER: patched client, 2 accounts, Retry-After: 6 s ===
[ 0.00s] account A refresh -> UpdateFailed: Spotify rate limit active for this client id. Refresh of entry `account-a` paused for 6 s (until 17:37:27)
         server hits so far: {'account-a': 1}
[ 0.00s] account B refresh -> UpdateFailed (0.001s): ... paused for 6 s (until 17:37:27)
         server hits so far: {'account-a': 1}  <- B made no request
[ 0.00s] play_media on B -> HomeAssistantError (0.000s): Spotify is rate limiting this client id. Try again in 6 s (after 17:37:27)
         server hits so far: {'account-a': 1}
[ 6.10s] window expired, polling resumes
[ 6.11s] account A refresh OK: playlists_count=3 devices=[]
[ 6.12s] account B refresh OK: playlists_count=3 devices=[]

The simulation caught a real gap in the first commit: removing 429 from status_forcelist was not enough, urllib3 retries any 429/503 carrying Retry-After whenever respect_retry_after_header is set (the default) and spotipy's session builder cannot turn it off. The second commit overrides _build_session and adds tests that go through the real requests/urllib3 stack against a local server (429 returns in < 1 s with one request; 5xx keep their 3 retries; exhausted 5xx are not mistaken for a rate limit).

@Mincka
Mincka merged commit 07c1097 into main Aug 23, 2026
7 checks passed
@Mincka
Mincka deleted the fix/shared-rate-limit-backoff branch August 23, 2026 15:41
@Mincka Mincka mentioned this pull request Aug 23, 2026
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.

Feature: Shared rate-limit backoff across accounts/intergartion. 429 penalties escalate with multiple spotify accounts?

1 participant