The Redis Service Types and Configurations module forms a critical part of Sophra’s high-performance caching infrastructure. This TypeScript-based component defines the essential interfaces and types that govern the behavior, configuration, and integration of Redis within the Sophra ecosystem. By leveraging Redis as a distributed in-memory data store, Sophra achieves remarkable speed improvements in data retrieval operations, particularly for frequently accessed information.

At its core, this module establishes the foundation for Redis integration by defining the RedisServiceConfig interface. This interface extends Sophra’s BaseServiceConfig, adding Redis-specific properties such as the Redis client instance, default Time-To-Live (TTL) settings, and an optional search service for cache revalidation. The configuration also includes crucial system-wide components like the logger and environment specification, ensuring seamless integration with Sophra’s observability and deployment frameworks.

The architectural decisions reflected in these type definitions showcase Sophra’s commitment to flexibility and performance. By allowing configurable TTL and including an optional search service, the system can adapt its caching strategy based on data volatility and access patterns. This adaptability is further enhanced by the CacheStrategy interface, which enables fine-grained control over caching behavior for different data types.

Performance optimization is a key focus, as evidenced by the QueryPattern interface. This structure allows Sophra to track and analyze search patterns, providing valuable insights for cache optimization and predictive prefetching. By monitoring metrics such as query frequency, latency, and hit rates, Sophra can dynamically adjust its caching strategies to maximize efficiency.

The RedisHealth interface demonstrates Sophra’s comprehensive approach to system monitoring. It provides a detailed view of the Redis cluster’s operational status, including performance metrics and error tracking. This level of observability is crucial for maintaining the reliability and efficiency of the caching layer in a production environment.

Exported Components

interface RedisServiceConfig extends BaseServiceConfig {
  /** Redis client instance */
  client: RedisClient;
  /** Default TTL in seconds */
  defaultTTL?: number;
  /** Search service for cache revalidation */
  searchService?: DataSyncService;
  logger: Logger;
  environment: "development" | "production" | "test";
}

Implementation Examples

import { createRedisClient } from '@/lib/cortex/redis/client';
import { RedisServiceConfig } from '@/lib/cortex/redis/types';
import { SearchService } from '@/lib/cortex/search/service';
import { Logger } from '@/lib/shared/logger';

const redisConfig: RedisServiceConfig = {
  client: createRedisClient(process.env.SOPHRA_REDIS_URL),
  defaultTTL: 3600, // 1 hour
  searchService: new SearchService(),
  logger: new Logger('RedisService'),
  environment: process.env.NODE_ENV as 'development' | 'production' | 'test'
};

const redisService = new RedisService(redisConfig);

Sophra Integration Details

The Redis service integrates tightly with Sophra’s core systems, particularly the search and analytics services. Here’s a detailed look at the integration patterns:

Error Handling

Robust error handling is crucial for maintaining the reliability of the Redis service. Here’s how errors are managed:

class RedisService {
  private async handleRedisOperation<T>(operation: () => Promise<T>): Promise<T> {
    try {
      return await operation();
    } catch (error) {
      this.config.logger.error('Redis operation failed', { error });
      this.updateHealthStatus(false, error.message);
      throw new RedisOperationError('Redis operation failed', { cause: error });
    }
  }

  async get(key: string): Promise<any> {
    return this.handleRedisOperation(() => this.client.get(key));
  }

  async set(key: string, value: any, ttl?: number): Promise<void> {
    return this.handleRedisOperation(() => this.client.set(key, value, ttl || this.config.defaultTTL));
  }

  private updateHealthStatus(operational: boolean, error?: string) {
    this.health = {
      ...this.health,
      operational,
      errors: error ? [...this.health.errors, error].slice(-5) : this.health.errors
    };
  }
}

Data Flow

The following diagram illustrates the data flow within the Redis service:

Performance Considerations

Performance is a key focus of the Redis service. Here are some optimization strategies employed:

Caching Strategies

  • Implement adaptive TTL based on query patterns
  • Use pipelining for bulk operations
  • Employ read-through and write-through caching patterns

Query Pattern Analysis

  • Analyze QueryPattern data to optimize cache strategies
  • Implement predictive prefetching for frequently accessed data
  • Adjust cache priorities based on access patterns

Security Implementation

Security is paramount in the Redis service implementation:

import { createRedisClient } from '@/lib/cortex/redis/client';

const redisClient = createRedisClient({
  url: process.env.SOPHRA_REDIS_URL,
  password: process.env.REDIS_PASSWORD,
  tls: process.env.NODE_ENV === 'production' ? {} : undefined
});

const redisService = new RedisService({
  client: redisClient,
  // ... other config
});

Ensure that Redis is configured to use TLS in production environments and that access is restricted to authorized services only.

Configuration

The Redis service can be configured using environment variables and runtime options:

SOPHRA_REDIS_URL=redis://localhost:6379
REDIS_PASSWORD=your_secure_password
REDIS_DEFAULT_TTL=3600
NODE_ENV=production

By leveraging these configurations and type definitions, Sophra’s Redis service provides a robust, performant, and secure caching layer that integrates seamlessly with the broader system architecture.