django-redis

A full-featured Redis cache and session backend for Django, with pluggable clients, sharding, Sentinel, and compression built in.

Library
PyPI
v7.0.0
3,082stars
BSD 3-Clause License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
76/100Good
Development Activity76
Maintenance52
Community76
Maturity60
Momentum40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
84/100Excellent
Architecture85
Code Quality88
Innovation72
Learning Curve90

django-redis is the go-to Redis cache backend for Django applications, plugging directly into Django’s CACHES setting via django_redis.cache.RedisCache. It wraps redis-py’s native URL connection notation, so redis://, rediss://, and unix:// connection strings all work out of the box, and it exposes the full Django cache API (get/set/delete/incr/decr/many-key operations) plus Redis-specific extras that plain Django caching doesn’t offer, like TTL/PTTL introspection, key expiry management, glob-pattern key scanning and bulk deletion, and distributed locks via cache.lock().

Beyond the default client, the library ships pluggable client implementations for sharding across multiple Redis instances, connecting through Redis Sentinel for primary/secondary failover, and a legacy “herd” client for thundering-herd protection. Serialization is pluggable too (pickle by default, with JSON and MessagePack built in), and values can be transparently compressed with zlib, gzip, LZ4, LZMA, or Zstandard. A maintained project of the Jazzband collective, it has been the de facto standard Redis backend for Django for over a decade, used in production for both caching and session storage across a large number of Django deployments.

What You Get

  • Drop-in Django cache backend - implements the full django.core.cache.backends.base.BaseCache contract, so it’s a one-line BACKEND swap in CACHES with no code changes elsewhere in the app.
  • Native redis-py URL connection strings - supports redis://, rediss:// (TLS), and unix:// schemes, including username/password and ACL-based auth, instead of a bespoke connection config format.
  • Pluggable client architecture - ships DefaultClient, a sharded client for horizontal partitioning across multiple Redis nodes, a Sentinel client for primary/secondary failover, and a herd client for stampede protection, selectable via OPTIONS.CLIENT_CLASS.
  • Pluggable serializers and compressors - values are serialized with pickle (default), JSON, or MessagePack, and optionally compressed with zlib, gzip, LZ4, LZMA, or Zstandard, all configured per-cache via OPTIONS.
  • Redis-native cache extensions - ttl()/pttl(), persist(), expire()/expire_at()/pexpire()/pexpire_at(), glob-based keys()/iter_keys()/delete_pattern(), lock() for distributed locking, and direct access to Redis set/hash/sorted-set commands (sadd, hset, zadd, etc.) beyond what the Django cache interface exposes.
  • Session backend support - works as a Django session store with no extra dependency by reusing Django’s cache-backed session engine.
  • IGNORE_EXCEPTIONS / memcached-parity error handling - can be configured to swallow Redis connection errors the same way Django’s memcached backend does, with optional logging of ignored exceptions.
  • Raw client escape hatch - get_redis_connection(alias) returns the underlying redis-py client for advanced operations the Django cache API doesn’t cover, reusing the same connection pool.

Common Use Cases

  • Page and fragment caching for Django apps - use Redis as the backing store for Django’s per-view or template-fragment cache decorators with automatic connection pooling.
  • Session storage at scale - back Django’s session framework with Redis instead of the database, cutting session read/write latency for high-traffic sites.
  • Distributed locking around critical sections - use cache.lock() to serialize access to a resource across multiple app server processes/instances.
  • Bulk cache invalidation by key pattern - use delete_pattern() with a glob to invalidate a whole family of cache keys (e.g. all keys for a given user or tenant) in one call.
  • High-availability Redis deployments - use the Sentinel client to keep caching functional through Redis primary failover without app-level reconnection logic.
  • Sharding across multiple Redis instances - use the sharded client to spread cache keys across several Redis servers for capacity beyond a single instance.

Under The Hood

Architecture django-redis layers cleanly on top of Django’s cache framework and redis-py. django_redis/cache.py defines RedisCache(BaseCache), a thin dispatcher that lazily instantiates a pluggable client class (selected via OPTIONS.CLIENT_CLASS, defaulting to django_redis.client.DefaultClient) and forwards every Django cache method to it through an omit_exception decorator that centralizes the IGNORE_EXCEPTIONS error-swallowing behavior in one place. The client layer (django_redis/client/default.py, plus sharded.py, sentinel.py, and herd.py) implements the actual Redis interaction, composing a SortedSetMixin for sorted-set operations and delegating connection creation to a separate ConnectionFactory abstraction (django_redis/pool.py) that manages a process-global pool cache keyed by connection URL — connections are never torn down between requests, matching redis-py’s default pooling behavior. Serialization (django_redis/serializers/) and compression (django_redis/compressors/) are both resolved via import_string from OPTIONS, so swapping pickle for JSON/MessagePack or adding LZ4/Zstandard compression is a config change, not a code change. This separation — cache API, client behavior, connection management, and payload encoding as four independently swappable layers — is what lets the same backend serve simple single-node caching, Sentinel-backed HA, and multi-node sharding without branching application code.

Tech Stack The project targets Python 3.10+ and Django 5.2+ (with 6.0 support already in its classifiers), and its only hard runtime dependency is redis>=4.0.2 (redis-py), with typing_extensions pulled in for older Python versions to support modern typing constructs. Optional extras add hiredis for a faster C-based protocol parser, lz4, msgpack, and pyzstd for their respective serializer/compressor backends. The build uses a standard setuptools + pyproject.toml setup with dynamic versioning from django_redis.__version__, and releases are automated through GitHub Actions (.github/workflows/release.yml) alongside a separate CI workflow that runs the test matrix across Python and Django version combinations via tox.

Code Quality The test suite (tests/) is comprehensive relative to the library’s surface area, with dedicated files for the default client, sharding, sorted-set operations, cache option handling, connection factories/params, the consistent-hash ring, serializers, and session backend behavior, plus a dozen Django settings variants (tests/settings/sqlite_*.py) to exercise gzip/LZ4/zstd compression, msgpack/JSON serialization, sentinel configuration, sharding, and Unix-socket connections against real settings permutations. Configuration in pyproject.toml runs pytest --doctest-modules with coverage tracking and pytest-xdist for parallel execution, and a mypy tox environment runs strict type checking (strict = true) against the django_redis package using django-stubs for Django-aware typing. Code style is enforced via ruff with a broad rule set (bugbear, bandit, comprehensions, import sorting, pyupgrade, and more) wired into pre-commit, and CI runs both the test matrix and the pre-commit/mypy checks on every push. Error handling is explicit and centralized — Redis connection failures are caught once in the omit_exception decorator rather than scattered per-method, and custom exceptions (ConnectionInterrupted, CompressorError) wrap underlying redis-py errors with clearer semantics.

What Makes It Unique What distinguishes django-redis from simply pointing Django’s generic cache framework at a Redis client library is the depth of Redis-specific functionality it surfaces through a Django-native API: TTL/PTTL introspection, millisecond-precision expiry control, glob-based bulk key scanning and deletion tuned via DJANGO_REDIS_SCAN_ITERSIZE for large keyspaces, and direct exposure of Redis set/hash/sorted-set primitives as first-class cache methods — none of which the stock Django cache interface provides. Combined with pluggable sharding and Sentinel clients that swap in without touching call sites, and a compressor/serializer system that lets teams trade CPU for network/memory savings per cache, it functions less like a generic cache adapter and more like a fairly complete Redis client wrapped in Django’s familiar cache API, which explains its long-running status (maintained since 2011, now under Jazzband) as the default choice for Redis + Django.

Used by 6 apps in this directory

Python
68%
Other

Baserow

No Code Platforms · Databases

5,747

Open-source no-code platform to build databases, apps, automations, and AI agents — self-hosted or cloud, with full data ownership.

View details
88
Repo Health
84
Technical
69
Dependency
Built with
Python68%
JavaScript16%
Vue12%
Updated 2 days ago
Python
50%
MIT

Docs

File Storage · CMS

16,755

Open-source collaborative knowledge platform with real-time editing, AI writing tools, and full self-hosting control — built by the French and German governments.

View details
87
Repo Health
81
Technical
72
Dependency
Built with
Python50%
TypeScript41%
Updated 2 days ago
Python
64%
BSD 3

Flagsmith

Developer Tools · Devops · Ab Testing Experimentation

6,533

Open-source feature flagging, remote config, and A/B/multivariate testing platform for web, mobile, and server-side apps — self-host or use the hosted SaaS.

View details
91
Repo Health
82
Technical
64
Dependency
Built with
Python64%
TypeScript31%
Updated yesterday
Python
45%
GPL 3.0

MaxKB

AI Development · Knowledge Management

22,646

Build enterprise-grade AI agents with RAG, workflows & multi-modal support

View details
91
Repo Health
68
Technical
66
Dependency
Built with
Python45%
Vue37%
TypeScript17%
Updated yesterday
Python
54%
Other

PostHog

Analytics · Monitoring · Developer Tools

39,479

The all-in-one open source product platform combining analytics, session replay, feature flags, error tracking, AI observability, and a built-in data warehouse in a single self-hostable stack.

View details
92
Repo Health
80
Technical
66
Dependency
Built with
Python54%
TypeScript36%
Updated today
Python
91%
GPL 3.0

Weblate

Developer Tools

6,043

Continuous localization platform that commits translations directly into your version control system with full translator attribution.

View details
95
Repo Health
86
Technical
73
Dependency
Built with
Python91%
Updated today

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search