Plan Mode for Strategic Thinking: Architecture Before Implementation

James Phoenix
James Phoenix

Summary

Claude Code often jumps directly to implementation without considering architectural complexity, leading to rework and technical debt. Plan Mode (Shift+Tab) enables strategic thinking before execution, allowing you to map out architecture, identify dependencies, and validate approaches before writing code. Use it for architecture planning, feature design, migrations, and performance optimization.

The Problem

Claude Code jumps to implementation without thinking through complexity, leading to incomplete solutions, missed dependencies, architectural violations, and frequent rework. Developers waste time on implementation-then-refactor cycles instead of thinking strategically upfront.

The Solution

Use Claude Code’s Plan Mode (Shift+Tab) for strategic thinking before execution. Plan Mode lets you explore architecture, identify dependencies, validate approaches, and get feedback without writing code. Once the plan is solid, exit to execution mode for implementation. Pattern: Plan Mode (strategic thinking) → Exit Plan Mode → Execution Mode (implementation).

The Problem

When you ask Claude Code to implement a feature, it often jumps straight to writing code without pausing to think through:

  • Architectural complexity: How does this fit into the existing system?
  • Dependencies: What other components need to change?
  • Edge cases: What can go wrong?
  • Trade-offs: Are there better approaches?
  • Impact: What will this break?

This “code-first” approach leads to:

1. Incomplete Solutions

// You ask: "Add user authentication"
// Claude generates:
export function login(email: string, password: string) {
  // Basic implementation
  return verifyPassword(email, password);
}

// Missing:
// - Rate limiting
// - Session management
// - Password reset flow
// - Email verification
// - OAuth integration
// - Audit logging

2. Architectural Violations

// You ask: "Add a new API endpoint"
// Claude generates:
export async function handler(req: Request) {
  // Direct database access from API layer
  const result = await db.users.findMany();
  return Response.json(result);
}

// Problems:
// ❌ Violates layered architecture (API → DB directly)
// ❌ Skips application layer (business logic)
// ❌ No domain modeling
// ❌ No repository abstraction

3. Missed Dependencies

// You ask: "Change User type to include roles"
// Claude updates:
interface User {
  id: string;
  email: string;
  roles: Role[]; // Added
}

// Forgot to update:
// - UserRepository (database queries)
// - AuthService (permission checks)
// - API DTOs (request/response types)
// - Tests (user fixtures)
// - Migration scripts (database schema)

4. Implementation-Then-Refactor Cycles

Iteration 1: Implement basic version
Iteration 2: Realize it breaks layered architecture, refactor
Iteration 3: Realize it's missing error handling, add it
Iteration 4: Realize it doesn't handle edge cases, fix them
Iteration 5: Realize tests are failing, update them

Result: 5 iterations for something that could have been planned upfront

Why This Happens

Claude Code defaults to execution mode, which optimizes for:

  • Speed: Get to code as fast as possible
  • Action: Write files, make changes, run tests
  • Iteration: Generate → Test → Fix → Repeat

But some tasks need strategic thinking first:

  • Understanding: What are we really building?
  • Planning: How should this work architecturally?
  • Validation: Is this the right approach?
  • Risk assessment: What could go wrong?

The Solution: Plan Mode

Claude Code has a Plan Mode specifically designed for strategic thinking before implementation.

What is Plan Mode?

Plan Mode is a thinking-first mode where Claude:

  • Explores the problem space
  • Analyzes the codebase architecture
  • Proposes multiple approaches
  • Identifies dependencies and risks
  • Validates the plan with you
  • Does NOT write code yet

Once the plan is solid, you exit Plan Mode and Claude switches to execution mode to implement it.

Accessing Plan Mode

Keyboard shortcut: Shift + Tab

Normal Mode (Execution):  Type → Enter → Claude implements
Plan Mode (Strategic):    Type → Shift+Tab → Claude plans (no code)

The Two-Phase Pattern

Phase 1: PLAN MODE (Strategic Thinking)
├─ Understand requirements
├─ Analyze architecture
├─ Identify dependencies
├─ Propose approaches
├─ Validate with human
└─ Exit plan mode

Phase 2: EXECUTION MODE (Implementation)
├─ Follow the plan
├─ Write code
├─ Run tests
├─ Fix issues
└─ Done

When to Use Plan Mode

1. Architecture Planning

Use Plan Mode when:

  • Adding a new layer to the architecture
  • Introducing a new pattern (e.g., CQRS, event sourcing)
  • Refactoring from one pattern to another
  • Designing a new module or service

Example prompt:

"Plan how to add a caching layer to our application:
- Should it sit between API and application layer?
- Redis vs. in-memory?
- Cache invalidation strategy?
- Impact on existing code?

Don't implement yet, just give me a plan."

Plan Mode output:

# Caching Layer Architecture Plan

## Proposed Architecture

API Layer
  ↓
Cache Middleware (NEW)
  ↓
Application Layer
  ↓
Domain Layer
  ↓
Infrastructure Layer

## Technology Choice: Redis

Rationale:
- Distributed caching (multiple instances)
- TTL support (automatic expiration)
- Pub/sub for cache invalidation
- Production-ready

Trade-offs:
- Adds infrastructure dependency
- Network latency vs. in-memory
- Cost: ~$20/month for managed Redis

## Cache Invalidation Strategy

1. Time-based (TTL):
   - User data: 5 minutes
   - Static content: 1 hour
   - Config: 10 minutes

2. Event-based:
   - On user update → invalidate user cache
   - On content publish → invalidate content cache

## Files That Need Changes

1. packages/api/src/middleware/cache.ts (NEW)
   - Cache middleware with Redis client

2. packages/application/src/use-cases/*.ts (UPDATE)
   - Add cache checks before DB queries
   - Emit invalidation events

3. packages/infrastructure/src/redis/ (NEW)
   - Redis client factory
   - Connection pooling

4. docker-compose.yml (UPDATE)
   - Add Redis service

5. .env.example (UPDATE)
   - Add REDIS_URL config

## Risks

- Cache stampede on popular items
- Stale data if invalidation fails
- Increased complexity

## Recommendation

Start with:
1. Add Redis to docker-compose
2. Implement cache middleware
3. Apply to read-heavy endpoints only
4. Monitor hit rates before expanding

Now you can review, discuss, and refine before any code is written.

2. Feature Planning

Use Plan Mode when:

  • Adding a complex feature with many moving parts
  • Integrating a third-party service
  • Building a new user flow

Example prompt:

"Plan how to implement two-factor authentication:
- Where does it fit in the auth flow?
- What tables/types are needed?
- Which libraries should we use?
- Impact on existing login logic?

Provide a detailed plan before implementation."

Plan Mode output:

# Two-Factor Authentication Plan

## Architecture Overview

Current Flow:
Login → Password Verify → Session Created

New Flow:
Login → Password Verify → 2FA Challenge → Verify Code → Session Created

## Database Changes

New table: `user_2fa_settings`

```sql
CREATE TABLE user_2fa_settings (
  user_id UUID PRIMARY KEY REFERENCES users(id),
  enabled BOOLEAN DEFAULT false,
  secret TEXT NOT NULL,
  backup_codes TEXT[],
  created_at TIMESTAMPTZ DEFAULT NOW()
);

New Types

interface TwoFactorSettings {
  enabled: boolean;
  secret: string;
  backupCodes: string[];
}

interface TwoFactorChallenge {
  userId: string;
  challengeToken: string;
  expiresAt: Date;
}

Library Recommendation

Use otplib:

  • TOTP (Time-based OTP) support
  • QR code generation
  • Well-maintained
  • 2M downloads/week
npm install otplib qrcode

Implementation Steps

  1. Domain Layer (packages/domain/):

    • Add TwoFactorSettings entity
    • Add TwoFactorChallenge value object
  2. Infrastructure Layer (packages/infrastructure/):

    • Add TwoFactorRepository
    • Implement TOTP service wrapper
  3. Application Layer (packages/application/):

    • Update LoginUseCase to check 2FA
    • Add Enable2FAUseCase
    • Add Verify2FAUseCase
  4. API Layer (packages/api/):

    • Add POST /auth/2fa/enable
    • Add POST /auth/2fa/verify
    • Update POST /auth/login flow
  5. Database (migrations/):

    • Add user_2fa_settings table
  6. Tests:

    • Unit tests for TOTP service
    • Integration tests for 2FA flow
    • E2E tests for login with 2FA

Edge Cases to Handle

  • User loses phone → Use backup codes
  • Backup codes exhausted → Contact support flow
  • User wants to disable 2FA → Re-verify password
  • 2FA setup incomplete → Don’t enforce until confirmed

Timeline Estimate

  • Day 1: Domain + Infrastructure (2FA service)
  • Day 2: Application layer (use cases)
  • Day 3: API layer (endpoints)
  • Day 4: Tests + Documentation
  • Day 5: Buffer for issues

Total: ~1 week


**With this plan, you can:**
- Validate the approach
- Adjust timeline
- Identify missing pieces
- Get team buy-in
- **Then** start implementation with confidence

### 3. Migration Planning

**Use Plan Mode when**:
- Migrating from one technology to another
- Upgrading a major dependency
- Refactoring a large module
- Changing database schema

**Example prompt**:

“Plan how to migrate from REST API to tRPC:

  • What’s the migration strategy?
  • Can we do it incrementally?
  • Which endpoints to migrate first?
  • How to maintain backwards compatibility?

Provide a phased migration plan.”


**Plan Mode output**:

```markdown
# REST to tRPC Migration Plan

## Strategy: Incremental Parallel Migration

Run REST and tRPC side-by-side:
- New features → tRPC only
- Existing features → Migrate incrementally
- Keep REST until all clients migrated

## Phase 1: Infrastructure Setup (Week 1)

1. Add tRPC packages:
   ```bash
   npm install @trpc/server @trpc/client @trpc/react-query
  1. Create tRPC router structure:

    packages/api/src/trpc/
    ├── context.ts
    ├── router.ts
    └── routers/
        ├── users.ts
        ├── posts.ts
        └── index.ts
    
  2. Mount tRPC alongside REST:

    Udemy Bestseller

    Learn Prompt Engineering

    My O'Reilly book adapted for hands-on learning. Build production-ready prompts with practical exercises.

    4.5/5 rating
    306,000+ learners
    View Course
    app.use('/api/rest', restRouter); // Existing
    app.use('/api/trpc', trpcHandler); // New
    

Phase 2: Migrate Read Endpoints (Week 2-3)

Start with GET endpoints (lowest risk):

Priority 1: High-traffic, simple endpoints

  • GET /users/:id → trpc.users.getById
  • GET /posts → trpc.posts.list
  • GET /posts/:id → trpc.posts.getById

Implementation pattern:

// OLD: REST endpoint
app.get('/api/users/:id', async (req, res) => {
  const user = await getUserById(req.params.id);
  res.json(user);
});

// NEW: tRPC procedure
export const usersRouter = router({
  getById: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(({ input }) => getUserById(input.id)),
});

// Keep REST endpoint for backwards compatibility

Phase 3: Migrate Write Endpoints (Week 4-5)

POST/PUT/DELETE (higher risk, needs testing):

  • POST /users → trpc.users.create
  • PUT /users/:id → trpc.users.update
  • DELETE /users/:id → trpc.users.delete

Validation strategy:

// Use same validation schemas
import { createUserSchema } from '@repo/validation';

export const usersRouter = router({
  create: protectedProcedure
    .input(createUserSchema) // Reuse existing Zod schema
    .mutation(({ input }) => createUser(input)),
});

Phase 4: Update Clients (Week 6-8)

Web app (packages/web/):

// OLD: Fetch API
const user = await fetch('/api/users/123').then(r => r.json());

// NEW: tRPC client
const user = await trpc.users.getById.query({ id: '123' });

Incremental approach:

  • Update one feature at a time
  • Keep REST client as fallback
  • Remove REST calls after validation

Phase 5: Deprecate REST (Week 9-10)

  1. Add deprecation warnings:

    app.use('/api/rest', (req, res, next) => {
      res.setHeader('X-API-Deprecated', 'true');
      next();
    });
    
  2. Monitor REST usage (expect 0)

  3. Remove REST endpoints

  4. Clean up REST infrastructure

Rollback Plan

If tRPC has issues:

  • Keep REST endpoints active
  • Switch clients back to REST
  • Debug tRPC issues
  • Re-attempt migration

Success Metrics

  • ✅ 100% tRPC test coverage
  • ✅ 0 REST API calls in production
  • ✅ Type safety across client/server
  • ✅ No performance regression

### 4. Performance Planning

**Use Plan Mode when**:
- Optimizing slow endpoints
- Reducing database queries
- Improving frontend performance
- Scaling infrastructure

**Example prompt**:

“Plan how to optimize the /users endpoint that’s taking 5 seconds:

  • Analyze current implementation
  • Identify bottlenecks
  • Propose optimization strategies
  • Estimate impact of each optimization

Provide a detailed performance optimization plan.”


## Best Practices

### 1. Use Plan Mode for High-Stakes Changes

✅ USE PLAN MODE:

  • New architecture layers
  • Database schema changes
  • Third-party integrations
  • Security-critical features
  • Cross-cutting concerns

❌ DON’T NEED PLAN MODE:

  • Simple bug fixes
  • Typo corrections
  • Documentation updates
  • Adding a single function
  • Style/formatting changes

### 2. Be Specific in Plan Mode Prompts

❌ Vague:
“Plan how to add authentication”

✅ Specific:
“Plan how to add JWT-based authentication:

  • Where does it fit in our layered architecture?
  • What middleware is needed?
  • How to handle token refresh?
  • Impact on existing API endpoints?
  • Testing strategy?”

### 3. Review Plans Before Exiting

**Plan Mode gives you a checkpoint**:

```markdown
1. Read the plan carefully
2. Ask clarifying questions
3. Request alternatives if needed
4. Validate against CLAUDE.md patterns
5. Check for missed dependencies
6. Ensure tests are included
7. Only THEN exit to execution mode

4. Iterate on Plans

You can stay in Plan Mode and refine:

You: "Plan adding authentication"
Claude: [Provides plan with JWT]

You: "What if we used sessions instead of JWT?"
Claude: [Provides alternative plan]

You: "Compare both approaches - pros/cons"
Claude: [Provides comparison]

You: "Let's go with sessions. Refine the plan."
Claude: [Provides detailed session-based plan]

You: "Perfect. Exit plan mode and implement this."
Claude: [Exits plan mode → Starts implementation]

5. Combine with Hierarchical CLAUDE.md

Plan Mode reads your CLAUDE.md files:

packages/
├── api/
│   └── CLAUDE.md (API patterns)
├── application/
│   └── CLAUDE.md (Use case patterns)
├── domain/
│   └── CLAUDE.md (Domain patterns)
└── infrastructure/
    └── CLAUDE.md (Infrastructure patterns)

In Plan Mode:

"Plan adding a new use case following our patterns"

Claude reads:
- Root CLAUDE.md (architecture rules)
- packages/application/CLAUDE.md (use case patterns)
- Related CLAUDE.md files (domain, infrastructure)

Then provides a plan that follows YOUR patterns

6. Save Plans for Future Reference

After exiting Plan Mode, save the plan:

# docs/architecture-decisions/2025-11-02-add-caching-layer.md

## Context
API response times are slow (2-3 seconds)

## Decision
Add Redis caching layer between API and application

## Plan
[Paste Plan Mode output here]

## Implementation
Completed: 2025-11-05
PR: #123

Integration with Other Patterns

Plan Mode + Engineering Manager Mindset

Plan Mode embodies the Engineering Manager Mindset:

  • Strategic thinking: “What’s the right approach?”
  • Risk assessment: “What could go wrong?”
  • Resource planning: “How long will this take?”
  • Dependency mapping: “What else needs to change?”

See: Layered Prompts Architecture

Plan Mode + Hierarchical CLAUDE.md

Plan Mode reads your CLAUDE.md files to understand:

  • Architecture patterns
  • Coding standards
  • Domain rules
  • Infrastructure constraints

The plan will follow your documented patterns automatically.

See: Hierarchical Context Patterns

Plan Mode + Multi-Step Workflows

Plan Mode naturally creates multi-step workflows:

Plan Mode output:
"Step 1: Update domain types
Step 2: Update repository interface
Step 3: Implement repository
Step 4: Add use case
Step 5: Add API endpoint
Step 6: Write tests"

Execution Mode:
Follows steps sequentially, validating each before moving to next

See: Incremental Development Pattern

Common Pitfalls

❌ Pitfall 1: Skipping Plan Mode for Complex Changes

Problem: “This seems simple, I’ll just tell Claude to implement it”

Result: 5 iterations of refactoring to get it right

Solution: Use Plan Mode for anything touching >3 files or multiple layers

❌ Pitfall 2: Exiting Plan Mode Too Early

Problem: Plan has gaps, but you’re eager to start coding

Result: Implementation gets stuck on missing details

Solution: Ensure plan is complete before exiting:

  • All files identified
  • All dependencies mapped
  • All edge cases considered
  • Testing strategy defined

❌ Pitfall 3: Not Reviewing the Plan

Problem: Claude provides plan, you immediately say “implement it”

Result: Plan has issues you didn’t catch

Solution: Always read and validate the plan:

  • Does it follow our architecture?
  • Are there better approaches?
  • Did it miss anything?
  • Is the timeline realistic?

❌ Pitfall 4: Using Plan Mode for Simple Changes

Problem: Using Plan Mode for “fix typo in README”

Result: Overhead for no benefit

Solution: Plan Mode is for strategic work, not trivial changes

Measuring Success

Metrics to Track

Before Plan Mode:

  • Average iterations per feature: 5-7
  • Architectural violations: 30% of PRs
  • Missed dependencies: 20% of features
  • Time to first working version: 2-3 days

After Plan Mode:

  • Average iterations per feature: 2-3 (50% reduction)
  • Architectural violations: 5% of PRs (83% reduction)
  • Missed dependencies: 5% of features (75% reduction)
  • Time to first working version: 1 day (50% faster)

Qualitative Improvements

  • Higher confidence: “I know this will work before writing code”
  • Better architecture: “The plan caught issues upfront”
  • Fewer rewrites: “Less implementation-then-refactor cycles”
  • Clearer communication: “The plan helped me explain to my team”

Conclusion

Plan Mode is Claude Code’s strategic thinking mode – use it before jumping to implementation for:

Architecture planning: New layers, patterns, modules
Feature planning: Complex features, integrations, user flows
Migration planning: Technology changes, refactoring, upgrades
Performance planning: Optimization strategies, bottleneck analysis

The Pattern:

Phase 1: PLAN MODE (Shift+Tab)
├─ Understand the problem
├─ Analyze architecture
├─ Propose approaches
├─ Identify dependencies
├─ Validate the plan
└─ Exit plan mode

Phase 2: EXECUTION MODE
├─ Follow the plan
├─ Implement step-by-step
├─ Test as you go
└─ Done (fewer iterations!)

Key Insight: 10 minutes of planning saves hours of refactoring.

Related Concepts

References

Topics
ArchitectureClaude CodeDeveloper ExperienceExecution ModeFeature PlanningImplementationMigration PlanningPlan ModePlanningStrategic Thinking

More Insights

Cover Image for Thought Leaders

Thought Leaders

People to follow for compound engineering, context engineering, and AI agent development.

James Phoenix
James Phoenix
Cover Image for Systems Thinking & Observability

Systems Thinking & Observability

Software should be treated as a measurable dynamical system, not as a collection of features.

James Phoenix
James Phoenix