Skip to content

Redis

Database

Redis

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, on top of the redis crate.

Redis support is enabled through the redis Cargo feature, which is off by default. Enable it in your Cargo.toml:

1[dependencies]
2laravel-rust = { version = "0.1", features = ["redis"] }
1[dependencies]
2laravel-rust = { version = "0.1", features = ["redis"] }

Without the feature, the laravel::redis module is not compiled. Enabling it also allows the cache, sessions, and queues to store their data in Redis.

Configuration

Your application's Redis settings live in config.redis, which is also fully compatible with Valkey, including managed Laravel Valkey on Laravel Cloud. It defines 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 redis+unix:///run/redis.sock over a Unix socket:

1REDIS_URL=rediss://app:[email protected]:6380
1REDIS_URL=rediss://app:[email protected]:6380

Percent-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, create a src/config/redis.rs configuration file. Start from Redis::from_env, which already includes those two connections, and add yours. This one adds a reports connection on database 2:

1// src/config/redis.rs
2use laravel::config::redis::{ConnectionConfig, Redis};
3use laravel::config::{self, Env};
4 
5#[config::section]
6fn redis(env: &Env) -> Redis {
7 let mut redis = Redis::from_env(env);
8 
9 redis.add_connection(
10 "reports",
11 ConnectionConfig::new("redis://reports.internal:6379").database(2),
12 );
13 
14 redis
15}
1// src/config/redis.rs
2use laravel::config::redis::{ConnectionConfig, Redis};
3use laravel::config::{self, Env};
4 
5#[config::section]
6fn redis(env: &Env) -> Redis {
7 let mut redis = Redis::from_env(env);
8 
9 redis.add_connection(
10 "reports",
11 ConnectionConfig::new("redis://reports.internal:6379").database(2),
12 );
13 
14 redis
15}

Then add the file to src/config/mod.rs:

1mod redis;
1mod redis;

By default, connections use a 1-second connect timeout and a 5-second response timeout. You can override either on ConnectionConfig, such as .response_timeout(10.seconds()).

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 src/config/redis.rs and the client will discover the rest of the topology automatically:

1redis.add_connection("sessions", ConnectionConfig::cluster([
2 "redis://10.0.0.1:6379",
3 "redis://10.0.0.2:6379",
4]));
1redis.add_connection("sessions", ConnectionConfig::cluster([
2 "redis://10.0.0.1:6379",
3 "redis://10.0.0.2:6379",
4]));

Redis Cluster supports only database 0. 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. Cluster connections do not support Pub / Sub or blocking commands.

Running commands

Call everyday Redis commands directly on laravel::redis to run them against your default connection. For example, this handler increments a post's view counter and returns the updated count:

1use laravel::prelude::*;
2use laravel::redis;
3 
4pub async fn view(Params(id): Params<i64>) -> laravel::Result<Json<isize>> {
5 let views = redis::incr(format!("post:{id}:views"), 1).await?;
6 
7 Ok(Json(views))
8}
1use laravel::prelude::*;
2use laravel::redis;
3 
4pub async fn view(Params(id): Params<i64>) -> laravel::Result<Json<isize>> {
5 let views = redis::incr(format!("post:{id}:views"), 1).await?;
6 
7 Ok(Json(views))
8}

Each helper returns a concrete Rust type, such as Option<String> for get, Vec<String> for lrange, isize for incr, bool for exists, and HashMap<String, String> for hgetall. Looking up a missing key returns None or an empty collection rather than an error:

1redis::set("name", "Taylor").await?;
2 
3let name = redis::get("name").await?;
4let names = redis::lrange("names", 5, 10).await?;
1redis::set("name", "Taylor").await?;
2 
3let name = redis::get("name").await?;
4let names = redis::lrange("names", 5, 10).await?;

Top-level helpers cover strings and keys (get, set, set_ex, set_nx, del, exists, expire, ttl, incr, decr), hashes (hget, hset, hdel, hgetall), lists (lpush, rpush, lpop, rpop, lrange, llen), sets (sadd, srem, smembers, sismember), and sorted sets (zadd, zrem, zrange, zscore). To run any other Redis command on the default connection, import Commands and call it on redis::default_connection()?:

1use laravel::redis::{self, Commands};
2 
3let mut redis = redis::default_connection()?;
4 
5let names = redis.mget(&["user:1:name", "user:2:name"]).await?;
6let token = redis.get_del("invite:42").await?;
1use laravel::redis::{self, Commands};
2 
3let mut redis = redis::default_connection()?;
4 
5let names = redis.mget(&["user:1:name", "user:2:name"]).await?;
6let token = redis.get_del("invite:42").await?;

To expire a key automatically, pass a duration such as 5.minutes() to set_ex or expire:

1redis::expire("name", 5.minutes()).await?;
1redis::expire("name", 5.minutes()).await?;

Because Redis values are stored as strings, serialize structured Rust types yourself when storing them. For example, these handlers store and retrieve a user's preferences as JSON:

1use laravel::prelude::*;
2use laravel::redis;
3use serde::Serialize;
4 
5#[laravel::input]
6#[derive(Serialize)]
7pub struct Preferences {
8 pub theme: String,
9}
10 
11pub async fn update(
12 Params(id): Params<i64>,
13 Json(preferences): Json<Preferences>,
14) -> laravel::Result<()> {
15 let json = serde_json::to_string(&preferences)?;
16 
17 redis::set(format!("user:{id}:preferences"), json).await?;
18 
19 Ok(())
20}
21 
22pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<Option<Preferences>>> {
23 let json = redis::get(format!("user:{id}:preferences")).await?;
24 
25 Ok(Json(json.map(|json| serde_json::from_str(&json)).transpose()?))
26}
1use laravel::prelude::*;
2use laravel::redis;
3use serde::Serialize;
4 
5#[laravel::input]
6#[derive(Serialize)]
7pub struct Preferences {
8 pub theme: String,
9}
10 
11pub async fn update(
12 Params(id): Params<i64>,
13 Json(preferences): Json<Preferences>,
14) -> laravel::Result<()> {
15 let json = serde_json::to_string(&preferences)?;
16 
17 redis::set(format!("user:{id}:preferences"), json).await?;
18 
19 Ok(())
20}
21 
22pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<Option<Preferences>>> {
23 let json = redis::get(format!("user:{id}:preferences")).await?;
24 
25 Ok(Json(json.map(|json| serde_json::from_str(&json)).transpose()?))
26}

Choosing a connection

Call redis::default_connection() to access the default connection, or redis::connection(name) to access another configured connection:

1use laravel::redis::{self, Commands};
2 
3let mut reports = redis::connection("reports")?;
4 
5reports.hset("report:42", "status", "done").await?;
6reports.expire("report:42", 3600).await?;
1use laravel::redis::{self, Commands};
2 
3let mut reports = redis::connection("reports")?;
4 
5reports.hset("report:42", "status", "done").await?;
6reports.expire("report:42", 3600).await?;

Lookups are cheap and return a lightweight handle to the shared connection, so look connections up wherever you need them rather than storing them on structs. 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, invoke the command through client::AsyncCommands:

1use laravel::redis::{self, client::AsyncCommands};
2 
3let mut redis = redis::default_connection()?;
4 
5let avatar: Option<Vec<u8>> = AsyncCommands::get(&mut redis, "avatar:42").await?;
1use laravel::redis::{self, client::AsyncCommands};
2 
3let mut redis = redis::default_connection()?;
4 
5let avatar: Option<Vec<u8>> = AsyncCommands::get(&mut redis, "avatar:42").await?;

For commands without a typed helper method, build the command with command, attach arguments with arg, and await it. Annotate the expected return type, or bind the reply with let () = to ignore it:

1let info: String = redis.command("CLIENT").arg("INFO").await?;
1let info: String = redis.command("CLIENT").arg("INFO").await?;

Pipelines and transactions

When you need to send many commands to Redis at once, use pipeline to batch them into a single round trip instead of awaiting each command individually. Redis executes pipelined commands in order, though commands from other clients may interleave between them. For example, this pipeline resets the view counters of a thousand posts (calling ignore on each command so its reply is discarded):

1use laravel::redis;
2 
3let () = redis::default_connection()?
4 .pipeline(|pipe| {
5 for id in 1..=1000 {
6 pipe.set(format!("post:{id}:views"), 0).ignore();
7 }
8 })
9 .await?;
1use laravel::redis;
2 
3let () = redis::default_connection()?
4 .pipeline(|pipe| {
5 for id in 1..=1000 {
6 pipe.set(format!("post:{id}:views"), 0).ignore();
7 }
8 })
9 .await?;

When your commands must execute atomically without other clients interleaving between them, use transaction instead. It sends all commands in a single MULTI / EXEC block and returns their results as a tuple:

1let (user_visits, total_visits): (i64, i64) = redis::default_connection()?
2 .transaction(|tx| {
3 tx.incr("user_visits", 1).incr("total_visits", 1);
4 })
5 .await?;
1let (user_visits, total_visits): (i64, i64) = redis::default_connection()?
2 .transaction(|tx| {
3 tx.incr("user_visits", 1).incr("total_visits", 1);
4 })
5 .await?;

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. Pass the script to eval, attach key names with key (exposed as KEYS in Lua) and additional arguments with arg (exposed as ARGV). For example, this script increments one counter and also increments a second counter once the first exceeds five:

1use laravel::redis;
2 
3let counter: i64 = redis::default_connection()?
4 .eval(r#"
5 local counter = redis.call("incr", KEYS[1])
6 
7 if counter > 5 then
8 redis.call("incr", KEYS[2])
9 end
10 
11 return counter
12 "#)
13 .key("first-counter")
14 .key("second-counter")
15 .await?;
1use laravel::redis;
2 
3let counter: i64 = redis::default_connection()?
4 .eval(r#"
5 local counter = redis.call("incr", KEYS[1])
6 
7 if counter > 5 then
8 redis.call("incr", KEYS[2])
9 end
10 
11 return counter
12 "#)
13 .key("first-counter")
14 .key("second-counter")
15 .await?;

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. Call publish with any Serialize value; strings and numbers are sent as plain text, while structs are serialized as JSON:

1use laravel::redis;
2use serde::{Deserialize, Serialize};
3 
4#[derive(Serialize, Deserialize)]
5pub struct OrderShipped {
6 pub id: i64,
7}
8 
9redis::default_connection()?.publish("orders", OrderShipped { id: 42 }).await?;
10redis::default_connection()?.publish("news", "We're open").await?;
1use laravel::redis;
2use serde::{Deserialize, Serialize};
3 
4#[derive(Serialize, Deserialize)]
5pub struct OrderShipped {
6 pub id: i64,
7}
8 
9redis::default_connection()?.publish("orders", OrderShipped { id: 42 }).await?;
10redis::default_connection()?.publish("news", "We're open").await?;

Calling subscribe opens a dedicated connection and returns an async stream of incoming messages. Because a subscriber listens indefinitely until stopped, run it inside a console command:

1use laravel::redis;
2use laravel::stream::StreamExt;
3 
4let mut messages = redis::default_connection()?.subscribe("orders").await?;
5 
6while let Some(message) = messages.next().await {
7 let order: OrderShipped = message.json()?;
8 
9 // Handle the shipped order...
10}
1use laravel::redis;
2use laravel::stream::StreamExt;
3 
4let mut messages = redis::default_connection()?.subscribe("orders").await?;
5 
6while let Some(message) = messages.next().await {
7 let order: OrderShipped = message.json()?;
8 
9 // Handle the shipped order...
10}

Each Message provides these methods:

Method Returns
channel() The channel the message was published on
pattern() The pattern it matched for a pattern subscription, or None
body() The raw message bytes as published
text() The message payload as UTF-8 text
json::<T>() The message payload deserialized from JSON

You may pass a slice such as &["orders", "refunds"] to subscribe to multiple channels at once, or call psubscribe("users.*") to subscribe to every channel matching a glob pattern. Dropping the stream unsubscribes automatically.

If a subscription loses its connection, it attempts to reconnect for up to 30 seconds before ending the stream and exiting your while let loop. 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

By default, every request shares a single multiplexed connection per named Redis connection. Running a blocking command such as BLPOP on that shared connection would stall other requests waiting on it, and WATCH would interfere with other requests' transactions. Run blocking commands on a dedicated connection instead.

For example, this worker waits up to 5 seconds for an item on the uploads list, returning the list name and item or None on timeout:

1use laravel::redis::{self, Commands};
2 
3let mut worker = redis::default_connection()?.dedicated().await?;
4 
5let upload: Option<[String; 2]> = worker.blpop("uploads", 5.0).await?;
1use laravel::redis::{self, Commands};
2 
3let mut worker = redis::default_connection()?.dedicated().await?;
4 
5let upload: Option<[String; 2]> = worker.blpop("uploads", 5.0).await?;

dedicated opens a standalone connection to the same server and database with no response timeout and closes it when dropped. Dedicated connections do not reconnect automatically, so open a new one if an error occurs.

Lost connections

When Redis restarts or fails over, Laravel automatically opens a fresh connection on the next command. Read commands such as GET that were in flight when the connection dropped are retried once, while write commands return an error because the server may already have executed them.

Some Redis servers and proxies close idle connections. If the server hasn't answered for over five seconds, Laravel sends a PING before the next command. If the connection is lost, Laravel opens a new one before sending the command.

Adding connections at runtime

When a Redis connection's URL is not known until startup, such as a connection loaded from your database, you may add or replace connections inside a booted hook in src/app.rs:

1use laravel::config::redis::ConnectionConfig;
2use laravel::redis::RedisManager;
3 
4Application::configure().booted(async |app| {
5 app.resolve::<RedisManager>().await?.add_connection(
6 "reports",
7 ConnectionConfig::new("redis://reports.internal:6379"),
8 );
9 
10 Ok(())
11});
1use laravel::config::redis::ConnectionConfig;
2use laravel::redis::RedisManager;
3 
4Application::configure().booted(async |app| {
5 app.resolve::<RedisManager>().await?.add_connection(
6 "reports",
7 ConnectionConfig::new("redis://reports.internal:6379"),
8 );
9 
10 Ok(())
11});

You can also call redis::manager().add_connection(..) and redis::manager().remove_connection(..) directly from handlers or console commands. Any requests already using a replaced or removed connection will finish normally, and the old connection closes once they're done. Because registered connections stay in memory until removed, be sure to call remove_connection when retiring dynamic connections such as per-tenant servers.