---
description: Rails Performance Guide
applyTo: "**/*.rb"
---

# Rails Performance Guide

## Core Philosophy

- Measure before optimizing
- Optimize for the common case
- Keep solutions simple and maintainable
- Use Rails built-in performance features
- Monitor performance in production

## Database Optimization Principles

- Design efficient schemas from the start
- Index foreign keys and queried columns
- Use database-specific features wisely
- Keep queries simple and focused
- Monitor slow query logs

## Query Optimization

- Eliminate N+1 queries with includes
- Use select to limit returned columns
- Implement pagination for large datasets
- Use pluck for single column queries
- Batch process large operations

## Indexing Strategy

- Index all foreign keys
- Create composite indexes for multi-column queries
- Use partial indexes for filtered queries
- Monitor index usage and effectiveness
- Remove unused indexes

## Caching Principles

- Cache at multiple levels
- Use Russian doll caching for nested content
- Implement fragment caching for expensive views
- Cache database queries appropriately
- Monitor cache hit rates

## Rails Cache Store

- Use Solid Cache for database-backed caching
- Configure Redis for high-traffic applications
- Set appropriate cache expiration
- Use cache keys that auto-expire
- Monitor cache memory usage

## Fragment Caching

- Cache expensive view partials
- Use cache digests for automatic expiration
- Implement conditional caching
- Cache user-specific content carefully
- Profile view rendering times

## Query Caching

- Leverage Rails query cache
- Use low-level caching for expensive calculations
- Cache aggregated data
- Implement counter caches
- Update caches strategically

## Asset Optimization

- Use Propshaft for simple asset handling
- Implement CDN for asset delivery
- Compress assets appropriately
- Set proper cache headers
- Optimize image sizes

## Background Job Performance

- Process heavy operations asynchronously
- Use appropriate queue priorities
- Batch similar operations
- Monitor job queue depth
- Implement job timeouts

## Memory Management

- Profile memory usage regularly
- Fix memory leaks promptly
- Use streaming for large responses
- Implement pagination everywhere
- Monitor memory trends

## Database Connection Pooling

- Configure connection pool appropriately
- Monitor connection usage
- Use read replicas for scaling
- Implement connection timeouts
- Handle connection failures gracefully

## Eager Loading

- Use includes for associations
- Implement preload for separate queries
- Use joins for filtering
- Avoid loading unnecessary data
- Profile association loading

## SQL Optimization

- Use EXPLAIN to analyze queries
- Optimize slow queries first
- Use database views for complex queries
- Implement materialized views when needed
- Keep queries readable

## Pagination Best Practices

- Always paginate large datasets
- Use cursor-based pagination for APIs
- Implement infinite scroll carefully
- Cache pagination counts
- Optimize count queries

## Caching Strategies

- Cache computed values
- Use memoization for instance methods
- Implement HTTP caching headers
- Cache external API responses
- Invalidate caches intelligently

## Performance Monitoring

- Use APM tools in production
- Monitor response times
- Track database query times
- Alert on performance degradation
- Profile regularly

## Load Testing

- Test with realistic data volumes
- Simulate concurrent users
- Identify bottlenecks early
- Test cache effectiveness
- Monitor resource usage

## Code Optimization

- Keep methods small and focused
- Avoid unnecessary object allocations
- Use efficient algorithms
- Profile hot code paths
- Optimize critical sections only

## View Performance

- Minimize database queries in views
- Use streaming for large responses
- Implement lazy loading
- Optimize partial rendering
- Cache complex calculations

## API Performance

- Implement response pagination
- Use sparse fieldsets
- Cache API responses
- Compress responses
- Monitor API usage

## Database Maintenance

- Run VACUUM regularly (PostgreSQL)
- Update table statistics
- Monitor table bloat
- Archive old data
- Plan capacity ahead

## Scaling Strategies

- Start with vertical scaling
- Implement read replicas
- Use database partitioning
- Consider caching layers
- Plan for horizontal scaling

## Common Bottlenecks

- N+1 queries
- Missing indexes
- Large result sets
- Inefficient algorithms
- Memory leaks

## Performance Tools

- Use Bullet gem for N+1 detection
- Implement rack-mini-profiler
- Use database query analyzers
- Monitor with New Relic or similar
- Profile with Ruby profilers

## Development Practices

- Test with production-like data
- Profile during development
- Review queries in pull requests
- Monitor performance trends
- Document performance decisions

## Performance Checklist

- [ ] All foreign keys indexed
- [ ] N+1 queries eliminated
- [ ] Pagination implemented
- [ ] Caching strategy defined
- [ ] Slow queries optimized
- [ ] Memory usage monitored
- [ ] Response times acceptable
- [ ] Background jobs efficient
- [ ] Assets optimized
- [ ] Monitoring in place

## Best Practices Summary

- Measure before optimizing
- Fix biggest bottlenecks first
- Use Rails built-in features
- Monitor production performance
- Keep optimizations simple

Remember: Premature optimization is the root of all evil. Profile first, optimize what matters, and keep solutions maintainable.
