Redis Integration

Learn how to use @inceptools/db with Redis for caching and data storage.

Getting Started with Redis

@inceptools/db provides a simple interface for working with Redis. Here's how to get started:

import { RedisService, SUPPORTED_DBS } from "@inceptools/db";

// Create a Redis service instance
const redisService = new RedisService({
  type: SUPPORTED_DBS.REDIS,
  connectionString: "redis://localhost:6379",
});

// Connect to Redis
await redisService.connect();

// Basic operations
await redisService.set("key", "value");
const value = await redisService.get("key");
console.log(value); // "value"

// Close the connection when done
await redisService.closeConnection();

Basic Operations

Perform basic Redis operations:

// String operations
import { RedisService, SUPPORTED_DBS } from "@inceptools/db";

const redisService = new RedisService({
  type: SUPPORTED_DBS.REDIS,
  connectionString: "redis://localhost:6379",
});

await redisService.set("user:1:name", "John Doe");
await redisService.set("user:1:email", "[email protected]");
await redisService.set("counter", "10");

const name = await redisService.get("user:1:name");
console.log(name); // "John Doe"

// Set expiration (TTL)
await redisService.set("session:123", "session-data", "EX", 3600); // Expires in 1 hour

// Check if a key exists
const exists = await redisService.exists("user:1:name");
console.log(exists); // 1 (true)

// Delete a key
await redisService.del("user:1:name");

// Increment/decrement
await redisService.incr("counter");
const newCount = await redisService.get("counter");
console.log(newCount); // "11"

Caching Strategies

Implement common caching patterns with Redis:

Strategy
Cache-Aside Pattern
// Cache-Aside Pattern
import { RedisService, SUPPORTED_DBS } from "@inceptools/db";

const redisService = new RedisService({
  type: SUPPORTED_DBS.REDIS,
  connectionString: "redis://localhost:6379",
});

async function getUserWithCache(userId) {
  const cacheKey = `user:${userId}`;

  // Try to get from cache first
  const cachedUser = await redisService.get(cacheKey);
  if (cachedUser) {
    return JSON.parse(cachedUser);
  }

  // If not in cache, get from database
  const user = await database.getUserById(userId);

  if (user) {
    // Store in cache for 1 hour
    await redisService.set(cacheKey, JSON.stringify(user), "EX", 3600);
  }

  return user;
}
Strategy
Write-Through Cache
// Write-Through Cache Pattern
async function updateUserWithCache(userId, userData) {
  // Update the database first
  const updatedUser = await database.updateUser(userId, userData);

  // Then update the cache
  const cacheKey = `user:${userId}`;
  await redisService.set(cacheKey, JSON.stringify(updatedUser), "EX", 3600);

  return updatedUser;
}
Strategy
Rate Limiting
// Rate Limiting
async function rateLimit(userId, endpoint, maxRequests, timeWindowSeconds) {
  const key = `ratelimit:${userId}:${endpoint}`;

  // Increment the counter
  const count = await redisService.incr(key);

  // Set expiration if this is the first request in the window
  if (count === 1) {
    await redisService.expire(key, timeWindowSeconds);
  }

  // Check if rate limit is exceeded
  if (count > maxRequests) {
    return false; // Rate limit exceeded
  }

  return true; // Request allowed
}