Prompt Engineering
Beyond basic CLAUDE.md configuration, expert users develop systematic approaches to prompting that consistently produce better results.
The Prompt Stack
Section titled “The Prompt Stack”Claude Code processes prompts in layers:
┌─────────────────────────────────────────┐│ 1. System prompt (Anthropic's base) │ ← You can't change this├─────────────────────────────────────────┤│ 2. CLAUDE.md (project context) │ ← Always loaded├─────────────────────────────────────────┤│ 3. Session context (conversation) │ ← Accumulates├─────────────────────────────────────────┤│ 4. Your current message │ ← Most recent = most attention└─────────────────────────────────────────┘Each layer affects output. Optimize all of them.
CLAUDE.md Optimization
Section titled “CLAUDE.md Optimization”Your CLAUDE.md is always in context. Make every token count.
The Effective Structure
Section titled “The Effective Structure”# [Project Name]
## Critical (Read First)- [Absolute rules that must never be broken]- [Security constraints]- [Off-limits files/patterns]
## Context[One paragraph: what this is, tech stack, key patterns]
## Commands- `make dev` - start server- `make test` - run tests
## Conventions- [Code style rules]- [Naming conventions]- [File organization patterns]What to Include
Section titled “What to Include”| Include | Why |
|---|---|
| Critical constraints | Prevents catastrophic mistakes |
| Tech stack summary | Focuses tool/library suggestions |
| Key commands | Enables autonomous execution |
| Naming conventions | Produces consistent code |
| File patterns | Helps navigation |
What to Exclude
Section titled “What to Exclude”| Exclude | Why |
|---|---|
| Project history | Wastes tokens |
| Team member bios | Irrelevant to coding |
| Exhaustive file lists | Claude can explore |
| Full API documentation | Pull on-demand via MCP |
| Configuration details | Claude can read config files |
Message Construction
Section titled “Message Construction”The Anatomy of an Effective Prompt
Section titled “The Anatomy of an Effective Prompt”[Context] → [Task] → [Constraints] → [Format]Example:
> I'm working on the payment module (context).> Add retry logic for failed charges (task).> Use exponential backoff, max 3 retries,> don't retry on card_declined errors (constraints).> Add tests for each retry scenario (format/output).Specificity Beats Length
Section titled “Specificity Beats Length”# Bad: Long and vague> I need you to help me with the authentication> system in my application. There are some issues> with how users are being logged in and I want> to make it better and more secure.
# Good: Short and specific> Add rate limiting to POST /auth/login> - 5 attempts per IP per minute> - Return 429 with Retry-After header> - Store counts in RedisPrompt Patterns That Work
Section titled “Prompt Patterns That Work”1. The Constraint Sandwich
Section titled “1. The Constraint Sandwich”Put critical constraints at the start AND end:
> IMPORTANT: Do not modify any files in core/>> Refactor the user service to use dependency injection>> Remember: core/ is off-limitsWhy: Claude attends most to the beginning and end of prompts.
2. The Example Anchor
Section titled “2. The Example Anchor”Show, don’t just tell:
> Format new API routes like this existing one:
> @router.post("/users")> async def create_user(user: UserCreate, db: DB = Depends(get_db)):> """Create a new user."""> return await user_service.create(db, user)
> Now add: GET /users/{id}, PUT /users/{id}, DELETE /users/{id}3. The Explicit Negative
Section titled “3. The Explicit Negative”State what NOT to do:
> Add caching to the product queries>> Do NOT:> - Modify the Product model> - Add new dependencies> - Change the API response format4. The Phased Approach
Section titled “4. The Phased Approach”Break complex work into explicit phases:
> Let's do this in steps:>> Phase 1: Add the database migration> Phase 2: Update the model> Phase 3: Add the API endpoint> Phase 4: Write tests>> Start with Phase 1. Wait for my approval before each phase.5. The Output Template
Section titled “5. The Output Template”Specify exact output format:
> Review this code and output your findings as:>> ## Security Issues> - [issue]: [file:line] - [description]>> ## Bugs> - [issue]: [file:line] - [description]>> ## Suggestions> - [suggestion]: [rationale]Testing Your Prompts
Section titled “Testing Your Prompts”The A/B Approach
Section titled “The A/B Approach”When something isn’t working, test variations:
# Attempt Aclaude -p "add input validation to the user form"
# Attempt Bclaude -p "add input validation to the user form following the pattern in forms/product.py"
# Compare resultsThe Regression Check
Section titled “The Regression Check”After changing CLAUDE.md, verify it still handles known tasks:
# Your test tasksclaude -p "explain the auth flow" # Should match expected outputclaude -p "where is user data stored" # Should find correct filesclaude -p "add a new API endpoint" # Should follow conventionsCommon Anti-Patterns
Section titled “Common Anti-Patterns”❌ The Info Dump
Section titled “❌ The Info Dump”# Bad: Pasting everything upfront> Here's all our documentation: [10 pages]> Here's the relevant code: [5 files]> Here's the ticket: [500 words]> What do you think?Fix: Let Claude pull what it needs:
> The ticket is in docs/tickets/AUTH-123.md> Implement it following our patterns❌ The Mind Reader
Section titled “❌ The Mind Reader”# Bad: Assuming Claude knows your preferences> make it better> fix the issues> clean this upFix: Be explicit:
> Reduce the cyclomatic complexity of this function> Extract the validation logic into a separate method> Add type hints to all parameters❌ The Moving Target
Section titled “❌ The Moving Target”# Bad: Changing requirements mid-stream> add a login page> [Claude implements]> actually make it a modal> [Claude changes]> wait, add OAuth tooFix: Plan first:
> Before implementing, let's define:> - Login method: modal or page?> - Auth providers: password only or OAuth?> - Session handling: JWT or cookies?Advanced: Prompt Chaining
Section titled “Advanced: Prompt Chaining”For complex tasks, chain prompts across sessions:
# Session 1: Planningclaude -p "create a spec for adding search functionality" > spec.md
# Session 2: Implementationclaude -p "implement the spec in spec.md, start with the backend"
# Session 3: Testingclaude -p "write comprehensive tests for the search feature we just built"Each session gets fresh context focused on its phase.