Set Up Redis Cache

This guide shows you how to configure and use Redis for caching in Azu.

Prerequisites

Add the Redis shard to your shard.yml:

dependencies:
  redis:
    github: stefanwille/crystal-redis
    version: ~> 2.9.0

Run shards install.

Basic Setup

Configure the Redis cache store:

require "redis"

Azu.configure do |config|
  config.cache = Azu::Cache::RedisStore.new(
    url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0")
  )
end

Using the Redis Cache

Store and Retrieve Values

Fetch Pattern

Delete Keys

Increment/Decrement

Connection Pool

Use connection pooling for better performance:

Redis Configuration Options

Namespacing

Use namespaces to organize and isolate cache data:

Keys are automatically prefixed:

  • user:1 becomes myapp:production:user:1

Caching Complex Objects

Serialize objects for caching:

Cache-Aside Pattern

Write-Through Caching

Update cache when data changes:

Rate Limiting with Redis

Implement rate limiting:

Session Storage

Store sessions in Redis:

Health Check

Verify Redis connectivity:

See Also

Last updated

Was this helpful?