AWS CloudWatch Investigation

AWS CloudWatch Investigation

Gives an agent reusable AWS CloudWatch investigation patterns: Logs Insights queries, alarm-to-deployment correlation and a decision tree for narrowing incident blast radius.

Skill files1 file
SKILL.md334 lines
1
---
2
name: aws-cloudwatch-investigation
3
description: >
4
Reusable investigation patterns for AWS CloudWatch: Logs Insights query templates,
5
alarm-to-deployment correlation, blast-radius narrowing decision tree, and
6
PromQL-style metric query patterns for structured incident triage.
7
---
8
9
# AWS CloudWatch Investigation Skill
10
11
Reusable patterns for investigating production incidents using CloudWatch Logs, Metrics, and Alarms. These patterns are designed to be composed together during incident triage.
12
13
---
14
15
## Pattern 1: Logs Insights Query Templates
16
17
### Error Spike Detection
18
19
Find the top errors in a time window, grouped by error type:
20
21
```
22
fields @timestamp, @message, @logStream
23
| filter @message like /(?i)(error|exception|fatal|critical)/
24
| stats count(*) as errorCount by bin(5m), @logStream
25
| sort errorCount desc
26
| limit 20
27
```
28
29
### P99 Latency Breakdown by Operation
30
31
Identify which operations are driving latency spikes:
32
33
```
34
fields @timestamp, @duration, operation
35
| filter ispresent(@duration)
36
| stats avg(@duration) as avgMs,
37
pct(@duration, 50) as p50Ms,
38
pct(@duration, 95) as p95Ms,
39
pct(@duration, 99) as p99Ms,
40
count(*) as invocations
41
by operation
42
| sort p99Ms desc
43
| limit 15
44
```
45
46
### Lambda Cold Start Detection
47
48
Quantify cold start impact during an incident:
49
50
```
51
fields @timestamp, @duration, @initDuration, @memorySize, @maxMemoryUsed
52
| filter ispresent(@initDuration)
53
| stats count(*) as coldStarts,
54
avg(@initDuration) as avgInitMs,
55
max(@initDuration) as maxInitMs,
56
avg(@duration) as avgDurationMs
57
by bin(5m)
58
| sort @timestamp desc
59
```
60
61
### Out-of-Memory (OOM) Detection
62
63
Find Lambda functions or containers killed by memory pressure:
64
65
```
66
fields @timestamp, @message, @logStream, @memorySize, @maxMemoryUsed
67
| filter @message like /Runtime exited|out of memory|OOMKilled|Cannot allocate memory|MemoryError/
68
| stats count(*) as oomEvents by @logStream, bin(10m)
69
| sort oomEvents desc
70
| limit 10
71
```
72
73
For memory utilization trending before OOM:
74
75
```
76
fields @timestamp, @maxMemoryUsed, @memorySize
77
| filter ispresent(@maxMemoryUsed)
78
| stats max(@maxMemoryUsed / @memorySize * 100) as peakMemPct,
79
avg(@maxMemoryUsed / @memorySize * 100) as avgMemPct
80
by bin(5m)
81
| sort @timestamp desc
82
```
83
84
### Timeout Detection
85
86
Find invocations that hit the configured timeout:
87
88
```
89
fields @timestamp, @duration, @logStream, @requestId
90
| filter @message like /Task timed out/ or @duration > 28000
91
| stats count(*) as timeouts by @logStream, bin(5m)
92
| sort timeouts desc
93
```
94
95
---
96
97
## Pattern 2: Alarm History to Deploy-Event Correlation
98
99
### Process
100
101
1. **Get alarm transition time** — note the exact timestamp when the alarm entered ALARM state.
102
2. **Query CloudTrail** for deployment-related events in a window of [alarm_time - 30min, alarm_time]:
103
104
```
105
# CloudTrail Lake query for deployment events
106
SELECT eventTime, eventName, userIdentity.arn, requestParameters
107
FROM <event-data-store-id>
108
WHERE eventTime > '<alarm_time_minus_30m>'
109
AND eventTime < '<alarm_time>'
110
AND eventName IN (
111
'UpdateFunctionCode', 'UpdateFunctionConfiguration',
112
'UpdateService', 'CreateDeployment', 'RegisterTaskDefinition',
113
'CreateChangeSet', 'ExecuteChangeSet',
114
'StartPipelineExecution', 'PutImage'
115
)
116
ORDER BY eventTime DESC
117
```
118
119
3. **Correlation criteria** — a deploy is "correlated" if:
120
- It targets the same service/resource as the alarm
121
- It completed within 15 minutes before the alarm transition
122
- The deployer identity matches a CI/CD role (not a human applying a hotfix)
123
124
4. **Strengthening the correlation:**
125
- Check if the same alarm was healthy in the previous deployment cycle
126
- Verify no other environmental changes (scaling events, config changes) in the same window
127
- Look for canary/synthetic monitor failures that started at the same time
128
129
### Output Format
130
131
```
132
Deploy Correlation:
133
Event: UpdateFunctionCode
134
Time: 2024-03-15T14:23:07Z (12 min before alarm)
135
Actor: arn:aws:sts::123456789012:assumed-role/github-actions-deploy/session
136
Resource: arn:aws:lambda:us-east-1:123456789012:function:payment-processor
137
Correlation: STRONG — same resource, CI/CD actor, alarm was OK prior cycle
138
```
139
140
---
141
142
## Pattern 3: Narrow the Blast Radius Decision Tree
143
144
Use this tree to systematically scope an incident from broadest to most specific:
145
146
```
147
START
148
|
149
v
150
[1] ACCOUNT — Which account(s) show the alarm?
151
| - Check: Are alarms firing in multiple accounts?
152
| - If yes → suspect shared service (SSO, networking, shared deployment pipeline)
153
| - If no → proceed to Region
154
v
155
[2] REGION — Which region(s) are affected?
156
| - Check: Same alarm in other regions?
157
| - If multi-region → suspect global service (IAM, Route53, S3 global)
158
| - If single-region → proceed to Service
159
v
160
[3] SERVICE — Which service namespace shows degradation?
161
| - Check CloudWatch namespace: AWS/Lambda, AWS/ECS, AWS/ApiGateway, etc.
162
| - If multiple services → suspect shared dependency (VPC, NAT, DNS, IAM)
163
| - If single service → proceed to Operation
164
v
165
[4] OPERATION — Which API action or function is failing?
166
| - For Lambda: which function name?
167
| - For ECS: which service/task definition?
168
| - For API GW: which stage/resource/method?
169
| - If all operations → suspect service-level issue (throttling, quota)
170
| - If specific operation → proceed to Resource
171
v
172
[5] RESOURCE — Which specific resource instance?
173
- Function ARN, Task ID, DB instance identifier
174
- This is your investigation target
175
- Proceed to log and trace analysis scoped to this resource
176
```
177
178
### Shared Dependency Investigation
179
180
When blast radius spans multiple services, investigate in this order:
181
182
1. **VPC/Networking** — NAT Gateway ErrorPortAllocation, packet drops, DNS resolution failures
183
2. **IAM/STS** — ThrottlingException on AssumeRole, token vending latency
184
3. **Downstream dependency** — shared database, cache, or external API
185
4. **Deployment pipeline** — simultaneous deploys across services from same pipeline run
186
5. **AWS service event** — check AWS Health Dashboard and Service Health for the region
187
188
---
189
190
## Pattern 4: PromQL-Style Metric Query Patterns
191
192
These patterns use CloudWatch metric math and GetMetricData to build composite signals. Express them as metric queries for dashboards or programmatic retrieval.
193
194
### Error Rate as Percentage
195
196
```
197
MetricDataQueries:
198
- Id: errors
199
MetricStat:
200
Metric:
201
Namespace: AWS/Lambda
202
MetricName: Errors
203
Dimensions: [{Name: FunctionName, Value: TARGET}]
204
Period: 60
205
Stat: Sum
206
- Id: invocations
207
MetricStat:
208
Metric:
209
Namespace: AWS/Lambda
210
MetricName: Invocations
211
Dimensions: [{Name: FunctionName, Value: TARGET}]
212
Period: 60
213
Stat: Sum
214
- Id: error_rate
215
Expression: "errors / invocations * 100"
216
Label: "Error Rate %"
217
```
218
219
### Latency Anomaly Detection (Compare to Baseline)
220
221
```
222
MetricDataQueries:
223
- Id: current_p99
224
MetricStat:
225
Metric:
226
Namespace: AWS/Lambda
227
MetricName: Duration
228
Dimensions: [{Name: FunctionName, Value: TARGET}]
229
Period: 300
230
Stat: p99
231
- Id: baseline_p99
232
MetricStat:
233
Metric:
234
Namespace: AWS/Lambda
235
MetricName: Duration
236
Dimensions: [{Name: FunctionName, Value: TARGET}]
237
Period: 300
238
Stat: p99
239
# Use StartTime/EndTime set to same window last week
240
- Id: anomaly_ratio
241
Expression: "current_p99 / baseline_p99"
242
Label: "Latency vs Baseline (ratio > 2 = anomaly)"
243
```
244
245
### Throttling Pressure Score
246
247
Combine multiple throttling signals into a single pressure metric:
248
249
```
250
MetricDataQueries:
251
- Id: lambda_throttles
252
MetricStat:
253
Metric: {Namespace: AWS/Lambda, MetricName: Throttles}
254
Period: 60
255
Stat: Sum
256
- Id: api_gw_429s
257
MetricStat:
258
Metric: {Namespace: AWS/ApiGateway, MetricName: 4XXError, Dimensions: [{Name: ApiName, Value: TARGET}]}
259
Period: 60
260
Stat: Sum
261
- Id: dynamo_throttles
262
MetricStat:
263
Metric: {Namespace: AWS/DynamoDB, MetricName: ThrottledRequests, Dimensions: [{Name: TableName, Value: TARGET}]}
264
Period: 60
265
Stat: Sum
266
- Id: throttle_pressure
267
Expression: "lambda_throttles + api_gw_429s + dynamo_throttles"
268
Label: "Combined Throttle Pressure"
269
```
270
271
### Concurrent Execution Headroom
272
273
```
274
MetricDataQueries:
275
- Id: concurrent
276
MetricStat:
277
Metric: {Namespace: AWS/Lambda, MetricName: ConcurrentExecutions}
278
Period: 60
279
Stat: Maximum
280
- Id: headroom
281
Expression: "1000 - concurrent"
282
Label: "Remaining Concurrency (account limit 1000)"
283
```
284
285
---
286
287
## Pattern 5: Incident Timeline Reconstruction
288
289
### Process
290
291
Reconstruct a precise timeline by merging data from multiple sources:
292
293
1. **Collect timestamps:**
294
295
| Source | Query | Yields |
296
|--------|-------|--------|
297
| CloudWatch Alarms | Alarm history API | State transition times |
298
| CloudWatch Metrics | GetMetricData with 1-min period | First anomaly point |
299
| CloudWatch Logs | Logs Insights with `earliest(@timestamp)` | First error occurrence |
300
| CloudTrail | LookupEvents filtered by time | Deployment/change events |
301
| AWS Health | DescribeEvents | AWS-side incidents |
302
303
2. **Build the timeline:**
304
305
```
306
fields @timestamp, @message
307
| filter @message like /ERROR|WARN|timeout|refused|denied/
308
| stats earliest(@timestamp) as firstSeen, latest(@timestamp) as lastSeen, count(*) as occurrences
309
by @message
310
| sort firstSeen asc
311
| limit 20
312
```
313
314
3. **Identify the sequence:**
315
316
```
317
Timeline:
318
T-15m: CloudTrail — UpdateFunctionCode by CI/CD role
319
T-12m: Logs — first error "Connection refused to payments-api.internal"
320
T-10m: Metrics — Error count crosses 5/min threshold
321
T-8m: Alarm — PaymentProcessorErrors enters ALARM
322
T-5m: Metrics — p99 latency spikes to 28s (timeout)
323
T-0: Current — error rate at 45%, alarm still firing
324
```
325
326
4. **Determine root event** — the earliest change that preceded all symptoms. Walk backward from the first symptom to the most recent mutation (deploy, config change, scaling event, or external dependency shift).
327
328
### Gotchas
329
330
- CloudWatch metric timestamps are end-of-period. A 1-minute datapoint at 14:05 covers 14:04-14:05.
331
- CloudTrail events can have up to 15-minute delivery delay. Use `eventTime`, not ingestion time.
332
- Log group timestamps depend on the agent/SDK flush interval. Allow for 30-60s of clock skew.
333
- Alarm state changes have a built-in evaluation delay (periods x evaluation periods). The actual anomaly started earlier.
334

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 11,980 prompts

More by @OpenSourceBuffGuy

See all
Power Platform MCP Connector Development prompt image

Power Platform MCP Connector Development

Sets rules for building Power Platform custom connectors that expose MCP servers to Copilot Studio, covering JSON-RPC, schema limits, OAuth security and C# scripts.

rule-file, best-practices, api, mcp, developer-tools, authentication, power-apps, dotnet, csharp, for-developers, structured-output, advanced, backend, guardrails, documentation, copilot-studio

Algorithm Efficiency Expert prompt image

Algorithm Efficiency Expert

Acts as an algorithm optimisation expert that analyses time and space complexity, finds bottlenecks and recommends faster algorithms and data structures.

system-prompt, act-as, performance-optimization, algorithms, computer-science, code-review, refactoring, coding, for-developers, expert-advice, code, comparison, step-by-step-guide, xml-tags, structured-output, advanced, best-practices, debugging, coach

Luxury Skincare Vial Product Shot prompt image

Luxury Skincare Vial Product Shot

Renders a luxury skincare commercial photo of a faceted crystal elixir vial on an ivory marble pedestal with orchids and golden droplets, specified as JSON.

image-prompt, json-prompt, gpt-image, product-photography, luxury, photorealistic, studio-lighting, packaging-design, still-life, bokeh, text-rendering, flowers, structured-output, for-marketers, for-designers, low-angle, advertising, beauty, skincare, dramatic-lighting

Reviews

Loading reviews…

Discussion

Loading comments…