← 2026-05-24 📂 All Days 2026-05-27 →

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

Topic: Design a Distributed File System (HDFS/GFS)

Date: 2026-05-26 | Phase: Expert


🏗️ 系统设计 / System Design — 分布式文件系统 (HDFS/GFS)

⏱️ 预计阅读时间 / Estimated reading time: 3 min


场景导入 / Scenario

想象你在 Google 负责存储互联网上所有网页的爬虫数据——每天新增 PB 级数据,数千台机器并发写入,任何单台机器随时可能宕机。你怎么设计这个系统?

Imagine you're at Google storing petabytes of web crawl data — terabytes added daily, thousands of machines writing concurrently, any single machine can fail at any time. How do you design this?

这就是 GFS(Google File System)要解决的问题,也是 Hadoop HDFS 的原型。


架构图 / Architecture

Clients │ ├──► Master Node (NameNode) │ - Namespace tree (file → chunk IDs) │ - Chunk location map (in-memory!) │ - No data I/O — metadata only │ └──► Chunk Servers (DataNodes) ×N - Store 64MB chunks - 3x replication by default - Heartbeat to master Write Flow: Client ──► Master: "Where do I write /foo/bar?" Master ──► Client: "Primary=CS1, replicas=CS2,CS3" Client ──► CS1 (pipeline): CS1→CS2→CS3 (chain replication) CS1 ──► Master: "Chunk committed" Read Flow: Client ──► Master: "Where is chunk 42?" Master ──► Client: "CS2, CS5, CS7" (closest replica) Client ──────────► CS2 directly (bypasses master!)

关键设计决策 / Key Design Decisions

1. 大文件优先(64MB chunk size)

  • 减少 master 元数据量(1PB 数据 ≈ 只需几十万 chunk 记录)
  • 减少网络往返(一次 metadata 查询读取更多数据)
  • ❗ 代价:小文件效率差(1KB 文件占用 64MB chunk)

2. Master 只存元数据,不存数据

  • 所有数据直接在 client ↔ chunkserver 之间流动
  • Master 成为控制平面,不是数据瓶颈
  • Master 挂了 → 读写停止,但数据不丢失

3. 三副本 + 机架感知(Rack-Aware Replication)

Rack A: CS1 (primary), CS2 (replica 1)
Rack B: CS3 (replica 2)
  • 同机架故障(断电、网络交换机)时仍有 Rack B 副本

4. 追加写优化(Append-Only Workload)

  • GFS 的设计假设:文件一旦写入很少修改
  • 支持 record append(原子追加),不支持随机写
  • 适合 MapReduce、日志处理、大数据批处理

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

选择原因
中心化 Master简化一致性,避免分布式锁复杂度
大 chunk sizeGoogle 的 workload 就是大文件顺序读
Append-only简化并发控制,牺牲通用性换可靠性
心跳检测故障Chunkserver 每 N 秒向 master 心跳,超时自动踢出

别踩这个坑 / Common Mistakes

❌ "HDFS 适合小文件" — 错!HDFS 对小文件极不友好。1 亿个小文件 = 1 亿条 NameNode 内存记录,直接打爆 NameNode。

✅ 小文件场景改用 HBase、S3(object storage)或先合并再存 HDFS。

❌ "Master 单点 → 系统不可用" — 现代 HDFS 有 HA NameNode(active/standby + shared journal),不再是单点。

❌ 面试忘说 consistency model — GFS 是 relaxed consistency(宽松一致性)。并发追加可能有重复/填充字节,应用层需处理。


📚 References

🧒 ELI5

想象一个超级大图书馆。图书馆有一个"目录员"(Master/NameNode),他只记"哪本书放在哪个书架",但不实际搬书。书架工人(ChunkServer)负责存放真正的书页。每本书被复印成3份放在不同书架,这样就算一个书架着火了,书还在。

💻 算法 / Algorithms — Day 43

Topic: #146 LRU Cache (Medium) — Linked List Pattern

Date: 2026-05-26 | Phase: Expert


💻 算法 / Algorithms — #146 LRU Cache (Medium)

⏱️ 预计阅读时间 / Estimated reading time: 4 min


🧩 链表技巧模式 (9/11) — 延续 Day 41 开始的模式

🧩 Linked List Pattern (9/11) — building on the template from Day 41

前 8 题我们用快慢指针处理环检测、找中点、合并等问题。今天的 LRU Cache 是这个 pattern 的"Boss 关"——它需要把链表 + 哈希表结合起来,实现 O(1) 的所有操作。

The first 8 problems used fast-slow pointers for cycle detection, finding midpoints, and merging. LRU Cache is the "boss fight" — it combines linked list + hash map to achieve O(1) for all operations.


🔗 Links


现实类比 / Real-World Analogy

你的浏览器最多显示 10 个最近访问的标签历史。每次访问一个网站,如果它已在列表中就把它移到最前;如果列表满了,删掉最久没访问的那个。

Your browser's "recent tabs" keeps the last N sites. When you visit a site already in the list, bump it to the front. When the list is full, evict the least recently used one.


问题分析 / Problem

LRUCache(capacity):
- get(key): return value if exists, else -1. Mark key as recently used.
- put(key, value): insert/update. If capacity exceeded, evict LRU key.

All operations must be O(1).

关键洞察:为什么要用双向链表 + 哈希表?

  • 哈希表:O(1) 查找 key → node
  • 双向链表:O(1) 移动节点到头部、删除尾节点
  • 单向链表不行 → 删除节点需要找前驱,O(n)

与模式模板的关系 / Mapping to Pattern

快慢指针模板 → LRU 变体: 快慢指针用于遍历/找位置 LRU 用双向链表 + dummy head/tail 做 O(1) 插删 核心技巧相同:用额外的指针结构突破链表的 O(n) 限制

Python Solution (带 trace)

class LRUCache:
    def __init__(self, capacity: int):
        self.cap = capacity
        self.cache = {}  # key -> Node

        # Dummy head (most recent) & tail (least recent)
        # head <-> ... <-> tail
        self.head = Node(0, 0)
        self.tail = Node(0, 0)
        self.head.next = self.tail
        self.tail.prev = self.head

    def _remove(self, node):
        """Remove node from its current position."""
        node.prev.next = node.next
        node.next.prev = node.prev

    def _insert_front(self, node):
        """Insert node right after head (most recent)."""
        node.next = self.head.next
        node.prev = self.head
        self.head.next.prev = node
        self.head.next = node

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._insert_front(node)  # mark as recently used
        return node.val

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            self._remove(self.cache[key])
        node = Node(key, value)
        self.cache[key] = node
        self._insert_front(node)

        if len(self.cache) > self.cap:
            # Evict LRU: node right before tail
            lru = self.tail.prev
            self._remove(lru)
            del self.cache[lru.key]  # don't forget to remove from dict!

class Node:
    def __init__(self, key, val):
        self.key, self.val = key, val
        self.prev = self.next = None

# Trace: capacity=2
# put(1,1): head <-> [1,1] <-> tail
# put(2,2): head <-> [2,2] <-> [1,1] <-> tail
# get(1):   head <-> [1,1] <-> [2,2] <-> tail  (1 moved to front)
# put(3,3): capacity exceeded, evict LRU=2
#           head <-> [3,3] <-> [1,1] <-> tail
# get(2) -> -1 (evicted!)

复杂度 / Complexity:

  • Time: O(1) — 所有操作
  • Space: O(capacity)

举一反三 / Pattern Connections

在同一个 Linked List block 中:

  • #141 Linked List Cycle: fast/slow pointer 找环入口
  • #19 Remove Nth From End: fast/slow pointer 找倒数第 N 个
  • #146 LRU Cache: 双向链表 + 哈希表,O(1) 插删

下一步(block 剩余 2 题):

  • #23 Merge K Sorted Lists: 用堆合并,不是纯链表题
  • #25 Reverse Nodes in K-Group: 分组反转,递归/迭代

📚 References

🧒 ELI5

想象你有一个最多放 3 本书的桌子。每次你看一本书,就把它放到桌子最左边(最新)。桌子满了要放新书?把最右边的(最久没看的)扔掉。链表就是这张桌子,哈希表让你能瞬间找到任何书在哪里。

🗣️ 软技能 / Soft Skills — Day 42

Topic: Service Deprecation & Migration

Date: 2026-05-26 | Phase: Expert


🗣️ 软技能 / Soft Skills — 下线服务与迁移

⏱️ 预计阅读时间 / Estimated reading time: 2 min

问题 / Question:

Tell me about a time you had to deprecate or sunset a service. How did you handle the migration?

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

Senior/Staff 工程师不只是构建系统,还需要安全地结束系统的生命周期。服务下线是比上线更难的工程问题:你有未知的依赖方、不愿迁移的用户、以及"删掉就出故障"的恐惧。

Deprecating a service is often harder than building one. Unknown callers, resistant stakeholders, fear of breaking prod — this question tests operational maturity and communication skills, not just technical depth.


STAR 结构 / STAR Breakdown

Situation(情境):

描述为什么需要下线:技术债、安全风险、维护成本、重复功能、云迁移...

"我们有一个 5 年历史的 v1 内部 RPC 服务,没有 SLA、没有监控、没有鉴权。维护它每月消耗 2 人周,且影响了新功能的迭代速度。"

Task(任务):

你的职责范围——是否跨团队、是否有 hard deadline、是否有外部依赖?

"作为 Tech Lead,我负责协调 3 个依赖团队的迁移,目标是 6 个月内完成下线。"

Action(行动)— 这是核心:

  1. 发现阶段:搞清楚谁在用

- 在网关/日志层加 instrumentation,统计调用方

- 发现 2 个团队的 "legacy batch jobs" 每天深夜还在调用

  1. 沟通:不要直接 email 说"我们要关掉你的依赖"

- 设置 deprecation timeline,给足够的缓冲时间(建议 3-6 个月)

- 提供迁移指南和迁移工具,主动帮对方团队迁移

  1. 渐进式关闭:不要一刀切

```

Phase 1: 新流量禁止接入 (freeze new clients)

Phase 2: 已有流量加 deprecation warning header

Phase 3: 限流 + 增加延迟(让依赖方感到"痛苦")

Phase 4: 真正关闭

```

  1. 监控退出流量:

- 在 Grafana 看 request count 趋势,趋近 0 时才真正下线

Result(结果):

"6 个月内,所有依赖完成迁移,关闭前最后一周流量为 0。释放了约 15% 的基础设施成本,v1 的安全漏洞彻底消除。"

❌ 不好的回答 / Bad Answer

"我们直接在 flag day 关了服务,然后收到了很多 oncall 报警。"

告诉面试官你会直接关掉服务而不考虑下游影响——这是 flag。


✅ 好的回答要素 / Good Answer Elements

  • 主动发现未知依赖(Instrumentation)
  • 提前沟通,给充足 runway
  • 渐进式下线,有监控和 rollback plan
  • 定量结果(迁移时间、成本节省、故障数)

Senior/Staff 加分点 / Senior/Staff Tips

  • 政治敏感性:有些团队不愿迁移,因为"这不在我的 OKR 里"。你的解法是把迁移工作帮他们做掉,或者让他们的老板 buy in。
  • 技术策略:先提供一个"兼容层" adapter,让依赖方零修改迁移,再异步推动他们升级。
  • 提到 "strangler fig pattern":面试官会印象深刻。

Key Takeaways

  1. 下线和上线一样需要 planning,甚至更难
  2. 发现未知依赖 > 假设你知道所有依赖
  3. 渐进式关闭降低风险,监控是保障

📚 References

🧒 ELI5

就像老家的老房子要拆迁,你不能直接挖掉地基——得先确认屋里没人,把家具搬走,切断水电,再慢慢拆。服务下线也一样:先找到所有"住户",帮他们搬家,最后才能关门。

🤖 AI — Day 51

Topic: AI News Roundup

Date: 2026-05-26 | Mode: NEWS


🤖 AI 新闻速递 / AI News Roundup

⏱️ 预计阅读时间 / Estimated reading time: 2 min

Source: Stories found via The Verge AI section (theverge.com/ai-artificial-intelligence, fetched 2026-05-26)


📰 Story 1: 白宫申请 90 亿美元购买 AI 芯片用于情报机构

The White House is asking for $9 billion to buy AI chips for spy agencies.

据报道,CIA 和 NSA 缺乏足够的算力来运行最新的 AI 模型,白宫已批准一项申请,拟购置 Nvidia Grace Blackwell 超级芯片并建设相关基础设施,总计据报道约 90 亿美元,但仍需国会批准。

The White House has reportedly approved a request for ~$9 billion to buy cutting-edge chips and build infrastructure for spy agencies. The CIA and NSA reportedly lack the computing capacity to run the latest AI models. Infrastructure would support Nvidia's Grace Blackwell superchip. Congress must still approve the funds.

为什么重要 / Why It Matters:

国家情报机构的 AI 军备竞赛正在变得和民间科技公司一样白热化。算力即国力——这一点在 2026 年已经不是隐喻,而是字面意思。

The AI arms race has reached intelligence agencies. Compute = national power is no longer a metaphor.

📎 Source: The Verge, May 24 2026 (referencing NYT reporting)


📰 Story 2: Anthropic 与五角大楼的冲突:AI 自主战争的边界

Anthropic's fight with the Pentagon highlights risks of autonomous warfare.

Anthropic 据报道与美国国防部在 Claude 用于自主战争决策的边界问题上产生了摩擦,引发了业界对 AI 武器化的讨论。报道指出,虽然这一争议吸引了公众注意,但真正令人担忧的是:真正的自主 AI 军事系统比公众认知的要近得多。

Anthropic reportedly clashed with the Pentagon over the limits of Claude's use in autonomous warfare decisions. The Verge notes that while the public dispute makes headlines, the more alarming story is how close truly autonomous AI military systems actually are — closer than most people realize.

为什么重要 / Why It Matters:

AI 安全的战场已经不只是聊天机器人的对齐问题——它延伸到了字面意义上的"战场"。Anthropic 在商业利益和道德边界之间走钢丝。

AI safety is no longer just about chatbot alignment — it now extends to literal warfare. This is the real test of whether AI labs can hold ethical lines under pressure.

📎 Source: The Verge, May 26 2026


📰 Story 3: Anthropic Project Glasswing 更新:安全工具向用户开放

Anthropic makes Claude Mythos Preview security tools more available.

Anthropic 更新了 Project Glasswing(据报道是其内部红队/安全项目),包括技能工具、Claude 安全测试框架和威胁模型构建器,现在可向"符合资质"的客户开放申请。同时发布了一个开源漏洞披露仪表板。

Anthropic updated Project Glasswing, making security tools — including skills, a Claude harness, and a threat model builder — available to "qualifying" customers upon request. Anthropic also published a dashboard of open-source vulnerabilities discovered by Claude Mythos Preview.

为什么重要 / Why It Matters:

AI 公司开始把"安全能力"本身作为产品输出,而不只是内部自用。这反映了 AI 安全生态系统的逐渐成熟——把模型的攻击性理解能力转化为防御工具。

AI companies are beginning to productize their safety capabilities. This reflects a maturing AI security ecosystem: turning the model's adversarial understanding into defensive tools for others.

📎 Source: Anthropic Project Glasswing Update (via The Verge, May 22 2026)


💡 本周主题 / This Week's Theme

三条新闻共同指向一个趋势:AI 正在快速进入高风险领域——情报、军事、安全。民间实验室(Anthropic、OpenAI)突然需要回答以前只有政府才需要回答的问题:算力谁控制?决策权给不给 AI?红线在哪里?

All three stories point to a trend: AI is rapidly entering high-stakes domains — intelligence, warfare, security. Civilian labs now need to answer questions previously reserved for governments: Who controls the compute? How much autonomy for AI? Where are the red lines?


📚 References

🧒 ELI5

AI 不只是帮你写邮件和做作业了。这周的新闻说:间谍机构要花很多钱买超级电脑跑 AI、军队想用 AI 做战争决策、AI 公司在争论能不能帮他们做这些事。AI 长大了,但世界还没准备好规则。