Skills · Coding

Debugging Strategies

Unverified33/40

Master systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.

Originally by wshobson · MIT

Claude CodePartialHas SKILL.md but declares no allowed-tools — Claude Code will ask for permission each time
Cursor·UnknownWe have not crawled the repo tree, so we will not guess
Codex·UnknownWe have not crawled the repo tree, so we will not guess
Gemini CLI·UnknownThe spec defines no detection rule for Gemini
Copilot·UnknownWe have not crawled the repo tree, so we will not guess
npx agentalley add debugging-strategies

This command does not work yet — the CLI is still being built. Until then, use Raw in the reader below to take the file.

Who is stuck, and on what

Master systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.

The whole source

No sign-in, no blur, nothing truncated
debugging-strategies/SKILL.md528 lines11.6 KBRawView on GitHub
Frontmatter — 2 properties
namedebugging-strategies
descriptionMaster systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.
1---
2name: debugging-strategies
3description: Master systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.
4---A5No allowed-tools declared — no way to tell what this skill may touch
5 
6# Debugging Strategies
7 
8Transform debugging from frustrating guesswork into systematic problem-solving with proven strategies, powerful tools, and methodical approaches.
9 
10## When to Use This Skill
11 
12- Tracking down elusive bugs
13- Investigating performance issues
14- Understanding unfamiliar codebases
15- Debugging production issues
16- Analyzing crash dumps and stack traces
17- Profiling application performance
18- Investigating memory leaks
19- Debugging distributed systems
20 
21## Core Principles
22 
23### 1. The Scientific Method
24 
25**1. Observe**: What's the actual behavior?
26**2. Hypothesize**: What could be causing it?
27**3. Experiment**: Test your hypothesis
28**4. Analyze**: Did it prove/disprove your theory?
29**5. Repeat**: Until you find the root cause
30 
31### 2. Debugging Mindset
32 
33**Don't Assume:**
34 
35- "It can't be X" - Yes it can
36- "I didn't change Y" - Check anyway
37- "It works on my machine" - Find out why
38 
39**Do:**
40 
41- Reproduce consistently
42- Isolate the problem
43- Keep detailed notes
44- Question everything
45- Take breaks when stuck
46 
47### 3. Rubber Duck Debugging
48 
49Explain your code and problem out loud (to a rubber duck, colleague, or yourself). Often reveals the issue.
50 
51## Systematic Debugging Process
52 
53### Phase 1: Reproduce
54 
55```markdown
56## Reproduction Checklist
57 
581. **Can you reproduce it?**
59 - Always? Sometimes? Randomly?
60 - Specific conditions needed?
61 - Can others reproduce it?
62 
632. **Create minimal reproduction**
64 - Simplify to smallest example
65 - Remove unrelated code
66 - Isolate the problem
67 
683. **Document steps**
69 - Write down exact steps
70 - Note environment details
71 - Capture error messages
72```
73 
74### Phase 2: Gather Information
75 
76```markdown
77## Information Collection
78 
791. **Error Messages**
80 - Full stack trace
81 - Error codes
82 - Console/log output
83 
842. **Environment**
85 - OS version
86 - Language/runtime version
87 - Dependencies versions
88 - Environment variables
89 
903. **Recent Changes**
91 - Git history
92 - Deployment timeline
93 - Configuration changes
94 
954. **Scope**
96 - Affects all users or specific ones?
97 - All browsers or specific ones?
98 - Production only or also dev?
99```
100 
101### Phase 3: Form Hypothesis
102 
103```markdown
104## Hypothesis Formation
105 
106Based on gathered info, ask:
107 
1081. **What changed?**
109 - Recent code changes
110 - Dependency updates
111 - Infrastructure changes
112 
1132. **What's different?**
114 - Working vs broken environment
115 - Working vs broken user
116 - Before vs after
117 
1183. **Where could this fail?**
119 - Input validation
120 - Business logic
121 - Data layer
122 - External services
123```
124 
125### Phase 4: Test & Verify
126 
127```markdown
128## Testing Strategies
129 
1301. **Binary Search**
131 - Comment out half the code
132 - Narrow down problematic section
133 - Repeat until found
134 
1352. **Add Logging**
136 - Strategic console.log/print
137 - Track variable values
138 - Trace execution flow
139 
1403. **Isolate Components**
141 - Test each piece separately
142 - Mock dependencies
143 - Remove complexity
144 
1454. **Compare Working vs Broken**
146 - Diff configurations
147 - Diff environments
148 - Diff data
149```
150 
151## Debugging Tools
152 
153### JavaScript/TypeScript Debugging
154 
155```typescript
156// Chrome DevTools Debugger
157function processOrder(order: Order) {
158 debugger; // Execution pauses here
159 
160 const total = calculateTotal(order);
161 console.log("Total:", total);
162 
163 // Conditional breakpoint
164 if (order.items.length > 10) {
165 debugger; // Only breaks if condition true
166 }
167 
168 return total;
169}
170 
171// Console debugging techniques
172console.log("Value:", value); // Basic
173console.table(arrayOfObjects); // Table format
174console.time("operation");
175/* code */ console.timeEnd("operation"); // Timing
176console.trace(); // Stack trace
177console.assert(value > 0, "Value must be positive"); // Assertion
178 
179// Performance profiling
180performance.mark("start-operation");
181// ... operation code
182performance.mark("end-operation");
183performance.measure("operation", "start-operation", "end-operation");
184console.log(performance.getEntriesByType("measure"));
185```
186 
187**VS Code Debugger Configuration:**
188 
189```json
190// .vscode/launch.json
191{
192 "version": "0.2.0",
193 "configurations": [
194 {
195 "type": "node",
196 "request": "launch",
197 "name": "Debug Program",
198 "program": "${workspaceFolder}/src/index.ts",
199 "preLaunchTask": "tsc: build - tsconfig.json",
200 "outFiles": ["${workspaceFolder}/dist/**/*.js"],
201 "skipFiles": ["<node_internals>/**"]
202 },
203 {
204 "type": "node",
205 "request": "launch",
206 "name": "Debug Tests",
207 "program": "${workspaceFolder}/node_modules/jest/bin/jest",
208 "args": ["--runInBand", "--no-cache"],
209 "console": "integratedTerminal"
210 }
211 ]
212}
213```
214 
215### Python Debugging
216 
217```python
218# Built-in debugger (pdb)
219import pdb
220 
221def calculate_total(items):
222 total = 0
223 pdb.set_trace() # Debugger starts here
224 
225 for item in items:
226 total += item.price * item.quantity
227 
228 return total
229 
230# Breakpoint (Python 3.7+)
231def process_order(order):
232 breakpoint() # More convenient than pdb.set_trace()
233 # ... code
234 
235# Post-mortem debugging
236try:
237 risky_operation()
238except Exception:
239 import pdb
240 pdb.post_mortem() # Debug at exception point
241 
242# IPython debugging (ipdb)
243from ipdb import set_trace
244set_trace() # Better interface than pdb
245 
246# Logging for debugging
247import logging
248logging.basicConfig(level=logging.DEBUG)
249logger = logging.getLogger(__name__)
250 
251def fetch_user(user_id):
252 logger.debug(f'Fetching user: {user_id}')
253 user = db.query(User).get(user_id)
254 logger.debug(f'Found user: {user}')
255 return user
256 
257# Profile performance
258import cProfile
259import pstats
260 
261cProfile.run('slow_function()', 'profile_stats')
262stats = pstats.Stats('profile_stats')
263stats.sort_stats('cumulative')
264stats.print_stats(10) # Top 10 slowest
265```
266 
267### Go Debugging
268 
269```go
270// Delve debugger
271// Install: go install github.com/go-delve/delve/cmd/dlv@latest
272// Run: dlv debug main.go
273 
274import (
275 "fmt"
276 "runtime"
277 "runtime/debug"
278)
279 
280// Print stack trace
281func debugStack() {
282 debug.PrintStack()
283}
284 
285// Panic recovery with debugging
286func processRequest() {
287 defer func() {
288 if r := recover(); r != nil {
289 fmt.Println("Panic:", r)
290 debug.PrintStack()
291 }
292 }()
293 
294 // ... code that might panic
295}
296 
297// Memory profiling
298import _ "net/http/pprof"
299// Visit http://localhost:6060/debug/pprof/
300 
301// CPU profiling
302import (
303 "os"
304 "runtime/pprof"
305)
306 
307f, _ := os.Create("cpu.prof")
308pprof.StartCPUProfile(f)
309defer pprof.StopCPUProfile()
310// ... code to profile
311```
312 
313## Advanced Debugging Techniques
314 
315### Technique 1: Binary Search Debugging
316 
317```bash
318# Git bisect for finding regression
319git bisect start
320git bisect bad # Current commit is bad
321git bisect good v1.0.0 # v1.0.0 was good
322 
323# Git checks out middle commit
324# Test it, then:
325git bisect good # if it works
326git bisect bad # if it's broken
327 
328# Continue until bug found
329git bisect reset # when done
330```
331 
332### Technique 2: Differential Debugging
333 
334Compare working vs broken:
335 
336```markdown
337## What's Different?
338 
339| Aspect | Working | Broken |
340| ------------ | ----------- | -------------- |
341| Environment | Development | Production |
342| Node version | 18.16.0 | 18.15.0 |
343| Data | Empty DB | 1M records |
344| User | Admin | Regular user |
345| Browser | Chrome | Safari |
346| Time | During day | After midnight |
347 
348Hypothesis: Time-based issue? Check timezone handling.
349```
350 
351### Technique 3: Trace Debugging
352 
353```typescript
354// Function call tracing
355function trace(
356 target: any,
357 propertyKey: string,
358 descriptor: PropertyDescriptor,
359) {
360 const originalMethod = descriptor.value;
361 
362 descriptor.value = function (...args: any[]) {
363 console.log(`Calling ${propertyKey} with args:`, args);
364 const result = originalMethod.apply(this, args);
365 console.log(`${propertyKey} returned:`, result);
366 return result;
367 };
368 
369 return descriptor;
370}
371 
372class OrderService {
373 @trace
374 calculateTotal(items: Item[]): number {
375 return items.reduce((sum, item) => sum + item.price, 0);
376 }
377}
378```
379 
380### Technique 4: Memory Leak Detection
381 
382```typescript
383// Chrome DevTools Memory Profiler
384// 1. Take heap snapshot
385// 2. Perform action
386// 3. Take another snapshot
387// 4. Compare snapshots
388 
389// Node.js memory debugging
390if (process.memoryUsage().heapUsed > 500 * 1024 * 1024) {
391 console.warn("High memory usage:", process.memoryUsage());
392 
393 // Generate heap dump
394 require("v8").writeHeapSnapshot();
395}
396 
397// Find memory leaks in tests
398let beforeMemory: number;
399 
400beforeEach(() => {
401 beforeMemory = process.memoryUsage().heapUsed;
402});
403 
404afterEach(() => {
405 const afterMemory = process.memoryUsage().heapUsed;
406 const diff = afterMemory - beforeMemory;
407 
408 if (diff > 10 * 1024 * 1024) {
409 // 10MB threshold
410 console.warn(`Possible memory leak: ${diff / 1024 / 1024}MB`);
411 }
412});
413```
414 
415## Debugging Patterns by Issue Type
416 
417### Pattern 1: Intermittent Bugs
418 
419```markdown
420## Strategies for Flaky Bugs
421 
4221. **Add extensive logging**
423 - Log timing information
424 - Log all state transitions
425 - Log external interactions
426 
4272. **Look for race conditions**
428 - Concurrent access to shared state
429 - Async operations completing out of order
430 - Missing synchronization
431 
4323. **Check timing dependencies**
433 - setTimeout/setInterval
434 - Promise resolution order
435 - Animation frame timing
436 
4374. **Stress test**
438 - Run many times
439 - Vary timing
440 - Simulate load
441```
442 
443### Pattern 2: Performance Issues
444 
445```markdown
446## Performance Debugging
447 
4481. **Profile first**
449 - Don't optimize blindly
450 - Measure before and after
451 - Find bottlenecks
452 
4532. **Common culprits**
454 - N+1 queries
455 - Unnecessary re-renders
456 - Large data processing
457 - Synchronous I/O
458 
4593. **Tools**
460 - Browser DevTools Performance tab
461 - Lighthouse
462 - Python: cProfile, line_profiler
463 - Node: clinic.js, 0x
464```
465 
466### Pattern 3: Production Bugs
467 
468```markdown
469## Production Debugging
470 
4711. **Gather evidence**
472 - Error tracking (Sentry, Bugsnag)
473 - Application logs
474 - User reports
475 - Metrics/monitoring
476 
4772. **Reproduce locally**
478 - Use production data (anonymized)
479 - Match environment
480 - Follow exact steps
481 
4823. **Safe investigation**
483 - Don't change production
484 - Use feature flags
485 - Add monitoring/logging
486 - Test fixes in staging
487```
488 
489## Best Practices
490 
4911. **Reproduce First**: Can't fix what you can't reproduce
4922. **Isolate the Problem**: Remove complexity until minimal case
4933. **Read Error Messages**: They're usually helpful
4944. **Check Recent Changes**: Most bugs are recent
4955. **Use Version Control**: Git bisect, blame, history
4966. **Take Breaks**: Fresh eyes see better
4977. **Document Findings**: Help future you
4988. **Fix Root Cause**: Not just symptoms
499 
500## Common Debugging Mistakes
501 
502- **Making Multiple Changes**: Change one thing at a time
503- **Not Reading Error Messages**: Read the full stack trace
504- **Assuming It's Complex**: Often it's simple
505- **Debug Logging in Prod**: Remove before shipping
506- **Not Using Debugger**: console.log isn't always best
507- **Giving Up Too Soon**: Persistence pays off
508- **Not Testing the Fix**: Verify it actually works
509 
510## Quick Debugging Checklist
511 
512```markdown
513## When Stuck, Check:
514 
515- [ ] Spelling errors (typos in variable names)
516- [ ] Case sensitivity (fileName vs filename)
517- [ ] Null/undefined values
518- [ ] Array index off-by-one
519- [ ] Async timing (race conditions)
520- [ ] Scope issues (closure, hoisting)
521- [ ] Type mismatches
522- [ ] Missing dependencies
523- [ ] Environment variables
524- [ ] File paths (absolute vs relative)
525- [ ] Cache issues (clear cache)
526- [ ] Stale data (refresh database)
527```
528 

Reviews

Installed this one?Write the first review and take the Trailblazer badge.

Reviews only open after a real install, so this is empty — and we leave it empty rather than invent one.

Alternatives

Also in Coding