Skip to main content

Official FastAPI integration for Redis

Idiomatic Redis integration for FastAPI - connection management and DI-based caching with automatic key consistency.

Integration PyPI - Version Python Version MIT licensed Checked with mypy Ruff codecov Guide

Discord Twitch YouTube Twitter Stack Exchange questions

Features

  • Fluent setupFastAPIRedis(app).lifespan().caching() configures pools and caching in one chain, attaching to the FastAPI lifespan events
  • Dependency injectioncache(), cache_evict(), cache_put() as Depends() factories, plus CacheBackend for complex invalidation and conditional logic
  • HTTP-native cachingETag, 304 Not Modified, Cache-Control directives out of the box
  • Rate limitingrate_limit() dependency with a fluent rate language ("10/second"), X-RateLimit-* / Retry-After headers, and distributed per-client counters
  • Testable — full dependency_overrides support; no need for monkey-patching
  • Pydantic-validated configuration — fully configurable via environment variables or via an .env file

Requirements

Dependency Supported versions
Python 3.10 to 3.14
FastAPI 0.115+
redis-py 6.0+
Pydantic 2.0+
Redis server 7.4+

Installation

pip install fastapi-redis-sdk

Caching

Cache GET responses with a dependency — on a hit the endpoint is skipped, on a miss the response is stored after it returns:

from fastapi import Depends, FastAPI
from redis_fastapi import FastAPIRedis, cache

app = FastAPI()
FastAPIRedis(app).lifespan().caching()

@app.get("/products/{product_id}", dependencies=[Depends(cache(ttl=300, eviction_group="products"))])
async def get_product(product_id: int):
    return await db.get_product(product_id)

cache_evict() and cache_put() handle invalidation and write-through with matching keys, and CacheBackendDep exposes imperative get/set/delete/has/delete_group for conditional logic. Cached responses carry X-Redis-Cache (HIT/MISS), Cache-Control, and ETag headers with 304 Not Modified support.

See the Caching Guide for the full patterns, CacheBackend usage, Pydantic model caching, feature comparison, and best practices.

Rate limiting

Protect an endpoint with the rate_limit() dependency. Stack two limits to cap bursts and sustained traffic at once — a short high-rate window plus a longer low-rate window:

from fastapi import Depends, FastAPI
from redis_fastapi import FastAPIRedis, rate_limit

app = FastAPI()
FastAPIRedis(app).lifespan().rate_limiting()

@app.get(
    "/search",
    dependencies=[
        Depends(rate_limit("10/second", scope="search:burst")),      # burst
        Depends(rate_limit("100/minute", scope="search:sustained")),  # sustained
    ],
)
async def search():
    return {"results": [...]}

Both limits count per client IP by default; a request must satisfy both, and the distinct scope keeps the two counters independent on the same route. When either is exceeded the request gets a 429 Too Many Requests with Retry-After, and every response carries X-RateLimit-Limit / -Remaining / -Reset. Counters live in Redis, so limits hold across every worker and pod.

See the Rate Limiting Guide for identifiers, the global limiter, custom responses, IETF headers, and the imperative backend.

Configuration

All settings are read from environment variables (prefixed REDIS_) or a .env file. Set REDIS_URL for the simplest setup:

export REDIS_URL=redis://user:pass@host:6379/0

Or configure individual fields:

export REDIS_HOST=redis.example.com
export REDIS_PORT=6380
export REDIS_PASSWORD=secret

Additional options: TLS (REDIS_SSL, REDIS_SSL_CERTFILE, etc.), connection pool (REDIS_MAX_CONNECTIONS, REDIS_SOCKET_TIMEOUT), OSS Cluster mode (REDIS_CLUSTER=true), key prefix (REDIS_PREFIX), and default cache TTL (REDIS_DEFAULT_TTL, default 0 = no expiry).

For programmatic configuration:

from redis_fastapi import get_settings

settings = get_settings()
settings.url = "redis://custom:6379/0"
settings.default_ttl = 120

See the Configuration Guide for the full environment variable reference and API details.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_redis_sdk-0.8.0.tar.gz (39.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_redis_sdk-0.8.0-py3-none-any.whl (44.5 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_redis_sdk-0.8.0.tar.gz.

File metadata

  • Download URL: fastapi_redis_sdk-0.8.0.tar.gz
  • Upload date:
  • Size: 39.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for fastapi_redis_sdk-0.8.0.tar.gz
Algorithm Hash digest
SHA256 a414e25ca1f41c277b06de6a640ddb1e8389e7d654280342746ce4d087dc04ed
MD5 30366dd81c46bab2c35f39c6c7bac863
BLAKE2b-256 b8481a8824d80385c1cf3f35dac11ede8d54470777267ebf04ba43bb7b906a50

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_redis_sdk-0.8.0.tar.gz:

Publisher: release.yml on redis/fastapi-redis-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastapi_redis_sdk-0.8.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_redis_sdk-0.8.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1f8d56e0279cc4941bfd6b4440d5e1bdf836ba35c10524f647aac823141ac8bd
MD5 13b70b132aa5c936a04752df386a1582
BLAKE2b-256 a26b433d99fe935ab3bab540a18fec67b110b04013c4a8216c4ec323989967ef

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_redis_sdk-0.8.0-py3-none-any.whl:

Publisher: release.yml on redis/fastapi-redis-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

0.8.0 This release

2 files

0.7.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page