Getting started with Redis
Redis is an in-memory data structure server that is widely used for caching, sessions, queues and real-time counters. Every command in this guide was run against a live server, and the outputs are copied from that run.
Database profile: Redis (license, deployment options, alternatives and benchmarks).
Prerequisites
- Linux or macOS with Redis installed (on Ubuntu 24.04: sudo apt install redis-server)
- redis-cli on your PATH (it ships with the server package)
- Python 3.9+ with pip install redis for steps 4 to 8
Steps
Start a Redis server and check it responds
On Ubuntu the redis-server package installs and starts a service automatically. Here the server is started by hand in the background so you can see the moving parts; PING should answer PONG.
bashredis-server --version redis-server --port 6379 --daemonize yes --dir "$PWD" --save "" --logfile redis.log sleep 1 redis-cli pingExpected outputRedis server v=7.0.15 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=d064f9f48c901a92 PONGStore and read simple values
Redis is a key-value store held in memory. Strings are the basic type, and counters can be incremented atomically, which makes them safe to update from many clients at once.
bashredis-cli SET greeting "hello radar" redis-cli GET greeting redis-cli INCR page:views redis-cli INCRBY page:views 10Expected outputOK hello radar 1 11Model records with hashes
Redis has no tables. A common pattern is one hash per record, with a key prefix such as product: playing the role of a table name.
bashredis-cli HSET product:1 name "Mechanical keyboard" category peripherals price 89 redis-cli HGET product:1 price redis-cli HGETALL product:1Expected output3 89 name Mechanical keyboard category peripherals price 89Connect from Python and insert in a pipeline
The redis-py client talks to the same server. A pipeline sends many commands in one round trip, which matters when loading data; decode_responses=True returns str instead of bytes.
python# pip install redis import redis r = redis.Redis(host="localhost", port=6379, decode_responses=True) products = { 2: {"name": "Wireless mouse", "category": "peripherals", "price": 29.5}, 3: {"name": "27-inch monitor", "category": "displays", "price": 249}, 4: {"name": "USB-C hub", "category": "accessories", "price": 39.9}, } pipe = r.pipeline() for pid, fields in products.items(): pipe.hset(f"product:{pid}", mapping=fields) print(pipe.execute()) print(r.hgetall("product:3"))Expected output[3, 3, 3] {'name': '27-inch monitor', 'category': 'displays', 'price': '249'}Build a secondary index with a sorted set
Redis only looks keys up by name, so range queries need an index you maintain yourself. A sorted set keyed by price lets you fetch products in a price range, cheapest first.
pythonfor pid in range(1, 5): r.zadd("idx:product:price", {f"product:{pid}": float(r.hget(f"product:{pid}", "price"))}) for key, price in r.zrangebyscore("idx:product:price", 0, 50, withscores=True): print(key, r.hget(key, "name"), price)Expected outputproduct:2 Wireless mouse 29.5 product:4 USB-C hub 39.9Expire keys automatically with TTL
Any key can be given a time to live, after which Redis deletes it. This is the usual way to implement caches, sessions and rate-limit windows.
pythonimport time r.set("session:abc123", "user:42", ex=2) # expires in 2 seconds print("ttl:", r.ttl("session:abc123")) print("value:", r.get("session:abc123")) time.sleep(2.5) print("after expiry:", r.get("session:abc123"), "exists:", r.exists("session:abc123"))Expected outputttl: 2 value: user:42 after expiry: None exists: 0Append events to a stream
A stream is an append-only log in which every entry gets an ID based on time. XADD appends entries, and XRANGE reads them back in order.
pythonfor event in [{"type": "view", "product": "1"}, {"type": "cart", "product": "1"}, {"type": "buy", "product": "1"}]: r.xadd("events:shop", event) print("length:", r.xlen("events:shop")) for entry_id, fields in r.xrange("events:shop"): print(fields)Expected outputlength: 3 {'type': 'view', 'product': '1'} {'type': 'cart', 'product': '1'} {'type': 'buy', 'product': '1'}Process a stream with a consumer group
Consumer groups split a stream between workers and track which entries each one has handled. Entries stay pending until a worker acknowledges them with XACK.
pythonr.xgroup_create("events:shop", "billing", id="0") batch = r.xreadgroup("billing", "worker-1", {"events:shop": ">"}, count=2) ids = [entry_id for _, entries in batch for entry_id, _ in entries] print("worker-1 received", len(ids), "entries") print("pending before ack:", r.xpending("events:shop", "billing")["pending"]) r.xack("events:shop", "billing", *ids) print("pending after ack:", r.xpending("events:shop", "billing")["pending"])Expected outputworker-1 received 2 entries pending before ack: 2 pending after ack: 0
Next steps
- Turn on persistence (RDB snapshots or AOF) before storing data you cannot rebuild
- Set maxmemory and an eviction policy when using Redis as a cache
- Look at Pub/Sub and Lua scripting or functions for more advanced patterns
- Compare Redis with Valkey, its open-source fork, on DatabaseRadar
FAQ
- Will this tutorial work with Valkey?
- Valkey was forked from Redis 7.2.4 and keeps the same protocol and commands, so the redis-cli commands and redis-py code here are expected to work against it unchanged. We ran these steps on Redis 7.0 only, so re-test on your exact Valkey version.
- Is data in Redis lost when the server restarts?
- Only if persistence is off. Redis can write periodic snapshots (RDB), an append-only log of writes (AOF), or both. In this tutorial snapshots were disabled with --save "" to keep the sandbox clean.
- How do I query Redis by a field value, like SQL WHERE?
- Core Redis only looks up keys by name, so you maintain your own indexes, for example sorted sets for numeric ranges and sets for tags. Search modules such as the Redis Query Engine add secondary indexing on hashes and JSON documents.
More tested tutorials
- Getting started with ClickHouse SQL using chDB
- Getting started with DuckDB in Python
- Getting started with LanceDB in Python
- Getting started with PostgreSQL
- Getting started with SQLite in Python
Sources
Last verified:
- redis.io/docs/latest redis.io
- redis.io/docs/latest/develop/data-types/hashes redis.io
- redis.io/docs/latest/develop/data-types/sorted-sets redis.io
- redis.io/docs/latest/commands/expire redis.io
- redis.io/docs/latest/develop/data-types/streams redis.io
- redis-py.readthedocs.io/en/stable redis-py.readthedocs.io
- valkey.io/topics valkey.io
Found an error? See how to report a correction.