Golang wrapper - valkey-io/valkey-glide GitHub Wiki

Go Wrapper Examples

Please refer to the README of the Go examples for the instructions on how to run Standalone Example and Cluster Example.

Client Initialization

Valkey GLIDE provides support for both Cluster and Standalone configurations. Please refer to the relevant section based on your specific setup.

Cluster

Valkey GLIDE supports Cluster deployments, where the database is partitioned across multiple primary shards, with each shard being represented by a primary node and zero or more replica nodes.

To initialize a ClusterClient, you need to provide a ClusterClientConfiguration that includes the addresses of initial seed nodes. Valkey GLIDE automatically discovers the entire cluster topology, eliminating the necessity of explicitly listing all cluster nodes.

Connecting to a Cluster

The NodeAddress struct represents the host and port of a cluster node. The host can be either an IP address, a hostname, or a fully qualified domain name (FQDN).

Example - Connecting to a cluster

import (
    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectCluster() {
    myConfig := config.NewClusterClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "address.example.com", Port: 6379})

    client, err := glide.NewClusterClient(myConfig)
}

Request Routing

In the cluster, data is divided into slots, and each primary node within the cluster is responsible for specific slots. Valkey GLIDE adheres to Valkey OSS guidelines when determining the node(s) to which a command should be sent in clustering mode.

For more details on the routing of specific commands, please refer to the documentation within the code for routing configuration.

Response Aggregation

When requests are dispatched to multiple shards in a cluster (as discussed in the Request routing section), the client needs to aggregate the responses for a given command. Valkey GLIDE follows Valkey OSS guidelines for determining how to aggregate the responses from multiple shards within a cluster.

To learn more about response aggregation for specific commands, please refer to the documentation within the code.

Topology Updates

The cluster's topology can change over time. New nodes can be added or removed, and the primary node owning a specific slot may change. Valkey GLIDE is designed to automatically rediscover the topology whenever the server indicates a change in slot ownership. This ensures that the Valkey GLIDE client stays in sync with the cluster's topology.

Standalone

Valkey GLIDE also supports Standalone deployments, where the database is hosted on a single primary node, optionally with replica nodes. To initialize a Client for a standalone setup, you should create a ClientConfiguration that includes the addresses of primary and all replica nodes.

Example - Connecting to a standalone

import (
    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectStandalone() {
    myConfig := config.NewClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "primary.example.com", Port: 6379}).
        WithAddress(&config.NodeAddress{Host: "replica1.example.com", Port: 6379}).
        WithAddress(&config.NodeAddress{Host: "replica2.example.com", Port: 6379})

    client, err := glide.NewClient(myConfig)
}

Valkey Commands

For information on the supported commands and their corresponding parameters, we recommend referring to the documentation in the code. This documentation provides in-depth insights into the usage and options available for each command.

Transaction

A transaction in Valkey GLIDE allows you to execute a group of commands in a single, atomic step. This ensures that all commands in the transaction are executed sequentially and without interruption. See Valkey Transactions.

This is equivalent to the Valkey commands MULTI / EXEC.

See Valkey Batch Release notes for more details about the design and implementation.

Client Usage

Batch: Transaction and Pipelining (GLIDE 2.0)

Valkey GLIDE 2.0 introduces the concept of Batch and ClusterBatch. This feature provides flexible support for both atomic batches (Transactions) and non-atomic batches (Pipelining), while ensuring easy configuration and clear, detailed examples for each scenario.

Overview

GLIDE 2.0 introduces a robust Batch API with two primary modes:

  • Atomic Batch: Guarantees that all commands in a batch execute as a single, atomic unit. No other commands can interleave (similar to MULTI/EXEC).
  • Non-Atomic Batch (Pipeline): Sends multiple commands in one request without atomic guarantees. Commands can span multiple slots/nodes in a cluster and do not block other operations from being processed between them.

Both modes leverage the same classes — StandaloneBatch for standalone mode and ClusterBatch for cluster mode — distinguished by an isAtomic flag. Extra configuration is provided via StandaloneBatchOptions or ClusterBatchOptions, allowing control over timeouts, routings, and retry strategies.

Key Concepts

Atomic Batch (Transaction)

  • Definition: A set of commands executed together as a single, indivisible operation.
  • Guarantees: Sequential execution without interruption. Other clients cannot interleave commands between the batched operations.
  • Slot Constraint (Cluster Mode): When running against a cluster, all keys in an atomic batch must map to the same hash slot. Mixing keys from different slots will cause the transaction to fail.
  • Underlying Valkey: Equivalent to MULTI/EXEC Valkey commands.
  • Use Case: When you need consistency and isolation.
  • See: Valkey Transactions.

Non-Atomic Batch (Pipeline)

  • Definition: A group of commands sent in a single request, but executed without atomicity or isolation.
  • Behavior: Commands may be processed on different slots/nodes (in cluster mode), and other operations from different clients may interleave during execution.
  • Underlying Valkey: Similar to pipelining, minimizing round-trip latencies by sending all commands at once.
  • Use Case: Bulk reads or writes where each command is independent.
  • See: Valkey Pipelines.

Classes and API

StandaloneBatch

For standalone (non-cluster, cluster mode disabled) clients.

import "github.com/valkey-io/valkey-glide/go/v2/pipeline";

// Create an atomic batch (transaction)
transaction := pipeline.NewStandaloneBatch(true)
// Create a non-atomic batch (pipeline)
pipeline := pipeline.NewStandaloneBatch(false)

Note: Standalone Batches are executed on primary node.

ClusterBatch

For cluster (cluster mode enabled) clients (Mirrors StandaloneBatch but routes commands based on slot ownership, splitting into sub-pipelines if needed, Read more in Multi-Node support).

import "github.com/valkey-io/valkey-glide/go/v2/pipeline";

// Create an atomic cluster batch (must use keys mapping to same slot)
transaction := pipeline.NewClusterBatch(true)
// Create a non-atomic cluster batch (pipeline may span multiple slots)
pipeline := pipeline.NewClusterBatch(false)

Note: When isAtomic = true, all keys in the ClusterBatch must map to the same slot. Attempting to include keys from different slots will result in an exception. Read more in Multi-Node support. If the client is configured to read from replicas (PreferReplica, AzAffinity, AzAffinityReplicaAndPrimary) read commands may be routed to the replicas, in a round robin manner, if this behavior impacts your application, consider creating a dedicated client, with the desired ReadFrom configuration.

Error handling - Return an Error

Determines how errors are surfaced when calling Exec(...) and ExecWithOptions(...). It is passed directly:

// Standalone Mode
Exec(ctx context.Context, batch pipeline.StandaloneBatch, raiseOnError bool) ([]any, error)
ExecWithOptions(ctx context.Context, batch pipeline.StandaloneBatch, raiseOnError bool, options pipeline.StandaloneBatchOptions) ([]any, error)

// Cluster Mode
Exec(ctx context.Context, batch pipeline.ClusterBatch, raiseOnError bool) ([]any, error)
ExecWithOptions(ctx context.Context, batch pipeline.ClusterBatch, raiseOnError bool, options pipeline.ClusterBatchOptions) ([]any, error)

Behavior:

  • raiseOnError = true: When set to true, the first encountered error within the batch (after all configured retries and redirections have been executed) is raised as a RequestException.

  • raiseOnError = false:

    • When set to false, errors are returned as part of the response array rather than thrown.
    • Each failed command’s error details appear as a RequestException instance in the corresponding position of the returned []any.
    • Allows processing of both successful and failed commands together.

Example:

// Cluster pipeline with raiseOnError = false
pipeline := pipeline.NewClusterBatch(false).
	Set("key", "value").                                   // OK
	LPop("key").                                           // WRONGTYPE error (not a list)
    Rename("{non-existing-key}", "{non-existing-key}:1")   // NO SUCH KEY error
res, err := clusterClient.Exec(ctx, *pipeline, false)
fmt.Printf("Result is: %+v\n", res)
// Output: Result is: [OK WRONGTYPE: Operation against a key holding the wrong kind of value An error was signalled by the server: - ResponseError: no such key]
// Transaction with raiseOnError = true
transaction := pipeline.NewStandaloneBatch(true).
	Set("key", "value").                   // OK
	LPop("key").                           // WRONGTYPE error (not a list)
    Get("key")                             // Would be executed, but no response would be returned due to the error
res, err := client.Exec(ctx, *transaction, true)
fmt.Printf("Batch execution aborted: %+v\n", res)
// Output: Batch execution aborted: WRONGTYPE: Operation against a key holding the wrong kind of value

BatchOptions

Configuration for standalone batches.

Option Type Default Description
timeout time.Duration Client-level request timeout (e.g., 5000 ms) Maximum time to wait for the batch response. If exceeded, a timeout error is returned for the batch.
import "github.com/valkey-io/valkey-glide/go/v2/pipeline"

options := pipeline.NewStandaloneBatchOptions().
	WithTimeout(2 * time.Second)  // 2-second timeout

ClusterBatchOptions

Configuration for cluster batches.

Option Type Default Description
timeout time.Duration Client’s requestTimeout Maximum time to wait for entire cluster batch response.
retryStrategy ClusterBatchRetryStrategy nil (defaults to no retries) Configures retry settings for server and connection errors. Not supported ifisAtomic = true — retry strategies only apply to non-atomic (pipeline) batches.
route config.SingleNodeRoute nil Configures single-node routing for the batch request.

ClusterBatchRetryStrategy

Defines retry behavior (only for non-atomic cluster batches).

Option Type Default Description
retryServerError bool false Retry commands that fail with retriable server errors (e.g.TRYAGAIN). May cause out-of-order results.
retryConnectionError bool false Retry entire batch on connection failures. May cause duplicate executions since server might have processed the request before failure.
import "github.com/valkey-io/valkey-glide/go/v2/pipeline"

retryStrategy := pipeline.NewClusterBatchRetryStrategy().
	WithRetryConnectionError(true).
	WithRetryServerError(true)

Note: The ClusterBatchRetryStrategy configuration is only for non-atomic cluster batches, If provided for an atomic cluster batch (a cluster transaction), an error will be returned.

Full usage

import "github.com/valkey-io/valkey-glide/go/v2/pipeline"

options := pipeline.NewStandaloneBatchOptions().
	WithTimeout(1 * time.Second).  // 1-second timeout
	WithRetryStrategy(pipeline.NewClusterBatchRetryStrategy().
		WithRetryConnectionError(true).
		WithRetryServerError(true)
	).
	WithRoute(config.RandomRoute)

Configuration Details

Timeout

  • Specifies the maximum time to wait for the batch (atomic or non-atomic) request to complete.
  • If the timeout is reached before receiving all responses, the batch fails with a timeout error.
  • Defaults to the client’s requestTimeout if not explicitly set.

Retry Strategies (Cluster Only, Non-Atomic Batches)

  • Retry on Server Errors

    • Applies when a command fails with a retriable server error (e.g., TRYAGAIN).
    • GLIDE will automatically retry the failed command on the same node or the new master, depending on the topology update.
    • ⚠️ Caveat: Retried commands may arrive later than subsequent commands, leading to out-of-order execution if commands target the same slot.
  • Retry on Connection Errors

    • If a connection error occurs, the entire batch (or sub-pipeline, Read more in Multi-Node support) is retried from the start.
    • ⚠️ Caveat: If the server received and processed some or all commands before the connection failure, retrying the batch may lead to duplicate executions.

Route (Cluster Only)

Configures single-node routing for the batch request. The client will send the batch to the specified node defined by route. If a redirection error occurs:

  • For Atomic Batches (Transactions): The entire transaction will be redirected.
  • For Non-Atomic Batches (Pipelines): only the commands that encountered redirection errors will be redirected.

Usage Examples

Standalone (Atomic Batch)

import (
	glide "github.com/valkey-io/valkey-glide/go/v2"
	"github.com/valkey-io/valkey-glide/go/v2/config"
	"github.com/valkey-io/valkey-glide/go/v2/pipeline"
)

// Create client configuration
clientConf := config.NewClientConfiguration().
		WithAddress(WithAddress(&config.NodeAddress{Host: "localhost", Port: 6379})

// Initialize client
client, _ := glide.NewClient(config)

// Configure batch options
options := pipeline.NewStandaloneBatchOptions().
	WithTimeout(2 * time.Second)  // 2-second timeout

// Create atomic batch
transaction := pipeline.NewStandaloneBatch(true).
    Set("account:source", "100").
    Set("account:dest", "0").
    IncrBy("account:dest", 50).
    DecrBy("account:source", 50).
    Get("account:source")

// Execute with raiseOnError = true
res, err := client.Exec(ctx, *transaction, true)
fmt.Printf("Atomic Batch Results: %+v\n", res)
// Atomic Batch Results: [OK OK 50 50 50]

Standalone (Non-Atomic Batch)

import (
	glide "github.com/valkey-io/valkey-glide/go/v2"
	"github.com/valkey-io/valkey-glide/go/v2/config"
	"github.com/valkey-io/valkey-glide/go/v2/pipeline"
)

// Create client configuration
clientConf := config.NewClientConfiguration().
		WithAddress(WithAddress(&config.NodeAddress{Host: "localhost", Port: 6379})

// Initialize client
client, _ := glide.NewClient(config)

// Configure batch options
options := pipeline.NewStandaloneBatchOptions().
	WithTimeout(2 * time.Second)  // 2-second timeout

// Create atomic batch
pipeline := pipeline.NewStandaloneBatch(false).
    Set("temp:key1", "value1").
    Set("temp:key2", "value2").
    Get("temp:key1").
    Get("temp:key2")

res, err := client.Exec(ctx, *pipeline, true)
fmt.Printf("Atomic Batch Results: %+v\n", res)
// Pipeline Results: [OK OK value1 value2]

Cluster (Atomic Batch)

import (
	glide "github.com/valkey-io/valkey-glide/go/v2"
	"github.com/valkey-io/valkey-glide/go/v2/config"
	"github.com/valkey-io/valkey-glide/go/v2/pipeline"
)

// Create client configuration
clientConf := config.NewClusterClientConfiguration().
		WithAddress(WithAddress(&config.NodeAddress{Host: "localhost", Port: 6379})

// Initialize client
client, _ := glide.NewClusterClient(config)

// Configure batch options
options := pipeline.NewClusterBatchOptions().
	WithTimeout(3 * time.Second)  // 3-second timeout

// Create atomic batch
transaction := pipeline.NewClusterBatch(true).
    Set("{user:100}:visits", "1")
    IncrBy("{user:100}:visits", 5)
    Get("{user:100}:visits")

// Execute with raiseOnError = true
res, err := client.Exec(ctx, *transaction, true)
fmt.Printf("Atomic Batch Results: %+v\n", res)
// Atomic Cluster Batch Results: [OK 6 6]

Important: If you attempt to include keys from different slots, the batch creation will throw an exception informing you that keys must map to the same slot when isAtomic = true.

Cluster (Non-Atomic Batch / Pipeline)

import (
	glide "github.com/valkey-io/valkey-glide/go/v2"
	"github.com/valkey-io/valkey-glide/go/v2/config"
	"github.com/valkey-io/valkey-glide/go/v2/pipeline"
)

// Create client configuration
clientConf := config.NewClusterClientConfiguration().
		WithAddress(WithAddress(&config.NodeAddress{Host: "localhost", Port: 6379})

// Initialize client
client, _ := glide.NewClusterClient(config)

// Configure retry strategy and pipeline options
retryStrategy := pipeline.NewClusterBatchRetryStrategy().
	WithRetryConnectionError(true).
	WithRetryServerError(false)

options := pipeline.NewClusterBatchOptions().
	WithTimeout(5 * time.Second)  // 5-second timeout
	WithRetryStrategy(retryStrategy)

// Create pipeline spanning multiple slots
pipeline := pipeline.NewClusterBatch(false).
    Set("page:home:views", "100").
    IncrBy("page:home:views", 25).
    Get("page:home:views").
    Lpush("recent:logins", "user1").
    Lpush("recent:logins", "user2").
    Lrange("recent:logins", 0, 1)

// Execute with raiseOnError = false
res, err := client.ExecWithOptions(ctx, *pipeline, false, *options)
fmt.Printf("Pipeline Cluster Results: %+v\n", res)
// Pipeline Cluster Results: [OK 125 125 1 2 [user2 user1]]

Multi-Node Support

While atomic batches (transactions) are restricted to a single Valkey node — all commands must map to the same hash slot in cluster mode—non-atomic batches (pipelines) can span multiple nodes. This enables operations that involve keys located in different slots or even multi-node commands.

When GLIDE processes a pipeline:

  1. Slot Calculation and Routing: For each key-based command (e.g., GET, SET), GLIDE computes the hash slot and determines which node owns that slot. If a command does not reference a key (e.g., INFO), it follows the command’s default request policy.
  2. Grouping into Sub-Pipelines: Commands targeting the same node are grouped together into a sub-pipeline. Each sub-pipeline contains all commands destined for a specific node.
  3. Dispatching Sub-Pipelines: GLIDE sends each sub-pipeline independently to its target node as a pipelined request.
  4. Aggregating Responses: Once all sub-pipelines return their results, GLIDE reassembles the responses into a single array, preserving the original command order. Multi-node commands are automatically split and dispatched appropriately.

Retry Strategy in Pipelines

When errors occur during pipeline execution, GLIDE handles them efficiently and granularly — each command in the pipeline receives its own response, whether successful or not. This means pipeline execution is not all-or-nothing: some commands may succeed while others may return errors (See the ClusterBatchRetryStrategy configuration and error handling details in the classes and API section for how to handle these errors programmatically).

GLIDE distinguishes between different types of errors and handles them as follows:

  • Redirection Errors (e.g., MOVED or ASK): These are always handled automatically. GLIDE will update the topology map if needed and redirect the command to the appropriate node, regardless of the retry configuration.
  • Retriable Server Errors (e.g., TRYAGAIN): If the retryServerError option is enabled in the batch's retry strategy, GLIDE will retry commands that fail with retriable server errors. ⚠️ Retrying may cause out-of-order execution for commands targeting the same slot.
  • Connection Errors: If the retryConnectionError option is enabled, GLIDE will retry the batch if a connection failure occurs. ⚠️ Retrying after a connection error may result in duplicate executions, since the server might have already received and processed the request before the error occurred.

Retry strategies are currently supported only for non-atomic (pipeline) cluster batches. You can configure these using the ClusterBatchRetryStrategy options:

  • retryServerError: Retry on server errors.
  • retryConnectionError: Retry on connection failures.

Example Scenario:

Suppose you issue the following commands:

MGET key {key}:1
SET key "value"

When keys are empty, the result is expected to be:

[null, null]
OK

However, suppose the slot of key is migrating. In this case, both commands will return an ASK error and be redirected. Upon ASK redirection, a multi-key command (like MGET) may return a TRYAGAIN error (triggering a retry), while the SET command succeeds immediately. This can result in an unintended reordering of commands if the first command is retried after the slot stabilizes:

["value", null]
OK

OpenTelemetry (GLIDE 2.0)

Observability is consistently one of the top feature requests by customers. Valkey GLIDE 2.0 introduces support for OpenTelemetry (OTel), enabling developers to gain deep insights into client-side performance and behavior in distributed systems. OTel is an open source, vendor-neutral framework that provides APIs, SDKs, and tools for generating, collecting, and exporting telemetry data—such as traces, metrics, and logs. It supports multiple programming languages and integrates with various observability backends like Prometheus, Jaeger, and AWS CloudWatch.

How It Works

GLIDE's OpenTelemetry integration is designed to be both powerful and easy to adopt. Once an OTel collector endpoint is configured, GLIDE begins emitting default metrics and traces automatically—no additional code changes are required. This simplifies the path to observability best practices and minimizes disruption to existing workflows.

Metrics Overview

GLIDE emits several built-in metrics out of the box. These metrics can be used to build dashboards, configure alerts, and monitor performance trends:

  • Timeouts: Number of requests that exceeded their timeout duration.
  • Retries: Count of operations retried due to transient errors or topology changes.
  • Moved Errors: Number of MOVED responses received, indicating key reallocation in the cluster.

These metrics are emitted to your configured OpenTelemetry collector and can be viewed in any supported backend (Prometheus, CloudWatch, etc.).

Tracing Integration

GLIDE creates a trace span for each Valkey command, giving detailed visibility into client-side performance. Each trace captures:

  • The entire command lifecycle: from creation to completion or failure.
  • A nested send_command span, measuring communication time with the Valkey server.
  • A status tag indicating success or error for each span, helping you identify failure patterns.

This distinction helps developers separate client-side queuing latency from server communication delays, making it easier to troubleshoot performance issues.

⚠ Note: Some advanced commands are not yet included in tracing instrumentation:

  • The SCAN family of commands (SCAN, SSCAN, HSCAN, ZSCAN)
  • Lua scripting commands (EVAL, EVALSHA)

Support for these commands will be added in a future version as we continue to expand tracing coverage.

Even with these exceptions, GLIDE 2.0 provides comprehensive insights across the vast majority of standard operations, making it easy to adopt observability best practices with minimal effort.

Getting Started

To begin collecting telemetry data with GLIDE 2.0:

  • Set up an OpenTelemetry Collector to receive trace and metric data.
  • Configure the GLIDE client with the endpoint to your collector.
  • Alternatively, you can configure GLIDE to export telemetry data directly to a local file for development or debugging purposes, without requiring a running collector.

GLIDE does not export data directly to third-party services—instead, it sends data to your collector, which routes it to your backend (e.g., CloudWatch, Prometheus, Jaeger).

Supported Collector Protocols

You can configure the OTel collector endpoint using one of the following protocols:

  • http:// or https:// - Send data via HTTP(S)
  • grpc:// - Use gRPC for efficient telemetry transmission
  • file:// - Write telemetry data to a local file (ideal for local dev/debugging)

Optional Parameters

When initializing OpenTelemetry, you can customize behavior using the openTelemetryConfig object. Note: Both traces and metrics are optional—but at least one must be provided in the openTelemetryConfig. If neither is set, OpenTelemetry will not emit any data.

Tracing

openTelemetryConfig.traces
  • endpoint (required): The trace collector endpoint.
  • samplePercentage (optional): Percentage (0–100) of commands to sample for tracing. Default: 1.
    • For production, a low sampling rate (1–5%) is recommended to balance performance and insight.

Metrics

openTelemetryConfig.metrics
  • endpoint (required): The metrics collector endpoint.

Flush Interval

openTelemetryConfig.flushIntervalMs
  • (optional): Time in milliseconds between flushes to the collector. Default: 5000.

File Exporter Details

If using file:// as the endpoint:

  • The path must begin with file://.
  • If a directory is provided (or no file extension), data is written to signals.json in that directory.
  • If a filename is included, it will be used as-is.
  • The parent directory must already exist.
  • Data is appended, not overwritten.

Validation Rules

  • flushIntervalMs must be a positive integer.
  • samplePercentage must be between 0 and 100.
  • File exporter paths must start with file:// and have an existing parent directory.
  • Invalid configuration will throw an error synchronously when calling OpenTelemetry.init().

⚠️ Important: OpenTelemetry.init() can only be called once per process. Subsequent calls will be ignored. To change configuration, restart the process.

Full Example (Go)

import "github.com/valkey-io/valkey-glide/go/v2"

config := glide.OpenTelemetryConfig{
	Traces: &glide.OpenTelemetryTracesConfig{
		Endpoint: "http://localhost:4318/v1/traces",
		SamplePercentage: 10, // Optional, defaults to 1. Can also be changed at runtime via `SetSamplePercentage()`
	},
	Metrics: &glide.OpenTelemetryMetricsConfig{
		Endpoint: "http://localhost:4318/v1/metrics",
	},
	FlushIntervalMs: &interval, // Optional, defaults to 5000, e.g. interval := int64(1000)
}
err := glide.GetOtelInstance().Init(config)
if err != nil {
	log.Fatalf("Failed to initialize OpenTelemetry: %v", err)
}

Advanced Configuration Settings

Authentication

By default, when connecting to Valkey, Valkey GLIDE operates in an unauthenticated mode.

Valkey GLIDE also offers support for an authenticated connection mode.

In authenticated mode, you have the following options:

  • Use both a username and password, which is recommended and configured through ACLs on the server.
  • Use a password only, which is applicable if the server is configured with the requirepass setting.

To provide the necessary authentication credentials to the client, you can use the ServerCredentials struct.

Example - Connecting with Username and Password to a Cluster

import (
    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectClusterWithCredentials() {
    myConfig := config.NewClusterClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "address.example.com", Port: 6379}).
        WithCredentials(config.NewServerCredentials("user1", "passwordA"))

    client, err := glide.NewClusterClient(myConfig)
}

Example - Connecting with Username and Password to a Standalone

import (
    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectStandaloneWithCredentials() {
    myConfig := config.NewClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "primary.example.com", Port: 6379}).
        WithCredentials(config.NewServerCredentials("user1", "passwordA"))

    client, err := glide.NewClient(myConfig)
}

TLS

Valkey GLIDE supports secure TLS connections to a data store.

It's important to note that TLS support in Valkey GLIDE relies on rustls. Currently, Valkey GLIDE employs the default rustls settings with no option for customization.

Example - Connecting with TLS Mode Enabled to a Cluster

import (
    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectClusterWithTLS() {
    myConfig := config.NewClusterClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "address.example.com", Port: 6379}).
        WithUseTLS(true)

    client, err := glide.NewClusterClient(myConfig)
}

Example - Connecting with TLS Mode Enabled to a Standalone server

import (
    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectStandaloneWithTLS() {
    myConfig := config.NewClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "primary.example.com", Port: 6379}).
        WithUseTLS(true)

    client, err := glide.NewClient(myConfig)
}

Read Strategy

By default, Valkey GLIDE directs read commands to the primary node that owns a specific slot. For applications that prioritize read throughput and can tolerate possibly stale data, Valkey GLIDE provides the flexibility to route reads to replica nodes.

Valkey GLIDE provides support for next read strategies, allowing you to choose the one that best fits your specific use case.

Strategy Description
Primary Always read from primary, in order to get the freshest data.
PreferReplica Spread requests between all replicas in a round robin manner. If no replica is available, route the requests to the primary.
AZAffinity Spread the read requests between replicas in the same client's availability zone in a round robin manner, falling back to other replicas or the primary if needed.
AzAffinityReplicaAndPrimary Spread the read requests among nodes within the client's Availability Zone (AZ) in a round robin manner, prioritizing local replicas, then the local primary, and falling back to any replica or the primary if needed.

Example - Use PreferReplica Read Strategy

import (
    "context"

    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectClusterWithReadStrategyPreferReplica() {
    myConfig := config.NewClusterClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "address.example.com", Port: 6379}).
        WithReadFrom(config.PreferReplica)

    client, _ := glide.NewClusterClient(myConfig)

    client.Set(context.Background(), "key1", "val1")

    // Get will read from one of the replicas
    client.Get(context.Background(),"key1")
}

Example - Use AZAffinity Read Strategy

If ReadFrom strategy is AZAffinity, 'clientAZ' setting is required to ensures that readonly commands are directed to replicas within the specified AZ if exits.

import (
    "context"

    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectClusterWithReadStrategyAZAffinity() {
    myConfig := config.NewClusterClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "address.example.com", Port: 6379}).
        WithReadFrom(config.AzAffinity).
        WithClientAZ("us-east-1a")

    client, _ := glide.NewClusterClient(myConfig)

    client.Set(context.Background(), "key1", "val1")

    // Get will read from one of the replicas in the same client's availability zone if exits.
    client.Get(context.Background(),"key1")
}

Example - Use AzAffinityReplicaAndPrimary Read Strategy

If ReadFrom strategy is AzAffinityReplicaAndPrimary, 'clientAZ' setting is required to ensures that readonly commands are directed to replicas or primary within the specified AZ if exits.

import (
    "context"

    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectClusterWithReadStrategyAZAffinity() {
    myConfig := config.NewClusterClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "address.example.com", Port: 6379}).
        WithReadFrom(config.AzAffinityReplicaAndPrimary).
        WithClientAZ("us-east-1a")

    client, _ := glide.NewClusterClient(myConfig)

    client.Set(context.Background(), "key1", "val1")

    // Get will read from one of the replicas or the primary in the same client's availability zone if exits.
    client.Get(context.Background(),"key1")
}

Timeouts and Reconnect Strategy

Valkey GLIDE allows you to configure timeout settings and reconnect strategies. These configurations can be applied through the ClusterClientConfiguration and ClientConfiguration parameters.

Configuration setting Description Default value
requestTimeout This specified time duration, measured in milliseconds, represents the period during which the client will await the completion of a request. This time frame includes the process of sending the request, waiting for a response from the node(s), and any necessary reconnection or retry attempts. If a pending request exceeds the specified timeout, it will trigger a timeout error. If no timeout value is explicitly set, a default value will be employed. 250 milliseconds
reconnectStrategy The reconnection strategy defines how and when reconnection attempts are made in the event of connection failures. Exponential backoff

Example - Setting Increased Request Timeout for Long-Running Commands

import (
    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func ConnectClusterWithTimeout() {
    myConfig := config.NewClusterClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "address.example.com", Port: 6379}).
        WithRequestTimeout(500)

    client, err := glide.NewClusterClient(myConfig)
}

Full Example with All Client Configurations

import (
    glide "github.com/valkey-io/valkey-glide/go/v2"
    "github.com/valkey-io/valkey-glide/go/v2/config"
)

func FullConfigExample() {
    // GlideClient example
    standaloneConfig := config.NewClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "primary.example.com", Port: 6379}).
        WithClientName("some client name").
        WithCredentials(config.NewServerCredentials("user1", "passwordA")).
        WithDatabaseId(1).
        WithReadFrom(config.PreferReplica).
        WithReconnectStrategy(config.NewBackoffStrategy(5, 10, 50)).
        WithRequestTimeout(500).
        WithUseTLS(true)

    standaloneClient, err := glide.NewClient(standaloneConfig)

    // GlideClusterClient example
    clusterConfig := config.NewClusterClientConfiguration().
        WithAddress(&config.NodeAddress{Host: "address.example.com", Port: 6379}).
        WithClientName("some client name").
        WithCredentials(config.NewServerCredentials("user1", "passwordA")).
        WithReadFrom(config.PreferReplica).
        WithRequestTimeout(500).
        WithUseTLS(true)

    clusterClient, err := glide.NewClusterClient(clusterConfig)
}