All prompts

Metaprompting

Coding metaprompt examples

Worked examples spanning implementation, debugging, refactoring, and design.

Format
Markdown
Length
2690 words
Read
~12 min

Source

Markdown
Download
# Coding Metaprompt Examples for Claude Code

## Code Generation Examples

### Example 1: React Component with TypeScript

**Metaprompt Input:**
"Create a React component for a searchable, sortable data table that supports pagination and CSV export."

**Generated Prompt:**

```text
Create a DataTable React component in TypeScript that:

Context:
- Language: TypeScript 5.x
- Framework: React 18 with hooks
- Project structure: components/, hooks/, utils/, types/
- Existing patterns: Custom hooks for data fetching, Material-UI components

Requirements:
- Must support: Search across all columns, Sort by any column (asc/desc), Pagination with customizable page size, CSV export of filtered data
- Should handle: Empty states, Loading states, Error states, Large datasets (1000+ rows)
- Performance: Virtual scrolling for 1000+ rows, Debounced search, Memoized sort operations
- Security: XSS prevention in rendered cells, Safe CSV generation

Technical Specifications:
- Input: Array of objects with any shape, Column definitions with key, label, sortable, searchable flags
- Output: Rendered table with controls, CSV download functionality
- Error handling: Network errors, Invalid data, Export failures
- Logging: Search queries, Sort operations, Export events

Code Style:
- Naming convention: camelCase for functions, PascalCase for components
- Documentation: JSDoc comments for public methods
- Test coverage: Unit tests for utilities, Integration tests for component

Deliverables:
1. Main DataTable component
2. useTableData custom hook
3. Utility functions (search, sort, export)
4. TypeScript interfaces
5. Unit tests using Jest/React Testing Library
```

### Example 2: Python FastAPI Service

**Metaprompt Input:**
"Build a rate-limited authentication service with JWT tokens and refresh token rotation."

**Generated Prompt:**

```text
Implement a REST API authentication service using FastAPI:

Endpoint Details:
- POST /auth/register - User registration
- POST /auth/login - User login with credentials
- POST /auth/refresh - Refresh access token
- POST /auth/logout - Invalidate refresh token
- GET /auth/me - Get current user info

Request/Response:
- Register: {email, password, name} → {user_id, message}
- Login: {email, password} → {access_token, refresh_token, expires_in}
- Refresh: {refresh_token} → {access_token, expires_in}
- All responses follow: {success: bool, data?: any, error?: string}

Business Logic:
- Password requirements: 8+ chars, 1 uppercase, 1 number, 1 special
- Token expiry: Access = 15 minutes, Refresh = 7 days
- Refresh rotation: New refresh token on each use
- Rate limiting: 5 attempts per minute per IP for login/register

Security Requirements:
- Bcrypt for password hashing (12 rounds)
- JWT with RS256 algorithm
- Refresh tokens stored in Redis with expiry
- Rate limiting using Redis
- CORS configuration for SPA frontend

Performance Requirements:
- Response time: <100ms for auth operations
- Concurrent requests: Support 1000 concurrent users
- Redis connection pooling
- Async database operations with asyncpg

Include:
- Pydantic models for validation
- Custom exception handlers
- Comprehensive logging with request IDs
- Unit tests with pytest
- Docker compose setup with PostgreSQL and Redis
- Migration scripts using Alembic
```

### Example 3: Rust System Utility

**Metaprompt Input:**
"Create a CLI tool that monitors system resources and sends alerts when thresholds are exceeded."

**Generated Prompt:**

```text
Implement a system monitoring CLI tool in Rust:

Problem Specification:
- Monitor: CPU usage, Memory usage, Disk I/O, Network traffic
- Alert when: Any metric exceeds configured threshold for 30 seconds
- Output: Terminal UI with graphs, Log file, Optional webhook notifications

Examples:
- Input: sysmon --cpu-threshold 80 --mem-threshold 90
  Output: Real-time dashboard with alerts
- Input: sysmon --export csv --duration 1h
  Output: CSV file with hourly metrics

Requirements:
- Architecture: Multi-threaded with separate collectors per metric
- Update frequency: 1 second for display, 5 seconds for logging
- Memory usage: <50MB resident memory
- Platform support: Linux, macOS, Windows

Implementation Details:
- Use tokio for async runtime
- crossterm for terminal UI
- sysinfo crate for system metrics
- clap for CLI argument parsing
- serde for configuration
- reqwest for webhook notifications

Configuration:
- TOML config file support
- Environment variable overrides
- Command line arguments highest priority

Error Handling:
- Graceful degradation if metric unavailable
- Retry logic for webhook notifications
- Panic-free with Result types throughout

Testing:
- Unit tests for each collector
- Integration tests with mock system data
- Benchmarks for performance validation
```

## Debugging Examples

### Example 4: React State Management Bug

**Metaprompt Input:**
"Debug why my React component re-renders infinitely when fetching user data."

**Generated Prompt:**

```text
Debug the following infinite re-render issue:

Problem Description:
- What's broken: UserProfile component re-renders continuously
- When it occurs: After adding data fetching in useEffect
- Impact: Browser freezes, high CPU usage

Expected Behavior:
Component should fetch user data once on mount and re-fetch only when userId prop changes

Actual Behavior:
Component enters infinite loop, making continuous API calls

Code Context:
\`\`\`tsx
const UserProfile = ({ userId }) => {
  const [user, setUser] = useState(null);
  const [friends, setFriends] = useState([]);

  useEffect(() => {
    fetchUser(userId).then(data => {
      setUser(data);
      setFriends(data.friends);
    });
  });

  useEffect(() => {
    friends.forEach(friend => {
      fetchUserDetails(friend.id).then(details => {
        setFriends([...friends, details]);
      });
    });
  });

  return <div>{/* render user and friends */}</div>;
};
\`\`\`

Error Information:
- Console shows: "Maximum update depth exceeded"
- Network tab: Hundreds of API calls per second

Environment:
- React: 18.2.0
- Node: 18.x
- Browser: Chrome 120

What I've Tried:
1. Added console.logs - confirms infinite loop
2. Removed second useEffect - first one still loops

Please:
1. Identify the root cause of infinite re-renders
2. Explain the React rendering cycle issue
3. Provide corrected implementation
4. Suggest best practices for dependent data fetching
```

### Example 5: Python Memory Leak

**Metaprompt Input:**
"Investigate memory leak in data processing pipeline that handles large CSV files."

**Generated Prompt:**

```text
Investigate performance degradation in CSV processor:

Performance Problem:
- Operation: Processing large CSV files (1GB+)
- Current performance: Memory usage grows to 10GB for 1GB file
- Expected performance: Memory usage should stay under 2GB
- When it started: After adding data transformation features

Code Section:
\`\`\`python
class CSVProcessor:
    def __init__(self):
        self.processed_data = []
        self.cache = {}

    def process_file(self, filepath):
        df = pd.read_csv(filepath)

        for index, row in df.iterrows():
            # Transform data
            transformed = self.transform_row(row)
            self.processed_data.append(transformed)

            # Cache for lookups
            self.cache[row['id']] = transformed

        # Additional processing
        self.enriched_data = self.enrich_data(self.processed_data)

        return self.enriched_data

    def transform_row(self, row):
        # Complex transformation creating new objects
        result = {
            'original': row.to_dict(),
            'processed': heavy_computation(row),
            'metadata': generate_metadata(row)
        }
        return result
\`\`\`

Profiling Results:
- Memory profiler shows: CSVProcessor.cache grows unbounded
- processed_data list never cleared between files
- pandas DataFrame not released after processing

Requirements:
1. Identify memory leak sources
2. Explain Python's memory management in this context
3. Provide memory-efficient solution
4. Maintain same functionality
5. Consider streaming approach for large files
```

### Example 6: Node.js API Integration Timeout

**Metaprompt Input:**
"Debug intermittent timeout errors when calling third-party payment API from our Express server."

**Generated Prompt:**

```text
Debug integration failure between Express server and Payment Gateway API:

Integration Context:
- System A: Express.js server (Node 18)
- System B: Payment Gateway REST API
- Communication: HTTPS with OAuth2
- Data format: JSON

Error Symptoms:
- Error message: "ETIMEDOUT" or "Socket hang up"
- HTTP status: Request never completes
- Timing: Fails after exactly 30 seconds
- Frequency: ~20% of requests, increases during peak hours

Request Details:
\`\`\`javascript
const processPayment = async (paymentData) => {
  const token = await getOAuthToken();

  const response = await axios.post(
    'https://api.payment-gateway.com/v1/charge',
    {
      amount: paymentData.amount,
      currency: 'USD',
      customer: paymentData.customerId,
      metadata: paymentData.metadata
    },
    {
      headers: {
        'Authorization': \`Bearer \${token}\`,
        'Content-Type': 'application/json',
        'X-Idempotency-Key': generateIdempotencyKey()
      }
    }
  );

  return response.data;
};
\`\`\`

What Works:
- Same requests work fine from Postman
- Calls to other endpoints work reliably
- Works fine during low traffic periods

What Fails:
- Larger payment amounts (>$1000) fail more often
- Bulk processing triggers more timeouts
- Failures cluster during 9-11 AM EST

Environment Configuration:
- Server: AWS EC2 t3.medium
- Node: Running with 4 workers (cluster mode)
- Reverse proxy: Nginx with 60s timeout
- Network: Private subnet with NAT gateway

Please Investigate:
1. Connection pooling issues
2. DNS resolution problems
3. Keep-alive settings
4. Timeout configuration mismatches
5. Network layer issues (MTU, packet loss)
6. Rate limiting or throttling
```

## Refactoring Examples

### Example 7: Legacy JavaScript to Modern TypeScript

**Metaprompt Input:**
"Refactor legacy JavaScript validation module to TypeScript with improved type safety and testability."

**Generated Prompt:**

```text
Refactor the following validation code for improved type safety and testability:

Current Code:
\`\`\`javascript
var Validator = {
  rules: {},

  addRule: function(name, fn) {
    this.rules[name] = fn;
  },

  validate: function(data, schema) {
    var errors = [];

    for (var field in schema) {
      var rules = schema[field].split('|');
      var value = data[field];

      for (var i = 0; i < rules.length; i++) {
        var rule = rules[i].split(':');
        var ruleName = rule[0];
        var ruleParam = rule[1];

        if (this.rules[ruleName]) {
          var result = this.rules[ruleName](value, ruleParam);
          if (!result) {
            errors.push(field + ' failed ' + ruleName);
          }
        }
      }
    }

    return errors.length ? errors : null;
  }
};

// Usage
Validator.addRule('required', function(value) {
  return value !== null && value !== undefined && value !== '';
});

Validator.addRule('minLength', function(value, param) {
  return value && value.length >= parseInt(param);
});

var errors = Validator.validate(
  {name: 'John', email: ''},
  {name: 'required|minLength:2', email: 'required'}
);
\`\`\`

Refactoring Goals:
- Primary: Full TypeScript conversion with strict types
- Secondary: Improve testability, Support async validators, Better error messages

Specific Issues to Address:
1. No type safety - anything can be passed
2. Global state in rules object
3. String parsing for rule definitions
4. Poor error messages
5. No support for custom error messages
6. Can't validate nested objects
7. No async validation support

Constraints:
- Must preserve: Basic API shape for backward compatibility
- Can modify: Internal implementation completely
- Cannot change: Rule string format (e.g., "required|minLength:2")

Design Patterns to Consider:
- Strategy pattern for validators
- Builder pattern for schema creation
- Result type for validation outcomes

Please Provide:
1. Full TypeScript implementation
2. Type definitions for all inputs/outputs
3. Support for async validators
4. Improved error messages with field context
5. Unit test examples
6. Migration guide from old to new API
```

### Example 8: SQL Query Optimization

**Metaprompt Input:**
"Optimize complex analytical query that times out on large dataset."

**Generated Prompt:**

```text
Optimize the following query for better performance:

Current Implementation:
\`\`\`sql
SELECT
  c.customer_id,
  c.name,
  c.email,
  COUNT(DISTINCT o.order_id) as total_orders,
  SUM(oi.quantity * oi.price) as lifetime_value,
  AVG(oi.quantity * oi.price) as avg_order_value,
  MAX(o.created_at) as last_order_date,
  DATEDIFF(NOW(), MAX(o.created_at)) as days_since_last_order,
  (
    SELECT GROUP_CONCAT(DISTINCT p.category)
    FROM order_items oi2
    JOIN products p ON oi2.product_id = p.product_id
    JOIN orders o2 ON oi2.order_id = o2.order_id
    WHERE o2.customer_id = c.customer_id
  ) as purchased_categories,
  CASE
    WHEN COUNT(DISTINCT o.order_id) > 10 THEN 'VIP'
    WHEN COUNT(DISTINCT o.order_id) > 5 THEN 'Regular'
    ELSE 'New'
  END as customer_tier
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
LEFT JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.created_at >= DATE_SUB(NOW(), INTERVAL 2 YEAR)
GROUP BY c.customer_id, c.name, c.email
HAVING lifetime_value > 100
ORDER BY lifetime_value DESC
LIMIT 1000;
\`\`\`

Performance Profile:
- Current execution time: 45+ seconds (timeout)
- Table sizes: customers (1M), orders (10M), order_items (50M)
- Execution plan shows: Full table scans, Using temporary, Using filesort

Database Info:
- MySQL 8.0
- Available indexes: Primary keys only
- Memory: 16GB available for MySQL
- Storage: SSD

Usage Patterns:
- Run hourly for dashboard
- Filters change based on date range
- Sometimes need all customers, sometimes top 1000

Requirements:
1. Reduce execution time to under 5 seconds
2. Maintain exact same result set
3. Consider materialized views if helpful
4. Suggest index strategy
5. Provide incremental optimization steps
```

### Example 9: Microservice Extraction

**Metaprompt Input:**
"Extract user notification functionality from monolithic Django app into separate microservice."

**Generated Prompt:**

```text
Refactor monolithic notification system into microservice:

Current Architecture:
- Monolithic Django application
- Notifications handled in multiple views
- Direct database writes to notification tables
- Celery tasks for email/SMS sending
- Tightly coupled with user model

Current Code Structure:
\`\`\`python
# In various views and models
def create_order(request):
    order = Order.objects.create(...)

    # Inline notification logic
    Notification.objects.create(
        user=order.user,
        type='order_created',
        title=f'Order #{order.id} created',
        body=render_to_string('notifications/order_created.html', {...})
    )

    # Send email
    send_email_task.delay(
        to=order.user.email,
        subject='Order Confirmation',
        template='order_confirmation.html',
        context={...}
    )

    # Send SMS if premium user
    if order.user.is_premium:
        send_sms_task.delay(order.user.phone, message)

# Notification preferences in User model
class User(AbstractUser):
    email_notifications = models.BooleanField(default=True)
    sms_notifications = models.BooleanField(default=False)
    notification_frequency = models.CharField(choices=...)
\`\`\`

Target Architecture:
- Separate notification service
- Event-driven communication
- Support multiple channels (email, SMS, push, in-app)
- User preference management
- Template management

Migration Requirements:
- Zero downtime deployment
- Gradual migration (feature flags)
- Data migration strategy
- Rollback capability

Technical Constraints:
- Keep Django for main app
- Use Python for notification service
- Message queue: RabbitMQ or Kafka
- Must support existing notification types

Please Provide:
1. Microservice API design
2. Event schema definitions
3. Database schema for notification service
4. Migration plan with phases
5. Example code for:
   - Event publisher (Django side)
   - Event consumer (microservice side)
   - API endpoints
6. Deployment configuration
7. Monitoring and debugging strategy
```

## Architecture Design Examples

### Example 10: Real-time Collaboration System

**Metaprompt Input:**
"Design a system for real-time collaborative document editing like Google Docs."

**Generated Prompt:**

```text
Design a real-time collaborative document editing system:

Functional Requirements:
1. Multiple users can edit the same document simultaneously
2. Changes appear in real-time for all users (<100ms latency)
3. Conflict resolution for concurrent edits
4. Cursor positions and selections visible to all users
5. Revision history with ability to revert
6. Offline support with sync when reconnected
7. Permission management (view, edit, admin)
8. Comments and suggestions feature

Non-Functional Requirements:
- Performance: Support 50 concurrent editors per document
- Scalability: 1M active documents, 10M total users
- Availability: 99.9% uptime
- Security: End-to-end encryption option, SOC2 compliance
- Latency: <100ms for edit propagation

Use Cases:
1. User types: Edit appears for all viewers in real-time
2. Conflict: Two users edit same sentence - both changes preserved
3. Offline: User edits offline, changes sync when online

Technical Constraints:
- Browser-based (no plugins)
- Mobile app support required
- Limited to text documents initially
- 10MB max document size

Please Design:
1. Overall system architecture
2. Real-time synchronization approach (OT vs CRDT)
3. Backend services breakdown
4. Data models for documents and changes
5. WebSocket vs WebRTC decision
6. Scaling strategy for concurrent connections
7. Conflict resolution algorithm
8. Client architecture (state management)
9. Caching and performance optimizations
10. Deployment architecture
```

### Example 11: Event-Driven E-commerce Platform

**Metaprompt Input:**
"Design an event-driven architecture for an e-commerce platform handling flash sales."

**Generated Prompt:**

```text
Design an event-driven e-commerce system optimized for flash sales:

Event Sources:
- User actions: Browse, add to cart, checkout, payment
- Inventory: Stock updates, reservations, releases
- Pricing: Flash sale start/end, dynamic pricing
- System: Order processing, shipment, notifications

Event Types:
1. ProductViewed: {userId, productId, timestamp, source}
2. CartItemAdded: {userId, productId, quantity, price}
3. StockReserved: {orderId, productId, quantity, expiresAt}
4. OrderPlaced: {orderId, userId, items[], total}
5. PaymentProcessed: {orderId, status, transactionId}
6. FlashSaleStarted: {saleId, products[], startTime, endTime}

Flash Sale Requirements:
- Handle 100K concurrent users
- 10K orders per minute at peak
- Prevent overselling (strict inventory)
- Fair queuing system
- Real-time inventory updates

Processing Requirements:
- Inventory reservations expire after 10 minutes
- Payment must complete within 15 minutes
- Event ordering crucial for inventory
- Exactly-once payment processing

Service Breakdown:
- API Gateway: REST/GraphQL endpoints
- Inventory Service: Stock management
- Cart Service: Session management
- Order Service: Order orchestration
- Payment Service: Payment processing
- Notification Service: Email/SMS/Push
- Analytics Service: Real-time metrics

Please Design:
1. Event bus architecture (Kafka setup)
2. Service communication patterns
3. Inventory management strategy
4. Flash sale queuing mechanism
5. Saga pattern for order processing
6. Event sourcing for audit trail
7. CQRS for read/write separation
8. Monitoring and alerting
9. Data consistency guarantees
10. Failure recovery procedures
```

### Example 12: Machine Learning Pipeline Platform

**Metaprompt Input:**
"Design a platform for building, training, and deploying ML models with experiment tracking."

**Generated Prompt:**

```text
Design an ML platform for end-to-end model lifecycle:

Functional Requirements:
1. Dataset versioning and management
2. Experiment tracking and comparison
3. Distributed model training
4. Hyperparameter optimization
5. Model versioning and registry
6. A/B testing for model deployment
7. Real-time and batch inference
8. Model monitoring and drift detection
9. AutoML capabilities
10. Jupyter notebook integration

Non-Functional Requirements:
- Scalability: Support 1000 concurrent experiments
- Performance: Train on datasets up to 1TB
- Multi-cloud: AWS, GCP, Azure support
- Security: Data encryption, access control
- Cost optimization: Spot instance usage

User Workflows:
1. Data scientist uploads dataset, versions it
2. Creates experiment, selects algorithm
3. Configures hyperparameters, starts training
4. Monitors progress, compares results
5. Deploys best model to staging
6. Runs A/B test against production
7. Promotes to production if successful

Technical Stack Considerations:
- Python-based (scikit-learn, TensorFlow, PyTorch)
- Kubernetes for orchestration
- Object storage for datasets
- GPU support required
- Real-time feature store needed

Please Design:
1. High-level platform architecture
2. Data pipeline architecture
3. Training job orchestration
4. Model registry design
5. Serving infrastructure (real-time/batch)
6. Experiment tracking schema
7. Feature store implementation
8. Monitoring and observability
9. CI/CD for ML workflows
10. Multi-tenancy approach
11. Cost allocation system
12. Security architecture
```