← 2026-06-21 📂 All Days 2026-06-23 →

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

Topic: Design an LLM Inference Serving System

Date: 2026-06-22 | Difficulty: Expert


想象你在设计... / Imagine You're Designing...

你是 OpenAI 的基础设施工程师。公司刚刚发布了 GPT-X,每秒涌入数万个请求。每个请求都需要调用一个数十亿参数的模型。如何在保证低延迟的同时,让成本不至于爆炸?

You're an infra engineer at OpenAI. The company just launched GPT-X, and tens of thousands of requests per second are flooding in. Every request needs to run through a billion-parameter model. How do you keep latency low without bankrupting the company?


架构图 / Architecture Diagram

┌─────────────────────────────┐ │ Load Balancer │ │ (Request Routing) │ └────────────┬────────────────┘ │ ┌──────────────────┼──────────────────┐ │ │ │ ┌────────▼────────┐ ┌───────▼───────┐ ┌───────▼────────┐ │ Inference Node │ │ Inference Node│ │ Inference Node │ │ (A100 x 8) │ │ (A100 x 8) │ │ (A100 x 8) │ │ ┌────────────┐ │ │ │ │ │ │ │ KV Cache │ │ │ │ │ │ │ │ (Per-req) │ │ │ │ │ │ │ └────────────┘ │ │ │ │ │ └────────┬────────┘ └───────┬───────┘ └───────┬────────┘ │ │ │ ┌────────▼──────────────────▼──────────────────▼────────┐ │ Continuous Batching Engine │ │ (vLLM / TensorRT-LLM — PagedAttention) │ └────────────────────────────┬───────────────────────────┘ │ ┌───────────────────┼────────────────────┐ │ │ │ ┌────────▼──────┐ ┌────────▼──────┐ ┌────────▼──────┐ │ Model Store │ │ Request Queue │ │ Result Store │ │ (S3 + NVMe) │ │ (Redis/Kafka)│ │ (Cache/Redis) │ └───────────────┘ └───────────────┘ └───────────────┘

关键组件 / Key Components:

  1. Continuous Batching — 不等批次填满就开始推理,动态合并请求
  2. PagedAttention (KV Cache) — 将 KV cache 分页管理,像操作系统管理内存一样
  3. Tensor Parallelism — 一个模型切分到多张 GPU 卡上并行推理
  4. Speculative Decoding — 用小模型预测 token,大模型验证,加速 3-5x

核心权衡 / Key Tradeoffs

为什么不用普通 batching?

传统 static batching 需要等最长请求完成才能处理下一批。Continuous batching 允许请求随时进出队列,GPU 利用率从 ~30% 提升到 ~80%+。

Tensor Parallelism vs Pipeline Parallelism:

  • Tensor Parallelism: 把一层的权重切分到多卡,通信在层内 → 低延迟,适合单请求
  • Pipeline Parallelism: 把不同层放到不同卡,流水线处理 → 高吞吐,适合批量

Model Quantization tradeoffs:

  • FP16 → INT8: 内存减半,速度翻倍,精度损失 <1%
  • INT4 (GPTQ/AWQ): 内存减少 4x,精度损失稍大,适合低优先级任务

别踩这个坑 / Common Mistakes

❌ 用 sequence length 做 batching — 不同请求长度差异极大,固定 batch size 严重浪费 GPU

✅ 用 token budget 做 batching,按 token 数而非请求数打包

❌ KV Cache 不做内存管理 — 长上下文会吃光所有显存,新请求无法调度

✅ 用 PagedAttention,把 KV cache 切成固定大小的 page 按需分配

❌ 冷启动未预热 — 第一个请求触发模型加载,延迟高达分钟级

✅ 预热策略 + 模型预加载到 GPU,保持 warm pool

❌ 忽略 prefill 和 decode 阶段差异 — Prefill(处理 prompt)是计算密集型,Decode(生成 token)是内存带宽密集型,应该分开优化

✅ Prefill-decode disaggregation:不同节点专门处理两个阶段


容量估算 / Capacity Estimation

假设 10K QPS,平均 prompt 500 tokens,输出 200 tokens:

  • 每请求 FLOPs ≈ 2 × params × tokens (llama-70B = ~140B × 700 = 98T FLOPs)
  • 一块 A100 (312 TFLOPS FP16) 可处理 ~3 req/s
  • 10K QPS 需要 ~3,300 A100 → 实际用 continuous batching 后大概 ~600-800 卡

🧒 ELI5

想象一家餐厅(GPU)同时做很多道菜(请求)。普通餐厅一次只做一桌的菜,做完再做下一桌。聪明的餐厅会把多桌的菜同时放进烤箱,一锅出。LLM 推理系统也一样,KV Cache 就像厨师的记忆,记住每道菜做到哪一步了。


📚 References

  • vLLM (PagedAttention paper): https://arxiv.org/abs/2309.06180
  • Continuous Batching Explained: https://www.anyscale.com/blog/continuous-batching-llm-inference
  • TensorRT-LLM Docs: https://nvidia.github.io/TensorRT-LLM/
  • Prefill-Decode Disaggregation: https://arxiv.org/abs/2401.09670

💻 算法 / Algorithms — Day 60

Problem: #297 Serialize and Deserialize Binary Tree 🔴 Hard

Pattern: Trees (15/15) — Final problem in the block!

Date: 2026-06-22

🔗 LeetCode: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/

📹 NeetCode: https://neetcode.io/problems/serialize-and-deserialize-binary-tree


🧩 树遍历模式 (15/15) — 收官之作!

🧩 Trees Pattern (15/15) — building on the DFS template from Day 56

从第 1 题(翻转二叉树)到第 15 题(序列化/反序列化),我们完整走过了树的所有经典问题。今天是这个 block 的终点站。

今天是变体 / Today's variation:

不只是"遍历"树,而是需要把树完整地编码成字符串,再从字符串精确还原。核心挑战:如何区分 null 节点和有值节点?


真实场景 / Real-World Analogy

你在做分布式系统,需要把内存中的决策树发送给另一台机器执行。不能传递指针,只能传字符串或 JSON。序列化 = 把树"打印"成字符串;反序列化 = 从字符串"重建"树。

Redis 存树形结构、网络传输对象、数据库存嵌套文档 — 本质上都是这个问题。


解题思路 / Approach

关键洞察: 用 BFS(层序遍历)序列化,null 节点用特殊标记(如 "N")占位。反序列化时按队列逐层重建。

也可以用 preorder DFS(前序遍历),两种方法都行,但 BFS 更直观。

from collections import deque

class Codec:
    def serialize(self, root):
        # BFS serialization
        if not root:
            return ""
        
        result = []
        queue = deque([root])
        
        while queue:
            node = queue.popleft()
            
            if node is None:
                result.append("N")
            else:
                result.append(str(node.val))
                queue.append(node.left)   # Push left (even if None)
                queue.append(node.right)  # Push right (even if None)
        
        # Trim trailing 'N's for cleaner output (like LeetCode format)
        while result and result[-1] == "N":
            result.pop()
        return ",".join(result)
    
    def deserialize(self, data):
        # BFS deserialization
        if not data:
            return None
        
        vals = data.split(",")
        root = TreeNode(int(vals[0]))
        queue = deque([root])
        i = 1  # Index into vals
        
        while queue and i < len(vals):
            node = queue.popleft()
            
            # Left child
            if vals[i] != "N":
                node.left = TreeNode(int(vals[i]))
                queue.append(node.left)
            i += 1
            
            # Right child
            if i < len(vals) and vals[i] != "N":
                node.right = TreeNode(int(vals[i]))
                queue.append(node.right)
            i += 1
        
        return root

执行轨迹 / Trace

Tree: 1 / \ 2 3 / \ 4 5 serialize() BFS 遍历: queue: [1] → append "1", push 2, 3 queue: [2, 3] → append "2", push null, null queue: [3, N, N] → append "3", push 4, 5 queue: [N,N,4,5] → N, N, "4", "5"... result: "1,2,3,N,N,4,5" deserialize() 重建: root = TreeNode(1), queue = [1] pop 1: left=TreeNode(2), right=TreeNode(3) pop 2: left=N(skip), right=N(skip) pop 3: left=TreeNode(4), right=TreeNode(5) ✅ 完整还原

时间复杂度 / Complexity:

  • Time: O(n) — 每个节点访问一次
  • Space: O(n) — 队列最大存一层节点,最坏 O(n/2)

与模版的映射 / Mapping to Template

标准 DFS 模板:

def dfs(node):
    if not node: return BASE_CASE
    left = dfs(node.left)
    right = dfs(node.right)
    return COMBINE(node.val, left, right)

本题用 BFS 而非 DFS,但核心思想相同:按某种顺序遍历每个节点,对 null 进行显式处理,保留结构信息。

DFS 版本(preorder)也完全可行:

# serialize with preorder DFS
def serialize_dfs(root):
    if not root: return "N,"
    return str(root.val) + "," + serialize_dfs(root.left) + serialize_dfs(root.right)

举一反三 / Pattern Connections

这是树 block 的第 15 题,回顾整个 block 的核心递推关系:

  • #226 Invert → dfs: swap left/right, return node
  • #104 Max Depth → dfs: return 1 + max(left, right)
  • #543 Diameter → dfs: 全局维护 max,return 1 + max(left, right)
  • #110 Balanced → dfs: return height or -1 if unbalanced
  • #124 Max Path Sum (昨天) → dfs: 全局维护 max,return node.val + max(0, left, right)
  • #297 Serialize (今天) → BFS 完整遍历,null 也要标记

规律: 树问题的难度提升,通常是"返回值语义"变复杂,或者需要额外的全局状态。


🧒 ELI5

想象你要把一棵家谱树打电话告诉朋友。你按层从上到下说:「1号,左边是2号,右边是3号,2号没孩子,3号左边4号右边5号。」朋友记下来,就能画出一模一样的树。序列化就是你说的那串话,反序列化就是朋友画树的过程。


📚 References

  • LeetCode 297: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
  • NeetCode Solution: https://neetcode.io/problems/serialize-and-deserialize-binary-tree
  • BFS Tree Traversal: https://en.wikipedia.org/wiki/Breadth-first_search

🗣️ 软技能 / Soft Skills — Day 59

Topic: Crisis Management — On-Call for a System You Didn't Build

Question: How do you handle being on-call for a system you didn't build?

Date: 2026-06-22 | Level: Senior/Staff


为什么这很重要 / Why This Matters

这是面试里经典的高分题。每个工程师都会被要求 on-call 一个不熟悉的系统。面试官想看的是:

  • 你在不确定环境下的系统思维
  • 你是否会主动建立 context,而不是被动等着出事
  • 你怎么在压力下保持冷静

This is a classic high-signal interview question. Every engineer gets paged for systems they don't own. The interviewer wants to see your systematic thinking under uncertainty, proactive behavior, and composure under pressure.


STAR 分解 / STAR Breakdown

Situation(背景):

"我接手了另一个团队的支付处理服务的 on-call。那个服务是他们三年前写的,文档很少,原作者已经离职了。"

Task(任务):

"我需要在第一次 on-call 前确保自己能处理任何 P0 事故,同时不能打扰原团队的工作。"

Action(行动):

  1. 主动 context 建立 — 接手前两周,每天花 30 分钟读代码、traces、历史 alert。重点看过去 6 个月的 incident tickets,找出 top 5 告警类型。
  2. 制作 runbook — 把每种告警写成 runbook:症状、常见原因、第一步排查命令、升级标准。没有 runbook 的告警我不接受接手。
  3. 预演 — 找原团队 senior 工程师做一次 shadowing,他们 walk through 一个 P1 场景,我主导排查,他们纠错。
  4. 建立 escalation 路径 — 明确什么情况应该立刻叫醒谁,而不是自己扛。

Result(结果):

"第一个月接了 3 个告警,2 个独立解决,1 个在 15 分钟内升级。MTTR 比原团队历史平均低了 20%,因为 runbook 比他们之前的文档更新更清晰。"


❌ Bad vs ✅ Good

❌ 差答案:

"我会边学边做,出了问题再去找人问。"

— 没有准备,等到出事才行动,让人担心你能否独立应对。

✅ 好答案:

"我会在 on-call 开始前主动建立 context,写 runbook,做 shadowing,并明确升级路径。出事了按流程走,不超出我能力范围就独立处理,超出就快速升级。"

❌ 陷阱回答:

"我相信自己能学得很快。" — 这是关于过程和系统性思维的问题,不是能力问题。


Senior/Staff 加分点 / Senior/Staff Tips

Staff level 思维 — 不只是个人 on-call:

  1. 把 runbook 标准化 — 将自己做的 runbook 模板推广到整个 org,减少 knowledge silos
  2. 做 alert 质量审查 — 接手后发现 30% 的 alert 是 noisy,提议做 alert fatigue review,降低 false positive 率
  3. 推动 ownership 模型改进 — 提出"服务转移 checklist",防止下次又有人接手残缺系统

关键词 / Key Phrases:

  • "Proactive context building before the first page"
  • "Alert-to-runbook mapping"
  • "Clear escalation criteria — I know exactly when to call someone"
  • "Service handoff checklist"

关键要点 / Key Takeaways

  1. 接手前主动建立 context — 不要等到 3 AM 才去读代码
  2. Runbook 是硬性要求 — 没有 runbook 的服务不应该接
  3. 知道何时升级 — 快速升级不是失败,犹豫不决才是
  4. 把经验制度化 — 把你学到的转化为团队资产

🧒 ELI5

想象你要帮同学照顾他的宠物狗,但你从没见过这只狗。好的做法是:事先问清楚狗的习惯、医疗记录、遇到紧急情况打谁的电话。而不是等狗生病了再说"我不知道怎么办"。On-call 就是这只狗。


📚 References

  • Google SRE Book — Being On-Call: https://sre.google/sre-book/being-on-call/
  • PagerDuty Runbook Guide: https://www.pagerduty.com/resources/learn/what-is-a-runbook/
  • Increment — On-Call: https://increment.com/on-call/

🤖 AI 新闻 / AI News — Day 73

Mode: NEWS

Date: 2026-06-22

🔍 Sources: VentureBeat (venturebeat.com/feed), The Verge (theverge.com/ai-artificial-intelligence), Reuters via The Verge

📰 本周 AI 大事 / This Week in AI


🔴 Story 1: AI 框架大规模安全漏洞爆发 — LangGraph、Langflow、LangChain 全中招

AI Agent Framework Security Crisis: LangGraph, Langflow & LangChain All Vulnerable

据 VentureBeat 报道,目前三大最广泛使用的 AI agent 框架同时出现严重安全漏洞,其中 Langflow 已有约 7,000 台服务器遭到实际攻击。

As reported by VentureBeat, the three most widely deployed AI agent frameworks are all affected by serious security vulnerabilities. Langflow reportedly has around 7,000 exposed servers under active attack.

漏洞摘要 / Vulnerability Summary:

框架CVE(据报道)危险级别类型状态
LangflowCVE-2026-5027(据报道 CVSS ~8.8)高路径遍历 → RCE🔴 在野攻击
LangGraphCVE-2025-67644 等(据报道)中高SQL注入 → RCEPoC 公开
LangChain-coreCVE-2026-34070 等(据报道)高路径遍历 → 密钥泄露已修复

关键点 / Key Takeaways for Engineers:

  • Langflow 默认配置开启了 auto-login,单次未认证 HTTP 请求即可 RCE
  • 这些框架持有你的 OpenAI 密钥、数据库凭证、CRM token — 攻破一个等于暴露全部
  • 漏洞本质是老问题(SQL注入、路径遍历、不安全反序列化),不是 AI 特有风险

如果你在用这些框架 / If you use these:

# 检查版本 / Check your versions
pip show langflow langgraph langchain-core

# 修复版本 / Fix versions
# langflow → 1.9.0+
# langgraph → 1.0.10+, langgraph-checkpoint-sqlite → 3.0.1+
# langchain-core → 1.2.22+ or 0.3.86+

📎 来源 / Source: https://venturebeat.com/security/7000-langflow-servers-under-attack-langgraph-langchain-same-holes


🟡 Story 2: AI Agent 自我进化 — Self-Harness 框架让 Agent 重写自己的运行规则,性能提升最高 60%

Self-Harness: AI Agents That Rewrite Their Own Rules, Up to 60% Performance Boost

上海人工智能实验室研究人员发布了 Self-Harness 框架。核心思想:让 AI agent 分析自身执行轨迹,自动修改 system prompt、工具调用策略、错误恢复流程等,不依赖人工调试或更强的外部模型。

Researchers at Shanghai AI Lab introduced Self-Harness — a framework where AI agents systematically improve their own "harnesses" (system prompts, tools, memory, orchestration logic) by analyzing their own execution traces, without human engineers or stronger external models.

三阶段循环 / Three-Stage Loop:

  1. Weakness Detection — 分析失败 traces,识别系统性错误
  2. Edit Proposal — 生成针对性的 harness 修改方案
  3. Validation — 在 hold-out 任务上验证改动有效性

为什么重要 / Why It Matters:

  • Agent 的性能不只取决于底层模型,还取决于它的 harness(就像 Claude Code 和 Codex 用同一个模型但行为很不同)
  • 手动调 harness 依赖直觉和 ad-hoc 调试,Self-Harness 引入了实证反馈环
  • 意义:每个企业都可以用同一个基础模型,通过自进化的 harness 做出差异化

论文: https://arxiv.org/abs/2606.09498

📎 来源 / Source: https://venturebeat.com/orchestration/researchers-introduce-self-harness-a-framework-that-lets-ai-agents-rewrite-their-own-rules-boosting-performance-up-to-60


🟢 Story 3: 挪威禁止小学生使用 AI,但要求高中生学会用 AI

Norway Bans AI Use for Elementary Students, Mandates It for High Schoolers

据 Reuters 报道,挪威将从 2026 年 8 月起实施分级 AI 使用限制:

  • 一至七年级(6-13岁):原则上禁止使用 AI
  • 初中(14-16岁):在教师监督下谨慎使用
  • 高中(17-19岁):应学会适当使用 AI,为未来工作和学习做准备

As reported by Reuters via The Verge, Norway will implement tiered AI restrictions in schools from August 2026.

背后的争论 / The Debate:

支持者认为,在认知能力发展阶段过早依赖 AI 会削弱批判性思维。反对者认为,禁止只会让学生在竞争中落后。挪威的分级方案试图走中间路线:按年龄差异化对待。

为什么工程师应该关注 / Why Engineers Should Care:

AI 在教育中的监管实验将影响未来 10 年的工程师来源。今天的政策决定明天的技术工作者如何思考和使用 AI。

📎 来源 / Source: https://www.theverge.com/ai-artificial-intelligence (Reuters via The Verge, 2026-06-19)


🧒 ELI5

本周 AI 新闻就像这样:第一个故事是"你的厨房刀把手有毒"(框架安全漏洞);第二个故事是"厨师学会了自己磨刀"(AI 自我改进);第三个故事是"政府规定多大年纪才能用厨师刀"(AI 教育监管)。


📚 References

  • VentureBeat AI Security: https://venturebeat.com/security/
  • Self-Harness Paper: https://arxiv.org/abs/2606.09498
  • Norway AI School Policy (Reuters/Verge): https://www.reuters.com/technology/norway-imposes-near-ban-ai-elementary-school-2026-06-19/