What is Redis?
Redis is an open-source, in-memory data structure store used as a database, cache, message broker, and streaming engine. It supports strings, hashes, lists, sets, and sorted sets with sub-millisecond latency.
// Table of Contents
Definition
Redis (Remote Dictionary Server) is an in-memory data structure store that can be used as a database, cache, message broker, and queue. Created by Salvatore Sanfilippo in 2009, it's one of the most popular key-value stores in the world.
Redis stores data primarily in memory, which makes it extraordinarily fast - typically handling hundreds of thousands of operations per second. It supports persistence to disk for durability and offers replication for high availability.
Common Use Cases
- Caching: Cache database queries, API responses, and session data with automatic expiration.
- Session storage: Store user sessions with fast read/write access and TTL support.
- Rate limiting: Implement API rate limiting using Redis counters and expiration.
- Real-time leaderboards: Sorted sets enable real-time ranking systems.
- Pub/Sub messaging: Lightweight publish/subscribe messaging for real-time notifications.
- Job queues: Background job processing with tools like Celery, RQ, or Bull.
- Distributed locks: Implement distributed locking for concurrent systems.
Redis with Python
Redis integrates seamlessly with Python backends:
- redis-py: Official Python client with sync and async support.
- Celery: Uses Redis as a message broker for distributed task queues.
- FastAPI caching: Cache endpoint responses using Redis for dramatic performance improvements.
- Django cache backend: Native Redis cache backend in Django 4.0+.
Code Example
import redis.asyncio as redis
from fastapi import FastAPI
import json
app = FastAPI()
cache = redis.Redis(host='localhost', port=6379, decode_responses=True)
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# Check cache first
cached = await cache.get(f"user:{user_id}")
if cached:
return json.loads(cached)
# Fetch from database
user = await fetch_user_from_db(user_id)
# Cache for 5 minutes
await cache.setex(f"user:{user_id}", 300, json.dumps(user))
return user
Frequently Asked Questions
Is Redis a database or a cache?
Redis can be both. It started as an in-memory cache but has evolved into a full database with persistence (RDB snapshots and AOF logs), replication, clustering, and Lua scripting. Many use it as both: primary data store for real-time data and cache for slower backend databases.
What happens to Redis data if the server crashes?
Redis offers two persistence mechanisms: RDB (point-in-time snapshots) and AOF (append-only file that logs every write). With AOF set to 'always', you lose at most one command. Most production setups use both RDB and AOF together.
Need expert backend development?
I build scalable Python APIs and backend systems. Let's discuss your project.
Get in Touch