Skip to content

Lazy Connect

GLIDE supports lazy connection mode, which defers the establishment of physical connections to Valkey servers until the first command is executed. This feature reduces startup latency and enables client creation in environments where the server may not be immediately available.

When lazy connect is enabled, the client initialization process completes without establishing actual network connections to the Valkey servers. Instead, connections are created on-demand when the first command is sent. This approach offers several advantages:

  • Reduced Startup Time: Client creation is faster since no network operations are performed during initialization
  • Disconnected Environment Support: Clients can be created even when Valkey servers are temporarily unavailable
  • Resource Efficiency: Network resources are only allocated when actually needed
  • First Command Latency: The initial command will experience additional latency as it must establish the connection before execution
  • Connection Timeout: During the initial connection establishment, the connectionTimeout setting (not requestTimeout) governs the timeout behavior
  • Error Handling: Connection failures will surface when the first command is attempted, not during client creation
import { GlideClient, GlideClusterClient } from "@valkey/valkey-glide";
// Standalone client with lazy connect
const standaloneClient = await GlideClient.createClient({
addresses: [{ host: "localhost", port: 6379 }],
lazyConnect: true,
requestTimeout: 5000
});
// Cluster client with lazy connect
const clusterClient = await GlideClusterClient.createClient({
addresses: [
{ host: "localhost", port: 7000 },
{ host: "localhost", port: 7001 }
],
lazyConnect: true,
requestTimeout: 5000
});
// No connection established yet - this will trigger the connection
const result = await standaloneClient.ping();
  • Use for Development: Lazy connect is particularly useful in development environments where services may start in different orders
  • Container Orchestration: Helpful in containerized environments where Valkey containers might not be ready immediately
  • Health Checks: Consider implementing application-level health checks that account for lazy connection behavior
  • Error Handling: Ensure proper error handling for the first command, as connection failures will manifest at that point