Use Per-Request Caching

Cache query results within a single HTTP request to avoid duplicate queries.

Prerequisites

  • CQL installed and configured

  • Web application with request lifecycle

The Problem

Within a single request, the same query may run multiple times:

# Header partial
current_user = User.find(session[:user_id])  # Query 1

# Sidebar partial
current_user = User.find(session[:user_id])  # Query 2 (duplicate!)

# Main content
current_user = User.find(session[:user_id])  # Query 3 (duplicate!)

Enable Request Cache

Wrap your request handling with a request cache context:

How It Works

With request caching enabled, identical queries are cached:

Automatic Caching

All queries within the request cache context are automatically cached:

Manual Cache Control

Skip Cache for a Query

Clear Request Cache

With Framework Integration

Kemal

Lucky

Amber

What Gets Cached

Cached:

  • find queries

  • where queries

  • count queries

  • exists? checks

Not cached:

  • Write operations (save, update, delete)

  • Raw SQL queries

  • Queries after write operations on the same table

Debugging

Log cache hits:

Verify It Works

Best Practices

  1. Enable for all requests - Use middleware for consistent behavior

  2. Clear after writes - Ensure fresh data after modifications

  3. Don't rely on it for long-term caching - Use Redis for that

  4. Monitor in development - Log hits/misses to find N+1 queries

See Also

Last updated

Was this helpful?