Redis Cache Configuration

CQL now supports configurable cache stores, allowing you to choose between in-memory caching and Redis-based caching for improved performance and scalability.

Overview

The cache system provides multiple backends:

  • Memory Cache: Fast in-process caching (default)

  • Redis Cache: Distributed caching with persistence and advanced features

Quick Start

Environment Variable Configuration

The simplest way to configure Redis caching is through environment variables:

export CQL_CACHE_TYPE=redis
export CQL_REDIS_URL=redis://localhost:6379/0
export CQL_CACHE_PREFIX=myapp
export CQL_CACHE_TTL=3600
require "cql"

# Configure from environment
CQL::Cache::Cache.configure_from_env

# Use the cache
CQL::Cache::Cache.set("user:123", user_data)
cached_user = CQL::Cache::Cache.get("user:123")

Programmatic Configuration

For more control, configure the cache programmatically:

Configuration Options

General Settings

Option
Environment Variable
Type
Default
Description

type

CQL_CACHE_TYPE

String

"memory"

Cache backend: "memory" or "redis"

key_prefix

CQL_CACHE_PREFIX

String

"cql"

Prefix for all cache keys

default_ttl

CQL_CACHE_TTL

Integer

3600

Default TTL in seconds

Redis-Specific Settings

Option
Environment Variable
Type
Default
Description

redis_url

CQL_REDIS_URL, REDIS_URL

String

"redis://localhost:6379/0"

Redis connection URL

redis_pool_size

CQL_REDIS_POOL_SIZE

Integer

25

Connection pool size

redis_timeout

CQL_REDIS_TIMEOUT

Integer

5

Connection timeout in seconds

Memory Cache Settings

Option
Environment Variable
Type
Default
Description

memory_max_size

CQL_MEMORY_CACHE_MAX_SIZE

Integer

nil

Maximum number of entries (unlimited if nil)

Usage Patterns

Basic Cache Operations

Using CacheStore Factory

Create specific cache instances:

Global Cache Convenience Methods

Advanced Redis Features

Batch Operations

Tag-Based Invalidation

Version-Based Invalidation

Production Configuration

Docker Compose Example

Environment Configuration

High Availability Setup

Performance Monitoring

Cache Statistics

Performance Summary

Best Practices

Key Naming Conventions

TTL Strategy

Error Handling

Memory Management

Migration Guide

From Built-in Cache to Redis

  1. Add Redis dependency (already included):

  2. Update configuration:

  3. Set environment variables:

  4. Test the migration:

Troubleshooting

Common Issues

Redis Connection Errors

High Memory Usage

Performance Issues

Debug Mode

Examples

See the complete working example in examples/redis_cache_demo.cr for a comprehensive demonstration of all features.

Last updated

Was this helpful?