← 2026-07-26 📂 All Days 2026-07-28 →

系统设计综合 / System Design Synthesis — Day 101

Day 61 (Synthesis Mode) · Expert Phase


🏗️ 系统设计 / System Design — Expert Synthesis

从单点到全局:分布式系统的权衡地图

From Single Points to Global Scale: The Trade-off Map of Distributed Systems


想象你在做技术 Review / Imagine You're Doing a Tech Review

你的团队正在设计一个新的后端服务。Tech Lead 问了这个问题:

"我们用 Kafka 还是 Redis Pub/Sub?要不要加 Consistent Hashing?要不要用 Saga 还是 2PC?"

这些不是孤立的问题——它们背后是一张权衡地图 (Trade-off Map)。

Your team is designing a new backend service. The Tech Lead asks:

"Kafka vs Redis Pub/Sub? Consistent Hashing or not? Saga vs 2PC?"

These aren't isolated questions — they're all part of a trade-off map.


核心权衡矩阵 / Core Trade-off Matrix

TOPIC OPTION A OPTION B WHEN TO PICK A ───────────────────────────────────────────────────────────────────────── 消息队列 Kafka Redis Pub/Sub 持久化/重放/高吞吐 Message Queue (persistent,durable) (ephemeral,fast) vs 低延迟/简单订阅 分布式事务 2PC (Strong) Saga (Eventual) 金融强一致 vs Distributed Txn (blocking, slow) (async, complex) 跨微服务最终一致 缓存策略 Write-Through Write-Behind 读多写少 vs Cache Strategy (sync, safe) (async, faster) 写密集型 一致性哈希 Consistent Hashing Modulo Hashing 节点增减频繁 vs Partitioning (minimal resharding) (simple, mass 固定分片数 resharding) 数据库选型 PostgreSQL (SQL) Cassandra (NoSQL) 复杂查询/事务 vs DB Selection (ACID, joins) (AP, wide-column) 写密集/地理分布 API 通信 REST gRPC 公开 API vs API Protocol (human-readable) (binary, fast) 内部微服务

系统组合:三种典型架构 / Three Archetypical Architectures

#### 1. 读密集型系统 (Read-Heavy) — e.g. Twitter Feed

[Client] → [CDN/Edge Cache] ↓ [API Gateway + Rate Limiter] ↓ [Read Replicas × N] ← hot data [Redis Cache Layer] ↓ [Primary DB] ← writes only

关键洞察 / Key Insight: 90%流量命中缓存,主库只处理写。

Read replicas + CDN absorb load. Primary DB is write-only.

#### 2. 写密集型系统 (Write-Heavy) — e.g. IoT / Metrics

[Devices] → [Kafka / Kinesis] → [Stream Processor] ↓ [Time-Series DB] (InfluxDB) ↓ [Aggregation Layer] ↓ [Dashboard / Alerts]

关键洞察 / Key Insight: 写操作先缓冲,异步落库。背压 (backpressure) 保护下游。

Buffer writes with a queue. Protect downstream with backpressure.

#### 3. 事务型系统 (Transaction-Heavy) — e.g. Payment

[API] → [Idempotency Check] → [DB Transaction (2PC or Saga)] ↓ (duplicate?) [Return cached result] ↓ (new?) [Debit Account → Credit Account → Record Ledger] via Saga: each step + compensating transaction

关键洞察 / Key Insight: Idempotency key 防止重复扣款。Saga 比 2PC 更适合跨服务。

Idempotency keys prevent duplicate charges. Saga > 2PC across microservices.


常见 Expert 面试陷阱 / Expert Interview Traps

陷阱 Trap错误思路 Wrong正确思路 Right
"用 Redis 做持久化"默认 Redis 可靠Redis 是缓存,不是主库;配合持久化 DB
"加更多副本解决写瓶颈"副本减少读压力写瓶颈需要分片 (sharding),不是副本
"Kafka 解决一切消息问题"Kafka 万能简单通知用 Redis Pub/Sub;Kafka 适合持久化/重放
"微服务就要用 2PC"跨服务强一致2PC 阻塞性强,跨服务首选 Saga + 补偿

面试答题框架:5分钟架构对话 / 5-Minute Architecture Framework

1. 澄清需求 (1 min): QPS? DAU? 读写比? 强一致还是最终一致? 2. 高层架构 (2 min): 画3层图 (Client → Service → DB) 3. 深入关键组件 (1 min): 面试官感兴趣的那一层 4. 权衡讨论 (1 min): "我选X而不是Y,因为..."

📚 References

🧒 ELI5

如果你家有5个孩子喝水:

  • 读密集 = 提前多备几瓶水 (缓存)
  • 写密集 = 所有孩子同时倒水,先排队等 (队列)
  • 事务型 = 钱包扣钱和存钱必须同时成功,否则都撤销

If you have 5 kids at home:

  • Read-heavy = Pre-fill many water bottles (cache)
  • Write-heavy = Everyone pours at once; line up first (queue)
  • Transactional = Debit and credit must both succeed, or neither does

算法 / Algorithms — Day 101

#200 Number of Islands (Medium) · Graphs · Day 80/150


💻 算法 / Algorithms — #200 Number of Islands 🟡 — Graphs


🧩 新模式 / New Pattern: 图遍历模式 (BFS/DFS)

📍 This block: 13 problems

什么时候用 / When to use: 连通性、最短路径、拓扑排序、岛屿问题

When to use: connected components, shortest path, topological sort, grid/matrix traversal, islands

识别信号 / Signals: connected components, shortest path, topological sort, grid/matrix traversal, islands

通用模版 / Template:

# BFS Template
from collections import deque

def bfs(graph, start):
    queue = deque([start])
    visited = {start}
    while queue:
        node = queue.popleft()
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

# DFS Template (Iterative)
def dfs(graph, start):
    stack = [start]
    visited = {start}
    while stack:
        node = stack.pop()
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                stack.append(neighbor)

# DFS Template (Recursive)
def dfs_recursive(graph, node, visited=None):
    if visited is None:
        visited = set()
    visited.add(node)
    for neighbor in graph[node]:
        if neighbor not in visited:
            dfs_recursive(graph, neighbor, visited)

核心洞察 / Key Insight: BFS = 最短路径(无权图),DFS = 连通性/路径探索。visited 集合防止死循环

BFS = shortest path (unweighted), DFS = connectivity/path exploration. visited set prevents infinite loops.


🔗 Links


现实类比 / Real-World Analogy

想象你有一张卫星地图,上面有陆地 '1' 和海洋 '0'。

你需要数清楚有多少块独立的陆地(岛屿)。

这就像 感染控制:每次发现一个新病例(未访问的 '1'),就把该病例的所有相连感染区域标记为已处理,然后统计独立的爆发次数。

Imagine a satellite map with land '1' and ocean '0'.

You need to count distinct landmasses. Think of it like infection control: each new unvisited '1' starts a new outbreak cluster — mark all connected cells and count clusters.


题目 → 套用模式 / Problem → Map to Template

grid:
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1

Answer: 3 islands

映射到图遍历模版:

  • 节点 Node = grid cell (row, col)
  • 邻居 Neighbor = 上下左右四个方向
  • 访问标记 Visited = 修改 grid 为 '0' (原地标记) 或用 visited set
  • 每次发现未访问的 '1',启动 BFS/DFS,计数器 +1

Python Solution with Trace

def numIslands(grid: list[list[str]]) -> int:
    if not grid:
        return 0
    
    rows, cols = len(grid), len(grid[0])
    islands = 0
    
    def dfs(r, c):
        # Base case: out of bounds or water
        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == '0':
            return
        
        # Mark as visited (sink the island)
        grid[r][c] = '0'
        
        # Explore 4 directions
        dfs(r + 1, c)
        dfs(r - 1, c)
        dfs(r, c + 1)
        dfs(r, c - 1)
    
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':  # Found unvisited land
                islands += 1        # New island!
                dfs(r, c)           # Sink entire island
    
    return islands

# Trace on small example:
# grid = [["1","1","0"],["0","1","0"],["0","0","1"]]
# (0,0) = '1' → islands=1, DFS sinks (0,0),(0,1),(1,1)
# (2,2) = '1' → islands=2, DFS sinks (2,2)
# Result: 2

时间复杂度 / Time: O(M×N) — visit each cell once

空间复杂度 / Space: O(M×N) — recursion stack in worst case (all land)


BFS 版本 / BFS Alternative

from collections import deque

def numIslands_bfs(grid):
    rows, cols = len(grid), len(grid[0])
    islands = 0
    
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':
                islands += 1
                grid[r][c] = '0'
                queue = deque([(r, c)])
                while queue:
                    row, col = queue.popleft()
                    for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
                        nr, nc = row + dr, col + dc
                        if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '1':
                            grid[nr][nc] = '0'  # Mark immediately to avoid duplicate queue entries
                            queue.append((nr, nc))
    
    return islands

BFS vs DFS 选哪个?/ Which to choose?

  • DFS:代码更简洁;深度大时有栈溢出风险
  • BFS:无递归栈溢出;更适合"最短路径"变体
  • 对本题:两者等价,DFS 更简洁

举一反三 / Pattern Block Preview (1/13)

题目变化点 Twist
#695 Max Area (next)不只是数个数,还要统计最大面积
#994 Rotting OrangesBFS + 时间层 (multi-source BFS)
#207 Course Schedule有向图 + 环检测 (cycle detection)
#127 Word LadderBFS 最短路径(字符变换)

核心模版不变,关键是识别:这是连通性问题还是最短路径问题?

The template stays the same — just identify: connectivity vs. shortest path?


📚 References

🧒 ELI5

想象你在玩扫雷,但反过来:

找到一块陆地,就把所有相连的陆地都染成蓝色(变成水)。

数一数你染了几次,就是有几座岛屿!

Think of it like Minesweeper in reverse:

When you find land, flood all connected land with water.

Count how many times you flood — that's your answer!


📝 Quiz

{"question":"#200 Number of Islands — 为什么 BFS 比 DFS 更适合超大 grid?","options":["BFS 时间复杂度更低","BFS 避免了递归栈溢出 (stack overflow)","BFS 不需要 visited 集合","BFS 代码更简洁"],"correct_index":1}

软技能 / Soft Skills — Day 101

Day 61 (Synthesis Mode) · Expert Phase


🗣️ 软技能 / Soft Skills — Expert Synthesis: The Art of the Difficult Conversation


为什么难话难说?/ Why Hard Conversations Are Hard

你已经走过了 60 个行为面试题的洗礼。回顾这些题目,有一个共同主线:

最难的不是技术决策,而是"说难听但正确的话"。

You've covered 60 behavioral questions. There's a recurring thread:

The hardest part isn't the technical decision — it's saying the uncomfortable-but-right thing.

五类"难话" / Five Types of Hard Conversations (Senior/Staff Level)

1. 向上管理 (Managing Up)
   "这个方向不对,老板。"
   
2. 横向推动 (Lateral Influence)
   "我不是你的上级,但这事得改。"
   
3. 向下反馈 (Downward Feedback)
   "你做得不够好,我们聊聊。"
   
4. 公开认错 (Owning Mistakes)
   "这个 incident 是我的决策导致的。"
   
5. 说不 (Saying No)
   "这个 feature 我们不做,原因是..."

场景题 / Fresh Senior Scenario

Q: 你是一位 Staff Engineer。你的 VP 要求在下个 sprint 内上线一个功能,但你评估这会引入严重的技术债务,且有安全风险。PM 已经向客户承诺了上线日期。你怎么办?

Q: You're a Staff Engineer. Your VP wants a feature shipped in the next sprint, but you assess it will introduce significant tech debt and a security vulnerability. The PM has already committed a date to customers. What do you do?


STAR Framework 拆解

Situation(情境):

我在上家公司遇到类似情况。PM 向大客户承诺了一个 auth 功能的上线日期,但我在 design review 时发现该实现会绕过 RBAC 检查,潜在暴露其他租户数据。

Task(任务):

我需要在不破坏客户关系的前提下,阻止上线,或找到一个可接受的替代方案。

Action(行动):

1. 先记录风险:写了一份 2 页的风险备忘录,附上 CVSS 评分和潜在影响。
2. 私下找 PM:不是"你答应了错误的事",而是"我发现了一个可能让你难堪的风险,我们一起看看"。
3. 提供选项,不是只说不:Option A(全量上线,2周)= 安全风险;Option B(限量灰度,本周)= 按时但范围受限;Option C(安全版本,+1周)= 推迟但正确。
4. 升级时机:PM 选了 A,我升级到 VP,带着同样的文档,同样的语气。

Result(结果):

VP 选了 Option C,推迟1周。事后 PM 感谢我帮她避免了一个客户数据事故。

❌ Bad vs ✅ Good

BadGood
说不方式"这样做不行""这里有个风险,我有3个选项"
升级时机背后直接找 VP先尝试横向解决,再升级
文档口头说说书面 + 数据 + 影响量化
语气对抗性解决问题导向

Senior/Staff 的"难话"原则

  1. 书面化比口头说更有力 — 一份 Loom 录像或文档,比 Slack 消息更难被忽略
  2. 选项 > 否决 — 说不时永远给 2-3 个替代选项
  3. 私下先试 — 公开场合升级是最后手段,不是第一步
  4. 量化影响 — "安全风险"比不上 "CVSS 7.8,可能暴露 N 个客户的数据"

Key Takeaways

  • 难话不难,难在时机和框架。 Hard conversations aren't hard — the hard part is timing and framing.
  • Senior engineers say the quiet part out loud. 初级工程师沉默,高级工程师说出来。
  • "我注意到一个风险"比"你错了"有效得多。 "I noticed a risk" > "you're wrong."

📚 References

🧒 ELI5

如果你的朋友要做一件危险的事,你怎么说?

"你这样不行!"→ 他生气

"我担心这样会受伤,我们能不能试试这个?"→ 他听进去了

If your friend is about to do something dangerous:

"You can't do that!" → they get defensive

"I'm worried this might hurt you — can we try this instead?" → they actually listen

AI — Day 101

AI News Roundup · Day 101


🤖 AI — 本周要闻 / AI News Roundup (Week of July 27, 2026)


📰 Story 1: AI 模型价格战重塑市场格局

AI Model Price War Reshapes the Market

各大 AI 服务商在 7 月掀起激烈价格竞争,包括 Google 新推出的 Gemini 3.6 Flash、Gemini 3.5 Flash-Lite,以及 xAI 的 Grok 4.5、OpenAI 的 GPT-5.6 多个变体(据报道代号 Sol/Terra/Luna)。据报道,输出 Token 成本从此前的 $25–$50 / 1M tokens 骤降至 $4–$6,降幅逾 80%。

A fierce price war erupted among AI providers in July. Google launched Gemini 3.6 Flash, 3.5 Flash-Lite, and 3.5 Flash Cyber; xAI released Grok 4.5; OpenAI reportedly released GPT-5.6 variants. Output token costs reportedly dropped from $25–$50 to $4–$6 per 1M tokens — an over 80% reduction.

对开发者的意义 / What it means for devs:

过去"AI 太贵,实验一下就好"的心态正在消失。许多原本因成本放弃的 production AI 功能,现在的成本已经可以接受。

The "AI is too expensive for production" mindset is fading. Features once shelved for cost reasons are now economically viable.

📎 Source: Google Blog — Gemini 3.6 Flash | buildez.ai AI July 2026 summary


📰 Story 2: EU AI Act 正式进入执法阶段

EU AI Act Enters Enforcement Phase

2026 年 7 月 10 日,欧盟《人工智能法案》(AI Act) 正式进入执法阶段。法案以风险分级为核心:高风险 AI 系统(如医疗、执法、就业决策)需通过合规审查;所有 AI 聊天机器人须明确披露其 AI 身份。

On July 10, 2026, the EU AI Act officially entered its enforcement phase. Core principle: risk-based tiers. High-risk AI (medical, law enforcement, employment decisions) must pass compliance reviews. All AI chatbots must disclose they are AI.

对工程师的实际影响 / Practical impact for engineers:

  • 在欧洲部署的 AI 系统需新增"AI 披露"UI
  • 高风险场景需要可解释性日志和人工审核接口
  • GDPR + AI Act 双重合规成为欧洲 AI 产品标配

In Europe: add AI disclosure UI, log model decisions for explainability, and build human-review hooks for high-risk flows. GDPR + AI Act compliance is now baseline.

📎 Source: teachaitools.blog — EU AI Act Enforcement Begins


📰 Story 3: MIT/Stanford 研究——自我纠错能力比模型规模更重要

MIT/Stanford: Self-Correction Beats Raw Model Size

MIT 和 Stanford 研究人员发表研究指出:对于复杂数学和逻辑推理任务,模型在推理过程中自我纠错的能力比模型参数规模更关键。这一发现支持了"o 系列"和"思维链"推理模型的设计方向。

Researchers from MIT and Stanford found that a model's ability to self-correct during reasoning is a more critical factor for hard math/logic tasks than sheer model size. This validates the design direction of "thinking" models like the o-series and Chain-of-Thought variants.

工程启示 / Engineering takeaway:

  • 在 Agent 系统中,给模型"反思"步骤可能比升级模型更有效
  • 小模型 + 多次推理迭代 > 大模型 + 单次推理(某些场景)

In agent pipelines, adding a reflection/self-critique step may outperform upgrading to a larger model.

📎 Source: skycrumbs.com — AI Research July 2026


💡 本周一句话总结 / One-line Summary

AI 的门槛在降低,合规的门槛在升高,推理能力在变深。
AI is getting cheaper, regulation is getting stricter, and reasoning is getting smarter.

📚 References

🧒 ELI5

AI 新闻三句话版:

  1. AI 越来越便宜了——以前贵得用不起,现在用得起了 💰
  2. 欧洲出了新规定:AI 要告诉你"我是 AI" 🇪🇺
  3. 科学家发现:AI 能自己检查错误比 AI 有多大更重要 🧠

AI news in 3 lines:

  1. AI got way cheaper — what was unaffordable is now viable 💰
  2. EU law: AI must say "I am an AI" to users 🇪🇺
  3. Self-correction matters more than model size for hard reasoning 🧠