StackPractices
intermediate By Mathias Paulenko

Cache HTTP Responses with httpx and CacheControl in Python

Cache HTTP responses in Python using httpx with CacheControl for HTTP-compliant caching, ETag handling, and conditional requests.

Overview

When a Python app calls external APIs over and over, caching the responses cuts latency, keeps you under rate limits, and saves bandwidth. httpx paired with CacheControl gives you caching that follows the same rules browsers do — it reads Cache-Control, ETag, and Last-Modified headers and behaves accordingly.

This recipe covers wiring CacheControlAdapter into an httpx client, choosing a backend (file, Redis, memory), sending conditional requests, and overriding the cache when you need to. If you want the header semantics themselves, see Set HTTP Cache-Control Headers.

When to Use This

  • Apps that hit third-party APIs repeatedly (weather, exchange rates, search) where responses don’t change every second
  • Cutting rate-limit consumption on APIs that bill per request
  • Speeding up test suites that call real endpoints — a warmed cache makes the second run instant
  • Any GET-heavy HTTP client where the server already sends proper cache headers

Prerequisites

  • Python 3.10+
  • httpx and cachecontrol packages (redis too, for the Redis backend)

Solution

1. Install Dependencies

pip install httpx cachecontrol

2. Basic File-Based Caching

import httpx
from cachecontrol import CacheControlAdapter

# Create an httpx client with a file-based cache adapter
adapter = CacheControlAdapter(cache_dir="/tmp/http_cache")
client = httpx.Client(
    mount={
        "https://": adapter,
        "http://": adapter,
    }
)

# First request — fetches and stores the response
response = client.get("https://api.example.com/products")
print(response.json())
print(f"From cache: {response.from_cache}")  # False

# Second request — served straight from disk
response = client.get("https://api.example.com/products")
print(f"From cache: {response.from_cache}")  # True

client.close()

3. Redis Backend

import httpx
import redis
from cachecontrol import CacheControlAdapter
from cachecontrol.caches.redis_cache import RedisCache

redis_client = redis.Redis(host="localhost", port=6379, db=2)
adapter = CacheControlAdapter(cache=RedisCache(redis_client))

client = httpx.Client(mount={"https://": adapter, "http://": adapter})

# Cached responses live in Redis — shared across processes and hosts
response = client.get("https://api.example.com/data")

Redis is the right call when several workers or machines should share one cache; it also gives you eviction policies through maxmemory for free. For patterns around Redis-backed caching, see the Redis caching strategies guide.

4. In-Memory Cache (Development)

import httpx
from cachecontrol import CacheControlAdapter

adapter = CacheControlAdapter()  # Default: in-memory cache
client = httpx.Client(mount={"https://": adapter})

# Cache lives only in this process — gone on restart
response = client.get("https://api.example.com/data")

5. Using Async httpx with CacheControl

import httpx
from cachecontrol import CacheControlAdapter

adapter = CacheControlAdapter(cache_dir="/tmp/http_cache")

async with httpx.AsyncClient(
    mount={"https://": adapter, "http://": adapter}
) as client:
    # First request — fetches
    r1 = await client.get("https://api.example.com/products")

    # Second request — from cache
    r2 = await client.get("https://api.example.com/products")
    print(f"From cache: {r2.from_cache}")

6. Manual Cache Control

import httpx
from cachecontrol import CacheControlAdapter

adapter = CacheControlAdapter(cache_dir="/tmp/http_cache")
client = httpx.Client(mount={"https://": adapter})

# Force revalidation — fetch fresh even if a cached copy exists
response = client.get(
    "https://api.example.com/products",
    headers={"Cache-Control": "no-cache"},
)

# Skip the cache entirely — nothing gets stored
response = client.get(
    "https://api.example.com/sensitive",
    headers={"Cache-Control": "no-store"},
)

# Only accept a cached copy younger than 60 seconds
response = client.get(
    "https://api.example.com/products",
    headers={"Cache-Control": "max-age=60"},
)

7. Conditional Requests (ETag / Last-Modified)

CacheControl handles ETag and Last-Modified for you:

# First request — server returns an ETag
response = client.get("https://api.example.com/products")
etag = response.headers.get("ETag")

# Second request — CacheControl sends If-None-Match automatically.
# When the server answers 304 Not Modified, the adapter returns the
# stored body with status 200 — your code never sees the 304.
response = client.get("https://api.example.com/products")

8. Wrapper Class with TTL Override

import httpx
from cachecontrol import CacheControlAdapter

class CachedHttpClient:
    def __init__(self, cache_dir="/tmp/http_cache", default_ttl=300):
        adapter = CacheControlAdapter(cache_dir=cache_dir)
        self.client = httpx.Client(mount={"https://": adapter, "http://": adapter})
        self.default_ttl = default_ttl

    def get(self, url: str, params: dict = None, force_refresh: bool = False) -> dict:
        headers = {}
        if force_refresh:
            headers["Cache-Control"] = "no-cache"
        elif self.default_ttl:
            # Cap freshness — ignore any longer max-age from the server
            headers["Cache-Control"] = f"max-age={self.default_ttl}"

        response = self.client.get(url, params=params, headers=headers)
        response.raise_for_status()
        return response.json()

    def post(self, url: str, json: dict = None) -> dict:
        # POST requests never hit the cache
        response = self.client.post(url, json=json)
        response.raise_for_status()
        return response.json()

    def close(self):
        self.client.close()

# Usage
api = CachedHttpClient(cache_dir="/tmp/api_cache", default_ttl=600)

# Cached GET (fresh for at most 600s)
data = api.get("https://api.example.com/products", params={"page": 1})

# Force a fresh fetch
fresh = api.get("https://api.example.com/products", force_refresh=True)

# POST — never cached
result = api.post("https://api.example.com/products", json={"name": "Widget"})

A runnable version of this client lives in the companion repo.

How It Works

flowchart diagram: Request

The adapter inspects the response’s Cache-Control header first: max-age decides how long a copy stays fresh, while no-store and no-cache tell it whether storing is allowed at all. When a stored response carries an ETag, the next request goes out with If-None-Match; a 304 Not Modified answer means the stored body gets reused, which saves the download. Last-Modified works the same way through If-Modified-Since.

Each cache key comes from the request URL plus the HTTP method, so query strings matter — ?page=1 and ?page=2 are separate entries. A Vary header in the response (say Vary: Accept-Encoding) splits storage further, one entry per variant.

Variants

Custom Cache Backend

from cachecontrol import CacheControlAdapter
from cachecontrol.caches.file_cache import FileCache

class CustomFileCache(FileCache):
    def __init__(self, directory, **kwargs):
        super().__init__(directory, **kwargs)

    def get(self, key):
        # Hook for logging or hit/miss metrics
        value = super().get(key)
        if value:
            print(f"Cache hit: {key}")
        return value

    def set(self, key, value, expires=None):
        print(f"Cache set: {key}, expires: {expires}")
        super().set(key, value, expires)

adapter = CacheControlAdapter(cache=CustomFileCache("/tmp/http_cache"))

Per-Request TTL Override

# Cap the server's Cache-Control with a shorter TTL
response = client.get(
    "https://api.example.com/long-cache",
    headers={"Cache-Control": "max-age=60"},  # 60s instead of the server's 3600s
)

Cache with Circuit Breaker

import httpx
from cachecontrol import CacheControlAdapter

class ResilientClient:
    def __init__(self):
        adapter = CacheControlAdapter(cache_dir="/tmp/http_cache")
        self.client = httpx.Client(mount={"https://": adapter})
        self.failure_count = 0
        self.circuit_open = False

    def get(self, url: str) -> dict:
        if self.circuit_open:
            # Serve cache only — don't touch the network
            cached = self.client.get(url, headers={"Cache-Control": "only-if-cached"})
            if cached.from_cache:
                return cached.json()
            raise Exception("Circuit open and no cached response available")

        try:
            response = self.client.get(url)
            response.raise_for_status()
            self.failure_count = 0
            return response.json()
        except (httpx.HTTPError, httpx.TimeoutException):
            self.failure_count += 1
            if self.failure_count >= 5:
                self.circuit_open = True
            raise

Best Practices

Pick the backend for the environment: in-memory dies with the process and can’t be shared between workers, so production wants the file backend at minimum, or Redis when several hosts pull from the same cache.

Respect what the server sends. A no-store directive exists because the data is sensitive or per-user — overriding it with your own max-age caches things the owner explicitly asked you not to. Only rewrite TTLs for APIs you control.

Let no-cache do force-refresh properly. It still sends the ETag, so a 304 costs a round trip but not a download. Reaching for no-store when you only wanted a fresh read throws away the cached copy for nothing.

Only GET and HEAD responses are cacheable — CacheControl won’t store POST, PUT, or DELETE, which is what you want anyway. And whatever backend you pick, keep an eye on disk or memory: file caches grow until entries expire, so point them at a directory you can clean.

Common Mistakes

Caching authenticated responses without private. A response fetched with an Authorization header can hold user-specific data; if a shared cache stores it, the next user may get the previous one’s payload. Either skip caching on authenticated endpoints or make sure the server marks them private.

Assuming the adapter sees what your code sees. CacheControl swallows the 304 and hands you the stored response with status 200 — don’t write logic that expects to observe 304 on the client side.

Leaking connections by never closing the client. httpx.Client pools connections; wrap it in with or call close() when the client goes out of scope, especially in short-lived scripts and workers.

Trusting Vary handling in a custom cache. The built-in backends split entries per Vary value, but a hand-rolled cache that ignores it will happily serve the wrong encoding or language to the next caller.

Further Reading

Frequently Asked Questions

Should I use httpx + CacheControl or requests-cache?

requests-cache plugs into the requests library and has the friendlier API. CacheControl works with both requests and httpx, so if you're on httpx for async or HTTP/2, CacheControl is the natural fit.

Does CacheControl store response bodies?

Yes — it serializes the whole response, headers and body (JSON, text, or binary), into the backend.

What happens with redirects?

The final response after the redirect chain gets cached; the intermediate 301/302 hops don't. Each redirect is still followed on every request unless you disable it with httpx.Client(follow_redirects=False).

Can I cache streaming responses?

Not out of the box. client.stream() consumes the body lazily, so there's nothing complete to store. Read the body fully first, or use regular (non-streaming) requests on endpoints you want cached.

What happens when the file cache grows too large?

There's no built-in size cap — entries only disappear when their max-age expires. For bounded caches, use Redis with maxmemory and an eviction policy, or clean the cache directory on a schedule.

How do I invalidate a cached response?

There's no public delete(url) API — cache keys are hashed internally. The practical options: send Cache-Control: no-cache to force revalidation, wipe the cache directory (or Redis db), or keep max-age short on endpoints that change often. Writing your own FileCache subclass (like the one above) lets you intercept set/delete if you need per-key control.