# Python caching libraries

Python caching libraries store the result of an expensive call for reuse when a later call has the same inputs. A cache evicts entries by a policy such as least recently used or a time-to-live. These libraries let web apps and data pipelines skip repeated database queries, API calls, and computations.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [cachetools](#cachetools) | 280.0M | 2.8K | Nov 2026 | MIT |
| [redis-py](#redis) | 249.6M | Not on GitHub | Jul 2026 | MIT |
| [Joblib](#joblib) | 200.3M | 4.4K | Aug 2026 | BSD-3-Clause |
| [CacheControl](#cachecontrol) | 106.6M | Not on GitHub | Nov 2026 | Apache-2.0 |
| [async-lru](#async-lru) | 45.0M | Not on GitHub | Oct 2026 | MIT |
| [boltons](#boltons) | 30.7M | Not on GitHub | Sep 2026 | BSD-3-Clause |
| [diskcache](#diskcache) | 26.6M | 2.9K | Aug 2023 | Apache-2.0 |
| [cachebox](#cachebox) | 14.3M | Not on GitHub | Oct 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[cachetools](#cachetools) has the most monthly downloads in this comparison, at 265.5M.

## Capabilities

| Library | Separate cache server required | Local disk cache backend |
| --- | --- | --- |
| [cachetools](#cachetools) | No | No |
| [redis-py](#redis) | Yes | No |
| [Joblib](#joblib) | No | Yes |
| [CacheControl](#cachecontrol) | No | Yes |
| [async-lru](#async-lru) | No | No |
| [boltons](#boltons) | No | No |
| [diskcache](#diskcache) | No | Yes |
| [cachebox](#cachebox) | No | No |

## Libraries

### cachetools

[GitHub](https://github.com/tkem/cachetools) · [PyPI](https://pypi.org/project/cachetools) · [Docs](https://cachetools.readthedocs.io/en/stable/)

Provides cache mappings and decorators for function results.

- Downloads / mo: 280.0M
- Stars: 2.8K
- Last release: 8.0.2
- License: MIT
- Capabilities: [From the cachetools docs](https://cachetools.readthedocs.io/en/stable/)

**Strengths**

- **Bounds retained cache values.** Set maxsize to control how much the cache retains.
- **Supports custom value sizing.** Use getsizeof when the cache budget should count value sizes.

**Watch out for**

- **Shared caches need synchronization.** Protect a shared cache with a lock when multiple threads access it.
- **Expired entries can retain memory.** Call expire to remove expired entries during read-only use.

```sh
python3.13 -m pip install cachetools==8.0.2
```

**streamlit/streamlit** (46.4K stars)

[streamlit/streamlit](https://github.com/streamlit/streamlit) 

```python
def __init__(self, persist_storage: CacheStorage, context: CacheStorageContext):
    self.function_key = context.function_key
    self.function_display_name = context.function_display_name
    self._ttl_seconds = context.ttl_seconds
    self._max_entries = context.max_entries
    self._mem_cache: TTLCache[str, bytes] = TTLCache(
        maxsize=self.max_entries,
        ttl=self.ttl_seconds,
        timer=cache_utils.TTLCACHE_TIMER,
    )
    self._mem_cache_lock = threading.Lock()
    self._persist_storage = persist_storage
```

[lib/streamlit/runtime/caching/storage/in_memory_cache_storage_wrapper.py](https://github.com/streamlit/streamlit/blob/bfcede21dec9bd0c5c69e6fb1ee88aa4a9381164/lib/streamlit/runtime/caching/storage/in_memory_cache_storage_wrapper.py) · [More projects using cachetools →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20cachetools%20for%20persistent%20cache%20setup%2C%20function-result%20memoization%2C%20cached%20pipelines%2C%20query%20caching%20and%20invalidation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from cachetools import TTLCache

cache = TTLCache(maxsize=128, ttl=60)
cache["answer"] = 42
print(cache["answer"])

```

From [README.rst](https://api.github.com/repos/tkem/cachetools/contents/src/cachetools/__init__.py?ref=v8.0.2)

### redis-py

[GitHub](https://github.com/redis/redis-py) · [PyPI](https://pypi.org/project/redis) · [Docs](https://redis.readthedocs.io/en/v8.1.0/commands.html)

Provides the Python client for the Redis database and key-value store.

- Downloads / mo: 249.6M
- Last release: 8.1.0
- License: MIT
- Capabilities: [From the redis-py docs](https://redis.readthedocs.io/en/v8.1.0/commands.html)

```sh
python3.13 -m pip install redis==8.1.0
```

**django/django** (91.8K stars)

[django/django](https://github.com/django/django) 

```python
def add(self, key, value, timeout):
    client = self.get_client(key, write=True)
    value = self._serializer.dumps(value)

    if timeout == 0:
        if ret := bool(client.set(key, value, nx=True)):
            client.delete(key)
        return ret
    else:
        return bool(client.set(key, value, ex=timeout, nx=True))
```

[django/core/cache/backends/redis.py](https://github.com/django/django/blob/9e2e5a31e2ef2e8673d3c2a38d2a391dbf42cf23/django/core/cache/backends/redis.py) · [More projects using redis-py →](https://dashboard.exa.ai/playground/search?q=redis%20GitHub%20projects)

**Quickstart**

```python
import redis

client = redis.Redis(host="localhost", port=6379, decode_responses=True)
client.set("answer", "42")

```

From [commands.html](https://redis.readthedocs.io/en/v8.1.0/commands.html)

### Joblib

[GitHub](https://github.com/joblib/joblib) · [PyPI](https://pypi.org/project/joblib) · [Docs](https://joblib.readthedocs.io/en/stable/generated/joblib.Memory.html)

Caches function results on the filesystem for reuse with the same arguments.

- Downloads / mo: 200.3M
- Stars: 4.4K
- Last release: 1.6.0
- License: BSD-3-Clause
- Capabilities: [From the Joblib docs](https://joblib.readthedocs.io/en/stable/generated/joblib.Memory.html)

**Strengths**

- **Caches function results on disk.** Reuse computed results through a named filesystem cache.
- **Expires results through validation callbacks.** Use expires_after to recompute results after a chosen duration.

**Watch out for**

- **Size limits need explicit cleanup.** Call reduce_size to enforce byte, item, or age limits.

```sh
python3.13 -m pip install joblib==1.6.0
```

**scikit-learn-contrib/imbalanced-learn** (7.1K stars)

[scikit-learn-contrib/imbalanced-learn](https://github.com/scikit-learn-contrib/imbalanced-learn) 

```python
def _fit(self, X, y=None, routed_params=None, raw_params=None):
    self.steps = list(self.steps)
    self._validate_steps()
    # Setup the memory
    memory = check_memory(self.memory)

    fit_transform_one_cached = memory.cache(_fit_transform_one)
    fit_resample_one_cached = memory.cache(_fit_resample_one)

    for step_idx, name, transformer in self._iter(
        with_final=False, filter_passthrough=False, filter_resample=False
    ):
        if transformer is None or transformer == "passthrough":
            with _print_elapsed_time("Pipeline", self._log_message(step_idx)):
                continue

        if hasattr(memory, "location") and memory.location is None:
            # we do not clone when caching is disabled to
            # preserve backward compatibility
            cloned_transformer = transformer
        else:
            cloned_transformer = clone(transformer)

        # Fit or load from cache the current transformer
        step_params = self._get_metadata_for_step(
            step_idx=step_idx,
            step_params=routed_params[name],
            all_params=raw_params,
        )
        if hasattr(cloned_transformer, "transform") or hasattr(
            cloned_transformer, "fit_transform"
        ):
            X, fitted_transformer = fit_transform_one_cached(
                cloned_transformer,
                X,
                y,
                weight=None,
                message_clsname="Pipeline",
                message=self._log_message(step_idx),
                params=step_params,
            )
        elif hasattr(cloned_transformer, "fit_resample"):
            X, y, fitted_transformer = fit_resample_one_cached(
                cloned_transformer,
                X,
                y,
                message_clsname="Pipeline",
                message=self._log_message(step_idx),
                params=routed_params[name],
            )
        # Replace the transformer of the step with the fitted
        # transformer. This is necessary when loading the transformer
        # from the cache.
        self.steps[step_idx] = (name, fitted_transformer)
    return X, y
```

[imblearn/pipeline.py](https://github.com/scikit-learn-contrib/imbalanced-learn/blob/8504e95f0160f61d1b617ca66f779646d2ee609e/imblearn/pipeline.py) · [More projects using Joblib →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20joblib%20for%20persistent%20cache%20setup%2C%20function-result%20memoization%2C%20cached%20pipelines%2C%20query%20caching%20and%20invalidation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from joblib import Memory

memory = Memory("./cache", verbose=0)

@memory.cache
def square(value):
    return value * value

square(2)

```

From [memory_basic_usage.py](https://joblib.readthedocs.io/en/stable/generated/joblib.Memory.html)

### CacheControl

[GitHub](https://github.com/psf/cachecontrol) · [PyPI](https://pypi.org/project/CacheControl) · [Docs](https://api.github.com/repos/psf/cachecontrol/contents/cachecontrol/adapter.py?ref=v0.15.0)

Adds HTTP caching to requests sessions.

- Downloads / mo: 106.6M
- Last release: 0.15.0
- License: Apache-2.0
- Capabilities: [From the CacheControl docs](https://api.github.com/repos/psf/cachecontrol/contents/cachecontrol/adapter.py?ref=v0.15.0)

```sh
python3.13 -m pip install CacheControl==0.15.0
```

**python-poetry/poetry** (34.3K stars)

[python-poetry/poetry](https://github.com/python-poetry/poetry) 

```python
def create_session(self) -> requests.Session:
    session = requests.Session()
    session.headers["User-Agent"] = self._user_agent

    if self._cache_control is None:
        return session

    adapter = CacheControlAdapter(
        cache=self._cache_control,
        pool_maxsize=self._pool_size,
    )
    session.mount("http://", adapter)
    session.mount("https://", adapter)

    return session
```

[src/poetry/utils/authenticator.py](https://github.com/python-poetry/poetry/blob/34ad5bf805506d78ef1bdef41d5ca2a343325150/src/poetry/utils/authenticator.py) · [More projects using CacheControl →](https://dashboard.exa.ai/playground/search?q=CacheControl%20GitHub%20projects)

**Quickstart**

```python
import requests
from cachecontrol import CacheControl

session = CacheControl(requests.session())
response = session.get("https://example.com")

```

From [README.rst](https://pypi.org/pypi/CacheControl/0.15.0/json)

### async-lru

[GitHub](https://github.com/aio-libs/async-lru) · [PyPI](https://pypi.org/project/async-lru) · [Docs](https://github.com/aio-libs/async-lru/blob/b43d835d026178c7bc0f0d2ad1c5ab7d5d16628d/README.rst)

Provides an LRU cache for asyncio.

- Downloads / mo: 45.0M
- Last release: 2.4.0
- License: MIT
- Capabilities: [From the async-lru docs](https://github.com/aio-libs/async-lru/blob/b43d835d026178c7bc0f0d2ad1c5ab7d5d16628d/README.rst)

```sh
python3.13 -m pip install async-lru==2.4.0
```

**TracecatHQ/tracecat** (3.9K stars)

[TracecatHQ/tracecat](https://github.com/TracecatHQ/tracecat) 

```python
@alru_cache(ttl=30)
async def _get_setting_cached_by_org(
    key: str,
    organization_id: OrganizationID | None,
    default: Any | None = None,
) -> Any | None:
    """Internal cached implementation keyed by (key, organization_id).

    This ensures different organizations have isolated cache entries.
    """
    logger.debug("Cache miss", key=key, organization_id=organization_id)
    role = ctx_role.get()
    sess = ctx_session.get(None)
    return await get_setting(key, role=role, session=sess, default=default)
```

[tracecat/settings/service.py](https://github.com/TracecatHQ/tracecat/blob/3d9754d0c046b7605c8d6c39d12b227f1c35b1e5/tracecat/settings/service.py) · [More projects using async-lru →](https://dashboard.exa.ai/playground/search?q=async-lru%20GitHub%20projects)

**jupyterlab/jupyterlab** (15.4K stars)

[jupyterlab/jupyterlab](https://github.com/jupyterlab/jupyterlab) 

```python
def _configure_package_metadata_cache(self, _change: object = None) -> None:
    self._fetch_package_metadata = cast(
        "FetchPackageMetadata",
        alru_cache(maxsize=self.package_metadata_cache_size)(
            partial(_fetch_package_metadata, self._httpx_client)
        ),
    )
    self._package_metadata_cache_expires = monotonic() + self.cache_timeout
```

[jupyterlab/extensions/pypi.py](https://github.com/jupyterlab/jupyterlab/blob/0d5e83530197cee73b15a11d2c2c29b168db6065/jupyterlab/extensions/pypi.py) · [More projects using async-lru →](https://dashboard.exa.ai/playground/search?q=async-lru%20GitHub%20projects)

**Quickstart**

```python
import asyncio
from async_lru import alru_cache

@alru_cache(maxsize=32)
async def double(value):
    return value * 2

asyncio.run(double(2))

```

From [README.rst](https://github.com/aio-libs/async-lru/blob/b43d835d026178c7bc0f0d2ad1c5ab7d5d16628d/README.rst)

### boltons

[GitHub](https://github.com/mahmoud/boltons) · [PyPI](https://pypi.org/project/boltons) · [Docs](https://boltons.readthedocs.io/en/latest/cacheutils.html)

Provides utilities that complement Python builtins.

- Downloads / mo: 30.7M
- Last release: 26.2.0
- License: BSD-3-Clause
- Capabilities: [From the boltons docs](https://boltons.readthedocs.io/en/latest/cacheutils.html)

```sh
python3.13 -m pip install boltons==26.2.0
```

**scaleway/netbox-netprod-importer** (109 stars)

[scaleway/netbox-netprod-importer](https://github.com/scaleway/netbox-netprod-importer) 

```python
def _thread_push_device(device_mapper, caches, device, props,
                        role_id, site_id):
    device_type = props.pop("model")
    platform = props.pop("platform", None)

    name = str(device)
    try:
        device = next(device_mapper.get(name=name.lower()))
    except StopIteration:
        device = device_mapper.post(
            name=name, slug=name.lower(),
            device_type=caches["device_types"][device_type.lower()],
            device_role=role_id, site=site_id,
        )

    update_netbox_obj_from(device, props)
    if platform:
        device.platform = caches["platforms"][platform.lower()]
    device.put()
```

[tools/push_devices.py](https://github.com/scaleway/netbox-netprod-importer/blob/0c2e8640bdaaaea4352c343c3f5b5f0f02c89cad/tools/push_devices.py) · [More projects using boltons →](https://dashboard.exa.ai/playground/search?q=boltons%20GitHub%20projects)

**Quickstart**

```python
from boltons.cacheutils import LRU

cache = LRU(max_size=128)
cache["answer"] = 42
print(cache["answer"])

```

From [cacheutils.html](https://boltons.readthedocs.io/en/latest/cacheutils.html)

### diskcache

[GitHub](https://github.com/grantjenks/python-diskcache) · [PyPI](https://pypi.org/project/diskcache) · [Docs](https://grantjenks.com/docs/diskcache/api.html)

Provides disk-backed caches using a SQLite database and filesystem storage.

- Downloads / mo: 26.6M
- Stars: 2.9K
- Last release: 5.6.3
- License: Apache-2.0
- Capabilities: [From the diskcache docs](https://grantjenks.com/docs/diskcache/api.html)

**Strengths**

- **Shares caches across processes.** Use the same cache directory across threads and processes.
- **Expires individual entries.** Set an expiration when writing each cache entry.

**Watch out for**

- **Database operations can time out.** Handle Timeout or enable retries for supported cache operations.

```sh
python3.13 -m pip install diskcache==5.6.3
```

**dottxt-ai/outlines** (16.0K stars)

[dottxt-ai/outlines](https://github.com/dottxt-ai/outlines) 

```python
@functools.lru_cache(1)
def get_cache():
    """Get the context object that contains previously-computed return values.

    The cache is used to avoid unnecessary computations and API calls, which can
    be long and expensive for large models.

    The cache directory defaults to `HOMEDIR/.cache/outlines`, but this choice
    can be overridden by the user by setting the value of the `OUTLINES_CACHE_DIR`
    environment variable.

    """
    from outlines._version import __version__ as outlines_version  # type: ignore

    outlines_cache_dir = os.environ.get("OUTLINES_CACHE_DIR")
    xdg_cache_home = os.environ.get("XDG_CACHE_HOME")
    home_dir = os.path.normpath(os.path.expanduser("~"))
    if outlines_cache_dir:
        # OUTLINES_CACHE_DIR takes precedence
        cache_dir = outlines_cache_dir
    elif xdg_cache_home:  # pragma: no cover
        cache_dir = os.path.join(xdg_cache_home, "outlines")
    elif home_dir != "/": # pragma: no cover
        cache_dir = os.path.join(home_dir, ".cache", "outlines")
    else:  # pragma: no cover
        # home_dir may be / inside a docker container without existing user
        tempdir = tempfile.gettempdir()
        cache_dir = os.path.join(tempdir, ".cache", "outlines")

    memory = Cache(
        cache_dir,
        eviction_policy="none",
        cull_limit=0,
        disk=CloudpickleDisk,
    )

    # ensure if version upgrade occurs, old cache is pruned
    if outlines_version != memory.get("__version__"):
        memory.clear()
    memory["__version__"] = outlines_version

    return memory
```

[src/outlines/caching.py](https://github.com/dottxt-ai/outlines/blob/c52af8472c6fe8a607a733ec11b709476af77a96/src/outlines/caching.py) · [More projects using diskcache →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20diskcache%20for%20persistent%20cache%20setup%2C%20function-result%20memoization%2C%20cached%20pipelines%2C%20query%20caching%20and%20invalidation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from diskcache import Cache

with Cache("./cache") as cache:
    cache.set("answer", 42)

```

From [api.html](https://grantjenks.com/docs/diskcache/api.html)

### cachebox

[GitHub](https://github.com/awolverp/cachebox) · [PyPI](https://pypi.org/project/cachebox) · [Docs](https://awolverp.github.io/cachebox/getting-started/)

Provides memoizing caches written in Rust.

- Downloads / mo: 14.3M
- Last release: 6.2.10
- License: MIT
- Capabilities: [From the cachebox docs](https://awolverp.github.io/cachebox/getting-started/)

```sh
python3.13 -m pip install cachebox==6.2.10
```

**Quickstart**

```python
import cachebox

cache = cachebox.LRUCache(maxsize=128)
cache["answer"] = 42
print(cache["answer"])

```

From [README.md](https://awolverp.github.io/cachebox/getting-started/) · [Find projects using cachebox →](https://dashboard.exa.ai/playground/search?q=cachebox%20GitHub%20projects)

## FAQ

### Which Python caching library should I use?

[cachetools](#cachetools) suits in-process caches with LRU, TTL, and other eviction policies. [redis-py](#redis) suits caches shared across processes and servers. [diskcache](#diskcache) suits caches that must survive a restart on one machine.

### How do I use Redis as a cache in Python?

[redis-py](#redis) is the Python client for Redis. A cache stores each result under a key with an expiry and reads that key before recomputing.

### Redis vs Memcached: what is the difference?

Redis stores strings and data structures such as hashes, lists, and sorted sets, with optional persistence. Memcached stores plain values in memory only and scales by adding nodes.

### How do I add an LRU cache in Python?

The standard library's functools.lru_cache decorator caches a function's results and evicts the least recently used entries. [cachetools](#cachetools) adds TTL caches, and [async-lru](#async-lru) covers coroutines.

### What is diskcache?

[diskcache](#diskcache) stores cache entries in a SQLite database and the filesystem. Entries persist across restarts and can be shared between processes on the same machine.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python caching libraries cachetools DiskCache joblib dogpile.cache examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
