Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

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 PyPI Downloads Guide

Discord Twitch YouTube Twitter Stack Exchange questions

Features

  • Fluent setup — FastAPIRedis(app).lifespan().caching() configures pools and caching in one chain, attaching to the FastAPI lifespan events
  • Dependency injection — cache(), cache_evict(), cache_put() as Depends() factories, plus CacheBackend for complex invalidation and conditional logic
  • HTTP-native caching — ETag, 304 Not Modified, Cache-Control directives out of the box
  • Rate limiting — rate_limit() dependency with a fluent rate language ("10/second"), X-RateLimit-* / Retry-After headers, and distributed per-client counters
  • Resumable streams — Server-Sent Events backed by Redis Streams: a client that reconnects resumes from its last event, and the run survives the disconnect
  • 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.2+
Pydantic 2.0+
Redis server 7.4+ (8.6.2+ for resumable streams)

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/BYPASS), Cache-Control and ETag headers, with 304 Not Modified for both If-None-Match and If-Modified-Since, and replay the response's own header fields on a hit.

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.

Sessions

Keep session data in Redis. The cookie holds only an opaque session ID:

from fastapi import Depends, FastAPI
from redis_fastapi import FastAPIRedis, SessionDep, valid_session

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

@app.post("/login")
async def login(session: SessionDep):
    session["user_id"] = 42  # rotates the session ID after the endpoint completes
    return {"ok": True}

@app.get("/me", dependencies=[Depends(valid_session())])
async def me(session: SessionDep):
    return {"user_id": session.get("user_id")}

Redis enforces an idle timeout and an absolute timeout. valid_session() returns 401 when a request has no live session, and request.session works as it does with Starlette's SessionMiddleware.

See the Sessions Guide for timeouts, sign-out everywhere, CSRF, encryption and migration.

Resumable streams

Stream an agent's output through Redis, so a client that loses its connection resumes from the last event it saw. The run is decoupled from the request: a disconnect never stops it.

from fastapi import FastAPI, Request
from redis_fastapi import FastAPIRedis, StreamBackendDep, StreamWriter

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

async def run_agent(writer: StreamWriter):
    async for chunk in model.stream(prompt):
        await writer.append("delta", {"text": chunk})

@app.post("/chats/{chat_id}/runs", status_code=202)
async def start(chat_id: str, run_id: str, streams: StreamBackendDep):
    # A retried POST with the same run_id finds the run and starts nothing.
    writer = await streams.start(run_agent, scope=f"chat:{chat_id}", stream_id=run_id)
    return {"stream_id": writer.stream_id}

@app.get("/chats/{chat_id}/runs/{stream_id}/events")
async def events(chat_id: str, stream_id: str, request: Request, streams: StreamBackendDep):
    return await streams.sse(stream_id, request=request, scope=f"chat:{chat_id}")

A browser EventSource on the events route reconnects with Last-Event-ID and gets exactly the events after it. A second tab or device follows the same run, cancel() stops it, and a producer that dies is detected and its stream ended. Resumable streams need Redis 8.6.2 or later; on an older server the feature turns itself off and the rest of the application runs.

See the Resumable Streams Guide for access control, cursors, error handling, the browser side and the settings.

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.

Metadata

Release files for fastapi-redis-sdk 0.10.0b1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-redis-sdk 0.10.0b1
File Size Uploaded Provenance Actions
fastapi_redis_sdk-0.10.0b1.tar.gz 119.2 kB With provenance Details for fastapi_redis_sdk-0.10.0b1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-redis-sdk 0.10.0b1
File Interpreter ABI Platform Actions
fastapi_redis_sdk-0.10.0b1-py3-none-any.whl Python 3 none any Details for fastapi_redis_sdk-0.10.0b1-py3-none-any.whl

Total release size: 246.8 kB

Release files / fastapi_redis_sdk-0.10.0b1.tar.gz

Download URL fastapi_redis_sdk-0.10.0b1.tar.gz
Size 119.2 kB
Tags Source
SHA-256 checksum
How to use checksums
4066f4da561e73495c5894908c90c82e68f264bd10f0432f787702b185d7d4c5
BLAKE2b-256 checksum
How to use checksums
fe5c5abb350f6c5ee205313210b755f0e8989e692916868313099578b69a2a08
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

Release files / fastapi_redis_sdk-0.10.0b1-py3-none-any.whl

Download URL fastapi_redis_sdk-0.10.0b1-py3-none-any.whl
Size 127.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
adbf20c158bee5a10af3f9c3bc94da07fdd166ed03687b3f4897f7439fa316cb
BLAKE2b-256 checksum
How to use checksums
bdfae024ed391cbc004bbf905a8ee420cf1e7a894c800a40e0bcb511bfe41fbd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

Security for fastapi-redis-sdk 0.10.0b1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fastapi_redis_sdk-0.10.0b1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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