Advanced25 min1 prerequisite

Master expert-level techniques for maximizing productivity with Claude Code in complex development scenarios.

Advanced Patterns

This lesson covers expert-level techniques for using Claude Code in complex development scenarios—from architecture decisions to team workflows.

Architecture-Level Work

System Design Sessions

Use Claude Code for architectural discussions. For example, you might say:

You: "I need to add real-time features to our e-commerce platform. Users should see live inventory updates and order status changes. We're currently on Next.js with PostgreSQL."

Claude Code will analyze your current architecture by reading database schema, API routes, and frontend structure. It then provides options:

Option 1: WebSockets with Socket.io

  • Pros: Full duplex, low latency, wide browser support
  • Cons: Requires separate server, connection management
  • Best for: High-frequency updates, bidirectional communication

Option 2: Server-Sent Events (SSE)

  • Pros: Simple, works with existing HTTP, auto-reconnect
  • Cons: One-way only, limited connections per browser
  • Best for: Server-to-client updates like inventory

Option 3: Supabase Realtime

  • Pros: Built on PostgreSQL, minimal code changes
  • Cons: Adds dependency, requires Supabase migration
  • Best for: Already considering Supabase

Claude Code might recommend SSE for inventory updates (simple, one-way) and WebSockets for order status (bidirectional, important).

Codebase Audits

Ask Claude Code to audit your codebase for potential issues:

You: "Audit this codebase for potential issues"

Claude Code performs a comprehensive audit and reports findings:

Security Issues (3 found):

  1. SQL Injection Risk at src/lib/search.ts:45
  2. Missing Rate Limiting at src/app/api/auth/login/route.ts
  3. Exposed API Keys at src/lib/analytics.ts:12

Performance Issues (5 found):

  1. N+1 Query at src/app/products/page.tsx:23
  2. Missing Indexes on orders.user_id, products.category_id

Migration Planning

You: "We need to migrate from JavaScript to TypeScript"

Claude Code analyzes your codebase:

  • 127 JavaScript files
  • 45 JSX components
  • 32 utility files
  • 28 API routes
  • 22 test files

And creates a phased migration plan:

  • Phase 1: Configuration (Day 1) - Add tsconfig, update build scripts
  • Phase 2: Utilities (Days 2-3) - Migrate /lib files
  • Phase 3: API Routes (Days 4-5) - Add request/response types
  • Phase 4: Components (Days 6-10) - Start with leaf components
  • Phase 5: Tests (Days 11-12) - Update test configuration

Complex Refactoring

Large File Decomposition

You: "UserDashboard.tsx is 2000 lines. Refactor it properly."

Claude Code analyzes the component and proposes a new architecture:

Terminal
components/dashboard/
├── UserDashboard.tsx          (80 lines - composition)
├── hooks/
   ├── useDashboardData.ts    (100 lines - data fetching)
   └── useDashboardState.ts   (80 lines - state)
├── sections/
   ├── ProfileSection.tsx     (200 lines)
   ├── OrdersSection.tsx      (180 lines)
   └── SettingsSection.tsx    (150 lines)
├── components/
   ├── OrderCard.tsx          (60 lines)
   ├── ProfileForm.tsx        (120 lines)
   └── SettingsForm.tsx       (100 lines)
└── utils/
    └── dashboardHelpers.ts    (80 lines)

Benefits: Each file under 200 lines, clear separation of concerns, reusable hooks and components, easier testing.

Pattern Implementation

You: "Add error boundaries with retry logic throughout the app"

Claude Code creates a comprehensive ErrorBoundary component with retry capability:

Terminal
'use client'

import { Component, ErrorInfo, ReactNode } from 'react'

interface Props {
  children: ReactNode
  fallback?: ReactNode
  onError?: (error: Error, info: ErrorInfo) => void
}

interface State {
  hasError: boolean
  error: Error | null
  retryCount: number
}

export class ErrorBoundary extends Component {
  state = { hasError: false, error: null, retryCount: 0 }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error, retryCount: 0 }
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    this.props.onError?.(error, info)
    logErrorToService(error, info)
  }

  handleRetry = () => {
    this.setState((prev: State) => ({
      hasError: false,
      error: null,
      retryCount: prev.retryCount + 1
    }))
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        // ErrorFallback component with retry button
        null
      )
    }
    return this.props.children
  }
}

Claude Code then wraps critical sections and adds error logging.

Multi-Repository Work

Monorepo Management

You: "This is a monorepo with apps/ and packages/. Add a new shared package for form validation."

Claude Code reads workspace configuration and existing packages, then:

  1. Creates packages/forms/package.json with proper workspace deps
  2. Creates tsconfig.json extending base
  3. Creates src/index.ts with exports
  4. Creates validation schemas
  5. Adds to turbo.json pipeline
  6. Updates root package.json
  7. Updates consumer apps

Cross-Repository Analysis

You: "Compare our backend API with the mobile team's client. Check for any mismatches."

Claude Code analyzes both repositories and reports:

Matching endpoints: 24/27

Mismatches found:

  1. GET /api/orders - Backend returns { orders, total }, mobile expects { data, count }
  2. POST /api/checkout - Backend expects { items }, mobile sends { products }
  3. User.avatar field - Backend uses avatar_url, mobile uses avatarUrl

Testing Strategies

Comprehensive Test Generation

You: "Generate tests for the checkout flow. Cover edge cases."

Claude Code creates comprehensive tests covering:

Terminal
describe('Checkout Flow', () => {
  describe('Happy Path', () => {
    it('completes checkout with valid cart and payment')
    it('applies discount codes correctly')
    it('calculates shipping based on address')
    it('sends confirmation email after success')
  })

  describe('Error Handling', () => {
    it('handles Stripe payment failure gracefully')
    it('retries on network timeout')
    it('shows clear error for declined card')
    it('preserves cart on checkout failure')
  })

  describe('Edge Cases', () => {
    it('handles empty cart submission')
    it('prevents checkout with out-of-stock items')
    it('recalculates total if prices changed')
    it('handles currency conversion')
    it('limits quantity to available inventory')
  })

  describe('Race Conditions', () => {
    it('prevents double submission')
    it('handles inventory depletion mid-checkout')
    it('manages concurrent checkouts for same item')
  })

  describe('Security', () => {
    it('validates cart items exist and belong to user')
    it('prevents price manipulation')
    it('requires authentication')
    it('rate limits checkout attempts')
  })
})

Test-Driven Bug Fixing

You: "There's a bug where orders show the wrong total. Fix it using TDD."

Claude Code approaches this methodically:

Step 1: Create a failing test

Terminal
it('calculates total correctly with discount', () => {
  const cart = [
    { price: 1000, quantity: 2 },  // $20
    { price: 500, quantity: 3 }     // $15
  ]
  const discount = { type: 'percentage', value: 10 }
  const total = calculateOrderTotal(cart, discount)
  expect(total).toBe(3150)  // $35 - 10% = $31.50
})

Step 2: Test fails - Expected 3150, Received 2835

Step 3: Identify the bug - discount applied per-item instead of to subtotal

Step 4: Fix and verify - test now passes

Step 5: Add regression tests

Performance Optimization

Systematic Profiling

You: "The products page is slow. Find and fix the bottlenecks."

Claude Code systematically identifies issues:

Phase 1: Database Queries

  • Current: 1.9s total (N+1 problem)
  • Fix: Single query with joins
  • After: 180ms

Phase 2: Component Rendering

  • Issues: ProductCard not memoized, images loading synchronously
  • Fixes: Add React.memo, implement next/image with lazy loading

Phase 3: Bundle Analysis

  • Large deps: moment.js (290kb), lodash (71kb)
  • Fixes: Replace with date-fns, import specific functions
  • Savings: 340kb reduced

Results:

  • Query time: 1.9s → 180ms
  • First paint: 2.3s → 800ms
  • Bundle size: 580kb → 240kb

Team Workflows

Code Review Assistance

You: "Review this PR for potential issues: #234"

Claude Code fetches the PR diff and provides a detailed review:

Critical Issues:

  1. Missing authorization check in DELETE /api/subscriptions/[id]
  2. Race condition in upgrade flow

Improvements Suggested:

  1. Add transaction around subscription changes
  2. Include audit logging for billing events
  3. Add tests for edge cases

Code Quality:

  • Consistent naming conventions ✓
  • TypeScript types complete ✓
  • Missing: JSDoc for public functions

Documentation Generation

You: "Generate API documentation from our routes"

Claude Code reads all API route files and creates comprehensive documentation:

  • Endpoint descriptions with request/response schemas
  • Authentication requirements
  • Error code reference
  • Example requests and responses

Automation Patterns

Scheduled Tasks

You: "Create a daily task to clean up expired sessions"

Claude Code creates:

  1. Cleanup script with logging
  2. GitHub Action running daily at 3 AM UTC
  3. Slack notification on failure
  4. Dashboard metric for session cleanup

CI/CD Integration

You: "Set up automated deployment with preview environments"

Claude Code configures:

  1. Push to feature branch → Preview deployment
  2. PR opened → Run tests, deploy preview
  3. PR merged to main → Deploy to staging
  4. Tag release → Deploy to production

Features include automatic preview URLs, required checks, rollback capability, and deployment notifications.

Summary

Advanced Claude Code patterns include:

  • Architecture work: Design sessions, audits, migrations
  • Complex refactoring: Large file decomposition, pattern implementation
  • Multi-repo work: Monorepo management, cross-repo analysis
  • Testing strategies: Comprehensive generation, TDD workflows
  • Performance: Systematic profiling and optimization
  • Team workflows: Code review, documentation generation
  • Automation: Scheduled tasks, CI/CD integration

What's Next

You've completed the Claude Code module. Consider exploring:

  • GitHub Copilot for IDE-integrated AI assistance
  • Windsurf for another agentic editing experience
  • MCP server development for custom integrations
Mark this lesson as complete to track your progress