Skip to main content
Agent Server includes a built-in cache you can use inside your deployed graphs. Call swr with a key and a loader function, and the server caches the result, revalidates stale entries in the background, and returns fresh data on every read. All cache APIs are server-side only and require the LangGraph Agent Server runtime. Values must be JSON-serializable.
swr requires Agent Server runtime v0.7.79 or later and is currently in beta. cache_get and cache_set require v0.7.29 or later.

Quick start

Pass a key and an async loader function. swr returns the cached value if available, or calls your loader to fetch it:
On the first call, swr awaits load_config() and caches the result. On subsequent calls, it returns the cached value instantly and revalidates in the background.

Configure freshness

Control how long cached values are considered fresh and when they expire:

How revalidation works

Use with Pydantic models

Pass a model parameter to automatically serialize and deserialize Pydantic models:
swr calls model_dump(mode="json") before storing and model.model_validate() when reading back.

Cache auth credentials

You can cache credential validation in a custom auth handler to avoid hitting your identity provider on every request:
With this setup, the server returns the cached user for 5 minutes without revalidation, then revalidates in the background for up to 1 hour. After 1 hour, the next request blocks until validate_and_fetch_user completes.

Inspect cache status

swr returns an SWRResult object with the value and cache status:
Call .mutate() to update the cached value or force a revalidation:

Low-level cache API

For simple get/set caching without revalidation, use cache_get and cache_set directly:

cache_get

Return the deserialized value, or None if the key does not exist or has expired.

cache_set

Next steps