← 2026-06-08 📂 All Days 2026-06-10 →

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

Topic: Design a Live Streaming System (Twitch)

Date: 2026-06-09 | Phase: Expert


🏗️ 系统设计 / System Design

设计直播系统 / Design a Live Streaming System (Twitch)

想象你在设计 Twitch...

每天有数百万主播同时开播,每位主播的视频流需要被数千甚至数十万观众实时观看。你需要处理极低延迟、海量并发、全球分发,还要支持聊天、订阅、打赏。这是一个真正复杂的实时系统。

Imagine you're designing Twitch...

Millions of streamers go live daily. Each stream needs to reach thousands to hundreds of thousands of viewers in real time. You must handle ultra-low latency, massive concurrency, global distribution, plus chat, subscriptions, and donations.


🏛️ 架构图 / Architecture

┌─────────────────────────────────┐ │ Streamer Client │ │ OBS / Browser / Mobile App │ └──────────────┬──────────────────┘ │ RTMP (push) ▼ ┌─────────────────────────────────┐ │ Ingest Servers (Edge PoPs) │ │ - Receive RTMP stream │ │ - Authenticate streamer │ └──────────────┬──────────────────┘ │ Raw video segments ▼ ┌─────────────────────────────────┐ │ Transcoding Cluster │ │ - 1080p / 720p / 480p / 360p │ │ - HLS / DASH segmentation │ │ - ~2-5 sec segments │ └──────────────┬──────────────────┘ │ Segmented chunks ▼ ┌─────────────────────────────────────────────────────┐ │ Origin Storage / CDN │ │ S3 / GCS ──────────► CDN Edge Nodes (global) │ │ .m3u8 manifests Akamai / CloudFront / Fastly │ └─────────────────────────────────────────────────────┘ │ HLS pull ▼ ┌─────────────────────────────────┐ │ Viewer Clients │ │ - Pull segments via CDN │ │ - ABR (Adaptive Bitrate) │ └─────────────────────────────────┘ ┌─────────────────────────────────────────────────────┐ │ Chat / Realtime Layer │ │ WebSocket Servers → Kafka → Chat Storage │ │ PubSub (Redis) for fan-out per channel │ └─────────────────────────────────────────────────────┘

⚡ 核心流程 / Core Flow

推流 (Streaming In):

  1. 主播用 OBS 通过 RTMP 推流到最近的 Ingest 节点
  2. Ingest 节点验证 stream key,转发到 Transcoding 集群
  3. Transcoder 生成多码率 HLS 分片(每段约 2-6 秒)
  4. 分片上传到 Origin Storage,CDN 立即缓存

拉流 (Watching):

  1. 观众请求频道 URL → 获取 .m3u8 playlist
  2. 客户端 ABR 算法根据网络选择码率
  3. 每 2-6 秒拉取最新分片,实现 "实时" 播放

⚖️ 关键权衡 / Key Tradeoffs

决策选项Why
传输协议RTMP(推) + HLS(拉)RTMP 低延迟推流;HLS CDN 友好
延迟 vs 稳定性6s 缓冲 vs 1s LL-HLS传统 HLS 稳定但 6s 延迟;LL-HLS 降到 ~1-2s 但更复杂
转码实时 vs 离线直播必须实时;使用 GPU 集群并行转码
CDN自建 vs 第三方Twitch 体量需自建部分 PoP;早期用 Akamai/Cloudfront
聊天WebSocket vs SSE聊天双向需要 WebSocket;每频道独立 pubsub 防止热点

🔢 容量估算 / Capacity Estimation

假设:
- 100K 并发主播,平均 1000 观众/主播
- 每路推流: ~6 Mbps (1080p)
- 转码输出: 3个码率 × 6 Mbps = ~18 Mbps/主播

推流带宽: 100K × 6 Mbps = 600 Gbps ingest
输出带宽: 100K × 1000 观众 × 3 Mbps avg = 300 Tbps CDN
存储: 100K 主播 × 6 MB/s × 3600s = ~2 PB/hour (VOD)

这就是为什么 Twitch 的 CDN 费用是天文数字。


❌ 常见错误 / Common Mistakes

别踩这个坑:

  1. 忘记 Transcoding 是瓶颈 — 一路 1080p 流需要大量 CPU/GPU。不要设计单机转码,必须水平扩展 + 任务队列。
  1. 忽视 CDN 缓存策略 — HLS 分片是内容可寻址的,可以强缓存。但 .m3u8 manifest 是动态的,缓存时间要短(~1-3秒)否则观众看不到新分片。
  1. 聊天设计的 fan-out 问题 — 1 个频道 10 万人同时发消息,不能 1:1 推送。需要 pubsub + 客户端拉取,或限速 + 采样(Twitch 真的会在高热时丢弃聊天消息)。
  1. 低估 Low-Latency 复杂性 — LL-HLS 需要 HTTP/2 push 和 chunked transfer encoding,实现复杂,慎重选择。

📚 References


🧒 ELI5

直播就像一个超级快的外卖系统:厨师(主播)做好菜后,配送员(CDN)把菜分发到全国各地的分拣站,你去最近的站取菜。厨师一直在做新菜,你每隔几秒就去取一次,所以看起来是"实时"的。

Live streaming is like a super-fast food delivery: the chef (streamer) keeps cooking dishes, delivery hubs (CDN) store copies near you, and you pick up the latest dish every few seconds. It feels "live" because the chef never stops cooking and you never stop picking up.

💻 算法 / Algorithms — Day 61

Topic: #572 Subtree of Another Tree (Easy) — Trees Pattern

Date: 2026-06-09 | Phase: Expert


💻 算法 / Algorithms

🧩 树遍历模式 (6/15) — building on the template from Day 56

今天是树遍历模式第 6 题。前几题(Invert, Max Depth, Diameter, Balanced, Same Tree)都是在练习 DFS 递归的不同"返回值语义"。今天的题把 Same Tree 作为子程序来用 — 这是模式复用的典型例子。

This is problem 6/15 in the Trees block. Previous problems trained DFS with different return semantics. Today we reuse Same Tree as a subroutine — a classic example of pattern composition.


🔗 LeetCode #572 🟢 Easy

📹 NeetCode Video


🌍 现实类比 / Real-World Analogy

你在 git 历史中搜索一个特定的 commit subtree 结构。git log --all 遍历每个 commit 节点,然后检查从那个节点开始的子树是否和目标结构完全匹配。

You're searching git history for a specific commit subtree structure. You walk every commit, then check if the subtree rooted there matches your target exactly.


📋 题目 / Problem

给定两棵二叉树 root 和 subRoot。 判断 subRoot 是否是 root 的某个子树(结构和值都相同)。 Given two binary trees root and subRoot. Return true if there is a subtree of root with the same structure and node values as subRoot, false otherwise. Example: root = [3,4,5,1,2] subRoot = [4,1,2] 3 4 / \ / \ 4 5 1 2 / \ 1 2 → true (subtree rooted at 4 matches)

🗺️ 映射到模板 / Mapping to Template

# 树遍历模板:
# def dfs(node):
#     if not node: return BASE_CASE
#     left = dfs(node.left)
#     right = dfs(node.right)
#     return COMBINE(node.val, left, right)

# 今天的题需要两层 DFS:
# 1. 外层 DFS: 遍历 root 的每个节点
# 2. 内层 DFS (isSameTree): 从某节点检查是否完全匹配 subRoot

与 Day 60 (Same Tree) 的区别:

  • Same Tree: 检查两棵树从根开始是否完全相同 → 单层 DFS
  • Subtree: 检查 root 的 任意节点 开始是否匹配 → 双层 DFS

🐍 Python 解法 / Solution

from typing import Optional

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        # BASE CASE: subRoot is None → empty tree is always a subtree
        if not subRoot:
            return True
        # If root is exhausted but subRoot isn't, no match
        if not root:
            return False
        
        # Check if current root matches subRoot exactly
        if self.isSameTree(root, subRoot):
            return True
        
        # Otherwise, try left or right subtree (DFS traverse root)
        return (self.isSubtree(root.left, subRoot) or 
                self.isSubtree(root.right, subRoot))
    
    def isSameTree(self, s: Optional[TreeNode], t: Optional[TreeNode]) -> bool:
        # Reuse Same Tree logic from Day 60!
        if not s and not t:
            return True
        if not s or not t:
            return False
        return (s.val == t.val and 
                self.isSameTree(s.left, t.left) and 
                self.isSameTree(s.right, t.right))

执行追踪 / Trace:

root = [3,4,5,1,2], subRoot = [4,1,2] isSubtree(3, 4): isSameTree(3,4)? → 3≠4 → False isSubtree(4, 4): isSameTree(4,4)? 4==4 ✓ isSameTree(1,1)? → True ✓ isSameTree(2,2)? → True ✓ → True! ✓ → return True

⏱️ 复杂度 / Complexity

Time: O(m × n) — m = root nodes, n = subRoot nodes — 每个 root 节点都可能触发一次 isSameTree Space: O(h) — h = height of root (recursion stack) 优化思路 (面试 follow-up): - Serialize trees → string matching → O(m+n) time - Hashing subtrees → O(m+n) time (但实现复杂,Easy 题不需要)

🔁 举一反三 / Pattern Connections

在这个树遍历模式块中:

题目核心操作返回值语义
#226 Invert Tree左右互换返回修改后的节点
#104 Max Depth取最大深度返回整数(深度)
#543 Diameter经过节点的最长路径返回深度,副作用更新全局
#110 Balanced检查高度差返回高度,-1 表示不平衡
#100 Same Tree比较结构+值返回 bool
#572 SubtreeSame Tree 作为子程序返回 bool,双层 DFS

关键洞察: 遇到"检查某属性是否存在于树中某处"→ 外层 DFS 遍历 + 内层 DFS 检查。


📚 References


🧒 ELI5

你想知道你的积木堆里,有没有一个角落和你朋友的积木堆一模一样。你从最顶上开始检查每一块积木,每次都问:从这块积木开始,是不是和朋友的一模一样?(用昨天学的 Same Tree 来问)。只要有一个角落匹配,就返回 true。

You want to know if any corner of your Lego pile looks exactly like your friend's pile. You check each brick one by one, and for each brick, you ask: "Does everything starting from here match my friend's pile?" (using the Same Tree check from yesterday). If any corner matches — you win!

🗣️ 软技能 / Soft Skills — Day 61

Topic: Handling Teammates Missing Deadlines

**Date:** 2026-06-09 | **Phase:** Expert | **Category:** Interpersonal

🗣️ 软技能 / Soft Skills

你的队友总是 miss deadline,你怎么处理?

How do you handle a teammate who consistently misses deadlines?


🎯 为什么这个问题很重要 / Why This Matters

这道题考察的不是你有多严厉,而是你有多成熟。面试官想看:

  • 你能否区分"问题"和"人"
  • 你是否先寻找根因,而不是直接上升
  • 你能否在团队关系和项目健康之间找平衡

This tests maturity, not toughness. Interviewers want to see:

  • Can you separate behavior from person?
  • Do you find root causes before escalating?
  • Can you balance team relationships with project health?

📖 STAR 框架 / STAR Breakdown

Situation: 后端同事连续两个 sprint miss 了 API 交付节点,导致前端被卡住,QA 窗口压缩。

Task: 作为 tech lead,我需要解决这个依赖问题,同时不破坏团队关系。

Action:

  1. 先私聊,不当众 — 找一个 1:1 时间,以关心而非质问的姿态开场:"我注意到你最近几个 sprint 的进度有些紧,是遇到什么挑战了吗?"
  2. 倾听根因 — 发现他在处理一个没有文档的遗留模块,估时严重低估。
  3. 拆分任务 + 设置中间检查点 — 把大任务拆成每 2-3 天一个可见里程碑,每天 standup 时做一个简短更新。
  4. 提供帮助,不是监控 — 主动问"你需要我帮你 review 这部分设计吗?"让他感到被支持而非被盯着。
  5. 调整估时流程 — 引入"乘以 1.5 法则"和 spike ticket for unknowns。

Result: 下一个 sprint 的交付节点全部按时完成。遗留模块也有了基础文档。这位同事后来主动在 retro 上分享了估时技巧。


❌ vs ✅ 对比 / Bad vs Good

❌ Bad answers:

  • "我会告诉他这是不可接受的" → 对抗性,没有根因分析
  • "我会帮他做完" → 解决了眼前问题,但没有解决系统性问题
  • "我会立即上报给 manager" → 过早上升,没有先尝试解决
  • "我会在 standup 上追问进度" → 公开施压,伤害关系

✅ Good answers:

  • 先私下了解情况,区分意愿问题 vs 能力问题 vs 流程问题
  • 提供具体支持(设计讨论、拆任务、文档)
  • 设置可见检查点,而不是等到 deadline 才发现问题
  • 如果问题持续,再考虑和 manager 一起讨论

👑 Senior/Staff 级别的升华 / Senior/Staff Tips

在 Senior/Staff 层级,面试官期待你能看到系统性问题:

  1. 单个人 miss deadline ≠ 只是个人问题 — 问自己:估时流程是否有问题?依赖关系是否提前暴露?是否有 buffer?
  1. 建立团队规范 — 引入 "definition of ready"(任务细化到可估时才进入 sprint),减少未来的估时风险。
  1. 心理安全 — 如果队友不敢在 standup 说"我被卡住了",这是团队文化问题,不只是个人问题。作为 senior,你的职责是创造能说"我需要帮助"的环境。
  1. 区分 pattern vs one-off — 一次是意外,两次要关注,三次要解决根因。题目说 "consistently" 所以要系统性解决。

💡 Key Takeaways

  1. 私聊优先,不要公开施压 — Assume positive intent first
  2. 根因 > 症状 — Miss deadline 背后往往是估时、依赖、或沟通问题
  3. 支持 > 监控 — 提供帮助比增加压力更有效
  4. 中间检查点 — 防止问题在 deadline 才暴露
  5. 系统性改进 — 解决这次问题的同时,改善流程避免下次发生

📚 References


🧒 ELI5

如果你的同学总是没做完作业,聪明的做法是先问他"是不是哪里不懂?"而不是马上告诉老师。搞清楚原因,然后一起想办法。如果每次都帮他做作业,他永远学不会;如果马上告诉老师,他会很生气。最好的办法是帮他学会自己完成。

If your classmate keeps forgetting homework, the smart move is to ask "do you need help understanding something?" instead of telling the teacher right away. Find the reason, then fix it together. Doing it for them doesn't help; escalating too fast hurts trust. The goal is helping them succeed on their own.

🤖 AI — Day 61

Topic: AI News Roundup

Date: 2026-06-09 | Phase: Expert


🤖 AI 新闻速递 / AI News Roundup

本周最重要的 AI 动态 / This Week's Top AI Stories


📰 Story 1: Anthropic 披露 80% 代码由 Claude 编写

Anthropic Reveals 80% of Production Code Written by Claude

Anthropic 披露,2026 年 5 月合并进生产代码库的代码中,据报道超过 80% 是由 Claude 本身编写的。这一披露被定性为对 AI 递归自我改进的警示——一个 AI 系统现在大量参与改进其继任者的开发工作。与此同时,Anthropic 据报道已申请 IPO,估值据报道接近 1 万亿美元。

Anthropic disclosed that reportedly over 80% of code merged into its production codebase in May 2026 was authored by Claude itself. The disclosure was framed as a caution about recursive self-improvement — an AI system now substantially participates in building its own successors. Anthropic has also reportedly filed for a landmark IPO, with valuations reportedly approaching $1 trillion.

🔗 Source: AI Weekly for Leaders — June 8, 2026

工程师视角: 这意味着 AI-assisted coding 已经从"好用的工具"进化到"主要贡献者"。如果你还没在工作流里深度整合 AI coding assistant,现在已经是竞争劣势了。

Engineer's take: AI-assisted coding has evolved from "useful tool" to "primary contributor." If you haven't deeply integrated AI coding assistants into your workflow, it's already a competitive disadvantage.


📰 Story 2: Snap 裁员 1000 人,AI 生成 65%+ 代码

Snap Lays Off 1,000, Citing AI-Driven Productivity

Snap 宣布裁员约 1,000 人并关闭 300+ 个职位,理由是"AI 的快速进步使更小的团队能实现相同的产出"。据报道,AI 现在生成了 Snap 超过 65% 的新代码。

Snap announced layoffs of approximately 1,000 employees and closure of 300+ open roles, citing "rapid advancements in AI allowing smaller teams to achieve the same output." AI reportedly now generates over 65% of Snap's new code.

🔗 Source: Axios — AI News June 8, 2026

关键信号: 这不只是 Snap 的问题。行业趋势很清楚:AI 正在压缩团队规模,但同时提高了留下的人的产出预期。

Key signal: This isn't just Snap. The industry trend is clear: AI is compressing team sizes while raising output expectations for those who remain.


📰 Story 3: Nvidia 发布 Cosmos 3 — 物理 AI 基础模型

Nvidia Unveils Cosmos 3 — Foundation Model for Physical AI

Nvidia 发布了 Cosmos 3,一个为物理 AI 设计的基础模型,用于训练能与物理世界交互的 AI 系统——例如控制工厂机器人。同时发布的还有 RTX Spark 处理器,为本地 AI 工作负载提供算力,已被微软 Surface Laptop Ultra 采用。

Nvidia unveiled Cosmos 3, a foundation model for physical AI designed to train systems that interact with the physical world — like controlling factory robots. Also announced: the RTX Spark processor for local AI workloads, already adopted by Microsoft's Surface Laptop Ultra.

🔗 Source: Axios — AI News June 8, 2026

为什么重要: 物理 AI(具身智能)正在从实验室走向工厂。Cosmos 3 是这个方向的基础设施层——类似于 CV 领域的 ImageNet 时刻。

Why it matters: Physical AI (embodied intelligence) is moving from lab to factory floor. Cosmos 3 is the infrastructure layer for this shift — similar to the ImageNet moment for computer vision.


💡 本周大趋势 / Big Picture

2024: "AI 会不会抢走我的工作?" (焦虑期) 2025: "AI 是好用的辅助工具" (工具期) 2026: "AI 正在写大部分代码,团队在缩小" (现实期) The transition from tool → coworker → primary contributor is happening faster than most engineers expected.

给工程师的实用建议 / Practical Advice:

  • 学会审查和引导 AI 生成的代码,不只是接受它
  • 你的差异化价值在于:系统设计判断力、业务理解、代码审查能力
  • "AI fluency" 已经是必备技能,不是加分项

📚 References


🧒 ELI5

这周 AI 世界发生了三件大事:1) Anthropic 的 AI 自己写了大部分自己公司的代码(有点像机器人在建造更好的机器人);2) Snap 因为 AI 太能干而裁了很多员工;3) Nvidia 造了一个让机器人能理解物理世界的 AI。总结:AI 不只会聊天了,它在真实工作中已经超过了很多人。

Three big things happened in AI this week: 1) Anthropic's AI wrote most of its own company's code (like robots building better robots); 2) Snap laid off employees because AI got too productive; 3) Nvidia built an AI to help robots understand the physical world. Summary: AI isn't just for chatting — it's outperforming humans in real work.