面试高频题:线上请求很慢,如何排查?

2025年10月25日

面试 性能优化 故障排查 后端开发 运维
面试高频题:线上请求很慢,如何排查?

面试高频题:线上请求很慢,如何排查?

这是一道非常经典的后端面试题,考察的是候选人的系统性思维、问题排查能力和实战经验。本文将从多个维度系统性地分析这个问题。

问题分析框架

在回答这个问题时,建议采用结构化的思维框架:

1. 问题定位 → 2. 指标收集 → 3. 层层排查 → 4. 解决方案 → 5. 预防措施

第一步:明确问题

在开始排查之前,先通过提问明确问题的具体情况:

关键问题清单

  1. 影响范围

    • 是所有用户都慢,还是部分用户?
    • 是所有接口都慢,还是特定接口?
    • 是突然变慢,还是逐渐变慢?
  2. 时间特征

    • 什么时候开始变慢的?
    • 是一直慢,还是间歇性慢?
    • 有没有明显的时间规律(高峰期/低峰期)?
  3. 具体表现

    • 响应时间从多少变到多少?
    • 有没有报错?错误类型是什么?
    • 有没有超时?
  4. 最近变更

    • 最近有没有发布新版本?
    • 有没有配置变更?
    • 有没有数据库迁移或表结构变更?

第二步:查看监控和日志

1. 应用层监控

APM监控工具

# 使用APM工具(如SkyWalking、Prometheus等)查看:
- 平均响应时间
- P50、P95、P99响应时间
- 错误率
- 吞吐量(QPS)
- 慢查询追踪

应用日志分析

# 查看应用日志
tail -f /var/log/application.log

# 统计错误日志
grep "ERROR" application.log | wc -l

# 查看慢请求日志
grep "slow" application.log | tail -100

# 分析错误类型分布
grep "ERROR" application.log | awk '{print $5}' | sort | uniq -c | sort -rn

请求链路追踪

# 使用分布式追踪系统(如Jaeger、Zipkin)
# 查看完整的请求链路,找出慢的环节:

请求 → 网关 → 服务A → 数据库
                ↓
              服务B → 缓存
                ↓
              服务C → 第三方API

2. 系统层监控

CPU使用率

# 查看CPU使用情况
top
htop

# 查看CPU占用最高的进程
ps aux | sort -k3 -rn | head -10

# 查看具体进程的线程情况
top -H -p <pid>

# 查看Java应用的线程栈
jstack <pid> > thread_dump.txt

内存使用

# 查看内存使用情况
free -h

# 查看进程内存占用
ps aux | sort -k4 -rn | head -10

# 查看Java堆内存
jmap -heap <pid>

# 生成堆内存dump
jmap -dump:format=b,file=heap.bin <pid>

# 分析GC情况
jstat -gcutil <pid> 1000

磁盘I/O

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

# 查看哪些进程在进行I/O操作
iotop

# 查看磁盘空间
df -h

# 查看inode使用情况
df -i

网络状态

# 查看网络连接状态
netstat -antp

# 查看TIME_WAIT连接数
netstat -antp | grep TIME_WAIT | wc -l

# 查看ESTABLISHED连接数
netstat -antp | grep ESTABLISHED | wc -l

# 查看网络流量
iftop

# 抓包分析
tcpdump -i eth0 port 8080 -w capture.pcap

3. 数据库监控

慢查询日志

-- MySQL慢查询日志
SHOW VARIABLES LIKE 'slow_query%';
SHOW VARIABLES LIKE 'long_query_time';

-- 查看慢查询
SELECT * FROM mysql.slow_log ORDER BY start_time DESC LIMIT 10;

数据库性能指标

-- 查看当前执行的查询
SHOW PROCESSLIST;

-- 查看表锁情况
SHOW OPEN TABLES WHERE In_use > 0;

-- 查看事务
SELECT * FROM information_schema.INNODB_TRX;

-- 查看锁等待
SELECT * FROM information_schema.INNODB_LOCK_WAITS;

-- 查看连接数
SHOW STATUS LIKE 'Threads_connected';
SHOW VARIABLES LIKE 'max_connections';

数据库连接池

# 检查连接池配置
{
    "maxPoolSize": 20,      # 最大连接数
    "minIdle": 5,           # 最小空闲连接
    "maxWaitMillis": 3000,  # 最大等待时间
    "activeConnections": 18, # 当前活跃连接
    "idleConnections": 2     # 当前空闲连接
}

第三步:层层排查

1. 网络层问题

DNS解析慢

# 测试DNS解析时间
dig example.com

# 解决方案
- 使用DNS缓存
- 配置本地hosts
- 使用更快的DNS服务器(如8.8.8.8)

网络延迟高

# 测试网络延迟
ping api.example.com
traceroute api.example.com

# 测试带宽
iperf -c server_ip

# 解决方案
- 使用CDN加速
- 优化网络路由
- 增加带宽
- 使用专线

连接池耗尽

# HTTP连接池配置优化
import requests
from requests.adapters import HTTPAdapter

session = requests.Session()
adapter = HTTPAdapter(
    pool_connections=100,  # 连接池大小
    pool_maxsize=100,      # 最大连接数
    max_retries=3,         # 重试次数
    pool_block=True        # 连接池满时阻塞
)
session.mount('http://', adapter)
session.mount('https://', adapter)

2. 应用层问题

代码性能问题

# 使用性能分析工具
# Python示例
import cProfile
import pstats

profiler = cProfile.Profile()
profiler.enable()

# 你的代码
slow_function()

profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(10)

常见性能瓶颈

1. N+1查询问题

# 问题代码:N+1查询
users = User.query.all()
for user in users:
    # 每次循环都会执行一次数据库查询
    orders = Order.query.filter_by(user_id=user.id).all()

# 优化:使用JOIN或预加载
from sqlalchemy.orm import joinedload

users = User.query.options(joinedload(User.orders)).all()
for user in users:
    orders = user.orders  # 不会触发额外查询

2. 循环中的重复计算

# 问题代码
for item in items:
    result = expensive_calculation(item, config)  # 每次都计算config

# 优化:提取不变量
config_result = expensive_calculation_once(config)
for item in items:
    result = fast_calculation(item, config_result)

3. 大数据量加载

# 问题代码:一次性加载所有数据
all_records = Record.query.all()  # 可能有百万条记录

# 优化:分页/流式处理
def process_in_batches(batch_size=1000):
    offset = 0
    while True:
        batch = Record.query.limit(batch_size).offset(offset).all()
        if not batch:
            break
        for record in batch:
            process(record)
        offset += batch_size

阻塞操作

# 问题:同步调用耗时的外部服务
response = requests.get('https://slow-api.com/data', timeout=30)

# 解决方案1:异步处理
import asyncio
import aiohttp

async def fetch_data():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://slow-api.com/data') as response:
            return await response.json()

# 解决方案2:使用消息队列异步处理
from celery import Celery

@celery.task
def fetch_data_async():
    response = requests.get('https://slow-api.com/data')
    return response.json()

# 立即返回,异步处理
task = fetch_data_async.delay()

并发问题

# 死锁检测
# 查看Python线程状态
import sys
import threading

def dump_threads():
    for thread_id, frame in sys._current_frames().items():
        print(f"Thread {thread_id}:")
        print(''.join(traceback.format_stack(frame)))

# Java线程死锁检测
jstack <pid> | grep -A 20 "deadlock"

3. 数据库层问题

慢查询优化

-- 1. 查看执行计划
EXPLAIN SELECT * FROM orders WHERE user_id = 123 AND status = 'pending';

-- 2. 常见问题和解决方案

-- 问题:没有使用索引
-- 解决:创建合适的索引
CREATE INDEX idx_user_status ON orders(user_id, status);

-- 问题:全表扫描
-- 解决:添加WHERE条件,使用索引

-- 问题:索引失效(使用函数)
SELECT * FROM users WHERE DATE(created_at) = '2025-01-01';
-- 优化:不要在索引列上使用函数
SELECT * FROM users WHERE created_at >= '2025-01-01' AND created_at < '2025-01-02';

-- 问题:JOIN表过多
-- 解决:减少JOIN,考虑适当的反范式化

-- 问题:子查询效率低
SELECT * FROM orders WHERE user_id IN (SELECT id FROM users WHERE vip = 1);
-- 优化:改用JOIN
SELECT o.* FROM orders o 
INNER JOIN users u ON o.user_id = u.id 
WHERE u.vip = 1;

索引优化

-- 查看索引使用情况
SHOW INDEX FROM orders;

-- 查看索引统计信息
SELECT * FROM sys.schema_unused_indexes;

-- 删除未使用的索引
ALTER TABLE orders DROP INDEX unused_index;

-- 创建覆盖索引
CREATE INDEX idx_covering ON orders(user_id, status, created_at);

锁等待

-- 查看锁等待
SELECT 
    r.trx_id waiting_trx_id,
    r.trx_mysql_thread_id waiting_thread,
    r.trx_query waiting_query,
    b.trx_id blocking_trx_id,
    b.trx_mysql_thread_id blocking_thread,
    b.trx_query blocking_query
FROM 
    information_schema.INNODB_LOCK_WAITS w
    INNER JOIN information_schema.INNODB_TRX b ON b.trx_id = w.blocking_trx_id
    INNER JOIN information_schema.INNODB_TRX r ON r.trx_id = w.requesting_trx_id;

-- 解决方案:
-- 1. 优化事务,减少持锁时间
-- 2. 使用乐观锁代替悲观锁
-- 3. 调整事务隔离级别

连接数不足

-- 查看当前连接数和最大连接数
SHOW STATUS LIKE 'Threads_connected';
SHOW VARIABLES LIKE 'max_connections';

-- 调整最大连接数
SET GLOBAL max_connections = 500;

-- 应用层优化:
-- 1. 使用连接池
-- 2. 及时释放连接
-- 3. 减少长连接

4. 缓存层问题

缓存穿透

# 问题:查询不存在的数据,导致大量请求打到数据库
def get_user(user_id):
    user = cache.get(f'user:{user_id}')
    if user is None:
        user = db.query(f'SELECT * FROM users WHERE id = {user_id}')
        # 如果user不存在,会一直查数据库
    return user

# 解决方案1:缓存空值
def get_user(user_id):
    user = cache.get(f'user:{user_id}')
    if user is None:
        user = db.query(f'SELECT * FROM users WHERE id = {user_id}')
        if user is None:
            cache.set(f'user:{user_id}', 'NULL', expire=60)  # 缓存空值
            return None
        cache.set(f'user:{user_id}', user, expire=3600)
    return user if user != 'NULL' else None

# 解决方案2:布隆过滤器
from pybloom_live import BloomFilter

user_bloom = BloomFilter(capacity=1000000, error_rate=0.001)

def get_user(user_id):
    if user_id not in user_bloom:
        return None  # 一定不存在
    # 可能存在,查询缓存和数据库
    ...

缓存击穿

# 问题:热点数据过期,大量请求同时打到数据库
import threading

locks = {}

def get_hot_data(key):
    data = cache.get(key)
    if data is None:
        # 加锁,只让一个请求去查数据库
        lock = locks.setdefault(key, threading.Lock())
        with lock:
            # 双重检查
            data = cache.get(key)
            if data is None:
                data = db.query(key)
                cache.set(key, data, expire=3600)
    return data

# 更好的方案:使用分布式锁
import redis

def get_hot_data_with_redis_lock(key):
    data = cache.get(key)
    if data is None:
        lock_key = f'lock:{key}'
        # 尝试获取锁
        if redis_client.set(lock_key, '1', nx=True, ex=10):
            try:
                data = db.query(key)
                cache.set(key, data, expire=3600)
            finally:
                redis_client.delete(lock_key)
        else:
            # 等待其他线程加载完成
            time.sleep(0.1)
            return get_hot_data_with_redis_lock(key)
    return data

缓存雪崩

# 问题:大量缓存同时过期
# 解决方案1:随机过期时间
import random

def set_cache_with_random_expire(key, value, base_expire=3600):
    # 在基础过期时间上加上随机时间
    expire = base_expire + random.randint(0, 300)
    cache.set(key, value, expire=expire)

# 解决方案2:热点数据永不过期,异步更新
def get_data_with_background_refresh(key):
    data, expire_time = cache.get_with_expire(key)
    if data is None:
        data = db.query(key)
        cache.set(key, (data, time.time() + 3600))
    elif time.time() > expire_time - 300:  # 提前5分钟
        # 异步刷新缓存
        threading.Thread(target=refresh_cache, args=(key,)).start()
    return data

5. 中间件问题

消息队列积压

# 监控队列长度
def monitor_queue():
    queue_length = rabbitmq.queue_length('task_queue')
    if queue_length > 10000:
        alert(f"队列积压严重: {queue_length}")

# 解决方案:
# 1. 增加消费者
# 2. 优化消费逻辑
# 3. 批量处理
def batch_consume(batch_size=100):
    messages = []
    for _ in range(batch_size):
        msg = queue.get()
        if msg:
            messages.append(msg)
    
    if messages:
        batch_process(messages)

线程池耗尽

# 监控线程池状态
from concurrent.futures import ThreadPoolExecutor
import threading

executor = ThreadPoolExecutor(max_workers=50)

def monitor_thread_pool():
    active_threads = threading.active_count()
    print(f"活跃线程数: {active_threads}")

# 解决方案:
# 1. 调整线程池大小
# 2. 使用队列限流
# 3. 使用异步IO代替多线程

第四步:解决方案

应急响应

  1. 限流降级
from flask_limiter import Limiter

limiter = Limiter(
    app,
    key_func=lambda: request.remote_addr,
    default_limits=["200 per day", "50 per hour"]
)

@app.route("/api/slow-endpoint")
@limiter.limit("10 per minute")
def slow_endpoint():
    return handle_request()
  1. 服务降级
def get_user_info(user_id):
    try:
        # 尝试从完整服务获取
        return full_service.get_user(user_id)
    except Exception:
        # 降级:返回基础信息
        return cache.get(f'user:basic:{user_id}') or {
            'id': user_id,
            'name': '用户',
            'avatar': 'default.jpg'
        }
  1. 熔断机制
from pybreaker import CircuitBreaker

breaker = CircuitBreaker(
    fail_max=5,
    timeout_duration=60
)

@breaker
def call_external_api():
    return requests.get('https://api.example.com/data', timeout=3)

长期优化

1. 数据库优化

  • 优化查询语句
  • 添加合适的索引
  • 分库分表
  • 读写分离
  • 使用数据库连接池

2. 缓存优化

  • 增加缓存层
  • 优化缓存策略
  • 使用多级缓存
  • 缓存预热

3. 代码优化

  • 异步处理
  • 并行处理
  • 减少不必要的计算
  • 优化算法复杂度

4. 架构优化

  • 微服务拆分
  • 负载均衡
  • CDN加速
  • 使用消息队列解耦

第五步:预防措施

1. 监控告警

# 设置监控指标
metrics = {
    'response_time': {
        'p50': 100,   # 毫秒
        'p95': 500,
        'p99': 1000
    },
    'error_rate': 0.01,  # 1%
    'qps': 10000
}

# 告警规则
def check_alerts():
    if response_time_p99 > 1000:
        send_alert('响应时间P99超过1秒')
    
    if error_rate > 0.05:
        send_alert('错误率超过5%')
    
    if cpu_usage > 0.8:
        send_alert('CPU使用率超过80%')

2. 性能测试

# 压力测试
# 使用locust进行压测
from locust import HttpUser, task, between

class PerformanceTest(HttpUser):
    wait_time = between(1, 3)
    
    @task
    def test_api(self):
        self.client.get("/api/endpoint")

3. 代码审查

  • 关注性能关键代码
  • 检查数据库查询
  • 检查循环嵌套
  • 检查资源释放

4. 容量规划

# 容量评估
current_qps = 1000
peak_qps = 5000
growth_rate = 1.5  # 预期增长50%

required_capacity = peak_qps * growth_rate * 1.2  # 20%余量
print(f"需要支持的QPS: {required_capacity}")

实战案例分析

案例1:电商大促请求慢

现象:

  • 双11期间,商品详情页响应时间从100ms上升到5秒
  • 部分用户无法下单

排查过程:

  1. 查看监控:发现数据库CPU 100%
  2. 查看慢查询:发现大量库存查询
  3. 分析代码:每次查询商品详情都实时查库存

解决方案:

# 原代码:实时查询库存
def get_product_detail(product_id):
    product = db.get_product(product_id)
    stock = db.get_stock(product_id)  # 慢查询
    return {**product, 'stock': stock}

# 优化:使用Redis缓存库存
def get_product_detail(product_id):
    product = cache.get(f'product:{product_id}')
    if not product:
        product = db.get_product(product_id)
        cache.set(f'product:{product_id}', product, expire=300)
    
    # 从Redis获取库存
    stock = redis.get(f'stock:{product_id}')
    return {**product, 'stock': stock}

# 库存变更时更新Redis
def update_stock(product_id, change):
    redis.incrby(f'stock:{product_id}', change)
    # 异步更新数据库
    queue.send({'product_id': product_id, 'change': change})

案例2:定时任务导致请求慢

现象:

  • 每天凌晨3点,请求响应时间突然飙升
  • 持续约30分钟后恢复

排查过程:

  1. 查看定时任务:发现凌晨3点有数据统计任务
  2. 查看数据库:大表全表扫描
  3. 查看监控:数据库连接数接近上限

解决方案:

# 原代码:全表统计
def daily_statistics():
    # 全表扫描,锁表
    total = db.execute('SELECT COUNT(*) FROM orders')
    revenue = db.execute('SELECT SUM(amount) FROM orders')

# 优化1:使用只读副本
def daily_statistics():
    # 从只读副本查询,不影响主库
    total = read_db.execute('SELECT COUNT(*) FROM orders')
    revenue = read_db.execute('SELECT SUM(amount) FROM orders')

# 优化2:增量统计
def daily_statistics():
    # 只统计昨天的数据
    yesterday = datetime.now() - timedelta(days=1)
    total = db.execute(
        'SELECT COUNT(*) FROM orders WHERE date = %s',
        yesterday
    )
    # 累加到总统计
    update_total_statistics(total)

案例3:内存泄漏导致GC频繁

现象:

  • 应用运行一段时间后变慢
  • 重启后恢复正常
  • GC时间占比越来越高

排查过程:

  1. 查看GC日志:Full GC频繁
  2. Dump堆内存:发现大量临时对象未释放
  3. 分析代码:全局缓存无限增长

解决方案:

# 原代码:全局字典无限增长
_cache = {}

def get_data(key):
    if key not in _cache:
        _cache[key] = fetch_data(key)  # 永不清理
    return _cache[key]

# 优化:使用LRU缓存
from functools import lru_cache

@lru_cache(maxsize=1000)
def get_data(key):
    return fetch_data(key)

# 或使用Redis等外部缓存
def get_data(key):
    data = redis.get(key)
    if data is None:
        data = fetch_data(key)
        redis.setex(key, 3600, data)
    return data

面试回答模板

当面试官问”线上请求很慢,如何排查”时,可以这样回答:

遇到线上请求慢的问题,我会按照以下步骤系统性地排查:

第一步,明确问题范围:确认是全部用户还是部分用户受影响,是所有接口还是特定接口,什么时候开始的,最近有无变更等。

第二步,查看监控和日志:

  • 应用层:查看APM监控、链路追踪、应用日志,找出慢的环节
  • 系统层:查看CPU、内存、磁盘I/O、网络状态
  • 数据库:查看慢查询、锁等待、连接数等
  • 缓存:查看缓存命中率、是否有大key等

第三步,针对性排查:

  • 如果是数据库慢:检查慢查询、索引、锁等待
  • 如果是代码慢:使用性能分析工具找出瓶颈
  • 如果是网络慢:检查网络延迟、连接池等
  • 如果是缓存问题:排查缓存穿透、击穿、雪崩

第四步,应急处理和长期优化:

  • 应急:限流、降级、熔断,快速恢复服务
  • 长期:优化代码、优化查询、加缓存、架构升级

第五步,建立预防机制:完善监控告警、做好压测、代码审查、容量规划等。

在我之前的项目中,遇到过[具体案例],当时的问题是[原因],通过[方法]解决了,后续通过[预防措施]避免了类似问题。

总结

线上请求慢的排查是一个系统工程,需要:

  1. 系统性思维:从网络到应用到数据库,层层排查
  2. 数据驱动:依靠监控和日志,不要凭感觉
  3. 快速响应:先止损,再优化
  4. 预防为主:建立完善的监控和测试体系
  5. 持续优化:性能优化是持续的过程

掌握这些知识和技能,不仅能帮助你通过面试,更重要的是能在实际工作中快速定位和解决问题。


记住:性能优化没有银弹,要根据具体情况具体分析。

返回博客列表