Awesome Go

redis

CategoryDatabase Drivers
SubcategoryNoSQL Database Drivers
Stars22,292

Redis client for Golang

About redis

This large README is shown as a plain-text preview. Read the full README at the source

# Redis client for Go

[![build workflow](https://github.com/redis/go-redis/actions/workflows/build.yml/badge.svg)](https://github.com/redis/go-redis/actions)
[![PkgGoDev](https://pkg.go.dev/badge/github.com/redis/go-redis/v9)](https://pkg.go.dev/github.com/redis/go-redis/v9?tab=doc)
[![Documentation](https://img.shields.io/badge/redis-documentation-informational)](https://redis.io/docs/latest/develop/clients/go/)
[![Go Report Card](https://goreportcard.com/badge/github.com/redis/go-redis/v9)](https://goreportcard.com/report/github.com/redis/go-redis/v9)
[![codecov](https://codecov.io/github/redis/go-redis/graph/badge.svg?token=tsrCZKuSSw)](https://codecov.io/github/redis/go-redis)

[![Discord](https://img.shields.io/discord/697882427875393627.svg?style=social&logo=discord)](https://discord.gg/W4txy5AeKM)
[![Twitch](https://img.shields.io/twitch/status/redisinc?style=social)](https://www.twitch.tv/redisinc)
[![YouTube](https://img.shields.io/youtube/channel/views/UCD78lHSwYqMlyetR0_P4Vig?style=social)](https://www.youtube.com/redisinc)
[![Twitter](https://img.shields.io/twitter/follow/redisinc?style=social)](https://twitter.com/redisinc)
[![Stack Exchange questions](https://img.shields.io/stackexchange/stackoverflow/t/go-redis?style=social&logo=stackoverflow&label=Stackoverflow)](https://stackoverflow.com/questions/tagged/go-redis)

> go-redis is the official Redis client library for the Go programming language. It offers a straightforward interface for interacting with Redis servers. 

## Supported versions

In `go-redis` we are aiming to support the last three releases of Redis. Currently, this means we do support:
- [Redis 8.0](https://raw.githubusercontent.com/redis/redis/8.0/00-RELEASENOTES) - using Redis CE 8.0
- [Redis 8.2](https://raw.githubusercontent.com/redis/redis/8.2/00-RELEASENOTES) - using Redis CE 8.2
- [Redis 8.4](https://raw.githubusercontent.com/redis/redis/8.4/00-RELEASENOTES) - using Redis CE 8.4
- [Redis 8.6](https://raw.githubusercontent.com/redis/redis/8.6/00-RELEASENOTES) - using Redis CE 8.6
- [Redis 8.8](https://raw.githubusercontent.com/redis/redis/8.8/00-RELEASENOTES) - using Redis CE 8.8
- [Redis 8.10](https://raw.githubusercontent.com/redis/redis/8.10/00-RELEASENOTES) - using Redis CE 8.10
- [Redis 8.12](https://raw.githubusercontent.com/redis/redis/8.12/00-RELEASENOTES) - using Redis CE 8.12

Although the `go.mod` states it requires at minimum `go 1.26`, our CI is configured to run the tests against all supported
versions of Redis and multiple versions of Go ([1.26](https://go.dev/doc/devel/release#go1.26.0), oldstable, and stable). We observe that some modules related test may not pass with
Redis Stack 7.2 and some commands are changed with Redis CE 8.0.
Although it is not officially supported, `go-redis/v9`  should be able to work with any Redis 7.0+.
Please do refer to the documentation and the tests if you experience any issues.

### Array data type (Redis 8.8+)

Starting with Redis 8.8, go-redis exposes the new array data type via the `AR*` command family
(`ARSET`, `ARGET`, `ARGETRANGE`, `ARMSET`, `ARMGET`, `ARINSERT`, `ARDEL`, `ARDELRANGE`,
`ARLEN`, `ARCOUNT`, `ARNEXT`, `ARSEEK`, `ARSCAN`, `ARGREP`, `ARRING`, `ARLASTITEMS`,
`ARINFO`/`ARINFOFULL`, and the `AROP*` reducers). See `array_commands.go` for the full
surface. The API is experimental and may change in a future release.

## How do I Redis?

[Learn for free at Redis University](https://university.redis.com/)

[Build faster with the Redis Launchpad](https://launchpad.redis.com/)

[Try the Redis Cloud](https://redis.com/try-free/)

[Dive in developer tutorials](https://developer.redis.com/)

[Join the Redis community](https://redis.com/community/)

[Work at Redis](https://redis.com/company/careers/jobs/)


## Resources

- [Discussions](https://github.com/redis/go-redis/discussions)
- [Chat](https://discord.gg/W4txy5AeKM)
- [Reference](https://pkg.go.dev/github.com/redis/go-redis/v9)
- [Examples](https://pkg.go.dev/github.com/redis/go-redis/v9#pkg-examples)
- [Release notes](./RELEASE-NOTES.md) ([GitHub Releases](https://github.com/redis/go-redis/releases))

## old documentation

- [English](https://redis.uptrace.dev)
- [简体中文](https://redis.uptrace.dev/zh/)

## Ecosystem

- [Entra ID (Azure AD)](https://github.com/redis/go-redis-entraid)
- [Distributed Locks](https://github.com/bsm/redislock)
- [Redis Cache](https://github.com/go-redis/cache)
- [Rate limiting](https://github.com/go-redis/redis_rate)

## Features

- Redis commands except QUIT and SYNC.
- Automatic connection pooling.
- [StreamingCredentialsProvider (e.g. entra id, oauth)](#1-streaming-credentials-provider-highest-priority)
- [Pub/Sub](https://redis.uptrace.dev/guide/go-redis-pubsub.html).
- [Pipelines and transactions](https://redis.uptrace.dev/guide/go-redis-pipelines.html).
- [Automatic pipelining](#automatic-pipelining) (experimental) — batches concurrent
  commands into pipelines for you; meant for high-throughput / high-load / scale
  use cases.
- [Scripting](https://redis.uptrace.dev/guide/lua-scripting.html).
- [Redis Sentinel](https://redis.uptrace.dev/guide/go-redis-sentinel.html).
- [Redis Cluster](https://redis.uptrace.dev/guide/go-redis-cluster.html).
- [Client-side caching](#client-side-caching).
- [MultiDB (Active-Active failover)](#multidb-active-active-failover) (experimental).
- [Redis Performance Monitoring](https://redis.uptrace.dev/guide/redis-performance-monitoring.html).
- [Redis Probabilistic [RedisStack]](https://redis.io/docs/data-types/probabilistic/)
- [Customizable read and write buffers size.](#custom-buffer-sizes)

## Installation

go-redis supports 2 last Go versions and requires a Go version with
[modules](https://github.com/golang/go/wiki/Modules) support. So make sure to initialize a Go
module:

```shell
go mod init github.com/my/repo
```

Then install go-redis/**v9**:

```shell
go get github.com/redis/go-redis/v9
```

## Quickstart

```go
import (
    "context"
    "fmt"

    "github.com/redis/go-redis/v9"
)

var ctx = context.Background()

func ExampleClient() {
    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })
    defer rdb.Close()

    err := rdb.Set(ctx, "key", "value", 0).Err()
    if err != nil {
        panic(err)
    }

    val, err := rdb.Get(ctx, "key").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("key", val)

    val2, err := rdb.Get(ctx, "key2").Result()
    if err == redis.Nil {
        fmt.Println("key2 does not exist")
    } else if err != nil {
        panic(err)
    } else {
        fmt.Println("key2", val2)
    }
    // Output: key value
    // key2 does not exist
}
```

### Dial retries and backoff

Connection establishment can be retried by the connection pool when dialing fails.

- **`DialerRetries`**: maximum number of dial attempts (default: 5).
- **`DialerRetryTimeout`**: default delay between attempts when no custom backoff is provided (default: 100ms).
- **`DialerRetryBackoff`**: optional function hook to control the delay between attempts.

Example:

```go
rdb := redis.NewClient(&redis.Options{
	Addr: "localhost:6379",

	DialerRetries:      5,
	DialerRetryTimeout: 100 * time.Millisecond, // used when DialerRetryBackoff is nil

	// Optional: exponential backoff with jitter and a cap.
	DialerRetryBackoff: redis.DialRetryBackoffExponential(100*time.Millisecond, 2*time.Second),
})
defer rdb.Close()
```

### Authentication

The Redis client supports multiple ways to provide authentication credentials, with a clear priority order. Here are the available options:

#### 1. Streaming Credentials Provider (Highest Priority)

The streaming credentials provider allows for dynamic credential updates during the connection lifetime. This is particularly useful for managed identity services and token-based authentication.

```go
type StreamingCredentialsProvider interface {
    Subscribe(listener CredentialsListener) (Credentials, UnsubscribeFunc, error)
}

type CredentialsListener interface {
    OnNext(credentials Credentials)  // Called when credentials are updated
    OnError(err error)              // Called when an error occurs
}

type Credentials interface {
    BasicAuth() (username string, password string)
    RawCredentials() string
}
```

Providers can optionally implement `auth.ContextStreamingCredentialsProvider` by
adding `SubscribeWithContext(ctx, listener)` alongside `Subscribe`. go-redis uses
this method during connection initialization so the caller's context can bound
the wait for credentials. This applies whether or not `ContextTimeoutEnabled` is
set. Canceling that context must not end an established subscription or cancel
token acquisition shared with other connections. Providers
and wrappers without this method retain synchronous `Subscribe` behavior; there
is no goroutine fallback. go-redis-entraid v1.1.0 and later support this method.

Example usage:
```go
rdb := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
    StreamingCredentialsProvider: &MyCredentialsProvider{},
})
```

**Note:** The streaming credentials provider can be used with [go-redis-entraid](https://github.com/redis/go-redis-entraid) to enable Entra ID (formerly Azure AD) authentication. This allows for seamless integration with Azure's managed identity services and token-based authentication.

Example with Entra ID:
```go
import (
    "github.com/redis/go-redis/v9"
    "github.com/redis/go-redis-entraid"
)

// Create an Entra ID credentials provider
provider := entraid.NewDefaultAzureIdentityProvider()

// Configure Redis client with Entra ID authentication
rdb := redis.NewClient(&redis.Options{
    Addr: "your-redis-server.redis.cache.windows.net:6380",
    StreamingCredentialsProvider: provider,
    TLSConfig: &tls.Config{
        MinVersion: tls.VersionTLS12,
    },
})
```

#### 2. Context-based Credentials Provider

The context-based provider allows credentials to be determined at the time of each operation, using the context.

```go
rdb := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
    CredentialsProviderContext: func(ctx context.Context) (string, string, error) {
        // Return username, password, and any error
        return "user", "pass", nil
    },
})
```

#### 3. Regular Credentials Provider

A simple function-based provider that returns static credentials.

```go
rdb := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
    CredentialsProvider: func() (string, string) {
        // Return username and password
        return "user", "pass"
    },
})
```

#### 4. Username/Password Fields (Lowest Priority)

The most basic way to provide credentials is through the `Username` and `Password` fields in the options.

```go
rdb := redis.NewClient(&redis.Options{
    Addr:     "localhost:6379",
    Username: "user",
    Password: "pass",
})
```

#### Priority Order

The client will use credentials in the following priority order:
1. Streaming Credentials Provider (if set)
2. Context-based Credentials Provider (if set)
3. Regular Credentials Provider (if set)
4. Username/Password fields (if set)

If none of these are set, the client will attempt to connect without authentication.

### Protocol Version

The client supports both RESP2 and RESP3 protocols. You can specify the protocol version in the options:

```go
rdb := redis.NewClient(&redis.Options{
    Addr:     "localhost:6379",
    Password: "", // no password set
    DB:       0,  // use default DB
    Protocol: 3,  // specify 2 for RESP 2 or 3 for RESP 3
})
```

### Redis Cluster fan-out safety

Cluster routing uses shared command metadata for key positions and read-only
status. The default resolver preserves existing routing behavior, including the
cluster-wide `DBSize`, `ScriptLoad`, `ScriptFlush`, and `ScriptExists` helpers.
`CommandMetadata` configuration alone does not enable new fan-out policies.

Opt into metadata-based fan-out and aggregation explicitly, before using the client:

```go
c := redis.NewClusterClient(&redis.ClusterOptions{
    Addrs: []string{"localhost:7000", "localhost:7001", "localhost:7002"},
})
c.SetCommandInfoResolver(redis.NewCommandMetadataResolver())
```

The resolver uses the client's metadata view, including configured overrides and
live metadata. To request a live metadata attempt during resolution, install
`c.NewDynamicResolver()` instead; this is also an explicit fan-out opt-in.
Supported policies can send `PING` to all masters or split commands such as
`MGET`, `DEL`, and `MSET` across slots. Without opt-in, their existing routing
and server-side `CROSSSLOT` behavior remain unchanged.

The default `CommandMetadataStatic` mode performs no metadata network requests
unless resolution reaches an explicitly installed `NewDynamicResolver`.
After that first live attempt, reconnects and topology changes trigger identity
verification, and a configured `RefreshInterval` also checks for module or
version changes on existing connections. With no interval, an in-place module
change needs a reconnect or topology change to be detected.
Only the initial verification can delay resolution. After failure or later
invalidation, commands immediately use the conservative metadata view while
background attempts retry with backoff. Live metadata is published only after
all required server compatibility checks succeed.
For commands missing from the bundled snapshot, configure
`CommandMetadataPreferLive` or `CommandMetadataConfig.Overrides` to supply their
key positions and read-only flags. Resolved key specifications take precedence
over `SetFirstKeyPos`; that hint applies when command metadata is unavailable.

For opted-in numeric fan-out, sum/min/max preserve integer replies as `int64`,
including raw `Do(...).Result()` values; integer overflow returns an error.
Aggregates containing floating-point replies return `float64`.

Explicit `Pipeline` and `TxPipeline` calls keep each command local to its selected
node; automatic metadata fan-out is suppressed inside these batches. A transaction
still requires all keys to share a slot. Ordered `AsyncAutoPipeline` rejects
metadata fan-out before dispatch; same-slot metadata commands remain batchable.
Use the blocking face or unordered half-duplex mode for automatic fan-out.
Existing direct helpers and special routing retain their separate execution
path: await prior async results before a dependent direct call.
`SCAN`, `INFO`, and known diagnostic commands remain node-local; use
`ForEachMaster` for whole-cluster inspection or scanning.

`FT.CURSOR READ` is not retried after a lost reply because the server may
already have advanced the cursor. Native cursor IDs and the existing cursor
routing remain unchanged; cluster-wide cursor ownership and reply parsing are
being addressed separately.

Cluster-wide operations and distributed DDL can affect multiple shards and are
not atomic across them, whether fan-out is performed by go-redis or by a Redis
server/coordinator. If one shard fails, earlier shards may already have applied
the command. There is no automatic rollback of those successful operations;
inspect the error and be prepared for manual intervention or cleanup.

### Redis Sentinel

`NewFailoverClient` and `NewFailoverClusterClient` both use Redis Sentinel for
automatic failover. `NewFailoverClient` does not support `RouteByLatency` or
`RouteRandomly`; prefer it when replica routing is not needed, as it avoids the
extra overhead of the `ClusterClient`'s hash-slot calculation.
`NewFailoverClusterClient` is also safe with a non-cluster Sentinel setup: it
handles master/replica role changes on Sentinel-triggered failover, and its
internal hash-slot calculation does not interfere with routing. Prefer it when
`RouteByLatency` or `RouteRandomly` is needed.

### Client-side caching

go-redis supports server-assisted client-side caching for standalone and Cluster clients.
Eligible read replies are stored in the application's memory, so repeated reads
can avoid a Redis round trip. Redis tracks which keys each connection has read
and sends RESP3 invalidation notifications when those keys change. go-redis
uses those notifications to evict affected entries automatically.

> **Experimental:** The client-side caching API may change in a minor release.

Enable the built-in bounded cache with `ClientSideCacheConfig`:

```go
rdb := redis.NewClient(&redis.Options{
    Addr:     "localhost:6379",
    Protocol: 3,
    DB:       0,
    ClientSideCacheConfig: &redis.ClientSideCacheConfig{
        MaxEntries: 10_000,
    },
})
defer rdb.Close()
```

Client-side caching currently requires RESP3 and database
0. Fixed `Username` and `Password` values are supported. It is disabled when a
dynamic credential provider is configured, because cached data must never be
reused after the client's ACL identity changes. Only deterministic read
commands supported by the cache are stored; writes and streaming responses
bypass it.

Tracking modes and application intent are configured on the client options:

```go
ClientSideCacheConfig: &redis.ClientSideCacheConfig{MaxEntries: 10_000},
ClientSideCacheTrackingMode: redis.TrackingModeOptIn,
ClientSideCacheable: func(command string, keys []string) bool {
    return command == "get" && len(keys) == 1 && strings.HasPrefix(keys[0], "user:")
},
```

`plain` (including the zero value) caches eligible reads by default; `optin`
bypasses by default; `optout` caches by default. The predicate has the same
meaning in every mode, including plain. It runs concurrently, outside cache
locks, on eligible unmarked calls, and receives actual Redis keys. Its owned
key slice may be retained but must not be modified. Mode/policy are fixed at
client construction. These options also apply with an explicit custom Cache;
setting them alone does not enable caching. An invalid tracking mode logs a
warning once at construction and disables caching without failing commands.

In plain mode, the predicate and context marks control only local cache use;
Redis still tracks reads on tracked connections. `OPTIN` and `OPTOUT` also limit
server tracking according to the caching decision. `NewLocalCache` configures
storage only and does not select a tracking mode or predicate.

Use a context mark to override intent for a call, with any client type:

```go
value, err := rdb.Get(redis.WithCache(ctx), "user:42").Result()
value, err = rdb.Get(redis.WithoutCache(ctx), "user:42").Result()
```

The returned context inherits cancellation, deadlines and other values from
`ctx`. It can be reused; every command submitted with it receives the mark.
The last mark wins when contexts are nested, and the original context is
unchanged. Intent is captured at submission and survives internal context
replacement, asynchronous dispatch and retries.

A bypass reads the server without using, refreshing or removing
an existing entry. `WithCache` requests caching when the command and execution
path support it; it never overrides eligibility or guarantees that every reply
will be stored. Otherwise the command executes normally without caching, with
no error or warning caused by the mark. Operational errors and diagnostics are
unchanged. A fully read Redis error from CLIENT CACHING returns successful data
uncached; protocol/transport failures retire the connection. Hits send no commands.

All three fetch paths (foreground, miss coalescer, background refresh) support
the modes. Context marks preserve AutoPipeline's normal call semantics:
blocking calls wait; `AsyncAutoPipeline` returns immediately and result accessors
wait for completion. Blocking and explicitly unordered faces use the normal
cache path. On ordered `AsyncAutoPipeline`, marked typed reads remain in the ordered
stream and execute uncached. Bypass marks also retain ordering. This does not
change the existing ordering exceptions for raw `Do` calls, blocking commands
and direct administrative helpers.

Frequently Asked Questions

What is redis?

redis is a Database Drivers library for the Go programming language. Redis client for Golang

How many GitHub stars does redis have?

redis has 22,292 GitHub stars in the directory's latest synchronization.

How do I install redis?

Install redis with the Go module system using `go get redis/go-redis`. Check the repository for the current installation instructions.

What category does redis belong to?

redis is listed under Database Drivers, specifically NoSQL Database Drivers.

← Back to NoSQL Database Drivers