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.
The path of a request
Section titled “The path of a request”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"]
How to read this
Section titled “How to read this”- The priority of the request is set where it started, by the server: see priorities.
use_cachereturns a fresh entry at once, without a request. An expired entry is served as is only withallow_expired_cache, and refreshed in the background.- On a miss, callers that ask for the same key at the same time share one fetch, so a burst costs one request.
throttle_with_retriessends each attempt through the throttler: first the cooldown that a rate limit armed, then a slot within the rate limit, highest priority first.- 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.
The cache
Section titled “The cache”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 daysasync 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. |
Key and scope
Section titled “Key and scope”- The key is the method name plus its arguments, each turned into text with
str()(selfis left out). Pass ids and strings, not objects whose text differs per call. get(x)andget(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.
What you can cache
Section titled “What you can cache”- 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 aslist[Track]orTrack | None: it rebuilds the cached value. - An exception is never cached: raise for a failure, return
Noneor 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.
When an entry goes
Section titled “When an entry goes”- It expires after
expiration. A daily task removes expired entries; withallow_expired_cachethey stay up to 90 days past expiry as fallback. - A forced refresh (
force_refresh) runs insidemass.cache.handle_refresh(True): the call skips the entry, fetches, and stores the new result. An entry withallow_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)Use the cache directly
Section titled “Use the cache directly”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.
The throttler
Section titled “The throttler”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.
Rate limits and errors
Section titled “Rate limits and errors”Raise one of these inside the throttled method; any other exception goes straight to the caller.
- On a 429, raise
RateLimitedwith the wait the service asked for asbackoff_time.parse_retry_after()reads aRetry-Afterheader 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, withbackoff_timewhen the service names a recovery time.
What happens next:
- After
RateLimitedthe call waits at leastbackoff_time, and longer as retries go on. For that time the throttler holds back its other calls too. - After
ResourceTemporarilyUnavailableit waitsbackoff_time, or backs off frominitial_backoffwhen 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.
Priorities
Section titled “Priorities”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.
Both on one method
Section titled “Both on one method”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_retriesasync 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 errWhen 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.
See it work
Section titled “See it work”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: ...andRetrying 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.