# Coding Metaprompt Templates for Claude Code ## Code Generation Templates ### Full Feature Implementation Template ```text Create a [feature name] for [project type] that: Context: - Language: [e.g., TypeScript, Python, Rust] - Framework: [e.g., React, Django, Actix] - Project structure: [brief description or tree] - Existing patterns: [e.g., MVC, Repository, Factory] Requirements: - Must support: [core functionality list] - Should handle: [edge cases] - Performance: [specific metrics if applicable] - Security: [authentication, validation needs] Technical Specifications: - Input: [data format, sources] - Output: [expected results, format] - Error handling: [how to handle failures] - Logging: [what should be logged] Code Style: - Naming convention: [e.g., camelCase, snake_case] - Documentation: [docstring format, comment style] - Test coverage: [unit, integration requirements] Deliverables: 1. Main implementation 2. Unit tests 3. Integration examples 4. Documentation ``` ### API Endpoint Template ```text Implement a REST API endpoint for [resource/action]: Endpoint Details: - Method: [GET/POST/PUT/DELETE] - Path: [/api/v1/resource] - Authentication: [Bearer token, API key, etc.] Request: - Headers: [required headers] - Body schema: [JSON structure] - Query parameters: [optional filters] - Validation rules: [constraints] Response: - Success (200/201): [response structure] - Client errors (4xx): [error format] - Server errors (5xx): [error handling] Business Logic: - Main operation: [what it does] - Side effects: [emails, webhooks, cache updates] - Transaction boundaries: [atomicity requirements] Performance Requirements: - Response time: [target milliseconds] - Concurrent requests: [expected load] - Caching strategy: [what to cache, TTL] Include: - Input validation - Error handling - Logging - Rate limiting check - Unit tests ``` ### Algorithm Implementation Template ```text Implement [algorithm name] to solve [problem description]: Problem Specification: - Input: [data structure, constraints, size] - Output: [expected result format] - Constraints: [time/space complexity requirements] Examples: - Input: [example 1] Output: [result 1] - Input: [example 2] Output: [result 2] - Edge case: [example 3] Output: [result 3] Requirements: - Time complexity: [O(n), O(n log n), etc.] - Space complexity: [O(1), O(n), etc.] - Must handle: [special cases] - Language features: [specific to use/avoid] Implementation Details: - Use iterative/recursive approach: [preference] - Data structures allowed: [arrays, maps, sets] - Libraries allowed: [standard library only?] - Optimization focus: [readability vs performance] Testing: - Include comprehensive test cases - Cover edge cases - Performance benchmarks if relevant ``` ### Component/Module Template ```text Create a [component/module name] that: Purpose: [what it does and why] Interface: - Public methods: [list with signatures] - Properties: [getters/setters] - Events: [emitted/listened] - Dependencies: [required services/modules] Behavior: - Initialization: [setup requirements] - Main functionality: [core operations] - Cleanup: [disposal, unsubscribe] - Error states: [how to handle/recover] Integration: - How it fits: [in the larger system] - Communication: [with other components] - Data flow: [input sources, output destinations] Quality Requirements: - Testability: [dependency injection, mocking] - Reusability: [configuration options] - Performance: [lazy loading, memoization] - Accessibility: [if UI component] Example Usage: [Code snippet showing typical usage] ``` ## Debugging Templates ### Bug Investigation Template ```text Debug the following issue: Problem Description: - What's broken: [specific functionality] - When it occurs: [conditions, frequency] - Impact: [who's affected, severity] Expected Behavior: [Describe what should happen] Actual Behavior: [Describe what actually happens] Error Information: - Error message: [full text] - Stack trace: [relevant portion] - Logs: [related log entries] Code Context: [Paste relevant code sections] Environment: - OS: [Windows/Mac/Linux version] - Runtime: [Node/Python/JVM version] - Dependencies: [relevant package versions] - Configuration: [relevant settings] What I've Tried: 1. [First attempt and result] 2. [Second attempt and result] Suspected Causes: - [Theory 1] - [Theory 2] Please: 1. Identify root cause 2. Explain why it's happening 3. Provide fix with explanation 4. Suggest prevention strategies ``` ### Performance Issue Template ```text Investigate performance degradation: Performance Problem: - Operation: [what's slow] - Current performance: [metrics] - Expected performance: [target metrics] - When it started: [if known] Metrics: - Response time: [average, p95, p99] - Memory usage: [before, during, after] - CPU usage: [percentage, cores] - I/O operations: [disk, network] Code Section: [Paste code suspected of causing issue] Data Characteristics: - Typical input size: [records, MB] - Data structure: [arrays, trees, graphs] - Access patterns: [sequential, random] Environment: - Hardware: [CPU, RAM, disk] - Load: [concurrent users/requests] - Database: [if applicable] Profiling Results: [If available, paste profiler output] Requirements: 1. Identify bottlenecks 2. Explain performance impact 3. Provide optimized solution 4. Maintain functionality 5. Consider trade-offs ``` ### Integration Error Template ```text Debug integration failure between [System A] and [System B]: Integration Context: - System A: [description, version] - System B: [description, version] - Communication: [REST, GraphQL, gRPC, etc.] - Data format: [JSON, XML, Protocol Buffers] Error Symptoms: - Error message: [from logs] - HTTP status: [if applicable] - Timing: [when it fails] - Frequency: [always, intermittent] Request Details: - Endpoint: [URL/method] - Headers: [relevant headers] - Body: [request payload] Response Details: - Status code: [actual vs expected] - Headers: [response headers] - Body: [response or error message] What Works: - [Successful similar requests] - [Conditions when it works] What Fails: - [Specific failure scenarios] - [Common patterns in failures] Please Investigate: 1. Protocol/format mismatches 2. Authentication/authorization issues 3. Data validation problems 4. Timeout/retry logic 5. Version compatibility ``` ## Refactoring Templates ### Code Quality Refactoring Template ```text Refactor the following code for improved [quality aspect]: Current Code: [Paste existing implementation] Refactoring Goals: - Primary: [e.g., reduce complexity, improve readability] - Secondary: [e.g., better testability, performance] Specific Issues to Address: 1. [e.g., Long methods - split into smaller functions] 2. [e.g., Duplicate code - extract common functionality] 3. [e.g., Poor naming - use descriptive names] 4. [e.g., Tight coupling - introduce abstractions] Constraints: - Must preserve: [public API, behavior] - Can modify: [internal structure, private methods] - Cannot change: [database schema, file formats] Quality Metrics: - Before: [cyclomatic complexity, lines of code] - Target: [desired metrics] Design Patterns to Consider: - [Relevant patterns for the context] Please Provide: 1. Refactored code 2. Explanation of changes 3. Benefits achieved 4. Any trade-offs made ``` ### Performance Optimization Template ```text Optimize the following code for [performance metric]: Current Implementation: [Paste code to optimize] Performance Profile: - Current metrics: [time, memory, CPU] - Bottlenecks: [identified slow parts] - Target improvement: [percentage or absolute] Constraints: - Maintain: [functionality, accuracy] - Acceptable trade-offs: [memory vs speed] - Platform limits: [memory, CPU cores] Usage Patterns: - Typical input: [size, characteristics] - Call frequency: [how often it runs] - Critical path: [yes/no] Optimization Strategies to Consider: 1. Algorithmic improvements 2. Data structure changes 3. Caching/memoization 4. Parallelization 5. I/O optimization Deliverables: 1. Optimized code 2. Performance comparison 3. Complexity analysis 4. Trade-off explanation ``` ### Architecture Refactoring Template ```text Refactor architecture from [current pattern] to [target pattern]: Current Architecture: - Pattern: [e.g., monolithic, tightly coupled] - Components: [list main components] - Dependencies: [how they connect] - Pain points: [specific problems] Target Architecture: - Pattern: [e.g., microservices, hexagonal] - Benefits sought: [scalability, testability] - New structure: [component organization] Migration Requirements: - Incremental steps: [can't do big bang] - Backward compatibility: [what must work] - Zero downtime: [if required] Technical Constraints: - Technology stack: [must use existing] - Team skills: [available expertise] - Timeline: [deadline considerations] Risk Mitigation: - Testing strategy: [ensure nothing breaks] - Rollback plan: [if something goes wrong] - Monitoring: [what to watch] Please Provide: 1. Step-by-step migration plan 2. Code examples for key changes 3. Interface definitions 4. Testing approach 5. Risk assessment ``` ## Architecture Design Templates ### System Design Template ```text Design a system for [purpose/domain]: Functional Requirements: 1. [User should be able to...] 2. [System must support...] 3. [Feature requirements...] Non-Functional Requirements: - Performance: [requests/second, latency] - Scalability: [users, data volume] - Availability: [uptime SLA] - Security: [auth, encryption, compliance] - Maintainability: [deployment, monitoring] Constraints: - Budget: [cloud costs, development time] - Technology: [existing stack, preferences] - Team: [size, expertise] - Timeline: [MVP date, phases] Use Cases: 1. [Primary use case with flow] 2. [Secondary use case] 3. [Edge case handling] Data Requirements: - Volume: [current and projected] - Velocity: [updates per second] - Variety: [types of data] - Retention: [how long to keep] Integration Points: - External APIs: [third-party services] - Internal systems: [existing services] - Client types: [web, mobile, API] Please Design: 1. High-level architecture diagram 2. Component responsibilities 3. Data flow 4. Technology choices with rationale 5. Scaling strategy 6. Failure handling 7. Security measures 8. Deployment architecture ``` ### Microservice Design Template ```text Design a microservice for [domain/capability]: Service Boundaries: - Responsibility: [what it owns] - Not responsible for: [explicit exclusions] - Domain entities: [data it manages] API Design: - Protocol: [REST, gRPC, GraphQL] - Endpoints: [operations exposed] - Data contracts: [request/response schemas] - Versioning strategy: [how to handle changes] Data Management: - Storage: [database type and why] - Schema: [key entities and relationships] - Consistency: [eventual, strong] - Caching: [strategy and invalidation] Communication: - Sync: [direct service calls] - Async: [events, messages] - Service discovery: [how services find each other] - Circuit breaking: [failure handling] Operational Concerns: - Monitoring: [metrics, logs, traces] - Deployment: [containers, orchestration] - Configuration: [environment management] - Secrets: [handling sensitive data] Cross-Cutting Concerns: - Authentication: [how users are verified] - Authorization: [access control] - Rate limiting: [protecting the service] - Audit logging: [compliance needs] Please Provide: 1. Service interface definition 2. Internal architecture 3. Database schema 4. Event contracts 5. Deployment configuration 6. Monitoring setup ``` ### Database Design Template ```text Design a database schema for [application type]: Business Requirements: - Core entities: [users, products, orders] - Relationships: [how entities connect] - Business rules: [constraints, validations] - Reporting needs: [analytics, dashboards] Data Characteristics: - Volume: [records per entity] - Growth rate: [daily/monthly increase] - Read/write ratio: [80/20, 50/50] - Peak times: [usage patterns] Query Patterns: 1. [Common query with frequency] 2. [Complex aggregation needs] 3. [Real-time vs batch queries] Performance Requirements: - Query response time: [targets] - Write throughput: [inserts/second] - Concurrent users: [expected load] Consistency Requirements: - ACID needs: [transactions required?] - Eventual consistency: [acceptable?] - Referential integrity: [strict or relaxed] Please Design: 1. Entity relationship diagram 2. Table definitions with types 3. Indexes and keys 4. Partitioning strategy 5. Denormalization decisions 6. Migration approach from current schema ``` ### Event-Driven Architecture Template ```text Design an event-driven system for [use case]: Event Sources: - User actions: [clicks, form submissions] - System events: [cron jobs, monitors] - External triggers: [webhooks, APIs] Event Types: 1. [Event name: payload structure] 2. [Event name: payload structure] Event Flow: - Producers: [who creates events] - Consumers: [who processes events] - Routing: [how events reach consumers] Processing Requirements: - Ordering: [FIFO, partial order, none] - Delivery: [at-least-once, exactly-once] - Latency: [real-time, near-real-time] - Throughput: [events per second] Error Handling: - Failed processing: [retry strategy] - Dead letter queue: [for failures] - Monitoring: [alerting on issues] Storage: - Event store: [retention period] - Replay capability: [reprocess events] - Audit trail: [compliance needs] Please Design: 1. Event schema definitions 2. Topic/queue structure 3. Consumer patterns 4. Error handling flows 5. Monitoring approach 6. Scaling strategy ```