CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-redis

A modern, high performance Redis client for Node.js with full TypeScript support and all Redis Stack modules

Pending
Overview
Eval results
Files

client-management.mddocs/

Client Management

Core functionality for creating Redis clients and managing connections, including support for single instances, clusters, and sentinel configurations with connection pooling and authentication.

Capabilities

Client Creation

Creates a Redis client with default modules pre-loaded and optional configuration.

/**
 * Creates a Redis client with default modules (bloom, json, search, time-series) pre-loaded
 * @param options - Optional client configuration
 * @returns Configured Redis client instance
 */
function createClient<M, F, S, RESP, TYPE_MAPPING>(
  options?: RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>
): RedisClientType<RedisDefaultModules & M, F, S, RESP, TYPE_MAPPING>;

interface RedisClientOptions<M = RedisModules, F = RedisFunctions, S = RedisScripts, RESP = RespVersions, TYPE_MAPPING = TypeMapping> {
  /** Connection URL in format redis://[username[:password]@]host[:port][/database] */
  url?: string;
  /** Socket configuration for fine-grained connection control */
  socket?: RedisSocketOptions;
  /** Username for authentication */
  username?: string;
  /** Password for authentication */
  password?: string;
  /** Credentials provider for dynamic authentication */
  credentialsProvider?: CredentialsProvider;
  /** Client name for identification */
  name?: string;
  /** Database number to select (0-15 typically) */
  database?: number;
  /** Maximum length of commands queue */
  commandsQueueMaxLength?: number;
  /** Disable offline queue behavior */
  disableOfflineQueue?: boolean;
  /** Enable readonly mode */
  readonly?: boolean;
  /** Ping interval for keep-alive (milliseconds) */
  pingInterval?: number;
  /** Default command options */
  commandOptions?: CommandOptions;
  /** Client-side cache configuration */
  clientSideCache?: ClientSideCacheOptions;
  /** Additional modules to load */
  modules?: M;
  /** Redis functions to register */  
  functions?: F;
  /** Redis scripts to define */
  scripts?: S;
}

interface RedisSocketOptions {
  /** Host to connect to */
  host?: string;
  /** Port to connect to */
  port?: number;
  /** Connection path for Unix sockets */
  path?: string;
  /** Connection timeout in milliseconds */
  connectTimeout?: number;
  /** Command timeout in milliseconds */
  commandTimeout?: number;
  /** Enable TLS/SSL */
  tls?: boolean;
  /** Additional socket options */
  [key: string]: any;
}

Usage Examples:

import { createClient } from "redis";

// Basic connection
const client = createClient();

// Connection with URL
const client = createClient({
  url: "redis://username:password@localhost:6379/0"
});

// Connection with detailed options
const client = createClient({
  socket: {
    host: "localhost",
    port: 6379,
    connectTimeout: 5000,
    commandTimeout: 5000
  },
  username: "default",
  password: "secret",
  database: 0,
  name: "my-client"
});

// Connection with TLS
const client = createClient({
  url: "rediss://username:password@redis.example.com:6380",
  socket: {
    tls: true,
    rejectUnauthorized: false
  }
});

Cluster Client Creation

Creates a Redis cluster client for distributed Redis setups.

/**
 * Creates a Redis cluster client for distributed Redis setups
 * @param options - Cluster configuration including root nodes
 * @returns Configured Redis cluster client instance
 */
function createCluster<M, F, S, RESP, TYPE_MAPPING>(
  options: RedisClusterOptions<M, F, S, RESP, TYPE_MAPPING>
): RedisClusterType<RedisDefaultModules & M, F, S, RESP, TYPE_MAPPING>;

interface RedisClusterOptions<M = RedisModules, F = RedisFunctions, S = RedisScripts, RESP = RespVersions, TYPE_MAPPING = TypeMapping> {
  /** Array of cluster root node configurations */
  rootNodes: Array<RedisClusterNode>;
  /** Default options applied to all nodes */
  defaults?: Partial<RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>>;
  /** Minimize connections by reusing existing connections */
  minimizeConnections?: boolean;
  /** Use replica nodes for read operations */
  useReplicas?: boolean;
  /** Maximum command redirections before giving up */
  maxCommandRedirections?: number;
  /** Node address mapping for NAT/proxy environments */
  nodeAddressMap?: Record<string, RedisClusterNode>;
  /** Additional modules to load */
  modules?: M;
  /** Redis functions to register */
  functions?: F;
  /** Redis scripts to define */
  scripts?: S;
}

interface RedisClusterNode {
  /** Node host */
  host: string;
  /** Node port */
  port: number;
}

Usage Examples:

import { createCluster } from "redis";

// Basic cluster setup
const cluster = createCluster({
  rootNodes: [
    { host: "localhost", port: 7000 },
    { host: "localhost", port: 7001 },
    { host: "localhost", port: 7002 }
  ]
});

// Cluster with replica reads
const cluster = createCluster({
  rootNodes: [
    { host: "redis-1.example.com", port: 6379 },
    { host: "redis-2.example.com", port: 6379 },
    { host: "redis-3.example.com", port: 6379 }
  ],
  useReplicas: true,
  maxCommandRedirections: 16,
  defaults: {
    username: "cluster-user",
    password: "cluster-password"
  }
});

Sentinel Client Creation

Creates a Redis sentinel client for high availability setups.

/**
 * Creates a Redis sentinel client for high availability setups
 * @param options - Sentinel configuration including sentinel nodes
 * @returns Configured Redis sentinel client instance
 */
function createSentinel<M, F, S, RESP, TYPE_MAPPING>(
  options: RedisSentinelOptions<M, F, S, RESP, TYPE_MAPPING>
): RedisSentinelType<RedisDefaultModules & M, F, S, RESP, TYPE_MAPPING>;

interface RedisSentinelOptions<M = RedisModules, F = RedisFunctions, S = RedisScripts, RESP = RespVersions, TYPE_MAPPING = TypeMapping> {
  /** Sentinel service name */
  name: string;
  /** Array of sentinel node configurations */
  sentinelRootNodes: Array<RedisSentinelNode>;
  /** Maximum command rediscoveries before giving up */
  maxCommandRediscovers?: number;
  /** Default options for Redis master/replica nodes */
  nodeClientOptions?: Partial<RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>>;
  /** Options for sentinel client connections */
  sentinelClientOptions?: Partial<RedisClientOptions>;
  /** Connection pool size for master nodes */
  masterPoolSize?: number;
  /** Connection pool size for replica nodes */
  replicaPoolSize?: number;
  /** Interval for scanning sentinel nodes (milliseconds) */
  scanInterval?: number;
  /** Additional modules to load */
  modules?: M;
  /** Redis functions to register */
  functions?: F;
  /** Redis scripts to define */
  scripts?: S;
}

interface RedisSentinelNode {
  /** Sentinel host */
  host: string;
  /** Sentinel port */
  port: number;
}

Usage Examples:

import { createSentinel } from "redis";

// Basic sentinel setup
const sentinel = createSentinel({
  name: "mymaster",
  sentinelRootNodes: [
    { host: "sentinel-1.example.com", port: 26379 },
    { host: "sentinel-2.example.com", port: 26379 },
    { host: "sentinel-3.example.com", port: 26379 }
  ]
});

// Sentinel with custom configuration
const sentinel = createSentinel({
  name: "mymaster",
  sentinelRootNodes: [
    { host: "localhost", port: 26379 },
    { host: "localhost", port: 26380 },
    { host: "localhost", port: 26381 }
  ],
  nodeClientOptions: {
    username: "redis-user",
    password: "redis-password",
    database: 0
  },
  masterPoolSize: 10,
  replicaPoolSize: 5,
  scanInterval: 30000
});

Connection Management

Core methods for managing client connections and lifecycle.

interface RedisClientType<M, F, S, RESP, TYPE_MAPPING> {
  /** Connect to Redis server */
  connect(): Promise<RedisClientType<M, F, S, RESP, TYPE_MAPPING>>;
  /** Disconnect from Redis server (deprecated, use close/destroy) */
  disconnect(): Promise<void>;
  /** Graceful quit (deprecated, use close) */
  quit(): Promise<string>;
  /** Close client, wait for pending commands to complete */
  close(): Promise<void>;
  /** Destroy client immediately, reject pending commands */
  destroy(): void;
  
  /** Whether socket is open */
  readonly isOpen: boolean;
  /** Whether client is ready for commands */
  readonly isReady: boolean;
  /** Whether pub/sub is active */
  readonly isPubSubActive: boolean;
  /** Socket reconnection counter */
  readonly socketEpoch: number;
  /** Whether WATCH is active */
  readonly isWatching: boolean;
  /** Whether WATCH has been invalidated */
  readonly isDirtyWatch: boolean;
}

Usage Examples:

import { createClient } from "redis";

const client = createClient();

// Connect and check status
await client.connect();
console.log("Connected:", client.isOpen);
console.log("Ready:", client.isReady);

// Perform operations
await client.set("key", "value");

// Graceful shutdown
await client.close();

// Or immediate destruction
client.destroy();

Client Utilities

Additional utility methods for client management and configuration.

interface RedisClientType<M, F, S, RESP, TYPE_MAPPING> {
  /** Create a duplicate client with optional overrides */
  duplicate(overrides?: Partial<RedisClientOptions>): RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
  
  /** Create a proxy with command options */
  withCommandOptions<OPTIONS>(options: CommandOptions<OPTIONS>): RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
  
  /** Create a proxy with type mapping */
  withTypeMapping<NEW_TYPE_MAPPING>(typeMapping: NEW_TYPE_MAPPING): RedisClientType<M, F, S, RESP, NEW_TYPE_MAPPING>;
  
  /** Create a proxy with abort signal */
  withAbortSignal(signal: AbortSignal): RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
  
  /** Create a proxy that executes commands ASAP */
  asap(): RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
  
  /** Reset client to default state */
  reset(): Promise<void>;
  
  /** Ref the underlying socket */
  ref(): void;
  
  /** Unref the underlying socket */
  unref(): void;
}

Usage Examples:

import { createClient } from "redis";

const client = createClient();
await client.connect();

// Create a duplicate with different database
const client2 = client.duplicate({ database: 1 });
await client2.connect();

// Create proxy with command options
const clientWithTimeout = client.withCommandOptions({
  timeout: 5000
});

// Create proxy with abort signal
const controller = new AbortController();
const clientWithAbort = client.withAbortSignal(controller.signal);

// Reset client state
await client.reset();

Connection Pool Management

Connection pooling functionality for high-performance applications.

/**
 * Creates a Redis client pool for connection pooling
 * @param options - Pool configuration options
 * @returns Redis client pool instance
 */
function createClientPool(options?: RedisPoolOptions): RedisClientPoolType;

interface RedisPoolOptions {
  /** Minimum number of connections to maintain */
  minimum?: number;
  /** Maximum number of connections allowed */
  maximum?: number;
  /** Maximum time a connection can be idle (milliseconds) */
  idleTimeout?: number;
  /** Time between connection validation checks (milliseconds) */
  validationInterval?: number;
  /** Function to validate connections */
  validate?: (client: RedisClientType) => Promise<boolean>;
}

interface RedisClientPoolType {
  /** Execute function with a client from the pool */
  use<T>(fn: (client: RedisClientType) => Promise<T>): Promise<T>;
  /** Get pool statistics */
  stats(): PoolStats;
  /** Destroy the pool and all connections */
  destroy(): Promise<void>;
}

interface PoolStats {
  /** Total connections in pool */
  total: number;
  /** Available connections */
  available: number;
  /** Connections currently in use */
  inUse: number;
  /** Pending connection requests */
  pending: number;
}

Usage Examples:

import { createClient, createClientPool } from "redis";

// Create client and pool
const client = createClient();
const pool = createClientPool({
  minimum: 2,
  maximum: 10,
  idleTimeout: 30000
});

// Use pool for operations
const result = await pool.use(async (client) => {
  await client.set("key", "value");
  return client.get("key");
});

// Check pool statistics
const stats = pool.stats();
console.log(`Pool: ${stats.inUse}/${stats.total} connections in use`);

// Cleanup
await pool.destroy();

Error Handling

// Connection errors
class ConnectionTimeoutError extends Error {
  constructor(message?: string);
}

class ClientClosedError extends Error {
  constructor(message?: string);
}

class ClientOfflineError extends Error {
  constructor(message?: string);
}

// Redis errors
class ErrorReply extends Error {
  constructor(message: string);
}

class ReconnectStrategyError extends Error {
  constructor(message?: string);
}

Install with Tessl CLI

npx tessl i tessl/npm-redis

docs

bloom-filters.md

client-management.md

index.md

json-operations.md

redis-commands.md

search-indexing.md

time-series.md

tile.json