Performance Monitoring

This tutorial shows you how to track and optimize query performance in your CQL application.

What You'll Learn

  • Setting up query logging

  • Identifying slow queries

  • Detecting N+1 query problems

  • Building a performance dashboard

  • Optimization strategies

Prerequisites

  • A working CQL application

  • Basic understanding of database performance concepts

Step 1: Enable Query Logging

Configure logging to capture all database queries:

# src/database.cr
require "log"

# Configure logging
Log.setup do |c|
  backend = Log::IOBackend.new
  c.bind("cql.*", :debug, backend)
end

AppDB = CQL::Schema.define(
  :app_db,
  adapter: CQL::Adapter::Postgres,
  uri: DATABASE_URL
) do
end

Step 2: Create a Query Monitor

Build a simple query monitor to track execution times:

Step 3: Wrap Database Operations

Create a timing wrapper:

Step 4: Detect N+1 Queries

N+1 queries happen when you load a list, then query for each item:

Solution: Eager Loading

Step 5: Create a Dashboard

Build a simple performance dashboard:

Step 6: Monitor in Tests

Add performance assertions to your tests:

Step 7: Production Monitoring

For production, integrate with your monitoring stack:

Optimization Checklist

When you find performance issues:

1. Add Missing Indexes

2. Use Select to Limit Columns

3. Batch Large Operations

4. Cache Expensive Queries

Summary

You've learned:

  1. How to enable query logging

  2. Building a query monitor

  3. Detecting N+1 queries

  4. Creating a performance dashboard

  5. Monitoring in tests and production

Next Steps

Last updated

Was this helpful?