Claude Code Prompt Patterns: Practical Examples and Templates
This guide provides practical, battle-tested prompt patterns for common development scenarios with Claude Code. Each pattern includes real-world examples and variations.
Quick Reference
| Pattern | Use Case | Key Benefit |
|---|---|---|
| Structured Analysis | Complex debugging | Systematic approach |
| Incremental Refinement | Large refactors | Manageable chunks |
| Context Preservation | Long tasks | Maintains focus |
| Parallel Exploration | Architecture decisions | Multiple perspectives |
| Test-Driven Development | Feature implementation | Quality assurance |
Structured Analysis Pattern
Break down complex problems into analyzable components.
Basic Template
claude "analyze [system/component]:
1. Current state assessment
2. Problem identification
3. Root cause analysis
4. Solution proposals
5. Implementation plan
6. Risk assessment"Real-World Example: Performance Analysis
claude "analyze our API performance issues:
1. Current State:
- Measure response times for all endpoints
- Identify slowest operations
- Check resource utilization
2. Problem Identification:
- List endpoints exceeding 200ms
- Find N+1 query patterns
- Detect missing indexes
3. Root Cause Analysis:
- Trace slow queries
- Profile memory usage
- Analyze network overhead
4. Solutions:
- Propose query optimizations
- Suggest caching strategies
- Recommend architectural changes
5. Implementation Plan:
- Priority order fixes
- Estimate impact per fix
- Define success metrics
Present findings in a markdown table with metrics"Variation: Security Analysis
claude "think hard and perform security analysis on our auth system:
Structure your analysis as:
<assessment>
- Current security measures
- Authentication flow
- Session management
</assessment>
<vulnerabilities>
- Potential attack vectors
- OWASP Top 10 compliance
- Code-level issues
</vulnerabilities>
<recommendations>
- Immediate fixes (critical)
- Short-term improvements
- Long-term hardening
</recommendations>
Include code examples for each fix"Incremental Refinement Pattern
Handle large changes through iterative improvements.
Basic Template
claude "refactor [component] incrementally:
- Step 1: Identify and extract [aspect]
- Step 2: Improve [quality attribute]
- Step 3: Integrate and test
- Checkpoint after each step"Real-World Example: Service Decomposition
claude "decompose the monolithic UserService:
Phase 1 - Analysis:
- Map all methods and their dependencies
- Identify cohesive responsibility groups
- Find coupling points
Phase 2 - Extraction Plan:
- AuthenticationService: login, logout, password reset
- ProfileService: user data, preferences
- PermissionService: roles, access control
Phase 3 - Incremental Migration:
For each service:
1. Create new service class
2. Move methods preserving signatures
3. Add facade pattern for compatibility
4. Update tests
5. Verify no regressions
After each extraction, run: npm test
Show me Phase 1 first, wait for approval before continuing"Variation: UI Component Refactor
claude "modernize our legacy jQuery components to React:
Target: FormValidator.js (2000 lines)
Approach:
1. Analyze current functionality
- List all validation rules
- Map DOM interactions
- Identify state management
2. Design React architecture
- Component hierarchy
- State structure (useState/useReducer)
- Custom hooks needed
3. Incremental conversion:
a. Create React wrapper around jQuery
b. Move validation logic to hooks
c. Replace DOM manipulation with React
d. Remove jQuery dependencies
e. Optimize and add TypeScript
Implement step 3a first, ensuring backward compatibility"Context Preservation Pattern
Maintain focus across long-running tasks.
Basic Template
claude "working on [feature]:
Context reminder:
- Goal: [end objective]
- Completed: [what's done]
- Current focus: [immediate task]
- Constraints: [key requirements]
Now: [specific next action]"Real-World Example: API Migration
claude "continuing API v2 migration:
Context:
- Goal: Migrate from REST to GraphQL
- Completed: User queries, auth mutations
- Current: Order management endpoints
- Constraints: Maintain v1 compatibility, zero downtime
Current focus: Convert order CRUD operations
- GET /orders → orders query
- POST /orders → createOrder mutation
- PUT /orders/:id → updateOrder mutation
- DELETE /orders/:id → cancelOrder mutation
Requirements:
- Maintain existing response structure
- Add new fields: estimatedDelivery, trackingHistory
- Implement DataLoader for N+1 prevention
- Add subscription for order status updates
Start with the orders query implementation"Variation: Multi-Day Feature
claude "resume implementing real-time collaboration:
Project state (Day 3):
✅ WebSocket infrastructure
✅ User presence tracking
✅ Cursor position sync
🔄 Collaborative editing (in progress)
⏳ Conflict resolution
⏳ Offline support
Today's objective: Implement operational transform for text editing
Last session ended with:
- Basic CRDT structure defined
- Insert operations working
- Delete operations buggy
Pick up from: src/collaboration/crdt.ts line 145
First, fix the delete operation index calculation"Parallel Exploration Pattern
Explore multiple solutions simultaneously.
Basic Template
claude "explore solutions for [problem]:
Approach A: [strategy 1]
Approach B: [strategy 2]
Approach C: [strategy 3]
For each approach:
- Implementation sketch
- Pros/cons analysis
- Performance implications
- Maintenance burden"Real-World Example: State Management
claude "evaluate state management solutions for our React app:
Current pain points:
- Props drilling in 10+ level components
- Complex async state with loading/error
- Performance issues with frequent updates
- Need time-travel debugging
Evaluate these approaches:
A. Redux Toolkit (RTK)
- Show store setup with slices
- Implement user and cart features
- Add RTK Query for API calls
- Demonstrate DevTools integration
B. Zustand
- Create equivalent stores
- Show subscription model
- Implement persistence
- Compare bundle size
C. Valtio
- Proxy-based state example
- Show React integration
- Demonstrate computed values
- Test performance with our dataset
Provide working code examples for a typical feature:
- User authentication state
- Shopping cart with items
- API loading states
Include migration effort estimate from current Context API"Variation: Architecture Decision
claude "think harder about microservices vs modular monolith:
Context: 50k LOC Node.js app, 5 developers, expecting 10x growth
Analyze both architectures for:
1. Development velocity
- Feature development time
- Testing complexity
- Debugging experience
2. Operational aspects
- Deployment complexity
- Monitoring requirements
- Infrastructure costs
3. Team implications
- Required expertise
- Onboarding time
- Coordination overhead
4. Technical considerations
- Data consistency
- Transaction handling
- Performance characteristics
Create decision matrix with weighted scores
Recommend based on our specific context"Test-Driven Development Pattern
Implement features starting with tests.
Basic Template
claude "implement [feature] using TDD:
1. Write failing tests for requirements
2. Implement minimal code to pass
3. Refactor for quality
4. Add edge case tests
5. Finalize implementation"Real-World Example: Payment Processing
claude "implement Stripe payment processing with TDD:
Requirements:
- Process one-time payments
- Handle subscriptions
- Support payment methods: card, bank
- Implement webhook handling
- Add idempotency
Step 1: Write comprehensive test suite
```typescript
describe('StripePaymentService', () => {
describe('processPayment', () => {
it('should charge a card successfully')
it('should handle insufficient funds')
it('should be idempotent with same key')
it('should timeout after 30s')
it('should log all attempts')
})
describe('createSubscription', () => {
it('should create monthly subscription')
it('should handle trial periods')
it('should upgrade/downgrade plans')
})
describe('webhooks', () => {
it('should verify webhook signatures')
it('should handle payment_success')
it('should handle payment_failed')
it('should be idempotent')
})
})Now implement each test case incrementally”
### Variation: API Endpoint Testing
```bash
claude "create comprehensive tests for user registration:
Test categories:
1. Happy path
2. Validation errors
3. Security concerns
4. Performance
5. Integration
Write tests first:
```javascript
// Happy path
test('POST /register creates user with valid data')
test('returns JWT token on success')
test('sends welcome email')
// Validation
test('rejects invalid email format')
test('requires strong password')
test('prevents duplicate emails')
// Security
test('rate limits registration attempts')
test('sanitizes user input')
test('hashes passwords with bcrypt')
// Performance
test('responds within 500ms')
test('handles 100 concurrent registrations')
// Integration
test('creates Stripe customer')
test('adds to email list')
test('triggers analytics event')
Implement the endpoint to pass all tests”
## Error Recovery Pattern
Build robust error handling into prompts.
### Basic Template
```bash
claude "implement [feature] with error handling:
- Try primary approach
- On failure: diagnose issue
- Attempt alternative solution
- Provide fallback option
- Document failure modes"
Real-World Example: Data Migration
claude "migrate user data with comprehensive error handling:
Source: MySQL (users table, 1M records)
Target: PostgreSQL (users table with new schema)
Requirements:
- Zero data loss
- Resumable on failure
- Rollback capability
- Progress tracking
- Detailed error logging
Implementation approach:
1. Pre-flight checks
- Verify connections
- Check disk space
- Validate schemas
- Test with 100 records
2. Main migration
```javascript
try {
// Batch processing
for (const batch of getBatches(1000)) {
try {
await migrateBatch(batch)
await saveCheckpoint(batch.lastId)
} catch (batchError) {
await handleBatchError(batch, batchError)
// Retry logic with exponential backoff
}
}
} catch (error) {
await rollback()
await notifyAdmins(error)
}-
Error handlers for:
- Connection failures
- Data validation errors
- Constraint violations
- Timeout issues
- Memory problems
-
Recovery mechanisms:
- Resume from checkpoint
- Skip and log bad records
- Partial rollback
- Manual intervention queue
Start with pre-flight checks implementation”
## Exploration and Learning Pattern
Use Claude to explore new technologies.
### Basic Template
```bash
claude "explore [technology] for our use case:
1. Core concepts explanation
2. Proof of concept
3. Integration with our stack
4. Best practices
5. Common pitfalls"
Real-World Example: WebAssembly Integration
claude "explore WebAssembly for our image processing needs:
Current problem: Browser freezes during large image operations
Investigation areas:
1. WASM basics for JavaScript developers
- What problems it solves
- Performance characteristics
- Browser compatibility
2. Proof of concept: Image resize function
- JavaScript implementation (baseline)
- Rust → WASM implementation
- Performance comparison
- Memory usage analysis
3. Integration approach:
- Build pipeline setup
- TypeScript bindings
- Worker thread usage
- Progressive enhancement
4. Production considerations:
- Bundle size impact
- Loading strategies
- Fallback for unsupported browsers
- Debugging tools
Start with a simple resize function comparison"Documentation Generation Pattern
Create comprehensive documentation efficiently.
Basic Template
claude "document [system/API]:
- Overview and purpose
- Architecture diagrams (mermaid)
- API reference with examples
- Common use cases
- Troubleshooting guide"Real-World Example: API Documentation
claude "generate complete API documentation for our order service:
Analyze code in: src/api/orders/
Output format: OpenAPI 3.0 + Markdown guides
Include:
1. OpenAPI specification
- All endpoints with parameters
- Request/response schemas
- Authentication requirements
- Error responses
2. Developer guide
- Getting started
- Authentication flow
- Rate limiting
- Pagination patterns
3. Code examples in:
- curl
- JavaScript/TypeScript
- Python
- Go
4. Postman collection
- All endpoints
- Example payloads
- Environment variables
- Pre-request scripts
5. Architecture overview
```mermaid
graph TD
Client --> Gateway
Gateway --> OrderService
OrderService --> Database
OrderService --> PaymentService
OrderService --> InventoryServiceGenerate OpenAPI spec first by analyzing the code”
## Performance Optimization Pattern
Systematic approach to performance improvements.
### Basic Template
```bash
claude "optimize [component] performance:
1. Profile current performance
2. Identify bottlenecks
3. Propose optimizations
4. Implement with measurements
5. Verify improvements"
Real-World Example: React App Optimization
claude "optimize our React dashboard performance:
Current issues:
- Initial load: 8 seconds
- Time to interactive: 12 seconds
- Lighthouse score: 42/100
- Large bundle size: 3.2MB
Analysis approach:
1. Bundle analysis
- Run webpack-bundle-analyzer
- Identify largest dependencies
- Find duplicate packages
- Check for dev dependencies in prod
2. Component profiling
- Use React DevTools Profiler
- Find unnecessary re-renders
- Identify expensive computations
- Check for memory leaks
3. Optimization strategies:
a. Code splitting
- Route-based splitting
- Component lazy loading
- Dynamic imports
b. React optimizations
- Add React.memo strategically
- useMemo for expensive calcs
- useCallback for stable refs
- Virtualize long lists
c. Asset optimization
- Image lazy loading
- WebP with fallbacks
- CDN integration
- Compression
4. Implementation priority:
- Quick wins first (est. 30% improvement)
- Medium effort (est. 40% improvement)
- Major refactors (est. 30% improvement)
Start with bundle analysis and quick wins"Best Practices for Prompt Patterns
1. Structure for Clarity
# Good: Clear sections and progression
claude "implement feature:
Context: [what and why]
Requirements: [specific needs]
Constraints: [limitations]
Approach: [how to proceed]"
# Bad: Unstructured rambling
claude "implement the feature we talked about with all those requirements"2. Provide Exit Criteria
claude "refactor until:
- All tests pass
- Cyclomatic complexity < 10
- No ESLint warnings
- Performance benchmark improves 20%"3. Include Checkpoints
claude "complete the migration:
Checkpoint 1: Schema updated ✓
Checkpoint 2: Data migrated (show count)
Checkpoint 3: Validators passing
Checkpoint 4: Old code removed
Alert me at each checkpoint"4. Specify Output Format
claude "analyze and report in this format:
## Summary
- One paragraph overview
## Findings
| Issue | Severity | Fix Effort | Impact |
|-------|----------|------------|--------|
## Recommendations
1. Immediate actions
2. Short-term fixes
3. Long-term improvements
## Code Examples
```typescript
// Specific fixes with comments
```"5. Build in Error Handling
claude "if you encounter errors:
1. Document the exact error
2. Explain why it occurred
3. Propose a solution
4. Try alternative approach
5. If still stuck, outline what's needed"Pattern Combinations
Combine patterns for complex scenarios:
claude "think hard about refactoring our monolith:
[Structured Analysis + Parallel Exploration + Incremental Refinement]
Phase 1: Analysis (Structured)
- Map all components and dependencies
- Identify service boundaries
- Assess complexity and risk
Phase 2: Strategy (Parallel)
- Option A: Microservices
- Option B: Modular monolith
- Option C: Hybrid approach
Compare all three options
Phase 3: Implementation (Incremental)
- Extract user service first
- Test thoroughly
- Extract payment service
- Continue until complete
Use extended thinking for Phase 1 and 2"