Redis
- Introduction
- Configuration
- Running commands
- Pipelines and transactions
- Pub / Sub
- Blocking commands
- Lost connections
- Adding connections at runtime
Introduction
Redis is an open source, in-memory key-value store that supports strings, hashes, lists, sets, and sorted sets, making it a great fit for shared counters, leaderboards, and distributed locks across multiple application servers. Laravel provides named Redis connections, configured similarly to database connections, and gives you a go-redis client for each one.
The client runs every Redis command, pipeline, script, and subscription. The same connections also let the cache, sessions, and queues store their data in Redis.
Configuration
Your application's Redis settings live in cfg.Redis.Connections, which also works with Valkey, including managed Laravel Valkey on Laravel Cloud. New applications have two connections: default, which most code uses, and cache, which the cache store uses. Both read the same environment variables, with defaults preconfigured for a local Redis server:
| Connection | URL | Default database |
|---|---|---|
default | REDIS_URL, or redis://127.0.0.1:6379 | REDIS_DB, or 0 |
cache | REDIS_URL, or redis://127.0.0.1:6379 | REDIS_CACHE_DB, or 1 |
The cache uses its own database, so clearing the cache doesn't erase your application's data. A database in the URL, such as the 2 in redis://redis.internal:6379/2, applies to both connections instead, so leave it out unless you want them to share one.
The URL also holds the scheme, the host, and any credentials. redis:// connects over TCP, rediss:// over TLS, and unix:///run/redis.sock over a Unix socket:
REDIS_URL=rediss://app:secret@redis.internal:6380Percent-encode the characters that mean something in a URL, such as @, :, /, and #, so the password p@ss becomes p%40ss.
When you need an additional Redis connection beyond default and cache, add it to cfg.Redis.Connections in your options' Configure function in bootstrap/app.go. This one adds a reports connection on database 2:
func configure(cfg *config.Config, env *config.Env) {
cfg.Redis.Connections["reports"] = config.RedisConnection{
URL: env.String("REDIS_REPORTS_URL", "redis://reports.internal:6379"),
DB: 2,
}
}By default, connections use a 5-second connect timeout and a 5-second response timeout. You can override either in the URL's query, such as ?read_timeout=10s, which also accepts the client's other options, such as pool_size=20.
警告
Queue keys, such as queues:{default}, and the keys you store yourself have no application prefix. If your production and staging environments share a Redis server, give each its own databases with REDIS_DB and REDIS_CACHE_DB. Otherwise one environment's queue workers run the other's jobs.
Clusters
If your application uses a Redis Cluster, list one or more seed nodes in the connection's Cluster field, in place of its URL, and the client will discover the rest of the topology automatically:
cfg.Redis.Connections["sessions"] = config.RedisConnection{
Cluster: []string{"redis://10.0.0.1:6379", "redis://10.0.0.2:6379"},
}The first node's credentials and query apply to every node. Redis Cluster supports only database 0, so a cluster connection that sets DB fails. Multi-key commands and transactions require all involved keys to live in the same hash slot, so group related keys with a hash tag such as {user:42}:name and {user:42}:email.
Running commands
Call redis.Default with a context to get your default connection's client, which has a method for every Redis command. In a handler, pass the request as the context. Each method takes the context too, and returns a command whose Result method waits for the reply. For example, this handler increments a post's view counter and returns the updated count:
package posts
import (
"fmt"
"go.laravel.com/redis"
"go.laravel.com/web"
)
func View(r *web.Request) *web.Response {
id, err := r.PathInt("post")
if err != nil {
return web.Fail(err)
}
views, err := redis.Default(r).Incr(r, fmt.Sprintf("post:%d:views", id)).Result()
if err != nil {
return web.Fail(err)
}
return web.JSON(views)
}Outside a request, such as in a console command or a job, pass the ctx that your Run or Handle method receives instead.
Each command's reply has a Go type, such as string for Get, []string for LRange, int64 for Incr, and map[string]string for HGetAll. Looking up a missing list or hash returns an empty collection, but Get on a missing key returns the error redis.Nil, so check for it when a missing key is expected:
name, err := redis.Default(r).Get(r, "user:42:name").Result()
if errors.Is(err, redis.Nil) {
name = "Guest"
} else if err != nil {
return web.Fail(err)
}To expire a key automatically, pass a lifetime to Set, as in Set(r, "report:42", data, 10*time.Minute), or call Expire. Pass 0 to Set to keep the key until you delete it.
Because Redis values are stored as strings, encode structured values yourself when storing them. For example, these handlers store and retrieve a user's preferences as JSON:
package preferences
import (
"encoding/json/v2"
"errors"
"fmt"
"go.laravel.com/redis"
"go.laravel.com/web"
)
type Preferences struct {
Theme string `json:"theme"`
}
func Update(r *web.Request) *web.Response {
id, err := r.PathInt("user")
if err != nil {
return web.Fail(err)
}
preferences, err := r.Bind[Preferences]()
if err != nil {
return web.Fail(err)
}
data, err := json.Marshal(preferences)
if err != nil {
return web.Fail(err)
}
key := fmt.Sprintf("user:%d:preferences", id)
if err := redis.Default(r).Set(r, key, data, 0).Err(); err != nil {
return web.Fail(err)
}
return web.NoContent()
}
func Show(r *web.Request) *web.Response {
id, err := r.PathInt("user")
if err != nil {
return web.Fail(err)
}
data, err := redis.Default(r).Get(r, fmt.Sprintf("user:%d:preferences", id)).Bytes()
if errors.Is(err, redis.Nil) {
return web.JSON(Preferences{Theme: "light"})
} else if err != nil {
return web.Fail(err)
}
var preferences Preferences
if err := json.Unmarshal(data, &preferences); err != nil {
return web.Fail(err)
}
return web.JSON(preferences)
}If you'd rather not encode values yourself, keep them in the cache, which encodes them for you.
Choosing a connection
Call redis.Default to access the default connection, or redis.Connection with a name to access another configured connection:
reports := redis.Connection(r, "reports")
if err := reports.HSet(r, "report:42", "status", "done").Err(); err != nil {
return web.Fail(err)
}
if err := reports.Expire(r, "report:42", time.Hour).Err(); err != nil {
return web.Fail(err)
}Every call with the same name returns the same client, which keeps a pool of connections that all requests share, so look clients up wherever you need them rather than storing them on structs, and don't close them. redis.Connection panics for a name that cfg.Redis.Connections doesn't have. Laravel waits until your first command to connect to Redis, so you won't see connection errors until a command actually runs.
Other commands and return types
To decode a reply into a different type, such as raw bytes or a number, call a method such as Bytes, Int, or Bool in place of Result:
avatar, err := redis.Default(r).Get(r, "avatar:42").Bytes()For commands without a method on the client, pass the command and its arguments to Do, then read the reply with Text, Int64, Slice, or another of its methods:
info, err := redis.Default(r).Do(r, "CLIENT", "INFO").Text()Pipelines and transactions
When you need to send many commands to Redis at once, use Pipelined to batch them into a single round trip instead of waiting for each command individually. Redis executes pipelined commands in order, though commands from other clients may interleave between them.
The pipeline's function receives a redis.Pipeliner, re-exported from Laravel's redis package so you don't need an extra import. For example, this console command's Run method resets the view counters of a thousand posts:
func (*ResetViews) Run(ctx context.Context, c *console.Console) error {
_, err := redis.Default(ctx).Pipelined(ctx, func(pipe redis.Pipeliner) error {
for id := 1; id <= 1000; id++ {
pipe.Set(ctx, fmt.Sprintf("post:%d:views", id), 0, 0)
}
return nil
})
return err
}When your commands must execute atomically without other clients interleaving between them, use TxPipelined instead. It sends all commands in a single MULTI / EXEC block, and each command holds its reply once TxPipelined returns:
var userVisits, totalVisits *redis.IntCmd
_, err := redis.Default(r).TxPipelined(r, func(tx redis.Pipeliner) error {
userVisits = tx.Incr(r, "user_visits")
totalVisits = tx.Incr(r, "total_visits")
return nil
})
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string]int64{"user": userVisits.Val(), "total": totalVisits.Val()})Because Redis executes every command in a transaction together after receiving the entire block, one command cannot inspect the result of an earlier command in the same transaction. Use a Lua script when you need conditional logic based on intermediate values.
Lua scripts
Lua scripts execute atomically on the Redis server while allowing you to read values and branch on the results. Define the script once with redis.NewScript, then call its Run method with the client, the key names (exposed as KEYS in Lua), and any additional arguments (exposed as ARGV). For example, this script increments one counter and also increments a second counter once the first exceeds five:
var countVisit = redis.NewScript(`
local counter = redis.call("incr", KEYS[1])
if counter > 5 then
redis.call("incr", KEYS[2])
end
return counter
`)
counter, err := countVisit.Run(r, redis.Default(r), []string{"first-counter", "second-counter"}).Int64()To learn more about writing Redis scripts, check out the Redis Lua scripting documentation.
Pub / Sub
Redis Pub / Sub lets one process broadcast messages to any number of listening processes. For example, a handler may publish an event when an order ships so every process subscribed to the orders channel receives it. Publish sends a string or bytes, so encode a struct as JSON first:
type OrderShipped struct {
ID int64 `json:"id"`
}
message, err := json.Marshal(OrderShipped{ID: 42})
if err != nil {
return web.Fail(err)
}
if err := redis.Default(r).Publish(r, "orders", message).Err(); err != nil {
return web.Fail(err)
}Calling Subscribe opens a dedicated connection and delivers incoming messages on a Go channel. Because a subscriber listens until stopped, run it inside a console command, whose context ends when you press Ctrl+C:
func (*WatchOrders) Run(ctx context.Context, c *console.Console) error {
subscription := redis.Default(ctx).Subscribe(ctx, "orders")
defer subscription.Close()
messages := subscription.Channel()
for {
select {
case <-ctx.Done():
return nil
case message := <-messages:
var order OrderShipped
if err := json.Unmarshal([]byte(message.Payload), &order); err != nil {
return err
}
// Handle the shipped order...
}
}
}Each message has these fields:
| Field | Holds |
|---|---|
Channel | The channel the message was published on |
Pattern | The pattern it matched for a pattern subscription, or an empty string |
Payload | The message as published, as a string |
You may pass several names to subscribe to multiple channels at once, as in Subscribe(ctx, "orders", "refunds"), or call PSubscribe(ctx, "users.*") to subscribe to every channel matching a glob pattern. Closing the subscription unsubscribes and closes its connection.
If a subscription loses its connection, the client reconnects for you. Because Redis does not buffer messages while a subscriber is disconnected, messages published during a reconnect are lost. For guaranteed delivery, use a queue instead.
Blocking commands
A blocking command such as BLPOP waits until a value arrives. The command holds one of the client's pooled connections while it waits, so other requests keep running their commands on the pool's other connections, and you don't need to open a connection of your own.
For example, this worker waits up to 5 seconds for an item on the uploads list, returning the list name and the item, or redis.Nil on timeout:
upload, err := redis.Default(ctx).BLPop(ctx, 5*time.Second, "uploads").Result()A blocking command waits for as long as you ask, even past the client's response timeout, and stops waiting when its context ends.
Lost connections
When Redis restarts or fails over, the client automatically opens fresh connections for the commands that follow. A command whose connection fails is retried up to three times, including writes, so a write that reached Redis before the connection dropped may run twice. Where a double count would matter, prefer writes that are safe to repeat, such as SET over INCR.
Adding connections at runtime
When a Redis connection's URL is not known until your application runs, such as a team's own server loaded from your database, you may add or replace connections with Add on redis.From. You can call it from handlers, console commands, or jobs:
redis.From(ctx).Add("team:"+team.Slug, config.RedisConnection{URL: team.RedisURL})
keys, err := redis.Connection(ctx, "team:"+team.Slug).DBSize(ctx).Result()Later calls to redis.Connection use the new settings. A client you received earlier keeps talking to the old server until your application closes, and so do the cache and session stores. Adding a connection with the settings it already has keeps the existing client, so you may add a team's connection on every request that needs it without opening a new pool each time. Give each server its own connection name, because reusing one name for different servers opens a new pool whenever the settings change.
Because added connections stay in memory until removed, be sure to call Remove when retiring dynamic connections, such as after you delete a team. Remove closes the connection's client, and any command still running on it fails:
if err := redis.From(ctx).Remove("team:" + team.Slug); err != nil {
return err
}