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

valkey-go

> 开发工具
Open source

A fast Golang Valkey client that supports Client Side Caching, Auto Pipelining, and RMDA.

663 stars0 likes0 views
WebsiteGitHub

About

A fast Golang Valkey client that supports Client Side Caching, Auto Pipelining, and RMDA.

valkey-go

A fast Golang Valkey client that does auto pipelining and supports server-assisted client-side caching.

Features

  • Auto pipelining for non-blocking valkey commands
  • Server-assisted client-side caching
  • Generic Object Mapping with client-side caching
  • Cache-Aside pattern with client-side caching
  • Distributed Locks with client-side caching
  • Helpers for writing tests with valkey mock
  • OpenTelemetry integration
  • Hooks and other integrations
  • Go-redis like API adapter by @418Coffee
  • Pub/Sub, Sharded Pub/Sub, Streams
  • Valkey Cluster, Sentinel, RedisJSON, RedisBloom, RediSearch, RedisTimeseries, etc.
  • Probabilistic Data Structures without Redis Stack
  • Availability zone affinity routing

Getting Started

go
package main

import (
  "context"
  "github.com/valkey-io/valkey-go"
)

func main() {
  client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{"127.0.0.1:6379"}})
  if err != nil {
    panic(err)
  }
  defer client.Close()

  ctx := context.Background()
  // SET key val NX
  err = client.Do(ctx, client.B().Set().Key("key").Value("val").Nx().Build()).Error()
  // HGETALL hm
  hm, err := client.Do(ctx, client.B().Hgetall().Key("hm").Build()).AsStrMap()
}

Check out more examples: Command Response Cheatsheet

Developer Friendly Command Builder

client.B() is the builder entry point to construct a valkey command:


Recorded by @FZambia Improving Centrifugo Redis Engine throughput and allocation efficiency with Rueidis Go library

Once a command is built, use either client.Do() or client.DoMulti() to send it to valkey.

You ❗️SHOULD NOT❗️ reuse the command to another client.Do() or client.DoMulti() call because it has been recycled to the underlying sync.Pool by default.

To reuse a command, use Pin() after Build() and it will prevent the command from being recycled.

Pipelining

Auto Pipelining

All concurrent non-blocking valkey commands (such as GET, SET) are automatically pipelined by default, which reduces the overall round trips and system calls and gets higher throughput. You can easily get the benefit of pipelining technique by just calling client.Do() from multiple goroutines concurrently. For example:

go
func BenchmarkPipelining(b *testing.B, client valkey.Client) {
  // the below client.Do() operations will be issued from
  // multiple goroutines and thus will be pipelined automatically.
  b.RunParallel(func(pb *testing.PB) {
    for pb.Next() {
      client.Do(context.Background(), client.B().Get().Key("k").Build()).ToString()
    }
  })
}

Benchmark Comparison with go-redis v9

Compared to go-redis, valkey-go has higher throughput across 1, 8, and 64 parallelism settings.

It is even able to achieve ~14x throughput over go-redis in a local benchmark of MacBook Pro 16" M1 Pro 2021. (see parallelism(64)-key(16)-value(64)-10)

Benchmark source code: https://github.com/rueian/rueidis-benchmark

A benchmark result performed on two GCP n2-highcpu-2 machines also shows that valkey-go can achieve higher throughput with lower latencies: https://github.com/redis/rueidis/pull/93

Disable Auto Pipelining

While auto pipelining maximizes throughput, it relies on additional goroutines to process requests and responses and may add some latencies due to goroutine scheduling and head of line blocking.

You can avoid this by setting DisableAutoPipelining to true, then it will switch to connection pooling approach and serve each request with dedicated connection on the same goroutine.

When DisableAutoPipelining is set to true, you can still send commands for auto pipelining with ToPipe():

go
cmd := client.B().Get().Key("key").Build().ToPipe()
client.Do(ctx, cmd)

This allows you to use connection pooling approach by default but opt-in auto pipelining for a subset of requests.

Manual Pipelining

Besides auto pipelining, you can also pipeline commands manually with DoMulti():

go
cmds := make(valkey.Commands, 0, 10)
for i := 0; i [KNN 5 @vec $V]").
    Params().Nargs(2).NameValue().NameValue("V", valkey.VectorString64([]float64{...})).
    Dialect(2).Build()
n, resp, err := client.Do(ctx, cmd).AsFtSearch()

Command Response Cheatsheet

While the command builder is developer-friendly, the response parser is a little unfriendly. Developers must know what type of Valkey response will be returned from the server beforehand and which parser they should use.

Error Handling: If an incorrect parser function is chosen, an errParse will be returned. Here's an example using ToArray which demonstrates this scenario:

go
// Attempt to parse the response. If a parsing error occurs, check if the error is a parse error and handle it.
// Normally, you should fix the code by choosing the correct parser function.
// For instance, use ToString() if the expected response is a string, or ToArray() if the expected response is an array as follows:
if _, err := client.Do(ctx, client.B().Get().Key("k").Build()).ToArray(); valkey.IsParseErr(err) {
    fmt.Println("Parsing error:", err)
}

It is hard to remember what type of message will be returned and which parsing to use. So, here are some common examples:

…

Use DecodeSliceOfJSON to Scan Array Result

DecodeSliceOfJSON is useful when you would like to scan the results of an array into a slice of a specific struct.

…

!!!!!! DO NOT DO THIS !!!!!!

Please make sure that all values in the result have the same JSON structures.

go
// Set a pure string value
if err = client.Do(ctx, client.B().Set().Key("user1").Value("userName1").Build()).Error(); err != nil {
  return err
}

// Bad
users := make([]*User, 0)
if err := valkey.DecodeSliceOfJSON(client.Do(ctx, client.B().Mget().Key("user1").Build()), &users); err != nil {
  return err
}
// -> Error: invalid character 'u' looking for the beginning of the value
// in this case, use client.Do(ctx, client.B().Mget().Key("user1").Build()).AsStrSlice()

Contributing

Contributions are welcome, including issues, pull requests, and discussions. Contributions mean a lot to us and help us improve this library and the community!

Thanks to all the people who already contributed!

Generate Command Builders

Command builders are generated based on the definitions in ./hack/cmds by running:

bash
go generate

Testing

Please use the ./dockertest.sh script for running test cases locally. And please try your best to have 100% test coverage on code changes.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Gocacheclient-side-cachingdistributed-lockrdma

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具