MCPcopy
hub / github.com/redis/go-redis

github.com/redis/go-redis @v9.21.0 sqlite

repository ↗ · DeepWiki ↗ · release v9.21.0 ↗
5,602 symbols 18,930 edges 310 files 2,100 documented · 37%
README

Redis client for Go

build workflow PkgGoDev Documentation Go Report Card codecov

Discord Twitch YouTube Twitter Stack Exchange questions

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 - using Redis CE 8.0 - Redis 8.2 - using Redis CE 8.2 - Redis 8.4 - using Redis CE 8.4 - Redis 8.8 - using Redis CE 8.8

Although the go.mod states it requires at minimum go 1.24, our CI is configured to run the tests against all supported versions of Redis and multiple versions of Go (1.24, 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

Build faster with the Redis Launchpad

Try the Redis Cloud

Dive in developer tutorials

Join the Redis community

Work at Redis

Resources

old documentation

Ecosystem

Features

Installation

go-redis supports 2 last Go versions and requires a Go version with modules support. So make sure to initialize a Go module:

go mod init github.com/my/repo

Then install go-redis/v9:

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

Quickstart

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:

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) - Experimental feature

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.

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
}

Example usage:

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

Note: The streaming credentials provider can be used with 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:

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.

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.

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.

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:

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
})

Connecting via a redis url

go-redis also supports connecting via the redis uri specification. The example below demonstrates how the connection can easily be configured using a string, adhering to this specification.

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

func ExampleClient() *redis.Client {
    url := "redis://user:password@localhost:6379/0?protocol=3"
    opts, err := redis.ParseURL(url)
    if err != nil {
        panic(err)
    }

    return redis.NewClient(opts)
}

Instrument with OpenTelemetry

import (
    "github.com/redis/go-redis/v9"
    "github.com/redis/go-redis/extra/redisotel/v9"
    "errors"
)

func main() {
    ...
    rdb := redis.NewClient(&redis.Options{...})

    if err := errors.Join(redisotel.InstrumentTracing(rdb), redisotel.InstrumentMetrics(rdb)); err != nil {
        log.Fatal(err)
    }

Buffer Size Configuration

go-redis uses 32KiB read and write buffers by default for optimal performance. For high-throughput applications or large pipelines, you can customize buffer sizes:

rdb := redis.NewClient(&redis.Options{
    Addr:            "localhost:6379",
    ReadBufferSize:  1024 * 1024, // 1MiB read buffer
    WriteBufferSize: 1024 * 1024, // 1MiB write buffer
})

Advanced Configuration

go-redis supports extending the client identification phase to allow projects to send their own custom client identification.

Default Client Identification

By default, go-redis automatically sends the client library name and version during the connection process. This feature is available in redis-server as of version 7.2. As a result, the command is "fire and forget", meaning it should fail silently, in the case that the redis server does not support this feature.

Disabling Identity Verification

When connection identity verification is not required or needs to be explicitly disabled, a DisableIdentity configuration option exists. Initially there was a typo and the option was named DisableIndentity instead of DisableIdentity. The misspelled option is marked as Deprecated and will be removed in V10 of this library. Although both options will work at the moment, the correct option is DisableIdentity. The deprecated option will be removed in V10 of this library, so please use the correct option name to avoid any issues.

To disable verification, set the DisableIdentity option to true in the Redis client options:

rdb := redis.NewClient(&redis.Options{
    Addr:            "localhost:6379",
    Password:        "",
    DB:              0,
    DisableIdentity: true, // Disable set-info on connect
})

RESP3 for RediSearch Commands (UnstableResp3 is deprecated)

As of v9.20, FT.SEARCH, FT.AGGREGATE, FT.INFO, FT.SPELLCHECK, and FT.SYNDUMP parse RESP3 (map) responses into the same typed result objects as RESP2. No flag is required — Val() / Result() work uniformly on both protocols.

The legacy UnstableResp3 option is now a no-op and is retained on every options struct only for backwards compatibility. It will be removed in a future release; new code should not set it.

RawResult() / RawVal() continue to work for callers that prefer the raw RESP payload directly:

res1, err := client.FTSearchWithArgs(ctx, "txt", "foo bar", &redis.FTSearchOptions{}).RawResult()
val1 := client.FTSearchWithArgs(ctx, "txt", "foo bar", &redis.FTSearchOptions{}).RawVal()

Redis-Search Default Dialect

In the Redis-Search module, **the def

Extension points exported contracts — how you extend this code

Hook (Interface)
------------------------------------------------------------------------------ [10 implementers]
redis.go
ConsistentHash (Interface)
------------------------------------------------------------------------------ [10 implementers]
ring.go
StreamingCredentialsProvider (Interface)
StreamingCredentialsProvider is an interface that defines the methods for a streaming credentials provider. It is used t [8 …
auth/auth.go
ResponseAggregator (Interface)
ResponseAggregator defines the interface for aggregating responses from multiple shards. [10 implementers]
internal/routing/aggregator.go
PubSubPooler (Interface)
(no doc) [7 implementers]
otel.go
Vector (Interface)
(no doc) [11 implementers]
vectorset_commands.go
Error (Interface)
(no doc) [13 implementers]
error.go
StatGetter (Interface)
StatGetter provides a method to get pool statistics. [4 implementers]
extra/redisprometheus/collector.go

Core symbols most depended-on inside this repo

Result
called by 2706
internal/routing/aggregator.go
Err
called by 2131
internal/otel/metrics.go
Val
called by 837
command.go
Printf
called by 441
internal/log.go
Run
called by 414
script.go
Set
called by 361
string_commands.go
Close
called by 338
universal.go
Del
called by 290
generic_commands.go

Shape

Method 3,443
Function 1,476
Struct 551
Interface 70
TypeAlias 44
FuncType 18

Languages

Go100%

Modules by API surface

command.go744 symbols
search_commands.go209 symbols
probabilistic.go193 symbols
commands.go136 symbols
sortedset_commands.go119 symbols
search_builders.go116 symbols
osscluster.go106 symbols
stream_commands.go94 symbols
timeseries_commands.go92 symbols
redis.go92 symbols
json.go88 symbols
string_commands.go84 symbols

Dependencies from manifests, versioned

github.com/beorn7/perksv1.0.1 · 1×
github.com/bsm/ginkgo/v2v2.12.0 · 1×
github.com/bsm/gomegav1.27.10 · 1×
github.com/cespare/xxhash/v2v2.3.0 · 1×
github.com/davecgh/go-spewv1.1.1 · 1×
github.com/go-logr/logrv1.4.3 · 1×
github.com/go-logr/stdrv1.2.2 · 1×
github.com/golang/groupcachev0.0.0-2021033122475 · 1×

For agents

$ claude mcp add go-redis \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact