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

Steps

  1. 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.

    bash
    redis-server --version
    redis-server --port 6379 --daemonize yes --dir "$PWD" --save "" --logfile redis.log
    sleep 1
    redis-cli ping
    Expected output
    Redis server v=7.0.15 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=d064f9f48c901a92
    PONG
  2. Store 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.

    bash
    redis-cli SET greeting "hello radar"
    redis-cli GET greeting
    redis-cli INCR page:views
    redis-cli INCRBY page:views 10
    Expected output
    OK
    hello radar
    1
    11
  3. Model 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.

    bash
    redis-cli HSET product:1 name "Mechanical keyboard" category peripherals price 89
    redis-cli HGET product:1 price
    redis-cli HGETALL product:1
    Expected output
    3
    89
    name
    Mechanical keyboard
    category
    peripherals
    price
    89
  4. Connect 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'}
  5. 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.

    python
    for 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 output
    product:2 Wireless mouse 29.5
    product:4 USB-C hub 39.9
  6. Expire 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.

    python
    import 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 output
    ttl: 2
    value: user:42
    after expiry: None exists: 0
  7. Append 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.

    python
    for 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 output
    length: 3
    {'type': 'view', 'product': '1'}
    {'type': 'cart', 'product': '1'}
    {'type': 'buy', 'product': '1'}
  8. 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.

    python
    r.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 output
    worker-1 received 2 entries
    pending before ack: 2
    pending after ack: 0

Next steps

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

All tutorials

Sources

Last verified:

  1. redis.io/docs/latest redis.io
  2. redis.io/docs/latest/develop/data-types/hashes redis.io
  3. redis.io/docs/latest/develop/data-types/sorted-sets redis.io
  4. redis.io/docs/latest/commands/expire redis.io
  5. redis.io/docs/latest/develop/data-types/streams redis.io
  6. redis-py.readthedocs.io/en/stable redis-py.readthedocs.io
  7. valkey.io/topics valkey.io

Found an error? See how to report a correction.