返回

04. OpenClaw 性能问题排查完全指南

深入排查 OpenClaw 性能问题,包括响应速度慢、内存占用高、CPU 使用率高、并发能力不足等。提供性能监控工具和优化策略。

适用于 OpenClaw v2026.2 | 本文适合遇到性能问题和需要优化的用户。

TL;DR: 查看资源使用:openclaw usagetop。内存不足增加限制:export NODE_OPTIONS="--max-old-space-size=8192"。响应慢检查模型配置和网络延迟。监控日志大小:du -sh ~/.openclaw/logs。使用缓存和异步处理优化性能。

常见问题速查表

问题 症状 快速解决
响应速度慢 等待时间过长 检查模型、网络、复杂任务
内存占用高 系统卡顿 增加 Node.js 内存限制
CPU 使用率高 风扇狂转 减少并发、优化任务
日志过大 磁盘空间不足 配置日志轮转
会话过多 资源耗尽 定期清理旧会话
网络延迟高 API 调用慢 使用更近的端点或代理

问题 1:响应速度慢

症状

  • 用户消息发送后,长时间无响应
  • Agent 处理任务耗时过长
  • Web UI 加载缓慢

原因分析

  1. 模型选择:使用了慢速模型(如 Opus)
  2. 网络延迟:API 调用延迟高
  3. 复杂任务:任务本身需要长时间处理
  4. 会话历史:会话上下文过长
  5. 系统资源:CPU/内存不足

诊断方法

# 1. 检查响应时间
time openclaw agent --message "你好"

# 2. 查看详细日志
openclaw logs --verbose --tail 50

# 3. 检查模型配置
openclaw config get agent.model

# 4. 检查网络延迟
curl -w "Time: %{time_total}s\n" -I https://api.anthropic.com

# 5. 检查系统资源
top -p $(pgrep -f openclaw)

解决方案

方案 1:优化模型选择

# 查看可用模型及速度对比
openclaw models list --with-speed

# 输出示例:
# Model                  Speed    Cost      Recommended For
# claude-haiku-3.5       Fast     $0.25/M   Simple tasks
# claude-sonnet-4        Medium   $3/M      Daily use
# claude-opus-4-6        Slow     $15/M     Complex reasoning

# 根据任务选择合适的模型
openclaw config set agent.model anthropic/claude-sonnet-4

# 配置模型 fallback(速度优先)
openclaw config set models.fallback '[
  {"model": "anthropic/claude-sonnet-4", "condition": "timeout"},
  {"model": "anthropic/claude-haiku-3.5", "condition": "rate_limit"}
]'

方案 2:优化会话历史

# 查看会话大小
openclaw session list --with-size

# 输出示例:
# Session      Messages  Tokens   Size
# main         156       45,000   Large
# telegram:1   23        6,000    Normal

# 重置过大会话
openclaw session reset main

# 配置自动压缩
openclaw config set session.autoCompress true
openclaw config set session.maxTokens 50000

# 配置历史保留策略
openclaw config set session.historyLimit 100

方案 3:启用缓存

{
  "cache": {
    "enabled": true,
    "ttl": 3600,
    "maxSize": "500MB",
    "strategies": {
      "apiResponses": true,
      "embeddings": true,
      "toolResults": true
    }
  }
}
# 启用缓存
openclaw config set cache.enabled true

# 清理缓存
openclaw cache clear

# 查看缓存统计
openclaw cache stats

方案 4:并行处理

{
  "performance": {
    "parallelRequests": true,
    "maxConcurrency": 5,
    "queueSize": 100
  }
}

性能基准测试

# 运行性能测试
openclaw benchmark

# 输出示例:
# Simple query:         0.8s
# Medium complexity:    2.3s
# High complexity:      5.7s
# File operation:       0.3s
# API call:             1.2s

# 对比不同模型
openclaw benchmark --model claude-opus-4-6
openclaw benchmark --model claude-haiku-3.5

问题 2:内存占用高

症状

Error: JavaScript heap out of memory
Error: ENOMEM: not enough memory

系统卡顿,其他应用响应慢。

诊断方法

# 查看内存使用
free -h

# 查看 OpenClaw 进程内存
ps aux | grep openclaw | awk '{print $6/1024 " MB"}'

# 使用 top 监控
top -p $(pgrep -f openclaw)

# 使用 htop(更友好)
htop -p $(pgrep -f openclaw)

# 查看内存详细分布
openclaw diagnostics memory

# 输出示例:
# Total Heap:        2048 MB
# Used Heap:         1850 MB (90%)
# External:          128 MB
# Array Buffers:     64 MB
# 
# Top Memory Consumers:
# - Sessions:        800 MB
# - Cache:           400 MB
# - Logs:            300 MB
# - Skills:          200 MB

解决方案

方案 1:增加 Node.js 内存限制

# 临时设置
export NODE_OPTIONS="--max-old-space-size=8192"
openclaw gateway

# 永久设置
echo 'export NODE_OPTIONS="--max-old-space-size=8192"' >> ~/.bashrc
source ~/.bashrc

# Docker 环境
docker run -e NODE_OPTIONS="--max-old-space-size=8192" openclaw/openclaw:latest

方案 2:优化会话管理

# 限制会话数量
openclaw config set session.maxSessions 10

# 自动清理旧会话
openclaw config set session.cleanup.enabled true
openclaw config set session.cleanup.maxAge 604800  # 7天

# 定期清理
openclaw session cleanup

# 或使用 cron 定时清理
openclaw cron add "0 2 * * *" "openclaw session cleanup --older-than 7d"

方案 3:优化缓存

# 限制缓存大小
openclaw config set cache.maxSize 200MB

# 禁用不必要的缓存
openclaw config set cache.strategies.embeddings false

# 定期清理缓存
openclaw cache clear --older-than 7d

方案 4:优化日志

# 查看日志大小
du -sh ~/.openclaw/logs/*

# 配置日志级别
openclaw config set logging.level warn

# 配置日志轮转
openclaw config set logging.rotation.enabled true
openclaw config set logging.rotation.maxSize 100MB
openclaw config set logging.rotation.maxFiles 5

# 清理旧日志
find ~/.openclaw/logs -name "*.log" -mtime +7 -delete

方案 5:重启释放内存

# 优雅重启
openclaw gateway --restart

# 或完全重启
openclaw gateway --stop
sleep 2
openclaw gateway --daemon

内存监控脚本

创建 monitor-memory.sh

#!/bin/bash

THRESHOLD=90

while true; do
    # 获取内存使用百分比
    MEM_USAGE=$(ps aux | grep "openclaw gateway" | grep -v grep | awk '{print $4}' | head -1)
    
    if [ ! -z "$MEM_USAGE" ]; then
        MEM_INT=${MEM_USAGE%.*}
        
        if [ "$MEM_INT" -gt "$THRESHOLD" ]; then
            echo "[$(date)] 警告: OpenClaw 内存使用 ${MEM_USAGE}%"
            
            # 可选:自动重启
            # openclaw gateway --restart
            
            # 可选:发送通知
            # curl -X POST https://api.example.com/notify -d "message=High memory usage: ${MEM_USAGE}%"
        fi
        
        echo "[$(date)] 内存使用: ${MEM_USAGE}%"
    fi
    
    sleep 60
done

问题 3:CPU 使用率高

症状

  • CPU 使用率持续在 80% 以上
  • 系统风扇高速运转
  • 其他应用卡顿

诊断方法

# 查看 CPU 使用
top -p $(pgrep -f openclaw)

# 使用 htop
htop -p $(pgrep -f openclaw)

# 查看线程
top -H -p $(pgrep -f openclaw)

# 使用 perf 分析(Linux)
sudo perf top -p $(pgrep -f openclaw)

# 查看调用栈
openclaw diagnostics cpu

# 输出示例:
# CPU Usage: 85%
# 
# Top Functions:
# - processMessage:     35%
# - toolExecution:      25%
# - jsonParser:         15%
# - sessionManagement:  10%

解决方案

方案 1:减少并发

# 查看当前并发
openclaw status --concurrency

# 限制最大并发
openclaw config set performance.maxConcurrency 3

# 启用请求队列
openclaw config set performance.queue.enabled true
openclaw config set performance.queue.maxSize 50

方案 2:优化任务调度

{
  "performance": {
    "taskScheduling": {
      "strategy": "priority",
      "priorities": {
        "userMessage": 10,
        "cron": 5,
        "webhook": 3,
        "background": 1
      }
    }
  }
}

方案 3:优化工具调用

# 限制工具并发
openclaw config set tools.maxConcurrency 3

# 启用工具超时
openclaw config set tools.timeout 30000

# 禁用不必要的工具
openclaw config set tools.disabled '["browser", "canvas"]'

方案 4:使用子进程

{
  "performance": {
    "workerThreads": {
      "enabled": true,
      "count": 4,
      "tasks": ["toolExecution", "fileProcessing"]
    }
  }
}

方案 5:限制日志输出

# 减少日志输出
openclaw config set logging.level warn

# 禁用详细日志
openclaw config set logging.verbose false

# 禁用调试日志
openclaw config set logging.debug false

问题 4:并发能力不足

症状

  • 多用户同时使用时响应慢
  • 消息队列堆积
  • Gateway 响应超时

诊断方法

# 查看当前连接数
openclaw status --connections

# 查看消息队列
openclaw status --queue

# 查看会话统计
openclaw session stats

# 输出示例:
# Active Sessions:    25
# Pending Messages:   150
# Avg Response Time:  5.2s
# Queue Size:         80/100

解决方案

方案 1:增加队列大小

{
  "performance": {
    "queue": {
      "enabled": true,
      "maxSize": 500,
      "timeout": 60000,
      "priority": true
    }
  }
}

方案 2:启用集群模式

# 启动多个 Gateway 实例
openclaw gateway --port 18789 --daemon
openclaw gateway --port 18790 --daemon
openclaw gateway --port 18791 --daemon

# 使用负载均衡(如 Nginx)

Nginx 负载均衡配置:

upstream openclaw_cluster {
    least_conn;
    server localhost:18789;
    server localhost:18790;
    server localhost:18791;
}

server {
    listen 18789;
    
    location / {
        proxy_pass http://openclaw_cluster;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

方案 3:优化会话管理

{
  "session": {
    "pooling": {
      "enabled": true,
      "maxSessions": 50,
      "idleTimeout": 300000
    },
    "persistence": {
      "enabled": true,
      "backend": "redis",
      "url": "redis://localhost:6379"
    }
  }
}

问题 5:磁盘 I/O 瓶颈

症状

  • 文件操作缓慢
  • 日志写入延迟
  • 会话保存卡顿

诊断方法

# 查看磁盘使用
df -h ~/.openclaw

# 查看磁盘 I/O
iostat -x 1

# 查看文件描述符
lsof -p $(pgrep -f openclaw) | wc -l

# 检查磁盘性能
dd if=/dev/zero of=~/.openclaw/test bs=1M count=100 oflag=direct
rm ~/.openclaw/test

解决方案

方案 1:启用写入缓冲

{
  "storage": {
    "writeBuffer": {
      "enabled": true,
      "size": "10MB",
      "flushInterval": 5000
    }
  }
}

方案 2:使用 SSD 或 NVMe

将 OpenClaw 数据目录移到高速存储:

# 移动数据目录
mv ~/.openclaw /mnt/ssd/openclaw

# 创建符号链接
ln -s /mnt/ssd/openclaw ~/.openclaw

# 或配置新路径
export OPENCLAW_HOME=/mnt/ssd/openclaw

方案 3:优化文件操作

# 限制并发文件操作
openclaw config set storage.maxConcurrentWrites 5

# 启用文件压缩
openclaw config set storage.compression.enabled true

方案 4:定期清理

# 清理临时文件
openclaw cleanup --temp

# 清理旧会话
openclaw cleanup --sessions --older-than 30d

# 清理缓存
openclaw cleanup --cache

# 一键清理
openclaw cleanup --all

问题 6:API 调用延迟高

症状

  • AI 响应生成慢
  • 工具调用延迟高
  • API 超时频繁

诊断方法

# 测试 API 延迟
time curl -X POST https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"claude-opus-4-6","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}'

# 查看 API 统计
openclaw api stats

# 输出示例:
# Total Requests:      1250
# Avg Response Time:   2.3s
# P50:                 1.8s
# P90:                 4.5s
# P99:                 8.2s
# Error Rate:          0.5%

解决方案

方案 1:使用更快的模型

# 日常任务使用快速模型
openclaw config set agent.model anthropic/claude-haiku-3.5

# 配置智能路由
openclaw config set modelRouting '{
  "simple": "claude-haiku-3.5",
  "medium": "claude-sonnet-4",
  "complex": "claude-opus-4-6"
}'

方案 2:减少 Token 消耗

# 限制输出 Token
openclaw config set agent.maxTokens 2000

# 启用自动压缩
openclaw config set session.autoCompress true

# 使用简洁提示词
# 在 AGENTS.md 中指导 Agent 简洁回复

方案 3:启用流式响应

{
  "agent": {
    "streaming": {
      "enabled": true,
      "chunkSize": 100
    }
  }
}

方案 4:配置重试策略

{
  "api": {
    "retry": {
      "enabled": true,
      "maxAttempts": 3,
      "backoff": {
        "type": "exponential",
        "initialDelay": 1000,
        "maxDelay": 30000
      }
    }
  }
}

性能优化最佳实践

1. 监控和告警

# 启用性能监控
openclaw config set monitoring.enabled true
openclaw config set monitoring.interval 60000

# 配置告警
openclaw config set monitoring.alerts '{
  "memory": {"threshold": 90, "action": "notify"},
  "cpu": {"threshold": 85, "action": "notify"},
  "responseTime": {"threshold": 5000, "action": "notify"}
}'

# 查看监控数据
openclaw monitoring stats

2. 定期维护

创建维护脚本 maintenance.sh

#!/bin/bash

echo "开始 OpenClaw 维护..."

# 1. 清理旧会话
echo "清理旧会话..."
openclaw session cleanup --older-than 30d

# 2. 清理日志
echo "清理日志..."
find ~/.openclaw/logs -name "*.log" -mtime +7 -delete

# 3. 清理缓存
echo "清理缓存..."
openclaw cache clear --older-than 7d

# 4. 优化数据库
echo "优化数据库..."
openclaw db optimize

# 5. 重启服务
echo "重启服务..."
openclaw gateway --restart

echo "维护完成!"

配置 cron 定时执行:

# 每周日凌晨 2 点执行
0 2 * * 0 /path/to/maintenance.sh >> ~/.openclaw/logs/maintenance.log 2>&1

3. 资源限制

# 设置资源限制
openclaw config set limits '{
  "memory": "4GB",
  "cpu": "80%",
  "concurrentSessions": 20,
  "messageQueueSize": 200
}'

4. 性能配置模板

创建 performance-config.json

{
  "performance": {
    "mode": "balanced",
    "maxConcurrency": 5,
    "queue": {
      "enabled": true,
      "maxSize": 200,
      "timeout": 30000
    },
    "cache": {
      "enabled": true,
      "ttl": 3600,
      "maxSize": "500MB"
    },
    "workerThreads": {
      "enabled": true,
      "count": 4
    }
  },
  "session": {
    "maxSessions": 20,
    "historyLimit": 100,
    "autoCompress": true
  },
  "logging": {
    "level": "info",
    "rotation": {
      "enabled": true,
      "maxSize": "100MB",
      "maxFiles": 5
    }
  }
}

应用配置:

openclaw config import performance-config.json

小结

性能优化是一个持续的过程:

  1. 响应速度:选择合适模型、优化网络、启用缓存
  2. 内存管理:增加限制、清理会话、优化日志
  3. CPU 优化:减少并发、优化调度、限制日志
  4. 并发能力:增加队列、启用集群、优化会话
  5. 磁盘 I/O:启用缓冲、使用 SSD、定期清理
  6. API 延迟:使用快速模型、减少 Token、启用流式

性能优化的核心原则:

  • 监控优先:先监控,再优化
  • 逐步调整:一次改一个参数,观察效果
  • 权衡取舍:速度 vs 成本 vs 质量
  • 定期维护:自动化维护任务

下一篇预告05. 安全问题排查 — 解决未授权访问、权限配置、数据泄露等安全问题。


更新记录

  • 2026-03-06:初版发布,涵盖 6 大类性能问题

系列导航