1. 面试场景下的三大痛点
- 实时性:面试官要求 300 ms 内返回答案,传统 REST 同步调用平均 600 ms,直接淘汰。
- 多轮一致性:候选人先问“年假几天”,再问“那病假呢”,必须绑定同一 session,否则上下文错位。
- 意图准确率:校招/社招/实习政策不同,BERT 微调后 96% 准确率,规则引擎仅 78%,差 18% 就能决定 Offer 与否。
2. 规则 vs 机器学习:一张表看懂
| 维度 | 规则引擎 | BERT 微调 |
|---|---|---|
| QPS 单卡 | 3 k | 800 |
| 成本(月) | 2 台 4C8G 约 600 元 | A10 单卡 2 k |
| 迭代周期 | 小时级发版 | 天级标注+训练 |
| 可解释性 | 高 | 低,需 Grad-CAM |
| 场景 | 固定 FAQ | 开放域多轮 |
结论:预算充足且准确率>95% 时直接上 BERT;边缘小场景用规则兜底。
3. 核心实现
3.1 Python 异步对话服务(FastAPI)
# main.py from fastapi import FastAPI, HTTPException, Depends from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials import aioredis, time, jwt, uvloop, asyncio app = FastAPI(title="ivbot-interview") security = HTTPBearer() redis = aioredis.from_url("redis://cluster:6379/0", decode_responses=True) def jwt_verify(cred: HTTPAuthorizationCredentials = Depends(security)): try: payload = jwt.decode(cred.credentials, key="secret", algorithms=["HS256"]) return payload["uid"] except jwt.ExpiredSignatureError: raise HTTPException(401, "token expired") @app.post("/chat") async def chat(req: dict, uid: str = Depends(jwt_verify)): start = time.time() sid = req["session_id"] query = req["query"] # 1. 读状态 ctx = await redis.hgetall(f"s:{sid}") # 2. 调 NLU intent = await call_nlu(query) # 3. 更新状态 ctx["last_intent"] = intent pipe = redis.pipeline() pipe.hset(f"s:{sid}", mapping=ctx) pipe.expire(f"s:{sid}", 600) await pipe.execute() cost = int((time.time() - start)*1000) # 4. 埋点 asyncio.create_task(report_metric("latency", cost)) return {"answer": intent2reply(intent), "latency": cost} async def call_nlu(txt: str) -> str: async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=0.2)) as s: try: async with s.post("http://go-nlu:9000/classify", json={"q": txt}) as r: return (await r.json())["intent"] except asyncio.TimeoutError: return "timeout_fallback"要点:
- 使用
uvloop把事件循环切换成 Cython 版,QPS 提升 18%。 - 所有 I/O 均异步,超时 200 ms 立即降级。
- JWT 中间件统一鉴权,方便后续做灰度。
3.2 Go 热更新意图分类模块
// nlu.go package main import ( "context" "sync/atomic" "google.golang.org/grpc" pb "ivbot/pb" ) var modelVersion int32 type server struct{ pb.UnimplementedNLUServer } func (s *server) Classify(ctx context.Context, in *pb.Query) (*pb.Result, error) { v := atomic.LoadInt32(&modelVersion) label, score := bertPredict(in.Q, int(v)) return &pb.Result{Intent: label, Score: score}, nil } func main() { lis, _ := net.Listen("tcp", ":9000") s := grpc.NewServer(grpc.UnaryInterceptor(RecoveryInterceptor)) pb.RegisterNLUServer(s, &server{}) go watchModelDir() // inotify 监听 /models/*.onnx s.Serve(lis} } func watchModelDir() { for event := range watcher.Events { if event.Op&fsnotify.Write == fsnotify.Write { newVer := extractVer(event.Name) atomic.StoreInt32(&modelVersion, newVer) log.Println("hot reload model", newVer) } } }- gRPC 接口定义仅 2 个字段,IDL 稳定,方便 Java/C++ 端复用。
- 热更新采用原子指针切换,请求零中断。
- 内部用 ONNXRuntime+Go 绑定,单卡 QPS 1.2 k,CPU 占用 60%。
4. 性能优化
4.1 Redis 集群分片策略
- 会话 key 格式
s:{sid},采用CRC16(sid)%16384一致性哈希到 8 个 master。 - 每 master 挂载 1 个 slave,跨机房 RPO<1 s。
- 热 key 问题:把高频 HR 政策问答结果缓存到本地 Caffeine,QPS 提升 30%。
4.2 Sentinel 故障转移
- 哨兵集群 3 节点, quorum=2,down-after-milliseconds 3000。
- 客户端使用
redis.sentinel.SentinelPool,自动感知主从切换。 - 切换期间,写请求直接进本地队列,最长 5 s,超时返回“系统繁忙,请稍候”。
5. 避坑指南
- 会话超时导致上下文丢失
- 把 TTL 设为 600 s,并在前端心跳 30 s 轮询续期;否则候选人刷新页面即丢。
- 第三方 NLP 服务降级
- 配置双层降级:① 200 ms 超时 ② 返回规则兜底答案;同时把失败率写入 Prometheus,>5% 自动告警。
- 版本热更新误杀
- 上线前先在 staging 环境压测 10 min,对比旧模型 F1 下降不超过 1% 才切流量。
6. 延伸思考:百万并发日志分析流水线
- 采集:Filebeat sidecar 写 Kafka,单分区 3 万条/s,按 session_id 做 key 保证有序。
- 流计算:Flink SQL 开窗 5 s,统计意图分布、平均延迟,结果写 ClickHouse。
- 离线:每日把冷数据导至 OSS,Spark 做 Levenshtein 距离聚类,挖掘新意图。
- 资源:Kafka 40 分区、Flink 64 TaskManager,可水平扩展到 200 万 QPS,成本约 1.5 万/月。
7. 小结
把 FastAPI 的异步优势、Go 的热更新能力、Redis 集群的高可用串成一条线,基本就能在面试场景里扛住高并发、低延迟的双重拷问。真实上线后,我们的 P99 延迟从 520 ms 降到 190 ms,意图准确率提升 18%,服务器成本只增加 12%。如果你也在准备智能客服方向的技术面试,不妨把上面的代码和指标直接写进简历,再画一张 Sentinel 故障转移图,基本能聊到终面。祝各位 Offer 多多。