Caching Guide

CQL provides powerful, multi-layered caching that dramatically improves application performance. This guide shows you how to set up and use all caching features effectively.

Quick Start

# Enable basic caching
CQL.configure do |c|
  c.db = "postgresql://localhost/myapp"
  c.cache.on = true                    # Enable caching
  c.cache.ttl = 30.minutes            # Cache for 30 minutes
  c.cache.memory_size = 2000          # Keep 2000 entries in memory
end

# Your queries are now automatically cached!
users = User.all  # First call hits database
users = User.all  # Second call uses cache

Cache Types

CQL provides multiple caching layers that work together:

  1. Query Cache - Automatic query result caching

  2. Request Cache - Per-request query deduplication

  3. Fragment Cache - Cache parts of complex operations

  4. Memory Cache - In-memory storage (default)

  5. Redis Cache - Distributed caching with Redis

Basic Configuration

Memory Caching (Default)

Redis Caching

Environment-Based Setup

Request-Scoped Caching

Perfect for web applications - eliminates duplicate queries within a single request.

Setup

Web Framework Integration

Kemal

Lucky

Azu

The Azu framework is a Crystal application development toolkit with expressive, elegant syntax. CQL integrates seamlessly with Azu through multiple approaches:

Any Framework

Fragment Caching

Cache expensive operations or complex query results.

Setup

Usage

Advanced Cache Configuration

Complete Setup

Invalidation Strategies

Cache Management

Runtime Control

Performance Monitoring

Cache Instances

Practical Examples

E-commerce Application

Blog Application

API Application

Azu Framework Application

Performance Tips

Cache Key Design

TTL Strategy

Memory Management

Troubleshooting

Cache Not Working

Memory Issues

Redis Connection Issues

Best Practices

  1. Start with memory cache - simple and effective for most applications

  2. Enable request caching for web applications - eliminates duplicate queries

  3. Use fragment caching for expensive operations - complex calculations, external API calls

  4. Monitor cache performance - watch hit rates and memory usage

  5. Set appropriate TTLs - balance data freshness with performance

  6. Use Redis for production - when you have multiple app instances

  7. Tag your fragments - enables precise cache invalidation

  8. Cache at the right level - query cache for raw data, fragment cache for processed results

Environment Examples

Development

Production

Caching in CQL is designed to be powerful yet simple to use. Start with basic query caching and gradually add more advanced features as your application grows!

Last updated

Was this helpful?