← 2026-07-02 📂 All Days 2026-07-06 →

🏗️ 系统设计 / System Design — Day 64

主题 / Topic: Design an AI Chatbot Platform (ChatGPT-scale)

难度 / Difficulty: Expert | 预计阅读 / Read time: 3 min


想象你在设计... / Imagine you're designing...

你是 OpenAI 的首席架构师,正在设计支撑 ChatGPT 的后端系统。每天 1 亿次对话请求、流式输出、多模型支持、会话上下文管理,怎么做?

You're the lead architect at OpenAI, designing the backend for ChatGPT. 100M conversations/day, streaming output, multiple models, session context management — how do you build this?


架构图 / Architecture Diagram

┌─────────────────────────────────┐ │ Client Apps │ │ (Web / iOS / Android / API) │ └──────────────┬──────────────────┘ │ HTTPS / WebSocket ┌──────────────▼──────────────────┐ │ API Gateway │ │ (Rate Limit / Auth / Routing) │ └──────┬───────────────┬──────────┘ │ │ ┌───────────────▼─┐ ┌───▼──────────────┐ │ Chat Service │ │ User Service │ │ (Stateless) │ │ (Auth / Profile) │ └───────┬─────────┘ └──────────────────┘ │ ┌────────────▼──────────────────────────┐ │ Message Queue │ │ (Kafka / SQS / Pub-Sub) │ └────────────┬──────────────────────────┘ │ async dispatch ┌────────────▼──────────────────────────┐ │ Inference Fleet │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ Model │ │ Model │ │ Model │ │ │ │ GPT-4o │ │ o1/o3 │ │ Mini │ │ │ └─────────┘ └─────────┘ └─────────┘ │ │ (A100/H100 GPU Cluster, vLLM) │ └────────────┬──────────────────────────┘ │ SSE streaming back ┌────────────▼──────────────────────────┐ │ Storage Layer │ │ ┌──────────────┐ ┌─────────────────┐ │ │ │ Conversation │ │ Vector Store │ │ │ │ Store (PG) │ │ (pgvector/Pine) │ │ │ └──────────────┘ └─────────────────┘ │ └───────────────────────────────────────┘

核心设计决策 / Key Design Decisions

1. 流式输出 / Streaming (Server-Sent Events)

  • 用户看到逐词输出,感知延迟从 10s 降到 <1s
  • 后端:vLLM 批量推理 + KV Cache,逐 token 通过 SSE 推送
  • 前端:EventSource API 消费,即时渲染
  • Use SSE for token-by-token streaming; perceived latency drops from 10s to <1s

2. 会话上下文管理 / Context Window Management

  • 每次请求需携带完整对话历史(消耗 tokens!)
  • 策略:短对话直接传;长对话 → 滑动窗口 保留最近 N 轮 + 摘要压缩 远程历史
  • Long conversations: sliding window (recent N turns) + summarization for older history

3. 推理路由 / Inference Routing

  • 简单问题 → GPT-4o mini(便宜快)
  • 复杂推理 → o1/o3(贵但准)
  • 路由依据:请求复杂度分类器 + 用户 tier
  • Route simple queries to cheap fast models; complex reasoning to expensive slow models

4. 多租户隔离 / Multi-tenancy

  • API 用户 vs. ChatGPT 用户走不同队列
  • 用户隔离:会话数据按 user_id 分区,GDPR 删除走 soft-delete + 异步清理
  • Separate queues for API vs. product traffic; per-user data partitioned for GDPR

为什么这样设计?/ Why This Design?

决策理由
Kafka 解耦推理失败可重试,不影响前端
无状态 Chat Service水平扩展简单
vLLM 批处理Continuous batching 提升 GPU 利用率 3-4x
PG + pgvector统一存储对话 + 语义搜索,减少运维复杂度

⚠️ 别踩这个坑 / Common Mistakes

坑 1: 把 LLM 调用做成同步请求 → 超时、连接堆积

✅ 用消息队列异步化,前端轮询或 WebSocket 接收结果

坑 2: 每次请求传全部历史 → token 爆炸,成本失控

✅ 实现上下文压缩策略(滑动窗口 + 摘要)

坑 3: 忽略 GPU 利用率 → 推理成本是最大成本项

✅ Continuous batching + 模型路由是降本核心

坑 4: 单点模型部署 → 一个模型版本更新导致全量中断

✅ 金丝雀发布 + 流量染色


📚 References

🧒 ELI5

想象 ChatGPT 是一个巨大的客服中心。你发消息 → 前台排号 → 传到最聪明的客服(GPU)→ 客服边想边回复你(流式输出)→ 聊天记录存起来。简单的问题给初级客服,复杂的给高级客服,这样又快又省钱。
Imagine ChatGPT is a huge call center. You send a message → it gets queued → routed to the smartest agent (GPU) → they answer you word by word (streaming) → chat saved. Simple questions go to junior agents, complex ones to senior — fast and cheap.

💻 算法 / Algorithms — Day 65

题目 / Problem: #1046 Last Stone Weight (Easy)

模式 / Pattern: Heap / Priority Queue (2/7)

预计阅读 / Read time: 4 min


🧩 堆/优先队列模式 (2/7) — 在 Day 79 的模版基础上继续

Building on the Heap/Priority Queue template from Day 79 (Kth Largest in Stream)


回顾模版 / Template Recap

import heapq

# Python heapq = min-heap by default
# For max-heap: negate the values!
heap = []
heapq.heappush(heap, -value)   # push (negated for max-heap)
top = -heapq.heappop(heap)     # pop max (negate back)

核心洞察 / Key Insight: Python 只有 min-heap,模拟 max-heap 的方法是取反。这题需要反复取最大的两块石头,完美匹配 max-heap。

Python only has min-heap. To simulate max-heap: negate values. This problem needs to repeatedly grab the 2 largest stones — perfect max-heap use case.


题目 / Problem

🔗 LeetCode #1046 🟢 Easy

📹 NeetCode Solution

场景 / Analogy: 你在玩石头碰撞游戏。每轮取出最重的两块石头相撞:如果一样重,两块都消失;如果不一样重,较轻的消失,较重的剩下 (y - x) 重量。最后返回剩余石头重量,或 0。

You have a pile of stones. Each round: smash the 2 heaviest. If equal weight → both gone. If different → heavier stone survives with weight `y - x`. Return last stone's weight, or 0.
输入: stones = [2,7,4,1,8,1] 轮1: 取 8,7 → 碰撞 → 剩 1 → stones = [2,4,1,1,1] 轮2: 取 4,2 → 碰撞 → 剩 2 → stones = [2,1,1,1] 轮3: 取 2,1 → 碰撞 → 剩 1 → stones = [1,1,1] 轮4: 取 1,1 → 碰撞 → 剩 0 → stones = [1] 输出: 1

与模版的映射 / Mapping to Template

模版概念本题应用
Max-heap (negate)存石头重量(取反)
heappop × 2取最重的两块
heappush碰撞后放回剩余
终止条件heap 长度 ≤ 1

Python 解法 / Solution

import heapq

def lastStoneWeight(stones: list[int]) -> int:
    # Convert to max-heap by negating all values
    max_heap = [-s for s in stones]
    heapq.heapify(max_heap)          # O(n) heapify
    
    while len(max_heap) > 1:
        y = -heapq.heappop(max_heap) # largest stone
        x = -heapq.heappop(max_heap) # second largest
        
        if y != x:
            # Remaining stone has weight (y - x)
            heapq.heappush(max_heap, -(y - x))
    
    # Return last stone or 0
    return -max_heap[0] if max_heap else 0

# Trace with [2,7,4,1,8,1]:
# heap = [-8,-7,-4,-2,-1,-1]
# Round 1: y=8, x=7 → push -1 → [-4,-2,-1,-1,-1]
# Round 2: y=4, x=2 → push -2 → [-2,-1,-1,-1]
# Round 3: y=2, x=1 → push -1 → [-1,-1,-1]
# Round 4: y=1, x=1 → equal, no push → [-1]
# Return 1 ✓

复杂度 / Complexity:

  • 时间 Time: O(n log n) — n 次 heapop/heappush,每次 O(log n)
  • 空间 Space: O(n) — heap 大小

和前一题的区别 / Difference from Day 79 (Kth Largest in Stream)

Kth Largest in StreamLast Stone Weight
Heap typeMin-heap (keep top-k)Max-heap (always grab max)
Heap sizeFixed at kShrinks over time
OperationAdd then maybe popAlways pop 2, maybe push 1
Python trickDirect min-heapNegate for max-heap

举一反三 / Connect to the Pattern Block

这个模版块里的其他题:

  • Day 79 已学: #703 Kth Largest in Stream (min-heap, size k)
  • 下一题: #973 K Closest Points to Origin (max-heap of size k, 比较距离)
  • 最终 Boss: #295 Find Median from Data Stream (两个 heap,一 max 一 min)
Pattern progression: single heap → fixed-size heap → two heaps

📚 References

🧒 ELI5

你有一堆积木,每次拿出最高的两块互相撞,高的那块变矮。一直这么玩,最后看剩多少高度。堆(heap)就像一个魔法盒子,每次都能最快找到最高那块积木。

You have a pile of blocks. Each time, grab the 2 tallest and smash them — the taller one shrinks. A heap is like a magic box that always finds the tallest block instantly.

🗣️ 软技能 / Soft Skills — Day 64

问题 / Question: Describe how you've contributed to hiring and growing a team

类别 / Category: Leadership | 级别 / Level: Staff

预计阅读 / Read time: 2 min


为什么这道题重要 / Why This Matters

招聘和培养团队是 Staff/Senior 工程师最大的乘数效应之一。面试官在考察你能否:

  1. 建立可扩展的招聘流程(不只是"我面试了很多人")
  2. 主动识别团队技能缺口
  3. 对成员成长有具体的投入

Hiring and growing people is one of the biggest force multipliers at Staff level. Interviewers want to know if you can build scalable hiring processes, identify skill gaps, and invest concretely in others' growth.


STAR 结构拆解 / STAR Breakdown

Situation(背景):

团队快速扩张,需要在 6 个月内从 5 人扩到 12 人,同时保持代码质量和文化。

Team scaled from 5 to 12 in 6 months while maintaining quality and culture.

Task(任务):

作为 lead,我负责重新设计面试流程并建立 onboarding 框架。

As lead, I redesigned the interview process and built an onboarding framework.

Action(行动):

  • 分析了前 10 次面试的结果,发现 "系统设计" 环节差异最大 → 写了评分 rubric
  • 建立了 "代码配对" 环节(而非白板),候选人反馈好感度大幅提升
  • 为每位新成员设计了 30-60-90 天计划,第一周 pair programming,第 30 天独立 feature
  • 为三名 junior 成员建立了月度 1:1 + 技术书单,其中两人在 18 个月内晋升
Actions: analyzed interview feedback → created rubric → replaced whiteboard with pair coding → built 30-60-90 onboarding plan → monthly 1:1s with growth plan for juniors

Result(结果):

offer 接受率从 40% 升至 70%;新人 30 天 productivity 提升(有效 PR 数量指标);两名 junior 18 个月内晋升。

Offer acceptance rate: 40% → 70%. Onboarding time cut by 2 weeks. 2 promotions in 18 months.


❌ 坏回答 vs ✅ 好回答

❌ 差回答:

"I participated in lots of interviews and gave feedback."

(太被动,没有体现主导性和系统思维)

✅ 好回答:

"I noticed our interview loop was inconsistent — strong candidates were getting conflicting signals. I redesigned the system design rubric, piloted paired coding instead of whiteboard, and tracked offer acceptance rate as the metric. It went from 40% to 70% in two quarters."

(有问题识别、有系统性解决方案、有量化结果)


Senior/Staff 加分点 / Senior/Staff Tips

  1. 规模化思考: 不只说"我帮了某个人",说"我建了一个系统让整个团队都能更好地 grow people"
  2. 量化 onboarding 效果: "30 天独立合并 PR" 这类指标比 "顺利融入" 更有说服力
  3. 强调文化传递: 技术面试不只是筛技能,也是在筛文化 fit,解释你如何把这个标准化
  4. 展示持续投入: 面试设计 vs. 主动做 1:1 vs. 推动晋升 — 全程参与才是 Staff level

Think systems, not anecdotes. "I mentored someone" is junior. "I built a mentorship framework that scaled across the team" is Staff.


Key Takeaways

  • 面试官要看的是乘数效应:你的投入如何让整个团队更强
  • 用数据说话:接受率、晋升数量、时间到第一个 PR
  • 体现主动性:发现问题 → 设计解决方案 → 跟踪结果
  • The interviewer wants force multiplier thinking: how your investment made the whole team stronger
  • Use metrics: offer rate, promotions, time-to-first-PR
  • Show agency: spotted problem → designed solution → tracked outcomes

📚 References

🧒 ELI5

就像你加入了一支篮球队,不只是自己打好球,还帮新队友练习、设计训练方案、让整个队都变强。Staff 工程师就是那种不只自己 carry,还让整个队都打得更好的人。

Like joining a basketball team — not just playing well yourself, but coaching new teammates, designing drills, making the whole team stronger. Staff engineers don't just carry; they make everyone better.

🤖 AI 新闻 / AI News — Day 81

日期 / Date: 2026-07-03 | 模式 / Mode: NEWS

预计阅读 / Read time: 2 min


本周 AI 头条 / This Week in AI

1. 🔄 Anthropic 恢复 Claude Fable 5 + 发布 Sonnet 5

Anthropic 旗舰模型 Claude Fable 5 在被政府暂停 19 天后于 7 月 1 日恢复上线,新增安全分类器以防止越狱攻击。同日,Claude Sonnet 5 正式发布,被描述为"最具代理性的 Sonnet",性能接近 Opus 4.8 但价格更低。

Mythos 5 仅对经联邦政府审批的美国机构开放。

Anthropic's Claude Fable 5 returned on July 1st after a 19-day government-ordered suspension, with a new safety classifier blocking jailbreak techniques. Claude Sonnet 5 also launched — most agentic Sonnet yet, near-Opus-4.8 performance at lower cost.

📰 来源 / Source: Anthropic Official | BuildFastWithAI


2. 🌐 联合国发布首份全球 AI 独立科学评估报告

7 月 1 日,联合国发布首份全球独立 AI 科学评估报告,将于 7 月 6-7 日日内瓦 UN 全球 AI 治理对话上呈交各国政府。报告警告:AI 代理系统没有科学保证不会违反人类指令,各国需建立治理框架。

On July 1st, the UN released its first global independent scientific assessment of AI. Key warning: there are no scientific guarantees that AI agent systems will follow human instructions. Presented at the inaugural UN Global Dialogue on AI Governance in Geneva, July 6–7.

📰 来源 / Source: UN News


3. 🤖 Agentic AI 成为行业基线

多家公司报告,自主 AI 代理正从简单任务升级为多步骤复杂工作流:数据分析、报告生成、参与代码审查。Google 准备发布 Gemini 3.5 Pro(具有代理能力的高级编程模型),OpenAI 的 GPT-5.6 系列仍在受限发布中。

Autonomous AI agents are evolving from simple tasks to complex multi-step workflows: data analysis, report generation, code review participation. Google preparing Gemini 3.5 Pro with agentic coding capabilities; OpenAI's GPT-5.6 series remains in restricted release.

📰 来源 / Source: Forbes Tech Council | BuildFastWithAI


💡 工程师视角 / Engineer's Take

Fable 5 复出 + 安全分类器 → 表明政府监管力度在提升,frontier model 的发布流程正在制度化。

UN 报告 + 白宫自愿标准 → 2026 下半年将是 AI 治理的关键窗口。做 AI infra 的工程师要开始关注 compliance 和 auditability。

Agentic AI 成主流 → 真正的挑战不是"让代理执行任务",而是"如何让代理可靠、可回滚、可审计"。这正是 Circuit Breaker(今天 Python Craft)等模式在 AI 系统中的价值所在。

The UN report and White House voluntary standards signal: AI governance is being formalized. For engineers: auditability, safety classifiers, and graceful degradation (← today's Circuit Breaker!) are becoming first-class requirements, not afterthoughts.


📚 References

🧒 ELI5

本周 AI 新闻:一个被政府暂时关掉的超强 AI 模型重新上线了,并装上了新的安全锁;联合国说"我们还没法保证 AI 一定听话";越来越多的 AI 开始自动帮你干复杂工作了。整个行业正在变得更强大,同时也更加需要监管。

This week: a powerful AI model got un-banned with new safety locks; the UN said "we can't guarantee AI will follow orders"; and AI agents are taking on increasingly complex work. The industry is getting stronger and more regulated at the same time.