Monitoring and Observability
Prometheus and Grafana Setup
Prometheus
Core Concepts
- Time-series database for metrics
- Pull-based metrics collection
- PromQL query language
- Alerting rules and notifications
Best Practices
- Use appropriate metric types (Counter, Gauge, Histogram, Summary)
- Label metrics with relevant dimensions
- Use metric naming conventions
- Implement relabeling for metric filtering
- Use federation for multi-cluster setups
Configuration
- Configure scrape targets for services
- Use service discovery for dynamic targets
- Configure retention policies
- Implement remote write for long-term storage
- Use alert rules for proactive monitoring
PromQL Examples
# CPU usage rate
rate(process_cpu_seconds_total[5m])
# Request error rate
rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m])
# P95 latency
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
# Memory usage
process_resident_memory_bytes / node_memory_MemTotal_bytes * 100
Grafana
Core Concepts
- Visualization and dashboard platform
- Multiple data source support
- Alerting and notifications
- Plugin ecosystem
Best Practices
- Use folder organization for dashboards
- Use dashboard variables for interactivity
- Implement dashboard versioning
- Use annotations for event marking
- Share dashboards via JSON export
Dashboard Design
- Create role-specific dashboards (SRE, developer, business)
- Use appropriate visualization types (graph, gauge, table, stat)
- Implement drill-down capabilities
- Use consistent color schemes
- Include context and descriptions
Alerting
- Configure alert rules in Grafana
- Use notification channels (email, Slack, PagerDuty)
- Implement alert grouping and routing
- Use alert templates for clear messages
- Configure alert silencing and downtime
CloudWatch (AWS) Monitoring
Core Concepts
- Metrics: Time-series data points
- Dashboards: Visualizations of metrics
- Alarms: Threshold-based alerts
- Logs: Log data collection and analysis
- Events: Event-driven monitoring
Best Practices
Metric Collection
- Use custom metrics for application-specific data
- Use metric filters for log-based metrics
- Use metric dimensions for filtering
- Implement metric aggregation
- Use metric streams for real-time processing
Dashboard Design
- Create service-specific dashboards
- Use widgets for different visualizations
- Implement dashboard variables
- Use cross-account dashboards
- Share dashboards with teams
Alarm Configuration
- Use appropriate alarm thresholds
- Implement alarm actions (SNS, Auto Scaling, EC2 actions)
- Use composite alarms for complex conditions
- Configure alarm states and transitions
- Use alarm tags for organization
CloudWatch Logs
- Log Groups: Logical containers for logs
- Log Streams: Sequences of log events
- Metric Filters: Extract metrics from logs
- Subscription Filters: Stream logs to other services
- Insights: Query and analyze logs
CloudWatch Examples
// Alarm configuration
{
"AlarmName": "HighCPUUsage",
"MetricName": "CPUUtilization",
"Namespace": "AWS/EC2",
"Statistic": "Average",
"Period": 300,
"EvaluationPeriods": 2,
"Threshold": 80,
"ComparisonOperator": "GreaterThanThreshold"
}
// Metric filter
{
"filterPattern": "[timestamp, request_id, status_code, latency]",
"metricTransformations": [
{
"metricName": "RequestLatency",
"metricNamespace": "Application",
"metricValue": "$latency"
}
]
}
Azure Monitor
Core Concepts
- Metrics: Time-series data
- Logs: Log data collection and analysis
- Alerts: Threshold-based alerts
- Dashboards: Visualizations
- Application Insights: Application monitoring
Best Practices
Metric Collection
- Use custom metrics for application data
- Use metric dimensions for filtering
- Implement metric aggregation
- Use metric alerts for proactive monitoring
- Configure metric collection rules
Log Analytics
- Use Kusto Query Language (KQL) for log queries
- Create custom log tables
- Implement log collection rules
- Use log alerts for monitoring
- Configure log retention policies
Application Insights
- Enable distributed tracing
- Use custom telemetry
- Implement dependency tracking
- Configure performance counters
- Use smart detection for anomalies
Azure Monitor Examples
// KQL query for error rate
requests
| where timestamp > ago(1h)
| summarize count() by success
| project error_rate = 100.0 * (count_ - count_success) / count_
// Query for slow requests
requests
| where timestamp > ago(1h)
| where duration > 1000
| summarize count() by name
| top 10 by count_
// Query for exceptions
exceptions
| where timestamp > ago(1h)
| summarize count() by type, problemId
| top 10 by count_
Stackdriver (GCP) Monitoring
Core Concepts
- Metrics: Time-series data
- Dashboards: Visualizations
- Alerting: Threshold-based alerts
- Logging: Log data collection
- Tracing: Distributed tracing
Best Practices
Metric Collection
- Use custom metrics for application data
- Use metric labels for filtering
- Implement metric aggregation
- Use metric-based alerting policies
- Configure metric descriptors
Dashboard Design
- Create service-specific dashboards
- Use dashboard variables
- Implement dashboard sharing
- Use dashboard templates
- Configure dashboard refresh intervals
Logging
- Use log sinks for log routing
- Implement log-based metrics
- Configure log exclusions
- Use log alerts for monitoring
- Configure log retention
Stackdriver Examples
# Alerting policy
displayName: "High Error Rate"
conditions:
- displayName: "Error rate > 5%"
conditionThreshold:
filter: 'metric.type="custom.googleapis.com/error_rate"'
comparison: COMPARISON_GT
thresholdValue: 0.05
duration: 300s
aggregations:
- alignmentPeriod: 60s
perSeriesAligner: ALIGN_RATE
Logging and Log Aggregation
ELK Stack (Elasticsearch, Logstash, Kibana)
- Elasticsearch: Search and analytics engine
- Logstash: Data processing pipeline
- Kibana: Visualization platform
- Beats: Data shippers
Best Practices
Log Collection
- Use centralized logging
- Implement log shippers (Filebeat, Fluentd, Logstash)
- Use log parsing and normalization
- Configure log retention policies
- Implement log archiving
Log Analysis
- Use index patterns for organization
- Implement log queries and filters
- Use saved searches for common queries
- Create visualizations for log data
- Use dashboards for log monitoring
Log Security
- Implement log encryption at rest
- Use secure log transmission (TLS)
- Implement log access controls
- Configure log audit trails
- Use log redaction for sensitive data
Loki
Core Concepts
- Lightweight log aggregation system
- Label-based indexing
- Grafana integration
- PromQL-like query language (LogQL)
Best Practices
- Use appropriate log labels
- Implement log retention policies
- Use log streams for organization
- Configure log scraping
- Implement log alerting
Alerting Strategies and Incident Response
Alerting Best Practices
Alert Design
- Use meaningful alert names and descriptions
- Include relevant context in alerts
- Use appropriate severity levels
- Configure alert thresholds carefully
- Implement alert deduplication
Alert Routing
- Route alerts to appropriate teams
- Use escalation policies
- Configure on-call rotations
- Implement alert grouping
- Use notification channels (email, Slack, PagerDuty)
Alert Quality
- Reduce alert noise with proper filtering
- Implement alert suppression
- Use alert correlation
- Configure alert cooldown periods
- Implement alert auto-resolution
Incident Response
Incident Lifecycle
- Detection: Identify incident
- Triage: Assess severity and impact
- Response: Mitigate incident
- Resolution: Restore service
- Post-Mortem: Learn and improve
Best Practices
- Use incident severity levels
- Implement incident communication
- Use runbooks for common incidents
- Conduct post-mortems
- Implement follow-up actions
Runbooks
- Document common incident scenarios
- Include step-by-step procedures
- Include relevant commands and tools
- Update runbooks based on incidents
- Share runbooks with teams
SLO/SLI Definitions and Tracking
SLI (Service Level Indicator)
- Definition: Quantitative measure of service performance
- Common SLIs:
- Availability: Percentage of time service is operational
- Latency: Response time for requests
- Error Rate: Percentage of failed requests
- Throughput: Requests per second
- Saturation: Resource utilization
SLO (Service Level Objective)
- Definition: Target value for SLI
- Best Practices:
- Set realistic SLOs based on business requirements
- Use SLOs to drive reliability improvements
- Monitor SLOs continuously
- Alert on SLO breaches
- Use error budgets for balancing reliability and innovation
Error Budget
- Definition: Allowable amount of unreliability
- Calculation: Error Budget = 100% - SLO
- Best Practices:
- Use error budget to guide release decisions
- Freeze deployments when error budget is exhausted
- Implement error budget alerts
- Track error budget consumption
- Use error budget for reliability planning
SLO/SLI Examples
# SLO configuration
slo_name: "API Availability"
sli_name: "api_availability"
slo_target: 0.999
slo_window: 30d
alert_threshold: 0.998
# SLI calculation
api_availability = 1 - (error_count / total_count)
# Error budget
error_budget = 1 - slo_target
error_budget_remaining = slo_target - current_availability
Monitoring SLOs
Tools:
- Prometheus and Grafana
- CloudWatch SLOs
- Azure Monitor SLOs
- Stackdriver SLOs
- SRE-specific tools (Sloth, sli-exporter)
Best Practices:
- Visualize SLOs in dashboards
- Alert on SLO breaches
- Track SLO trends over time
- Compare SLOs across services
- Use SLOs for capacity planning
Observability Best Practices
The Three Pillars of Observability
- Metrics: Quantitative data points
- Logs: Discrete events
- Traces: Request paths through distributed systems
Distributed Tracing
Core Concepts
- Trace: End-to-end request path
- Span: Individual operation
- Trace ID: Unique identifier for trace
- Span ID: Unique identifier for span
Best Practices
- Use distributed tracing for microservices
- Implement trace sampling
- Use trace context propagation
- Configure trace retention
- Analyze traces for performance issues
Tools
- Jaeger
- Zipkin
- AWS X-Ray
- Azure Application Insights
- Google Cloud Trace
Observability Patterns
- RED Method: Rate, Errors, Duration
- USE Method: Utilization, Saturation, Errors
- Golden Signals: Latency, Traffic, Errors, Saturation
- Four Golden Signals: Latency, Traffic, Errors, Saturation, SLOs
Observability Maturity Model
- Level 1: Basic metrics and logging
- Level 2: Structured logging and metrics
- Level 3: Distributed tracing
- Level 4: Automated alerting and incident response
- Level 5: SLO-driven development and error budgets
1---2name: monitoring-observability3description: Prometheus, Grafana, CloudWatch, Azure Monitor, Stackdriver, logging, alerting, and SRE practices4---5
6# Monitoring and Observability
7
8## Prometheus and Grafana Setup
9
10### Prometheus
11- **Core Concepts**
12 - Time-series database for metrics
13 - Pull-based metrics collection
14 - PromQL query language
15 - Alerting rules and notifications
16
17- **Best Practices**
18 - Use appropriate metric types (Counter, Gauge, Histogram, Summary)
19 - Label metrics with relevant dimensions
20 - Use metric naming conventions
21 - Implement relabeling for metric filtering
22 - Use federation for multi-cluster setups
23
24- **Configuration**
25 - Configure scrape targets for services
26 - Use service discovery for dynamic targets
27 - Configure retention policies
28 - Implement remote write for long-term storage
29 - Use alert rules for proactive monitoring
30
31- **PromQL Examples**
32 ```promql
33 # CPU usage rate
34 rate(process_cpu_seconds_total[5m])
35
36 # Request error rate
37 rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m])
38
39 # P95 latency
40 histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
41
42 # Memory usage
43 process_resident_memory_bytes / node_memory_MemTotal_bytes * 100
44 ```
45
46### Grafana
47- **Core Concepts**
48 - Visualization and dashboard platform
49 - Multiple data source support
50 - Alerting and notifications
51 - Plugin ecosystem
52
53- **Best Practices**
54 - Use folder organization for dashboards
55 - Use dashboard variables for interactivity
56 - Implement dashboard versioning
57 - Use annotations for event marking
58 - Share dashboards via JSON export
59
60- **Dashboard Design**
61 - Create role-specific dashboards (SRE, developer, business)
62 - Use appropriate visualization types (graph, gauge, table, stat)
63 - Implement drill-down capabilities
64 - Use consistent color schemes
65 - Include context and descriptions
66
67- **Alerting**
68 - Configure alert rules in Grafana
69 - Use notification channels (email, Slack, PagerDuty)
70 - Implement alert grouping and routing
71 - Use alert templates for clear messages
72 - Configure alert silencing and downtime
73
74## CloudWatch (AWS) Monitoring
75
76### Core Concepts
77- **Metrics**: Time-series data points
78- **Dashboards**: Visualizations of metrics
79- **Alarms**: Threshold-based alerts
80- **Logs**: Log data collection and analysis
81- **Events**: Event-driven monitoring
82
83### Best Practices
84- **Metric Collection**
85 - Use custom metrics for application-specific data
86 - Use metric filters for log-based metrics
87 - Use metric dimensions for filtering
88 - Implement metric aggregation
89 - Use metric streams for real-time processing
90
91- **Dashboard Design**
92 - Create service-specific dashboards
93 - Use widgets for different visualizations
94 - Implement dashboard variables
95 - Use cross-account dashboards
96 - Share dashboards with teams
97
98- **Alarm Configuration**
99 - Use appropriate alarm thresholds
100 - Implement alarm actions (SNS, Auto Scaling, EC2 actions)
101 - Use composite alarms for complex conditions
102 - Configure alarm states and transitions
103 - Use alarm tags for organization
104
105### CloudWatch Logs
106- **Log Groups**: Logical containers for logs
107- **Log Streams**: Sequences of log events
108- **Metric Filters**: Extract metrics from logs
109- **Subscription Filters**: Stream logs to other services
110- **Insights**: Query and analyze logs
111
112### CloudWatch Examples
113```json
114// Alarm configuration
115{
116 "AlarmName": "HighCPUUsage",
117 "MetricName": "CPUUtilization",
118 "Namespace": "AWS/EC2",
119 "Statistic": "Average",
120 "Period": 300,
121 "EvaluationPeriods": 2,
122 "Threshold": 80,
123 "ComparisonOperator": "GreaterThanThreshold"
124}
125
126// Metric filter
127{
128 "filterPattern": "[timestamp, request_id, status_code, latency]",
129 "metricTransformations": [
130 {
131 "metricName": "RequestLatency",
132 "metricNamespace": "Application",
133 "metricValue": "$latency"
134 }
135 ]
136}
137```
138
139## Azure Monitor
140
141### Core Concepts
142- **Metrics**: Time-series data
143- **Logs**: Log data collection and analysis
144- **Alerts**: Threshold-based alerts
145- **Dashboards**: Visualizations
146- **Application Insights**: Application monitoring
147
148### Best Practices
149- **Metric Collection**
150 - Use custom metrics for application data
151 - Use metric dimensions for filtering
152 - Implement metric aggregation
153 - Use metric alerts for proactive monitoring
154 - Configure metric collection rules
155
156- **Log Analytics**
157 - Use Kusto Query Language (KQL) for log queries
158 - Create custom log tables
159 - Implement log collection rules
160 - Use log alerts for monitoring
161 - Configure log retention policies
162
163- **Application Insights**
164 - Enable distributed tracing
165 - Use custom telemetry
166 - Implement dependency tracking
167 - Configure performance counters
168 - Use smart detection for anomalies
169
170### Azure Monitor Examples
171```kql
172// KQL query for error rate
173requests
174| where timestamp > ago(1h)
175| summarize count() by success
176| project error_rate = 100.0 * (count_ - count_success) / count_
177
178// Query for slow requests
179requests
180| where timestamp > ago(1h)
181| where duration > 1000
182| summarize count() by name
183| top 10 by count_
184
185// Query for exceptions
186exceptions
187| where timestamp > ago(1h)
188| summarize count() by type, problemId
189| top 10 by count_
190```
191
192## Stackdriver (GCP) Monitoring
193
194### Core Concepts
195- **Metrics**: Time-series data
196- **Dashboards**: Visualizations
197- **Alerting**: Threshold-based alerts
198- **Logging**: Log data collection
199- **Tracing**: Distributed tracing
200
201### Best Practices
202- **Metric Collection**
203 - Use custom metrics for application data
204 - Use metric labels for filtering
205 - Implement metric aggregation
206 - Use metric-based alerting policies
207 - Configure metric descriptors
208
209- **Dashboard Design**
210 - Create service-specific dashboards
211 - Use dashboard variables
212 - Implement dashboard sharing
213 - Use dashboard templates
214 - Configure dashboard refresh intervals
215
216- **Logging**
217 - Use log sinks for log routing
218 - Implement log-based metrics
219 - Configure log exclusions
220 - Use log alerts for monitoring
221 - Configure log retention
222
223### Stackdriver Examples
224```yaml
225# Alerting policy
226displayName: "High Error Rate"
227conditions:
228 - displayName: "Error rate > 5%"
229 conditionThreshold:
230 filter: 'metric.type="custom.googleapis.com/error_rate"'
231 comparison: COMPARISON_GT
232 thresholdValue: 0.05
233 duration: 300s
234 aggregations:
235 - alignmentPeriod: 60s
236 perSeriesAligner: ALIGN_RATE
237```
238
239## Logging and Log Aggregation
240
241### ELK Stack (Elasticsearch, Logstash, Kibana)
242- **Elasticsearch**: Search and analytics engine
243- **Logstash**: Data processing pipeline
244- **Kibana**: Visualization platform
245- **Beats**: Data shippers
246
247### Best Practices
248- **Log Collection**
249 - Use centralized logging
250 - Implement log shippers (Filebeat, Fluentd, Logstash)
251 - Use log parsing and normalization
252 - Configure log retention policies
253 - Implement log archiving
254
255- **Log Analysis**
256 - Use index patterns for organization
257 - Implement log queries and filters
258 - Use saved searches for common queries
259 - Create visualizations for log data
260 - Use dashboards for log monitoring
261
262- **Log Security**
263 - Implement log encryption at rest
264 - Use secure log transmission (TLS)
265 - Implement log access controls
266 - Configure log audit trails
267 - Use log redaction for sensitive data
268
269### Loki
270- **Core Concepts**
271 - Lightweight log aggregation system
272 - Label-based indexing
273 - Grafana integration
274 - PromQL-like query language (LogQL)
275
276- **Best Practices**
277 - Use appropriate log labels
278 - Implement log retention policies
279 - Use log streams for organization
280 - Configure log scraping
281 - Implement log alerting
282
283## Alerting Strategies and Incident Response
284
285### Alerting Best Practices
286- **Alert Design**
287 - Use meaningful alert names and descriptions
288 - Include relevant context in alerts
289 - Use appropriate severity levels
290 - Configure alert thresholds carefully
291 - Implement alert deduplication
292
293- **Alert Routing**
294 - Route alerts to appropriate teams
295 - Use escalation policies
296 - Configure on-call rotations
297 - Implement alert grouping
298 - Use notification channels (email, Slack, PagerDuty)
299
300- **Alert Quality**
301 - Reduce alert noise with proper filtering
302 - Implement alert suppression
303 - Use alert correlation
304 - Configure alert cooldown periods
305 - Implement alert auto-resolution
306
307### Incident Response
308- **Incident Lifecycle**
309 - Detection: Identify incident
310 - Triage: Assess severity and impact
311 - Response: Mitigate incident
312 - Resolution: Restore service
313 - Post-Mortem: Learn and improve
314
315- **Best Practices**
316 - Use incident severity levels
317 - Implement incident communication
318 - Use runbooks for common incidents
319 - Conduct post-mortems
320 - Implement follow-up actions
321
322- **Runbooks**
323 - Document common incident scenarios
324 - Include step-by-step procedures
325 - Include relevant commands and tools
326 - Update runbooks based on incidents
327 - Share runbooks with teams
328
329## SLO/SLI Definitions and Tracking
330
331### SLI (Service Level Indicator)
332- **Definition**: Quantitative measure of service performance
333- **Common SLIs**:
334 - Availability: Percentage of time service is operational
335 - Latency: Response time for requests
336 - Error Rate: Percentage of failed requests
337 - Throughput: Requests per second
338 - Saturation: Resource utilization
339
340### SLO (Service Level Objective)
341- **Definition**: Target value for SLI
342- **Best Practices**:
343 - Set realistic SLOs based on business requirements
344 - Use SLOs to drive reliability improvements
345 - Monitor SLOs continuously
346 - Alert on SLO breaches
347 - Use error budgets for balancing reliability and innovation
348
349### Error Budget
350- **Definition**: Allowable amount of unreliability
351- **Calculation**: Error Budget = 100% - SLO
352- **Best Practices**:
353 - Use error budget to guide release decisions
354 - Freeze deployments when error budget is exhausted
355 - Implement error budget alerts
356 - Track error budget consumption
357 - Use error budget for reliability planning
358
359### SLO/SLI Examples
360```yaml
361# SLO configuration
362slo_name: "API Availability"
363sli_name: "api_availability"
364slo_target: 0.999
365slo_window: 30d
366alert_threshold: 0.998
367
368# SLI calculation
369api_availability = 1 - (error_count / total_count)
370
371# Error budget
372error_budget = 1 - slo_target
373error_budget_remaining = slo_target - current_availability
374```
375
376### Monitoring SLOs
377- **Tools**:
378 - Prometheus and Grafana
379 - CloudWatch SLOs
380 - Azure Monitor SLOs
381 - Stackdriver SLOs
382 - SRE-specific tools (Sloth, sli-exporter)
383
384- **Best Practices**:
385 - Visualize SLOs in dashboards
386 - Alert on SLO breaches
387 - Track SLO trends over time
388 - Compare SLOs across services
389 - Use SLOs for capacity planning
390
391## Observability Best Practices
392
393### The Three Pillars of Observability
394- **Metrics**: Quantitative data points
395- **Logs**: Discrete events
396- **Traces**: Request paths through distributed systems
397
398### Distributed Tracing
399- **Core Concepts**
400 - Trace: End-to-end request path
401 - Span: Individual operation
402 - Trace ID: Unique identifier for trace
403 - Span ID: Unique identifier for span
404
405- **Best Practices**
406 - Use distributed tracing for microservices
407 - Implement trace sampling
408 - Use trace context propagation
409 - Configure trace retention
410 - Analyze traces for performance issues
411
412- **Tools**
413 - Jaeger
414 - Zipkin
415 - AWS X-Ray
416 - Azure Application Insights
417 - Google Cloud Trace
418
419### Observability Patterns
420- **RED Method**: Rate, Errors, Duration
421- **USE Method**: Utilization, Saturation, Errors
422- **Golden Signals**: Latency, Traffic, Errors, Saturation
423- **Four Golden Signals**: Latency, Traffic, Errors, Saturation, SLOs
424
425### Observability Maturity Model
426- **Level 1**: Basic metrics and logging
427- **Level 2**: Structured logging and metrics
428- **Level 3**: Distributed tracing
429- **Level 4**: Automated alerting and incident response
430- **Level 5**: SLO-driven development and error budgets