T-CREATOR

Claude Code トラブルシュート大全:Request timed out を根絶する 9 の対策

Claude Code トラブルシュート大全:Request timed out を根絶する 9 の対策

Claude Code を使用していて「Request timed out」エラーに遭遇したことはありませんか。このエラーは開発作業を中断させ、生産性を大幅に低下させる深刻な問題です。

API 呼び出しが失敗し、コード生成が途中で止まり、重要な作業が完了できない状況は、多くの開発者にとって大きなストレスとなっています。本記事では、これらの問題を根本的に解決する 9 つの実践的な対策をご紹介いたします。

Request timed out エラーの全体像

Claude Code の Request timed out エラーを効果的に解決するためには、まずエラーの構造と発生メカニズムを理解することが重要です。

エラーの基本構造

Request timed out エラーは、クライアント(Claude Code)とサーバー(Anthropic API)間の通信において、レスポンスが規定時間内に返されない場合に発生します。

mermaidsequenceDiagram
    participant C as Claude Code
    participant A as Anthropic API
    participant S as サーバー処理

    C->>A: リクエスト送信
    A->>S: 処理開始
    Note over S: 処理時間が長期化
    Note over C: タイムアウト時間経過
    C-->>A: 接続切断
    A-->>C: Request timed out

このエラーは以下の 3 つの要素が複合的に作用して発生します:

要素説明影響度
ネットワーク遅延通信経路の混雑や不安定性
サーバー負荷API 側の処理能力超過
クライアント設定タイムアウト値やリクエスト設定

発生パターンの分類

Request timed out エラーには、発生タイミングと原因によって以下のパターンがあります。

接続時タイムアウト

typescript// エラーメッセージ例
Error: Request timed out after 30000ms
Status: ETIMEDOUT
Code: ECONNABORTED

初期接続段階で発生するタイムアウトです。ネットワーク設定や DNS 解決に問題がある場合に多く見られます。

処理時タイムアウト

typescript// エラーメッセージ例
Error: Request timed out waiting for response
Status: 408
Code: REQUEST_TIMEOUT

接続は成功したものの、サーバー側の処理に時間がかかりすぎる場合のタイムアウトです。

読み取りタイムアウト

typescript// エラーメッセージ例
Error: Read timeout occurred
Status: ESOCKETTIMEDOUT
Code: TIMEOUT

レスポンスの受信中に発生するタイムアウトで、大きなレスポンスデータの処理時に発生しやすくなります。

影響範囲の把握

Request timed out エラーが発生した場合の影響範囲を整理すると以下のようになります:

mermaidflowchart TD
    timeout[Request Timeout] --> immediate[即座の影響]
    timeout --> longterm[長期的影響]

    immediate --> work_stop[作業停止]
    immediate --> data_loss[作業データ消失]
    immediate --> retry_cost[再試行コスト]

    longterm --> productivity[生産性低下]
    longterm --> trust[ツール信頼性低下]
    longterm --> workflow[ワークフロー中断]

9 つの根本対策

Claude Code の Request timed out エラーを根絶するための具体的な対策をご紹介します。各対策は実装の容易さと効果の高さを考慮して順番に配置されています。

対策 1: ネットワーク設定の最適化

最も基本的でありながら効果的な対策として、ネットワーク設定の見直しから始めましょう。

DNS 設定の変更

bash# Google Public DNS への変更
sudo nano /etc/resolv.conf
txt# 高速なDNSサーバーを設定
nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 1.1.1.1

DNS 応答速度の向上により、初期接続時間を大幅に短縮できます。

ネットワーク MTU 値の調整

bash# 現在のMTU値確認
ip link show

# MTU値の最適化(Ethernet接続の場合)
sudo ip link set dev eth0 mtu 1500

MTU(Maximum Transmission Unit)値を適切に設定することで、パケット分割によるオーバーヘッドを削減できます。

TCP 設定の最適化

bash# TCP設定の確認
sysctl net.ipv4.tcp_congestion_control

# TCP Fast Open の有効化
echo 'net.ipv4.tcp_fastopen = 3' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

対策 2: タイムアウト値の調整

Claude Code のタイムアウト設定を環境に応じて最適化します。

環境変数によるタイムアウト設定

bash# .bashrc または .zshrc に追加
export CLAUDE_TIMEOUT=60000        # 60秒
export CLAUDE_CONNECT_TIMEOUT=30000 # 30秒
export CLAUDE_READ_TIMEOUT=45000    # 45秒
bash# 設定の反映
source ~/.bashrc

設定ファイルによるタイムアウト管理

json{
  "timeout": {
    "request": 60000,
    "connect": 30000,
    "read": 45000,
    "retry": {
      "attempts": 3,
      "delay": 2000
    }
  }
}

設定ファイルを ~​/​.claude​/​config.json に配置することで、プロジェクト横断的な設定管理が可能になります。

対策 3: リクエストサイズの制限

大きなリクエストは処理時間が長くなる傾向があるため、適切なサイズ制限を設けます。

コンテキストサイズの管理

typescript// リクエストサイズの制限設定
const MAX_CONTEXT_SIZE = 8000; // 文字数制限
const MAX_FILES_PER_REQUEST = 5; // ファイル数制限

function validateRequestSize(
  context: string,
  files: string[]
): boolean {
  if (context.length > MAX_CONTEXT_SIZE) {
    console.warn(
      `Context size ${context.length} exceeds limit ${MAX_CONTEXT_SIZE}`
    );
    return false;
  }

  if (files.length > MAX_FILES_PER_REQUEST) {
    console.warn(
      `File count ${files.length} exceeds limit ${MAX_FILES_PER_REQUEST}`
    );
    return false;
  }

  return true;
}

バッチ処理によるリクエスト分割

typescript// 大きなタスクを小さな単位に分割
async function processLargeTask(
  items: string[]
): Promise<string[]> {
  const BATCH_SIZE = 10;
  const results: string[] = [];

  for (let i = 0; i < items.length; i += BATCH_SIZE) {
    const batch = items.slice(i, i + BATCH_SIZE);

    try {
      const batchResult = await processBatch(batch);
      results.push(...batchResult);
    } catch (error) {
      console.error(
        `Batch ${i / BATCH_SIZE + 1} failed:`,
        error
      );
      // 失敗したバッチのみ再試行
      const retryResult = await retryBatch(batch);
      results.push(...retryResult);
    }
  }

  return results;
}

対策 4: 並列処理の制御

同時リクエスト数を制限することで、サーバー負荷を軽減し安定性を向上させます。

リクエストプールの実装

typescriptclass RequestPool {
  private readonly maxConcurrent: number;
  private readonly queue: (() => Promise<any>)[] = [];
  private running: number = 0;

  constructor(maxConcurrent: number = 3) {
    this.maxConcurrent = maxConcurrent;
  }

  async execute<T>(task: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.queue.push(async () => {
        try {
          const result = await task();
          resolve(result);
        } catch (error) {
          reject(error);
        }
      });

      this.processQueue();
    });
  }

  private async processQueue(): Promise<void> {
    if (
      this.running >= this.maxConcurrent ||
      this.queue.length === 0
    ) {
      return;
    }

    this.running++;
    const task = this.queue.shift()!;

    try {
      await task();
    } finally {
      this.running--;
      this.processQueue();
    }
  }
}

使用例

typescriptconst requestPool = new RequestPool(2); // 最大2並列

// 複数のAPIコールを制御された並列度で実行
const tasks = [
  () => claudeAPI.generateCode('function1'),
  () => claudeAPI.generateCode('function2'),
  () => claudeAPI.generateCode('function3'),
];

const results = await Promise.all(
  tasks.map((task) => requestPool.execute(task))
);

対策 5: プロキシ設定の見直し

企業環境などでプロキシを使用している場合の最適化設定です。

プロキシ設定の確認と調整

bash# 現在のプロキシ設定確認
echo $HTTP_PROXY
echo $HTTPS_PROXY
echo $NO_PROXY
bash# プロキシタイムアウトの設定
export HTTP_PROXY="http://proxy.company.com:8080"
export HTTPS_PROXY="http://proxy.company.com:8080"
export NO_PROXY="localhost,127.0.0.1,.local"

# Claude Code 専用のプロキシ設定
export CLAUDE_PROXY_TIMEOUT=45000

プロキシバイパス設定

javascript// プロキシ設定のカスタマイズ
const proxyConfig = {
  host: 'proxy.company.com',
  port: 8080,
  timeout: 45000,
  keepAlive: true,
  auth: {
    username: process.env.PROXY_USER,
    password: process.env.PROXY_PASS,
  },
};

// プロキシを経由しない直接接続の設定
const directHosts = [
  'api.anthropic.com',
  '*.anthropic.com',
];

対策 6: DNS 解決の高速化

DNS 解決時間の短縮により、初期接続時間を大幅に改善できます。

ローカル DNS キャッシュの設定

bash# systemd-resolved の設定(Ubuntu/Debian)
sudo nano /etc/systemd/resolved.conf
ini[Resolve]
DNS=8.8.8.8 1.1.1.1
FallbackDNS=8.8.4.4 1.0.0.1
Cache=yes
CacheFromLocalhost=yes
DNSStubListener=yes
bash# 設定反映
sudo systemctl restart systemd-resolved

DNS prefetch の実装

typescript// DNS事前解決による高速化
const dns = require('dns').promises;

class DNSOptimizer {
  private cache = new Map<string, string>();

  async preResolve(hostnames: string[]): Promise<void> {
    const resolvePromises = hostnames.map(
      async (hostname) => {
        try {
          const addresses = await dns.lookup(hostname);
          this.cache.set(hostname, addresses.address);
          console.log(
            `DNS resolved: ${hostname} -> ${addresses.address}`
          );
        } catch (error) {
          console.error(
            `DNS resolution failed for ${hostname}:`,
            error
          );
        }
      }
    );

    await Promise.all(resolvePromises);
  }

  getResolvedIP(hostname: string): string | undefined {
    return this.cache.get(hostname);
  }
}
typescript// 使用例
const dnsOptimizer = new DNSOptimizer();
await dnsOptimizer.preResolve([
  'api.anthropic.com',
  'claude.ai',
]);

対策 7: キャッシュ戦略の実装

適切なキャッシュ戦略により、同じリクエストの重複実行を避けられます。

レスポンスキャッシュの実装

typescriptinterface CacheEntry {
  data: any;
  timestamp: number;
  ttl: number;
}

class ResponseCache {
  private cache = new Map<string, CacheEntry>();
  private readonly defaultTTL = 300000; // 5分

  generateKey(request: any): string {
    return require('crypto')
      .createHash('sha256')
      .update(JSON.stringify(request))
      .digest('hex');
  }

  set(key: string, data: any, ttl?: number): void {
    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      ttl: ttl || this.defaultTTL,
    });
  }

  get(key: string): any | null {
    const entry = this.cache.get(key);

    if (!entry) {
      return null;
    }

    const isExpired =
      Date.now() - entry.timestamp > entry.ttl;
    if (isExpired) {
      this.cache.delete(key);
      return null;
    }

    return entry.data;
  }

  clear(): void {
    this.cache.clear();
  }
}

キャッシュ付き API クライアント

typescriptclass CachedClaudeClient {
  private cache = new ResponseCache();

  async generateWithCache(
    prompt: string,
    options: any = {}
  ): Promise<string> {
    const cacheKey = this.cache.generateKey({
      prompt,
      options,
    });

    // キャッシュから結果を取得
    const cachedResult = this.cache.get(cacheKey);
    if (cachedResult) {
      console.log('Cache hit:', cacheKey.substring(0, 8));
      return cachedResult;
    }

    // API呼び出し実行
    console.log('Cache miss, making API call');
    const result = await this.makeAPICall(prompt, options);

    // 結果をキャッシュに保存
    this.cache.set(cacheKey, result, 600000); // 10分間キャッシュ

    return result;
  }

  private async makeAPICall(
    prompt: string,
    options: any
  ): Promise<string> {
    // 実際のAPI呼び出しロジック
    return 'Generated response';
  }
}

対策 8: エラーハンドリングの強化

包括的なエラーハンドリングにより、タイムアウト発生時の適切な対応を実現します。

指数バックオフによるリトライ機能

typescriptinterface RetryOptions {
  maxAttempts: number;
  initialDelay: number;
  maxDelay: number;
  backoffFactor: number;
}

class RetryHandler {
  private defaultOptions: RetryOptions = {
    maxAttempts: 3,
    initialDelay: 1000,
    maxDelay: 30000,
    backoffFactor: 2,
  };

  async executeWithRetry<T>(
    operation: () => Promise<T>,
    options?: Partial<RetryOptions>
  ): Promise<T> {
    const config = { ...this.defaultOptions, ...options };
    let lastError: Error;

    for (
      let attempt = 1;
      attempt <= config.maxAttempts;
      attempt++
    ) {
      try {
        return await operation();
      } catch (error) {
        lastError = error as Error;

        // 最後の試行の場合はエラーをそのまま投げる
        if (attempt === config.maxAttempts) {
          break;
        }

        // タイムアウトエラー以外は即座に失敗
        if (!this.isRetryableError(error)) {
          throw error;
        }

        // 指数バックオフでの待機
        const delay = Math.min(
          config.initialDelay *
            Math.pow(config.backoffFactor, attempt - 1),
          config.maxDelay
        );

        console.log(
          `Attempt ${attempt} failed, retrying in ${delay}ms...`
        );
        await this.sleep(delay);
      }
    }

    throw lastError!;
  }

  private isRetryableError(error: any): boolean {
    const retryableCodes = [
      'ETIMEDOUT',
      'ECONNABORTED',
      'REQUEST_TIMEOUT',
      'ESOCKETTIMEDOUT',
    ];

    return (
      retryableCodes.includes(error.code) ||
      error.message?.includes('timed out') ||
      (error.status >= 500 && error.status < 600)
    );
  }

  private sleep(ms: number): Promise<void> {
    return new Promise((resolve) =>
      setTimeout(resolve, ms)
    );
  }
}

エラー状況に応じた適応的処理

typescriptclass AdaptiveErrorHandler {
  private errorHistory: {
    type: string;
    timestamp: number;
  }[] = [];
  private readonly HISTORY_WINDOW = 300000; // 5分間

  async handleRequest<T>(
    operation: () => Promise<T>
  ): Promise<T> {
    try {
      return await operation();
    } catch (error) {
      this.recordError(error);

      // エラー頻度に基づく適応的な処理
      const errorFrequency = this.getRecentErrorFrequency();

      if (errorFrequency > 0.5) {
        // 50%以上の失敗率
        console.log(
          'High error rate detected, switching to conservative mode'
        );
        return this.executeConservative(operation);
      } else {
        console.log(
          'Normal error rate, applying standard retry'
        );
        return this.executeStandard(operation);
      }
    }
  }

  private recordError(error: any): void {
    this.errorHistory.push({
      type: error.code || error.message || 'unknown',
      timestamp: Date.now(),
    });

    // 古いエラー履歴を削除
    const cutoff = Date.now() - this.HISTORY_WINDOW;
    this.errorHistory = this.errorHistory.filter(
      (e) => e.timestamp > cutoff
    );
  }

  private getRecentErrorFrequency(): number {
    const recent = this.errorHistory.filter(
      (e) => Date.now() - e.timestamp < this.HISTORY_WINDOW
    );
    return recent.length / 10; // 過去10回の試行に対する比率(仮定)
  }

  private async executeConservative<T>(
    operation: () => Promise<T>
  ): Promise<T> {
    const retryHandler = new RetryHandler();
    return retryHandler.executeWithRetry(operation, {
      maxAttempts: 5,
      initialDelay: 5000,
      maxDelay: 60000,
      backoffFactor: 3,
    });
  }

  private async executeStandard<T>(
    operation: () => Promise<T>
  ): Promise<T> {
    const retryHandler = new RetryHandler();
    return retryHandler.executeWithRetry(operation);
  }
}

対策 9: モニタリング環境の構築

継続的なモニタリングにより、問題の早期発見と予防的対応を実現します。

パフォーマンス監視システム

typescriptinterface MetricData {
  timestamp: number;
  duration: number;
  success: boolean;
  errorType?: string;
}

class PerformanceMonitor {
  private metrics: MetricData[] = [];
  private readonly MAX_METRICS = 1000;

  async measureOperation<T>(
    operation: () => Promise<T>,
    operationName: string
  ): Promise<T> {
    const startTime = Date.now();
    let success = false;
    let errorType: string | undefined;

    try {
      const result = await operation();
      success = true;
      return result;
    } catch (error) {
      errorType = (error as Error).name || 'UnknownError';
      throw error;
    } finally {
      const duration = Date.now() - startTime;

      this.recordMetric({
        timestamp: startTime,
        duration,
        success,
        errorType,
      });

      // アラート判定
      this.checkAlerts(operationName, duration, success);
    }
  }

  private recordMetric(metric: MetricData): void {
    this.metrics.push(metric);

    // メトリクス数の制限
    if (this.metrics.length > this.MAX_METRICS) {
      this.metrics.shift();
    }
  }

  private checkAlerts(
    name: string,
    duration: number,
    success: boolean
  ): void {
    const SLOW_THRESHOLD = 30000; // 30秒
    const recentFailures =
      this.getRecentFailureRate(300000); // 5分間

    if (duration > SLOW_THRESHOLD) {
      console.warn(
        `⚠️ Slow operation detected: ${name} took ${duration}ms`
      );
    }

    if (!success) {
      console.error(`❌ Operation failed: ${name}`);
    }

    if (recentFailures > 0.3) {
      // 30%以上の失敗率
      console.error(
        `🚨 High failure rate: ${(
          recentFailures * 100
        ).toFixed(1)}%`
      );
    }
  }

  private getRecentFailureRate(windowMs: number): number {
    const cutoff = Date.now() - windowMs;
    const recentMetrics = this.metrics.filter(
      (m) => m.timestamp > cutoff
    );

    if (recentMetrics.length === 0) return 0;

    const failures = recentMetrics.filter(
      (m) => !m.success
    ).length;
    return failures / recentMetrics.length;
  }

  getStats(windowMs: number = 3600000): any {
    const cutoff = Date.now() - windowMs;
    const recentMetrics = this.metrics.filter(
      (m) => m.timestamp > cutoff
    );

    if (recentMetrics.length === 0) {
      return { message: 'No data available' };
    }

    const durations = recentMetrics.map((m) => m.duration);
    const successCount = recentMetrics.filter(
      (m) => m.success
    ).length;

    return {
      totalRequests: recentMetrics.length,
      successRate:
        (
          (successCount / recentMetrics.length) *
          100
        ).toFixed(2) + '%',
      averageDuration: Math.round(
        durations.reduce((a, b) => a + b, 0) /
          durations.length
      ),
      medianDuration: this.calculateMedian(durations),
      maxDuration: Math.max(...durations),
      minDuration: Math.min(...durations),
    };
  }

  private calculateMedian(numbers: number[]): number {
    const sorted = [...numbers].sort((a, b) => a - b);
    const mid = Math.floor(sorted.length / 2);
    return sorted.length % 2 === 0
      ? (sorted[mid - 1] + sorted[mid]) / 2
      : sorted[mid];
  }
}

ヘルスチェック機能

typescriptclass HealthChecker {
  private monitor = new PerformanceMonitor();

  async performHealthCheck(): Promise<void> {
    console.log('🔍 Starting health check...');

    const checks = [
      {
        name: 'DNS Resolution',
        check: () => this.checkDNS(),
      },
      {
        name: 'Network Connectivity',
        check: () => this.checkConnectivity(),
      },
      {
        name: 'API Availability',
        check: () => this.checkAPIAvailability(),
      },
      {
        name: 'Performance Baseline',
        check: () => this.checkPerformance(),
      },
    ];

    const results = await Promise.allSettled(
      checks.map(async ({ name, check }) => {
        try {
          await this.monitor.measureOperation(check, name);
          console.log(`✅ ${name}: OK`);
          return { name, status: 'OK' };
        } catch (error) {
          console.error(
            `❌ ${name}: ${(error as Error).message}`
          );
          return {
            name,
            status: 'FAILED',
            error: (error as Error).message,
          };
        }
      })
    );

    this.reportHealthStatus(results);
  }

  private async checkDNS(): Promise<void> {
    const dns = require('dns').promises;
    await dns.lookup('api.anthropic.com');
  }

  private async checkConnectivity(): Promise<void> {
    const https = require('https');

    return new Promise((resolve, reject) => {
      const req = https.request(
        {
          hostname: 'api.anthropic.com',
          port: 443,
          method: 'HEAD',
          timeout: 10000,
        },
        (res) => {
          resolve();
        }
      );

      req.on('error', reject);
      req.on('timeout', () =>
        reject(new Error('Connection timeout'))
      );
      req.end();
    });
  }

  private async checkAPIAvailability(): Promise<void> {
    // 簡単なAPIコールでサービス可用性を確認
    // 実際の実装では適切なエンドポイントを使用
    await new Promise((resolve) =>
      setTimeout(resolve, 100)
    );
  }

  private async checkPerformance(): Promise<void> {
    const stats = this.monitor.getStats(3600000); // 1時間

    if (stats.message) {
      throw new Error('Insufficient performance data');
    }

    const avgDuration = parseInt(stats.averageDuration);
    if (avgDuration > 20000) {
      // 20秒以上
      throw new Error(
        `Poor performance: average ${avgDuration}ms`
      );
    }

    const successRate = parseFloat(stats.successRate);
    if (successRate < 90) {
      // 90%未満
      throw new Error(`Low success rate: ${successRate}%`);
    }
  }

  private reportHealthStatus(
    results: PromiseSettledResult<any>[]
  ): void {
    const failed = results.filter(
      (r) =>
        r.status === 'rejected' ||
        (r.status === 'fulfilled' &&
          r.value.status === 'FAILED')
    );

    if (failed.length === 0) {
      console.log('🎉 All health checks passed!');
    } else {
      console.log(
        `⚠️ ${failed.length} health check(s) failed`
      );

      // 改善提案の表示
      this.suggestImprovements(failed);
    }
  }

  private suggestImprovements(failedChecks: any[]): void {
    const suggestions = {
      'DNS Resolution':
        '対策6: DNS解決の高速化を実施してください',
      'Network Connectivity':
        '対策1: ネットワーク設定の最適化を確認してください',
      'API Availability':
        '対策8: エラーハンドリングの強化を検討してください',
      'Performance Baseline':
        '対策2: タイムアウト値の調整が必要です',
    };

    console.log('\n💡 改善提案:');
    failedChecks.forEach((check) => {
      const name =
        check.status === 'rejected'
          ? 'Unknown'
          : check.value.name;
      if (suggestions[name]) {
        console.log(`  - ${suggestions[name]}`);
      }
    });
  }
}

トラブルシューティングフロー

実際に Request timed out エラーが発生した場合の体系的な解決手順をご紹介します。

症状別診断チャート

エラーの症状に応じて適切な対策を選択するための診断フローです。

mermaidflowchart TD
    start[Request Timeout 発生] --> check_network{ネットワーク接続確認}

    check_network -->|OK| check_dns{DNS解決確認}
    check_network -->|NG| net_fix[対策1: ネットワーク設定最適化]

    check_dns -->|OK| check_timeout{タイムアウト設定確認}
    check_dns -->|NG| dns_fix[対策6: DNS解決高速化]

    check_timeout -->|短すぎる| timeout_fix[対策2: タイムアウト値調整]
    check_timeout -->|適切| check_size{リクエストサイズ確認}

    check_size -->|大きすぎる| size_fix[対策3: リクエストサイズ制限]
    check_size -->|適切| check_concurrent{並列数確認}

    check_concurrent -->|多すぎる| concurrent_fix[対策4: 並列処理制御]
    check_concurrent -->|適切| advanced[高度な対策7-9を検討]

    net_fix --> verify[動作確認]
    dns_fix --> verify
    timeout_fix --> verify
    size_fix --> verify
    concurrent_fix --> verify
    advanced --> verify

    verify -->|成功| success[解決完了]
    verify -->|失敗| escalate[複数対策の組み合わせ]

段階的解決手順

Request timed out エラーの解決は以下の段階的アプローチで進めることが効果的です。

フェーズ 1: 即効性対策(5-10 分)

bash# 1. 基本的なネットワーク確認
ping api.anthropic.com
nslookup api.anthropic.com

# 2. DNS設定の変更
sudo nano /etc/resolv.conf
# nameserver 8.8.8.8 を追加

# 3. タイムアウト値の一時的増加
export CLAUDE_TIMEOUT=120000  # 2分に延長

フェーズ 2: 設定調整(15-30 分)

typescript// 1. 設定ファイルの作成・更新
const config = {
  timeout: {
    request: 90000, // 90秒
    connect: 30000, // 30秒
    read: 60000, // 60秒
  },
  retry: {
    maxAttempts: 3,
    backoffFactor: 2,
  },
  concurrency: {
    maxParallel: 2, // 並列数制限
  },
};

// 2. リクエスト分割の実装
const largeRequest = splitIntoChunks(originalRequest, 5000);

フェーズ 3: 高度な対策(30-60 分)

typescript// 1. キャッシュシステムの導入
const cache = new ResponseCache();
const client = new CachedClaudeClient();

// 2. モニタリングシステムの設定
const monitor = new PerformanceMonitor();
const healthChecker = new HealthChecker();

// 3. 定期的なヘルスチェック実行
setInterval(async () => {
  await healthChecker.performHealthCheck();
}, 300000); // 5分間隔

効果測定と継続改善

typescript// パフォーマンス改善の効果測定
class ImprovementTracker {
  private beforeStats: any;
  private afterStats: any;

  recordBefore(): void {
    this.beforeStats = monitor.getStats(3600000);
    console.log('改善前の状況:', this.beforeStats);
  }

  recordAfter(): void {
    this.afterStats = monitor.getStats(3600000);
    console.log('改善後の状況:', this.afterStats);
    this.calculateImprovement();
  }

  private calculateImprovement(): void {
    if (!this.beforeStats || !this.afterStats) return;

    const improvements = {
      successRate: this.calculatePercentageChange(
        parseFloat(this.beforeStats.successRate),
        parseFloat(this.afterStats.successRate)
      ),
      averageDuration: this.calculatePercentageChange(
        this.beforeStats.averageDuration,
        this.afterStats.averageDuration,
        true // 少ない方が良い
      ),
    };

    console.log('🎯 改善効果:');
    console.log(
      `  成功率: ${improvements.successRate}% 向上`
    );
    console.log(
      `  平均応答時間: ${improvements.averageDuration}% 改善`
    );
  }

  private calculatePercentageChange(
    before: number,
    after: number,
    lowerIsBetter = false
  ): number {
    const change = ((after - before) / before) * 100;
    return lowerIsBetter ? -change : change;
  }
}

まとめ

Claude Code の Request timed out エラーは、適切な対策を講じることで確実に解決できる問題です。本記事でご紹介した 9 つの対策を段階的に適用することで、安定した開発環境を構築できます。

対策の優先順位

優先度対策実装時間効果期待値
対策 1: ネットワーク設定最適化5 分★★★★☆
対策 2: タイムアウト値調整10 分★★★★★
対策 3: リクエストサイズ制限15 分★★★☆☆
対策 4: 並列処理制御20 分★★★★☆
対策 5: プロキシ設定見直し30 分★★☆☆☆
対策 6: DNS 解決高速化15 分★★★☆☆
対策 7: キャッシュ戦略実装45 分★★★★☆
対策 8: エラーハンドリング強化30 分★★★★★
対策 9: モニタリング環境構築60 分★★★☆☆

継続的な改善のポイント

Claude Code を長期間安定して使用するためには、以下の継続的改善が重要です:

  1. 定期的なパフォーマンス測定: 週次でのヘルスチェック実行
  2. 設定の見直し: 月次でのタイムアウト値とリソース設定の最適化
  3. 新機能への対応: Claude Code のアップデート時の設定確認
  4. 環境変化への適応: ネットワーク環境やインフラ変更時の再調整

これらの対策により、Request timed out エラーに悩まされることなく、Claude Code を最大限活用した効率的な開発を実現できるでしょう。

関連リンク