Skip to content

Cache and throttle your requests

A provider that talks to an online service keeps its requests down with two tools of the server: the cache answers what was asked before, and the throttler paces the rest and backs off when the service says so. Both are required by the rules for providers that stream.

flowchart TD
  CALL["Caller<br/>REQUEST_PRIORITY"] --> UC{"use_cache<br/>entry for this key?"}
  UC -->|"fresh"| HIT["Cached result"]
  UC -->|"expired, allow_expired_cache"| STALE["Stale result<br/>refreshed at LOW"]
  UC -->|"none or expired"| FLIGHT["One shared fetch per key"]
  STALE -.->|"in the background"| TWR
  FLIGHT --> TWR["throttle_with_retries"]
  TWR --> GATE["ThrottlerManager.acquire<br/>waits out a cooldown"]
  GATE --> SLOT["Throttler<br/>slot by priority"]
  SLOT --> API["Your request"]
  API -->|"RateLimited or<br/>ResourceTemporarilyUnavailable"| RETRY["Back off and retry"]
  RETRY --> GATE
  API -->|"result"| STORE["Stored, returned to every caller"]
  1. The priority of the request is set where it started, by the server: see priorities.
  2. use_cache returns a fresh entry at once, without a request. An expired entry is served as is only with allow_expired_cache, and refreshed in the background.
  3. On a miss, callers that ask for the same key at the same time share one fetch, so a burst costs one request.
  4. throttle_with_retries sends each attempt through the throttler: first the cooldown that a rate limit armed, then a slot within the rate limit, highest priority first.
  5. A rate limit or temporary error makes it back off and try again. The result is stored in the background; an error is never stored.

Put @use_cache on a method whose answer you can reuse: details of an item, a search, an album’s tracks, a lookup by ISRC.

from music_assistant.controllers.cache import use_cache
@use_cache(3600 * 24 * 7, allow_expired_cache=True) # 7 days
async def get_artist_albums(self, prov_artist_id: str) -> list[Album]:
...
Argument Default What it does
expiration 30 days Seconds the entry stays fresh.
allow_expired_cache False Serve an expired entry at once and refresh it in the background. Good for listings that make fine fallback data.
cache_none True Store a None result as an answer (“no lyrics for this track”). Set False when None means a failure.
cache_checksum None An entry stored with another checksum counts as missing. Bump it when the form of your parsed result changes.
persistent False The entry survives the Clear cache action of the cache settings, and by default a forced refresh.
allow_bypass not persistent Whether a forced refresh skips the entry.
base_class None Rebuild the result with base_class.from_dict(). Without it the return annotation says what to rebuild.
category 0 A number to group entries.
  • The key is the method name plus its arguments, each turned into text with str() (self is left out). Pass ids and strings, not objects whose text differs per call.
  • get(x) and get(item_id=x) give different keys. Call a cached method the same way everywhere.
  • On a provider, entries are kept per instance (instance_id): two accounts never share an entry.
  • The result is stored as JSON. Media items and other models with to_dict() work, and so do plain values, lists and dicts. A result that cannot be stored is logged and not kept.
  • Without base_class, the return annotation must match the result, such as list[Track] or Track | None: it rebuilds the cached value.
  • An exception is never cached: raise for a failure, return None or an empty list for “nothing found”.
  • An async generator cannot be decorated. Cache a helper that returns a list, and yield from it.
  • Keep what belongs to one user, such as the resume position of an episode, out of a cached result: the cache is shared by everyone who uses the provider.
  • Never cache audio, see the rules for providers that stream.
  • It expires after expiration. A daily task removes expired entries; with allow_expired_cache they stay up to 90 days past expiry as fallback.
  • A forced refresh (force_refresh) runs inside mass.cache.handle_refresh(True): the call skips the entry, fetches, and stores the new result. An entry with allow_bypass=False, the default for a persistent one, is not skipped.
  • When your provider changes something in the service, such as the tracks of a playlist, drop the entries yourself with forget_cached. It drops every call that starts with the arguments you give, so pass them by position:
from music_assistant.controllers.cache import forget_cached
await forget_cached(self._get_playlist_tracks_cached, prov_playlist_id)

For values that do not map to one method, use self.mass.cache.get() and self.mass.cache.set(). Pass provider=self.instance_id to keep the entries to your instance; the default provider is shared. set() takes expiration, checksum and persistent like the decorator, and get() takes checksum and base_class.

The cache README explains how the cache works inside.

Three tools in helpers/throttle_retry.py, from most to least complete:

Use When
ThrottlerManager on self.throttler, with @throttle_with_retries on the method that sends one request The usual choice: pacing, retries, and a cooldown after a rate limit. The decorator reads self.throttler and self.logger of your provider.
async with self.throttler.acquire(): on a ThrottlerManager You handle retries yourself. Call set_cooldown(seconds) when the service limits you.
Throttler, with async with throttler: Pacing and priority only, no retries and no cooldown.

Every request to the service goes through one of them. There is no switch to skip the throttler.

ThrottlerManager takes:

Argument Default What it does
rate_limit required Requests per period.
period 1 Length of the period in seconds.
retry_attempts 5 Attempts in total, the first one included.
initial_backoff 5 Seconds of the first wait without a hint from the service. It doubles per retry, up to 120.
low_priority_retry_attempts retry_attempts Attempts for background work. Use 1 when the job tries again on its next run anyway.
foreground_waits_out_cooldown True Set False when another route can serve the call meanwhile: user actions and playback then fail at once on any cooldown.

Set rate_limit and period to what the service documents. Without a documented limit, the keyless metadata providers use one request per second. Create the throttler per instance, or as a class attribute to share one limit between all accounts, as Qobuz does.

Raise one of these inside the throttled method; any other exception goes straight to the caller.

  • On a 429, raise RateLimited with the wait the service asked for as backoff_time. parse_retry_after() reads a Retry-After header in seconds or as a date, and returns 0 when there is none.
  • On a temporary error, such as a 502 or 503, raise ResourceTemporarilyUnavailable, with backoff_time when the service names a recovery time.

What happens next:

  • After RateLimited the call waits at least backoff_time, and longer as retries go on. For that time the throttler holds back its other calls too.
  • After ResourceTemporarilyUnavailable it waits backoff_time, or backs off from initial_backoff when there is none.
  • When the service asks for more than 60 seconds, the call is not retried. A rate limit then holds the throttler back for that time, and its calls fail at once while more than 60 seconds remain.
  • Calls wait out a shorter cooldown. Playback does not: it sends at once.
  • A call that gives up raises RetriesExhausted. Every retry takes a slot of the rate limit of its own.

A metadata provider overrides its rate_limited property with return self.throttler.cooldown_remaining > 0, so the metadata scan holds off while the limit lasts.

The throttler serves the highest priority first. Background work gets at most half of the rate limit, spread evenly over the period, which leaves room for user actions and playback. With a limit of one request per period, they can still wait behind one background call.

RequestPriority Set by the server for
HIGH Stream requests and loading a queue item to play.
NORMAL Commands from the app and the API. Also the default when nothing is set.
LOW Tasks of mass.tasks, such as library syncs and metadata scans, and background cache refreshes.

You set a priority only for work your provider starts itself. A task you start inherits the priority of the code that starts it.

  • set_request_priority(RequestPriority.LOW) at the start of a background task.
  • with request_priority(RequestPriority.LOW): around a block, such as a play report to the service.
  • @with_request_priority(RequestPriority.LOW) on a method that is always a background job.

Put @use_cache above @throttle_with_retries. A cache hit then returns without taking a slot, and only the final result of the retries is stored. From the LRCLIB provider:

@use_cache(3600 * 24 * 14) # 14 days
@throttle_with_retries
async def _get_data(self, /, **params: Any) -> dict[str, Any] | None:
try:
async with self.mass.http_session.get(f"{self.api_url}/get", params=params) as response:
if response.status in (204, 404):
return None # stored: there are no lyrics for this track
if response.status == 429:
raise RateLimited(
"LRCLIB rate limit",
backoff_time=parse_retry_after(response.headers.get("Retry-After")),
)
response.raise_for_status()
return await response.json()
except (ClientError, TimeoutError, JSONDecodeError) as err:
raise ResourceTemporarilyUnavailable("LRCLIB request failed") from err

When a public method sends several requests, put @use_cache on the public method and @throttle_with_retries on the method that sends one request, as Qobuz does with _get_data.

Set the Log level of your provider to debug (see Run and debug). throttle_with_retries logs to your provider’s logger:

  • ... was delayed for ... secs due to throttling (debug), when a call waited for a slot;
  • Attempt 1/5 failed: ... and Retrying in ... seconds... (info);
  • Not retrying ..., the server asked to wait ... seconds (warning);
  • ... skipped during a rate limit cooldown: ... (debug), when a call failed at once on a cooldown.

The cache logs nothing on a hit or a miss. A failed background refresh logs Background cache refresh failed for ... under the cache logger.

Music Assistant is a project of the Open Home Foundation.