Redis Client Libraries
redis-cli is great for exploring, but applications talk to Redis through a client library in their own language. Every library does the same job: open a TCP connection (usually pooled), encode commands in the RESP protocol, and decode the replies into native values such as strings, integers, lists and dictionaries.
The RESP protocol
RESP (REdis Serialization Protocol) is a simple text-based format. A command is sent as an array of bulk strings: * and the number of elements, then for each element $, its length in bytes, and the bytes, every part ending with \r\n. Replies start with a type character:
| First byte | Type | Example |
|---|---|---|
+ |
simple string | +OK\r\n |
- |
error | -ERR unknown command\r\n |
: |
integer | :42\r\n |
$ |
bulk string ($-1 = nil) |
$5\r\nhello\r\n |
* |
array | *2\r\n$1\r\na\r\n$1\r\nb\r\n |
RESP3 (available since Redis 6 with HELLO 3) adds maps, sets, doubles and booleans, so clients no longer have to guess that HGETALL returns a dictionary.
This small program encodes a command and decodes a few replies, exactly as a client library does:
def encode(*args):
out = [f"*{len(args)}\r\n"]
for a in args:
data = str(a).encode()
out.append(f"${len(data)}\r\n{data.decode()}\r\n")
return "".join(out).encode()
def decode(buf, pos=0):
kind, end = buf[pos:pos + 1], buf.index(b"\r\n", pos)
head, nxt = buf[pos + 1:end].decode(), end + 2
if kind == b"+": return head, nxt
if kind == b"-": return Exception(head), nxt
if kind == b":": return int(head), nxt
if kind == b"quot;:
n = int(head)
if n < 0: return None, nxt
return buf[nxt:nxt + n].decode(), nxt + n + 2
if kind == b"*":
items = []
for _ in range(int(head)):
item, nxt = decode(buf, nxt)
items.append(item)
return items, nxt
print(encode("SET", "user:1", "Ada"))
for reply in [b"+OK\r\n", b":42\r\n", b"$5\r\nhello\r\n", b"$-1\r\n",
b"*3\r\n$4\r\nrust\r\n:7\r\n$-1\r\n", b"-WRONGTYPE wrong kind\r\n"]:
value, _ = decode(reply)
print(repr(reply)[2:-1].ljust(38), "->", repr(value))b'*3\r\n$3\r\nSET\r\n$6\r\nuser:1\r\n$3\r\nAda\r\n'
+OK\r\n -> 'OK'
:42\r\n -> 42
$5\r\nhello\r\n -> 'hello'
$-1\r\n -> None
*3\r\n$4\r\nrust\r\n:7\r\n$-1\r\n -> ['rust', 7, None]
-WRONGTYPE wrong kind\r\n -> Exception('WRONGTYPE wrong kind')
Python: redis-py
import redis
# decode_responses=True returns str instead of bytes
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
r.set("user:1:name", "Ada", ex=3600)
print(r.get("user:1:name")) # Ada
r.hset("user:1", mapping={"name": "Ada", "lang": "python"})
print(r.hgetall("user:1")) # {'name': 'Ada', 'lang': 'python'}
r.zadd("scores", {"ada": 120, "linus": 95})
print(r.zrange("scores", 0, -1, desc=True, withscores=True))
# [('ada', 120.0), ('linus', 95.0)]For asyncio code use redis.asyncio.Redis with the same methods and await.
Node.js: node-redis and ioredis
import { createClient } from 'redis'; // node-redis, the official client
const client = createClient({ url: 'redis://localhost:6379' });
client.on('error', (err) => console.error('Redis error', err));
await client.connect();
await client.set('user:1:name', 'Ada', { EX: 3600 });
console.log(await client.get('user:1:name')); // Ada
await client.hSet('user:1', { name: 'Ada', lang: 'js' });
console.log(await client.hGetAll('user:1')); // { name: 'Ada', lang: 'js' }
await client.quit();import Redis from 'ioredis'; // ioredis, popular with Cluster and Sentinel
const redis = new Redis(); // localhost:6379
await redis.set('counter', 0);
await redis.incrby('counter', 5);
console.log(await redis.get('counter')); // '5'Java, Go and C#
// Jedis (Java); Lettuce is the reactive alternative used by Spring Data Redis
try (JedisPooled jedis = new JedisPooled("localhost", 6379)) {
jedis.set("greeting", "hello");
System.out.println(jedis.get("greeting"));
}// go-redis
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
err := rdb.Set(ctx, "greeting", "hello", time.Hour).Err()
val, err := rdb.Get(ctx, "greeting").Result()// StackExchange.Redis (.NET)
var mux = ConnectionMultiplexer.Connect("localhost");
IDatabase db = mux.GetDatabase();
db.StringSet("greeting", "hello");
Console.WriteLine(db.StringGet("greeting"));Connection strings
Most clients accept a URL:
redis://localhost:6379/0 plain TCP, database 0
redis://app:s3cret@cache.internal:6379/2 ACL user "app" with a password, database 2
rediss://cache.example.com:6380 TLS (note the double s)Good practices
| Practice | Why |
|---|---|
| Create one client (or pool) per process and reuse it | opening a connection costs a TCP (and maybe TLS) handshake |
| Set timeouts | a stuck Redis call should not hang a web request forever |
Use pipelines and MGET/MSET for batches |
fewer round trips |
| Keep a separate connection for pub/sub and blocking commands | those connections cannot run other commands meanwhile |
| Handle reconnects | servers restart, fail over, or drop idle connections |
Never use KEYS in application code |
use SCAN iterators (scan_iter, scanIterator) |
Test yourself
How is the command GET a sent in RESP?
GET a\n*2\r\n$3\r\nGET\r\n$1\r\na\r\n{"cmd":"GET","key":"a"}+GET a\r\n
Which RESP reply type starts with a colon :?
- Error
- Integer
- Array
- Bulk string
What is the recommended way to manage connections in a web application?
- Open a new connection for every command
- Create one client or pool per process and reuse it
- Use a single connection shared by all servers
- Use redis-cli from the application