Apply caching strategies, database optimization, and algorithmic improvements to enhance application performance
Apply proven optimization techniques including caching, query optimization, and algorithm selection to improve application performance systematically.
Identify Optimization Opportunities
Apply Caching
Optimize Database Access
Algorithm Improvements
Reduce Latency
Context: Optimizing a slow dashboard that shows user statistics
Before Optimization:
def get_dashboard_data(user_id):
# Multiple slow queries, no caching
user = db.query("SELECT * FROM users WHERE id = ?", user_id)
# O(n) query for each calculation
total_orders = db.query(
"SELECT COUNT(*) FROM orders WHERE user_id = ?", user_id
)[0][0]
revenue = db.query(
"SELECT SUM(amount) FROM orders WHERE user_id = ?", user_id
)[0][0]
# Inefficient: loads all orders into memory
recent_orders = db.query(
"SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC",
user_id
)[:5] # Only need 5, but fetches all
return {
'user': user,
'stats': {
'total_orders': total_orders,
'total_revenue': revenue
},
'recent_orders': recent_orders
}
# Performance: 450ms per request
After Optimization:
import redis
from functools import lru_cache
# Redis for distributed caching
cache = redis.Redis(host='localhost', port=6379, decode_responses=True)
def get_dashboard_data(user_id):
# Check cache first
cache_key = f"dashboard:{user_id}"
cached = cache.get(cache_key)
if cached:
return json.loads(cached)
# Single optimized query with indexes
result = db.query("""
SELECT
u.*,
COUNT(o.id) as total_orders,
COALESCE(SUM(o.amount), 0) as total_revenue
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.id = ?
GROUP BY u.id
""", user_id)[0]
# Efficient query: LIMIT at database level
recent_orders = db.query("""
SELECT id, amount, created_at
FROM orders
WHERE user_id = ?
ORDER BY created_at DESC
LIMIT 5
""", user_id)
data = {
'user': dict(result),
'stats': {
'total_orders': result['total_orders'],
'total_revenue': result['total_revenue']
},
'recent_orders': recent_orders
}
# Cache for 5 minutes
cache.setex(cache_key, 300, json.dumps(data))
return data
# Performance: 12ms (cache hit) or 45ms (cache miss)
# 90% reduction in query time, 97% with cache
Database Indexes Added:
-- Support the JOIN efficiently
CREATE INDEX idx_orders_user_id ON orders(user_id);
-- Support ORDER BY + LIMIT
CREATE INDEX idx_orders_user_created ON orders(user_id, created_at DESC);
Optimization Techniques Applied: