0
# Cache Monitoring
1
2
Monitor Django cache operations (get/hit/miss/fail) through instrumented cache backends for various cache systems. Provides visibility into cache performance and usage patterns.
3
4
## Capabilities
5
6
### Instrumented Cache Backends
7
8
Django-prometheus provides instrumented versions of Django's cache backends that automatically collect metrics on cache operations.
9
10
```python { .api }
11
# File-based cache backend
12
django_prometheus.cache.backends.filebased.FileBasedCache
13
14
# Local memory cache backend
15
django_prometheus.cache.backends.locmem.LocMemCache
16
17
# Memcached backends
18
django_prometheus.cache.backends.memcached.PyMemcacheCache
19
django_prometheus.cache.backends.memcached.PyLibMCCache
20
21
# Redis cache backends
22
django_prometheus.cache.backends.redis.RedisCache
23
django_prometheus.cache.backends.redis.NativeRedisCache
24
25
# Django Memcached Consul backend
26
django_prometheus.cache.backends.django_memcached_consul.MemcachedCache
27
```
28
29
### Cache Metrics Functions
30
31
The instrumented backends automatically track cache operations through method interception:
32
33
```python { .api }
34
class CacheBackendMixin:
35
"""
36
Mixin that adds Prometheus monitoring to Django cache backends.
37
Automatically applied to all instrumented cache backends.
38
"""
39
40
def get(self, key, default=None, version=None):
41
"""
42
Instrumented cache get operation.
43
Tracks get attempts, hits, and misses.
44
45
Parameters:
46
- key: cache key
47
- default: default value if key not found
48
- version: cache key version
49
50
Returns:
51
Cached value or default
52
"""
53
54
def set(self, key, value, timeout=None, version=None):
55
"""
56
Instrumented cache set operation.
57
58
Parameters:
59
- key: cache key
60
- value: value to cache
61
- timeout: cache timeout in seconds
62
- version: cache key version
63
"""
64
65
def delete(self, key, version=None):
66
"""
67
Instrumented cache delete operation.
68
69
Parameters:
70
- key: cache key to delete
71
- version: cache key version
72
"""
73
```
74
75
## Monitored Metrics
76
77
### Cache Operation Metrics
78
- `django_cache_get_total`: Total get requests on cache by backend
79
- `django_cache_get_hits_total`: Total cache hits by backend
80
- `django_cache_get_misses_total`: Total cache misses by backend
81
- `django_cache_get_fail_total`: Total get request failures by backend
82
83
## Configuration
84
85
### Settings Configuration
86
87
Configure cache backends in Django settings:
88
89
```python
90
# settings.py
91
CACHES = {
92
'default': {
93
'BACKEND': 'django_prometheus.cache.backends.redis.RedisCache', # Instead of 'django.core.cache.backends.redis.RedisCache'
94
'LOCATION': 'redis://127.0.0.1:6379/1',
95
},
96
'memcached': {
97
'BACKEND': 'django_prometheus.cache.backends.memcached.PyMemcacheCache', # Instead of 'django.core.cache.backends.memcached.PyMemcacheCache'
98
'LOCATION': '127.0.0.1:11211',
99
},
100
'file_cache': {
101
'BACKEND': 'django_prometheus.cache.backends.filebased.FileBasedCache', # Instead of 'django.core.cache.backends.filebased.FileBasedCache'
102
'LOCATION': '/var/tmp/django_cache',
103
},
104
'local_mem': {
105
'BACKEND': 'django_prometheus.cache.backends.locmem.LocMemCache', # Instead of 'django.core.cache.backends.locmem.LocMemCache'
106
'LOCATION': 'unique-snowflake',
107
}
108
}
109
```
110
111
### Multiple Cache Configuration
112
113
```python
114
CACHES = {
115
'default': {
116
'BACKEND': 'django_prometheus.cache.backends.redis.RedisCache',
117
'LOCATION': 'redis://127.0.0.1:6379/0',
118
},
119
'sessions': {
120
'BACKEND': 'django_prometheus.cache.backends.redis.RedisCache',
121
'LOCATION': 'redis://127.0.0.1:6379/1',
122
},
123
'api_cache': {
124
'BACKEND': 'django_prometheus.cache.backends.memcached.PyMemcacheCache',
125
'LOCATION': '127.0.0.1:11211',
126
}
127
}
128
129
# Each cache backend will be tracked separately with its backend name as a label
130
```
131
132
## Usage Examples
133
134
### Basic Cache Monitoring
135
136
```python
137
from django.core.cache import cache
138
139
# These operations will be automatically tracked in cache metrics:
140
cache.set('user:123', user_data, timeout=300) # Cache set (not directly tracked)
141
user_data = cache.get('user:123') # Cache get - tracked as hit if found, miss if not
142
cache.delete('user:123') # Cache delete (not directly tracked)
143
144
# Get with default
145
user_data = cache.get('user:456', default={}) # Tracked as hit/miss
146
```
147
148
### Multiple Cache Usage
149
150
```python
151
from django.core.cache import caches
152
153
# Use specific cache backends
154
default_cache = caches['default']
155
session_cache = caches['sessions']
156
api_cache = caches['api_cache']
157
158
# Each will be tracked separately by backend
159
default_cache.get('key1') # Tracked under 'redis' backend
160
session_cache.get('session:abc') # Tracked under 'redis' backend
161
api_cache.get('api:endpoint:123') # Tracked under 'memcached' backend
162
```
163
164
### Cache Decorators
165
166
```python
167
from django.views.decorators.cache import cache_page
168
from django.core.cache import cache
169
170
@cache_page(60 * 15) # Cache for 15 minutes
171
def my_view(request):
172
# View caching will be tracked in cache metrics
173
return HttpResponse("Cached content")
174
175
# Manual caching in views
176
def api_view(request):
177
cache_key = f"api:data:{request.user.id}"
178
data = cache.get(cache_key) # Tracked as hit/miss
179
180
if data is None:
181
data = expensive_computation()
182
cache.set(cache_key, data, timeout=300)
183
184
return JsonResponse(data)
185
```
186
187
### Cache Template Tags
188
189
```html
190
<!-- Template fragment caching is also tracked -->
191
{% load cache %}
192
{% cache 500 my_cache_key user.id %}
193
<!-- Expensive template rendering -->
194
{% for item in expensive_queryset %}
195
<div>{{ item.name }}</div>
196
{% endfor %}
197
{% endcache %}
198
```
199
200
## Metric Labels
201
202
All cache metrics include the following label:
203
- `backend`: Cache backend type (e.g., 'redis', 'memcached', 'filebased', 'locmem')
204
205
## Supported Cache Backends
206
207
### Redis
208
- **RedisCache**: Standard Redis cache backend
209
- Tracks all Redis cache operations
210
- Supports Redis clustering and sentinel configurations
211
212
### Memcached
213
- **PyMemcacheCache**: Pure Python memcached client
214
- **PyLibMCCache**: libmemcached-based client
215
- **MemcachedCache**: Memcached with Consul discovery
216
217
### File-based
218
- **FileBasedCache**: File system-based caching
219
- Suitable for single-server deployments
220
221
### Local Memory
222
- **LocMemCache**: In-process memory caching
223
- Per-process cache, not shared across workers
224
225
## Performance Considerations
226
227
- Cache monitoring adds minimal overhead to cache operations
228
- Hit/miss detection is efficient and doesn't impact cache performance
229
- Backend labeling allows for performance analysis across different cache systems
230
- No impact on cache timeout or eviction policies
231
232
## Cache Hit Rate Analysis
233
234
Use the metrics to calculate cache hit rates:
235
236
```python
237
# Hit rate calculation:
238
# hit_rate = django_cache_get_hits_total / django_cache_get_total
239
240
# Miss rate calculation:
241
# miss_rate = django_cache_get_misses_total / django_cache_get_total
242
243
# Failure rate calculation:
244
# failure_rate = django_cache_get_fail_total / django_cache_get_total
245
```
246
247
## Common Cache Patterns Monitored
248
249
- **View caching**: Automatic tracking of Django's cache framework
250
- **Template fragment caching**: Tracked through cache backend calls
251
- **Session caching**: When using cache-based session storage
252
- **Database query caching**: Manual cache operations in ORM
253
- **API response caching**: Custom cache operations in views
254
- **Static file caching**: When using cache backends for static content