Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

go-redis

> 数据库
Open source

Redis Go client

22.2K stars0 likes2 views
WebsiteGitHub

About

Redis Go client

Redis client for Go

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
  • Redis 8.10 - using Redis CE 8.10

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

  • Discussions
  • Chat
  • Reference
  • Examples
  • Release notes (GitHub Releases)

old documentation

  • English
  • 简体中文

Ecosystem

  • Entra ID (Azure AD)
  • Distributed Locks
  • Redis Cache
  • Rate limiting

Features

  • Redis commands except QUIT and SYNC.
  • Automatic connection pooling.
  • StreamingCredentialsProvider (e.g. entra id, oauth) (experimental)
  • Pub/Sub.
  • Pipelines and transactions.
  • Automatic pipelining (experimental) — batches concurrent commands into pipelines for you; meant for high-throughput / high-load / scale use cases.
  • Scripting.
  • Redis Sentinel.
  • Redis Cluster.
  • Client-side caching.
  • Redis Performance Monitoring.
  • Redis Probabilistic [RedisStack]
  • Customizable read and write buffers size.

Installation

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

bash
go mod init github.com/my/repo

Then install go-redis/v9:

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

Quickstart

…

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

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
}

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

Client-side caching

go-redis supports server-assisted client-side caching for standalone 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, a standalone client, 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.

While client-side caching is enabled, go-redis rejects SELECT, AUTH, HELLO with arguments, RESET, CLIENT TRACKING, and raw SUBSCRIBE, PSUBSCRIBE, or SSUBSCRIBE commands because they would change connection state that the cache relies on. A guarded command also fails its whole pipeline. The typed Subscribe, PSubscribe, and SSubscribe APIs remain supported because they use dedicated connections.

Invalidations are processed asynchronously. DrainInterval controls how often idle connections are checked for them, while MaxStaleness can provide an optional upper bound on an entry's lifetime. See the client-side caching example for a working demonstration.

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.

go
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

go
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:

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

Automatic pipelining

Experimental — the API may still change. Reach for autopipelining in high-throughput / high-load / scale scenarios; at low concurrency a pla

Issues· 90 open

View all issuesOpen on GitHub
  • #4049

    ClusterOptions: ReadTimeout/WriteTimeout -1 gives node clients the 5s default

    Updated Sep 30, 2026
  • #3100

    Set don't support unitptr

    v10Updated Sep 30, 2026
  • #3709

    Subscribe on Cluster client pins all subscriptions to a single shard instead of distributing across nodes

    bugpubsubUpdated Sep 29, 2026
  • #4030

    redisotel: unsigned used-connection subtraction can wrap to billions on inconsistent pool stats

    Updated Sep 29, 2026
  • #4027

    Streaming credentials: background re-auth can miss the idle transition and never re-authenticate the connection (lost wake-up in ConnStateMachine.AwaitAndTransition)

    Updated Sep 21, 2026
  • #3983

    Feature Request: Hope to support custom parameters for MonitorCmd

    Updated Sep 17, 2026
  • #4015

    ClientList() on a connection with many thousands of clients causes a large, avoidable memory spike

    Updated Sep 14, 2026
  • #3517

    Should HSetEX arguments be interface{}?

    Stalev10Updated Sep 14, 2026
  • #3104

    Set and Set* don't support custom type

    v10Updated Sep 3, 2026
  • #3999

    FailoverClusterClient leaks Sentinel connections

    Updated Aug 31, 2026

> Tags

Gogogolangredisredis-client

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库