Redis
suggest changeRedis is an in-memory key/value store. Values aren't just strings: Redis also has hashes, lists, sets, sorted sets and streams, each with its own commands. It's mostly used as a cache, a session store, a rate limiter, a job queue and a pub/sub message bus.
The most used Go client is go-redis, maintained by the Redis team. Add it to your module:
go get github.com/redis/go-redis/v9
The import path is github.com/redis/go-redis/v9. Older code uses github.com/go-redis/redis/v8. The v8 API is almost the same, but new code should use v9.
To follow along, run a local server with Docker:
docker run -d --name redis -p 6379:6379 redis:7
Connecting
package main
import (
"context"
"fmt"
"log"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password
DB: 0, // default database
})
defer rdb.Close()
// NewClient doesn't connect; Ping does.
pong, err := rdb.Ping(ctx).Result()
if err != nil {
log.Fatal(err)
}
fmt.Println(pong)
}
PONG
Things to know about the client:
*redis.Clientholds a pool of connections and is safe for concurrent use by many goroutines. Create one at startup and share it. Don't create a client per request.- Every command takes a context as its first argument.
- Commands return a typed command object like
*redis.StringCmdor*redis.IntCmd.Result()returns the value and the error.Val()returns just the value andErr()just the error.
You can also configure the client with a URL. redis.ParseURL turns one into *redis.Options:
opt, err := redis.ParseURL("redis://user:password@localhost:6379/0")
if err != nil {
log.Fatal(err)
}
rdb := redis.NewClient(opt)
Use the rediss:// scheme for TLS.
Strings, counters and expiration
The basic type is a string. Redis stores numbers as strings too, but it can increment them atomically.
package main
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
// SET name "gopher" (0 means no expiration)
if err := rdb.Set(ctx, "name", "gopher", 0).Err(); err != nil {
log.Fatal(err)
}
name, err := rdb.Get(ctx, "name").Result()
if err != nil {
log.Fatal(err)
}
fmt.Println("name:", name)
// A missing key is reported as the redis.Nil error.
_, err = rdb.Get(ctx, "no-such-key").Result()
if errors.Is(err, redis.Nil) {
fmt.Println("no-such-key does not exist")
} else if err != nil {
log.Fatal(err)
}
// Values are strings on the server; numbers are converted for you.
rdb.Set(ctx, "visits", 41, 0)
n, err := rdb.Incr(ctx, "visits").Result()
if err != nil {
log.Fatal(err)
}
fmt.Println("visits:", n)
v, err := rdb.Get(ctx, "visits").Int()
if err != nil {
log.Fatal(err)
}
fmt.Printf("visits as int: %d (%T)\n", v, v)
// Keys with a time to live.
rdb.Set(ctx, "session:abc", "user42", 30*time.Minute)
ttl, _ := rdb.TTL(ctx, "session:abc").Result()
fmt.Println("ttl:", ttl)
// SETNX: set only if the key doesn't exist yet.
ok, _ := rdb.SetNX(ctx, "name", "other", 0).Result()
fmt.Println("SetNX on existing key:", ok)
// Multiple keys at once.
rdb.MSet(ctx, "a", "1", "b", "2")
vals, _ := rdb.MGet(ctx, "a", "b", "missing").Result()
fmt.Printf("%q\n", vals)
deleted, _ := rdb.Del(ctx, "name", "visits", "a", "b", "session:abc").Result()
fmt.Println("deleted:", deleted)
}
name: gopher
no-such-key does not exist
visits: 42
visits as int: 42 (int)
ttl: 30m0s
SetNX on existing key: false
["1" "2" <nil>]
deleted: 5
The most common mistake is treating redis.Nil like a real failure. It just means "key not found". Always check for it with errors.Is(err, redis.Nil) before treating an error as a problem.
StringCmd has helper methods that parse the reply: Int(), Int64(), Float64(), Bool(), Bytes(), Time(). You can pass any Go value to Set. Strings, []byte, numbers, bool and time.Time are encoded for you. For other types, encode them yourself, for example to JSON (see the caching example below).
Use Expire(ctx, key, d) to set a TTL on an existing key and Persist to remove it. TTL returns -1 (as a duration of -1ns) if the key has no expiration and -2 if the key doesn't exist.
Hashes
A hash is a map of fields to values stored under one key. It's a good fit for objects. go-redis can map hashes to structs using redis struct tags.
package main
import (
"context"
"fmt"
"log"
"github.com/redis/go-redis/v9"
)
type User struct {
Name string `redis:"name"`
Email string `redis:"email"`
Age int `redis:"age"`
Admin bool `redis:"admin"`
}
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
// HSET accepts field/value pairs, a map, or a struct with redis tags.
err := rdb.HSet(ctx, "user:1", "name", "Alice", "email", "alice@example.com").Err()
if err != nil {
log.Fatal(err)
}
rdb.HSet(ctx, "user:1", map[string]any{"age": 30, "admin": true})
email, _ := rdb.HGet(ctx, "user:1", "email").Result()
fmt.Println("email:", email)
all, _ := rdb.HGetAll(ctx, "user:1").Result()
fmt.Println("fields:", len(all), "age:", all["age"], "admin:", all["admin"])
// Scan the hash into a struct.
var u User
if err := rdb.HGetAll(ctx, "user:1").Scan(&u); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", u)
// Write a struct.
bob := User{Name: "Bob", Email: "bob@example.com", Age: 25}
if err := rdb.HSet(ctx, "user:2", bob).Err(); err != nil {
log.Fatal(err)
}
age, _ := rdb.HIncrBy(ctx, "user:2", "age", 1).Result()
fmt.Println("bob's age:", age)
// Read only some fields.
var partial struct {
Name string `redis:"name"`
Age int `redis:"age"`
}
if err := rdb.HMGet(ctx, "user:2", "name", "age").Scan(&partial); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", partial)
rdb.Del(ctx, "user:1", "user:2")
}
email: alice@example.com
fields: 4 age: 30 admin: 1
{Name:Alice Email:alice@example.com Age:30 Admin:true}
bob's age: 26
{Name:Bob Age:26}
All hash values are strings on the server, so true is stored as "1". Scan converts them back to the field types. Scan supports strings, []byte, numbers, bool, and types that implement encoding.BinaryUnmarshaler. Fields without a redis tag are ignored. A missing hash isn't an error for HGetAll: you get an empty map and a zero-value struct.
Lists, sets and sorted sets
package main
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
rdb.Del(ctx, "jobs", "tags", "scores")
// Lists: push on the left, pop on the right = FIFO queue.
rdb.LPush(ctx, "jobs", "job1", "job2", "job3")
n, _ := rdb.LLen(ctx, "jobs").Result()
fmt.Println("queue length:", n)
items, _ := rdb.LRange(ctx, "jobs", 0, -1).Result()
fmt.Println("all:", items)
job, _ := rdb.RPop(ctx, "jobs").Result()
fmt.Println("popped:", job)
// BRPOP blocks until an element arrives or the timeout expires.
rdb.Del(ctx, "jobs")
go func() {
time.Sleep(100 * time.Millisecond)
rdb.LPush(ctx, "jobs", "urgent")
}()
res, _ := rdb.BRPop(ctx, 2*time.Second, "jobs").Result()
fmt.Println("BRPop:", res) // [key value]
// Sets: unordered, unique members.
rdb.SAdd(ctx, "tags", "go", "redis", "db", "go")
count, _ := rdb.SCard(ctx, "tags").Result()
isMember, _ := rdb.SIsMember(ctx, "tags", "redis").Result()
fmt.Println("tags:", count, "has redis:", isMember)
// Sorted sets: members ordered by score.
rdb.ZAdd(ctx, "scores",
redis.Z{Score: 120, Member: "alice"},
redis.Z{Score: 95, Member: "bob"},
redis.Z{Score: 150, Member: "carol"},
)
rdb.ZIncrBy(ctx, "scores", 40, "bob")
top, _ := rdb.ZRevRangeWithScores(ctx, "scores", 0, 1).Result()
for i, z := range top {
fmt.Printf("%d. %s %.0f\n", i+1, z.Member, z.Score)
}
rank, _ := rdb.ZRevRank(ctx, "scores", "alice").Result()
fmt.Println("alice rank (0-based):", rank)
between, _ := rdb.ZRangeByScore(ctx, "scores", &redis.ZRangeBy{
Min: "100", Max: "140",
}).Result()
fmt.Println("score 100..140:", between)
rdb.Del(ctx, "jobs", "tags", "scores")
}
queue length: 3
all: [job3 job2 job1]
popped: job1
BRPop: [jobs urgent]
tags: 3 has redis: true
1. carol 150
2. bob 135
alice rank (0-based): 2
score 100..140: [alice bob]
Notes:
BRPopreturnsredis.Nilwhen the timeout expires with no element. A timeout of0blocks forever.- Errors are ignored here to keep the example short. Real code should check them.
- Sorted sets are the standard way to build leaderboards, priority queues and sliding-window rate limiters. Score ranges are strings, so you can use
"-inf","+inf"and exclusive bounds like"(100".
Pipelines and transactions
Each command is one network round trip. When you send many commands, a pipeline sends them all together and reads all the replies at once.
package main
import (
"context"
"fmt"
"log"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
// Pipelined sends all commands in one round trip.
cmds, err := rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
for i := range 3 {
pipe.Set(ctx, fmt.Sprintf("key:%d", i), i*10, 0)
}
pipe.Incr(ctx, "counter")
pipe.Get(ctx, "key:2")
return nil
})
if err != nil {
log.Fatal(err)
}
fmt.Println("commands sent:", len(cmds))
// Results are in the returned commands.
fmt.Println("last:", cmds[len(cmds)-1].(*redis.StringCmd).Val())
// Or keep references to the commands you care about.
var incr *redis.IntCmd
var get *redis.StringCmd
_, err = rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
incr = pipe.Incr(ctx, "counter")
get = pipe.Get(ctx, "key:1")
return nil
})
if err != nil {
log.Fatal(err)
}
fmt.Println("counter:", incr.Val(), "key:1:", get.Val())
// TxPipelined wraps the commands in MULTI/EXEC: they run atomically.
_, err = rdb.TxPipelined(ctx, func(pipe redis.Pipeliner) error {
pipe.Decr(ctx, "counter")
pipe.Del(ctx, "key:0", "key:1", "key:2")
return nil
})
if err != nil {
log.Fatal(err)
}
fmt.Println("counter after tx:", rdb.Get(ctx, "counter").Val())
rdb.Del(ctx, "counter")
}
commands sent: 5
last: 20
counter: 2 key:1: 10
counter after tx: 1
Inside the callback, commands only get queued. Their values are filled in after the pipeline runs, so you can only read incr.Val() after Pipelined returns. If any command fails, Pipelined returns the first error. Each command still has its own error in cmd.Err(). Note that a GET of a missing key inside a pipeline also makes Pipelined return redis.Nil.
A pipeline is not atomic: other clients' commands can run between yours. TxPipelined wraps the commands in MULTI/EXEC, so they run as a block. But you can't read a value and then decide what to write inside a MULTI block.
Optimistic locking with WATCH
For read-modify-write, use Watch. It watches the keys, runs your function, and the EXEC fails with redis.TxFailedErr if another client changed a watched key in the meantime. You then retry.
package main
import (
"context"
"errors"
"fmt"
"log"
"sync"
"github.com/redis/go-redis/v9"
)
var ErrInsufficient = errors.New("insufficient funds")
// withdraw subtracts amount from the balance stored in key, but only if
// the balance is high enough. WATCH makes EXEC fail if another client
// modified the key in between.
func withdraw(ctx context.Context, rdb *redis.Client, key string, amount int) error {
txf := func(tx *redis.Tx) error {
balance, err := tx.Get(ctx, key).Int()
if err != nil && !errors.Is(err, redis.Nil) {
return err
}
if balance < amount {
return ErrInsufficient
}
_, err = tx.TxPipelined(ctx, func(pipe redis.Pipeliner) error {
pipe.Set(ctx, key, balance-amount, 0)
return nil
})
return err
}
for range 100 {
err := rdb.Watch(ctx, txf, key)
if errors.Is(err, redis.TxFailedErr) {
continue // key changed; retry
}
return err
}
return errors.New("too many retries")
}
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
rdb.Set(ctx, "balance", 100, 0)
// 15 goroutines try to withdraw 10 each from a balance of 100.
var wg sync.WaitGroup
var mu sync.Mutex
results := map[string]int{}
for range 15 {
wg.Go(func() {
err := withdraw(ctx, rdb, "balance", 10)
mu.Lock()
defer mu.Unlock()
if err != nil {
results[err.Error()]++
} else {
results["ok"]++
}
})
}
wg.Wait()
balance, err := rdb.Get(ctx, "balance").Int()
if err != nil {
log.Fatal(err)
}
fmt.Println("results:", results)
fmt.Println("balance:", balance)
rdb.Del(ctx, "balance")
}
results: map[insufficient funds:5 ok:10]
balance: 0
Exactly 10 withdrawals succeed and the balance never goes negative, even though the goroutines race. Without Watch, two goroutines could both read 100 and both write 90.
Lua scripts
A Lua script runs atomically on the server. It's often simpler than Watch because there are no retries. redis.NewScript sends the script with EVALSHA and falls back to EVAL the first time, so the script body isn't sent on every call.
A classic use is a simple lock. You set the lock with SET NX and a random token. When you release it, you delete it only if it still holds your token, so you never delete a lock that expired and was taken by someone else:
package main
import (
"context"
"crypto/rand"
"errors"
"fmt"
"log"
"time"
"github.com/redis/go-redis/v9"
)
// Delete the key only if it still holds our token.
var unlockScript = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0
`)
var ErrLocked = errors.New("lock is held by someone else")
type Lock struct {
rdb *redis.Client
key string
token string
}
func Acquire(ctx context.Context, rdb *redis.Client, key string, ttl time.Duration) (*Lock, error) {
token := rand.Text() // random, unique per lock holder
ok, err := rdb.SetNX(ctx, key, token, ttl).Result()
if err != nil {
return nil, err
}
if !ok {
return nil, ErrLocked
}
return &Lock{rdb: rdb, key: key, token: token}, nil
}
func (l *Lock) Release(ctx context.Context) (bool, error) {
n, err := unlockScript.Run(ctx, l.rdb, []string{l.key}, l.token).Int()
return n == 1, err
}
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
lock, err := Acquire(ctx, rdb, "lock:report", 10*time.Second)
if err != nil {
log.Fatal(err)
}
fmt.Println("acquired")
_, err = Acquire(ctx, rdb, "lock:report", 10*time.Second)
fmt.Println("second attempt:", err)
released, err := lock.Release(ctx)
fmt.Println("released:", released, err)
released, err = lock.Release(ctx)
fmt.Println("released again:", released, err)
}
acquired
second attempt: lock is held by someone else
released: true <nil>
released again: false <nil>
Pass keys in KEYS and other values in ARGV rather than building them into the script text. Redis Cluster needs to know which keys a script touches. rand.Text() (Go 1.24+) returns a random string that is safe to use as a token. For production-grade locking, see redsync.
Caching JSON values
The cache-aside pattern: look in Redis first. On a miss, load the value from the database and store it with a TTL. Values are encoded as JSON.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"time"
"github.com/redis/go-redis/v9"
)
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
}
// loadProductFromDB stands in for a slow database query.
func loadProductFromDB(id int) (*Product, error) {
time.Sleep(50 * time.Millisecond)
return &Product{ID: id, Name: "Keyboard", Price: 49.99}, nil
}
func getProduct(ctx context.Context, rdb *redis.Client, id int) (*Product, error) {
key := fmt.Sprintf("cache:product:%d", id)
data, err := rdb.Get(ctx, key).Bytes()
if err == nil {
var p Product
if err := json.Unmarshal(data, &p); err != nil {
return nil, err
}
return &p, nil
}
if !errors.Is(err, redis.Nil) {
// Redis is down or slow: log it and fall through to the database.
log.Printf("cache get: %v", err)
}
p, err := loadProductFromDB(id)
if err != nil {
return nil, err
}
data, err = json.Marshal(p)
if err != nil {
return nil, err
}
if err := rdb.Set(ctx, key, data, 10*time.Minute).Err(); err != nil {
log.Printf("cache set: %v", err)
}
return p, nil
}
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
rdb.Del(ctx, "cache:product:7")
for range 3 {
start := time.Now()
p, err := getProduct(ctx, rdb, 7)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v slow=%v\n", *p, time.Since(start) > 40*time.Millisecond)
}
raw, _ := rdb.Get(ctx, "cache:product:7").Result()
fmt.Println(raw)
}
{ID:7 Name:Keyboard Price:49.99} slow=true
{ID:7 Name:Keyboard Price:49.99} slow=false
{ID:7 Name:Keyboard Price:49.99} slow=false
{"id":7,"name":"Keyboard","price":49.99}
A cache is an optimization, so a Redis failure shouldn't fail the request. That's why errors other than redis.Nil are only logged here. When the underlying data changes, Del the cache key so the next read reloads it.
Pub/Sub
Publish sends a message to every client currently subscribed to a channel. Messages are not stored: a subscriber that isn't connected misses them.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
sub := rdb.Subscribe(ctx, "news")
defer sub.Close()
// Wait for the subscription confirmation before publishing,
// otherwise early messages could be lost.
if _, err := sub.Receive(ctx); err != nil {
log.Fatal(err)
}
done := make(chan struct{})
go func() {
defer close(done)
for msg := range sub.Channel() {
fmt.Printf("got %q on %s\n", msg.Payload, msg.Channel)
if msg.Payload == "bye" {
return
}
}
}()
for _, m := range []string{"hello", "world", "bye"} {
if err := rdb.Publish(ctx, "news", m).Err(); err != nil {
log.Fatal(err)
}
}
select {
case <-done:
fmt.Println("done")
case <-time.After(2 * time.Second):
fmt.Println("timeout")
}
}
got "hello" on news
got "world" on news
got "bye" on news
done
A *redis.PubSub uses its own dedicated connection. sub.Channel() returns a Go channel that is closed when you call sub.Close(). Use PSubscribe(ctx, "news.*") to subscribe to a pattern.
Streams
If messages must not be lost, use a stream instead of pub/sub. A stream is an append-only log. Consumer groups split entries between workers and track which entries each worker has acknowledged.
package main
import (
"context"
"fmt"
"log"
"strings"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
rdb.Del(ctx, "orders")
// Producer: append entries; Redis generates the IDs.
for _, item := range []string{"book", "pen", "lamp"} {
err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "orders",
Values: map[string]any{"item": item, "qty": 1},
}).Err()
if err != nil {
log.Fatal(err)
}
}
// Create a consumer group reading from the start ("0") of the stream.
err := rdb.XGroupCreateMkStream(ctx, "orders", "shipping", "0").Err()
if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
log.Fatal(err) // BUSYGROUP means the group already exists
}
streams, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "shipping",
Consumer: "worker-1",
Streams: []string{"orders", ">"}, // ">" = entries not yet delivered to the group
Count: 10,
Block: 0, // wait forever if there are no entries; -1 = don't block
}).Result()
if err != nil {
log.Fatal(err)
}
for _, msg := range streams[0].Messages {
fmt.Println("processing", msg.Values["item"])
rdb.XAck(ctx, "orders", "shipping", msg.ID)
}
pending, _ := rdb.XPending(ctx, "orders", "shipping").Result()
fmt.Println("pending after ack:", pending.Count)
rdb.Del(ctx, "orders")
}
processing book
processing pen
processing lamp
pending after ack: 0
Entries that a worker read but didn't XAck stay pending. If a worker crashes, another worker can take them over with XAutoClaim.
Iterating keys with SCAN
Never use KEYS pattern in production. It blocks the server while it walks the whole keyspace. SCAN returns the keys in small batches, and go-redis wraps it in an iterator:
package main
import (
"context"
"fmt"
"log"
"slices"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
for i := range 25 {
rdb.Set(ctx, fmt.Sprintf("product:%02d", i), i, 0)
}
// SCAN walks the keyspace in small batches without blocking the server.
var keys []string
iter := rdb.Scan(ctx, 0, "product:*", 10).Iterator()
for iter.Next(ctx) {
keys = append(keys, iter.Val())
}
if err := iter.Err(); err != nil {
log.Fatal(err)
}
slices.Sort(keys) // SCAN returns keys in no particular order
fmt.Println(len(keys), keys[:3])
n, err := rdb.Del(ctx, keys...).Result()
if err != nil {
log.Fatal(err)
}
fmt.Println("deleted:", n)
}
25 [product:00 product:01 product:02]
deleted: 25
The 10 is a hint for how much work each SCAN call does, not a limit on the results. HScan, SScan and ZScan do the same for the fields of a single hash, set or sorted set.
Timeouts, pool size and errors
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
opt, err := redis.ParseURL("redis://:secret@localhost:6379/2?dial_timeout=3s&pool_size=20")
if err != nil {
log.Fatal(err)
}
fmt.Println(opt.Addr, opt.DB, opt.DialTimeout, opt.PoolSize, opt.Password != "")
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DialTimeout: 2 * time.Second,
ReadTimeout: 500 * time.Millisecond,
WriteTimeout: 500 * time.Millisecond,
PoolSize: 20,
MinIdleConns: 2,
// Without this, context deadlines are ignored for network I/O.
ContextTimeoutEnabled: true,
})
defer rdb.Close()
ctx := context.Background()
// Server errors: the value under "greeting" is a string, not a list.
rdb.Set(ctx, "greeting", "hi", 0)
err = rdb.LPush(ctx, "greeting", "x").Err()
fmt.Println("error:", err)
var rerr redis.Error
if errors.As(err, &rerr) && strings.HasPrefix(rerr.Error(), "WRONGTYPE") {
fmt.Println("it's a WRONGTYPE server error")
}
// A context deadline cancels a command, even a blocking one.
ctx2, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel()
_, err = rdb.BLPop(ctx2, 0, "empty-list").Result()
fmt.Println("timed out:", errors.Is(err, os.ErrDeadlineExceeded))
stats := rdb.PoolStats()
fmt.Println("open connections:", stats.TotalConns > 0)
rdb.Del(ctx, "greeting")
}
localhost:6379 2 3s 20 true
error: WRONGTYPE Operation against a key holding the wrong kind of value
it's a WRONGTYPE server error
timed out: true
open connections: true
Important options:
DialTimeoutdefaults to 5s.ReadTimeoutdefaults to 5s in recent releases (older ones used 3s), andWriteTimeoutdefaults toReadTimeout. Blocking commands likeBLPopget their own read deadline: the command's timeout plus 10s.PoolSizedefaults to 10 connections perGOMAXPROCS.PoolTimeoutis how long a command waits for a free connection when all are busy.ContextTimeoutEnabledis off by default. Then the context deadline isn't applied to the socket, and a command can outlive its context. In the example above,BLPopwith a timeout of0would block forever. Turn it on if you rely on per-request deadlines.- Server errors (
WRONGTYPE,NOAUTH,ERR ...) implementredis.Error. Network errors are ordinaryneterrors. A timeout matchesos.ErrDeadlineExceeded. MaxRetries(default 3) retries a command on network errors. Make sure that's safe for non-idempotent commands likeINCR. Set it to-1to disable retries.
go-redis has other client types for other deployments: redis.NewClusterClient for Redis Cluster, redis.NewFailoverClient for Sentinel, and redis.NewUniversalClient, which picks one based on the options. All of them implement the redis.UniversalClient interface. Accept that interface in your functions so they work with any deployment. go-redis also works with Redis-compatible servers such as Valkey and Dragonfly.
For tests, miniredis is an in-process fake Redis server. It supports most commands and lets you fast-forward TTLs. Or you can run a real server in Docker with testcontainers-go.
For other databases see SQL, PostgreSQL and MongoDB.
Summary
- Create one
redis.NewClientper process and share it. It's a concurrency-safe connection pool. - A missing key returns
redis.Nil. Check it witherrors.Isand don't treat it as a failure. - Use hashes and
redisstruct tags for objects, or store JSON in a string. - Use
Pipelinedto batch commands,TxPipelinedfor atomic blocks,Watchfor optimistic read-modify-write, and Lua scripts for atomic logic on the server. - Pub/sub is fire-and-forget. Streams with consumer groups give you durable queues.
- Use
SCAN, neverKEYS, and setContextTimeoutEnabledif you need context deadlines to cancel commands.