← 2026-08-20 📂 All Days 2026-08-22 →

📊 Day 116 — System Design Synthesis

🔥 Expert Level | Synthesis: Distributed Transactions

🏗️ 系统设计 / System Design — 分布式事务大比拼

分布式事务的真相 / Distributed Transactions: 2PC vs SAGA vs 最终一致性


场景引入 / The Problem

想象你在设计一个电商支付系统。用户点击"购买"时,需要同时:

  1. 扣减库存(Inventory Service)
  2. 扣款(Payment Service)
  3. 创建订单(Order Service)

三个独立服务,如果支付成功但库存扣减失败怎么办?

Imagine: user clicks "Buy" — inventory, payment, and order creation must all succeed or all fail. Three different databases, three different services.


方案一:两阶段提交 / 2PC (Two-Phase Commit)

协调者 Coordinator │ ├─── Phase 1: PREPARE ──► Service A: "Can you commit?" │ ──► Service B: "Can you commit?" │ ──► Service C: "Can you commit?" │ └─── Phase 2: COMMIT ───► All: "Commit!" (or ROLLBACK if any said no)

优点: 强一致性,ACID 保证

缺点:

  • 协调者宕机 → 所有参与者卡住(锁住资源)
  • 网络分区 → 脑裂 (split-brain)
  • 延迟高(两轮网络往返)

何时用: 数据库内部(MySQL InnoDB Cluster),不推荐跨微服务


方案二:Saga 模式 / Saga Pattern

每步操作 + 对应的补偿事务 (compensating transaction):

Order Created → Payment Charged ✅ → Inventory Reserved ❌ FAIL → COMPENSATE: Refund Payment → COMPENSATE: Cancel Order

两种实现:

  • Choreography(编舞):每个服务发事件触发下一步,去中心化
  • Orchestration(编排):中央 Saga Orchestrator 控制流程

优点: 高可用,无分布式锁,适合微服务

缺点: 补偿逻辑复杂,无法保证隔离性(中间状态可见)


方案三:最终一致性 / Eventual Consistency + Idempotency

Write to local DB + Outbox table (same transaction) → Outbox Poller reads and publishes to Kafka → Consumers process with idempotency key

Outbox Pattern 是关键:先写本地,再异步传播。

幂等性 (Idempotency) 是保障:同一请求重试多次结果相同。


选型决策树 / Decision Framework

需要强一致性? ├── 是 → 单数据库能搞定吗? │ ├── 是 → 用单DB事务 ✅ │ └── 否 → 考虑 2PC(仅内部系统,短事务) └── 否 → 业务允许补偿? ├── 是 → SAGA(推荐跨微服务) └── 否 → 最终一致性 + Outbox Pattern

常见陷阱 / Common Mistakes

错误正确做法
用 2PC 跨公网服务用 SAGA + 幂等补偿
Saga 没有幂等保证每步加 idempotency key
补偿逻辑写得不完整画出所有失败路径,逐一实现
忽略中间状态的可见性用"待确认/pending"状态隐藏中间态

📚 References

🧒 ELI5

你和朋友一起去餐厅,各自点菜。如果你的菜来了但朋友的没来,你们有三种选择:等大家都到了再吃(2PC)、先吃先到的、没到的退款(SAGA)、或者大家异步到了再吃不管顺序(最终一致性)。

💻 Day 116 — Algorithms

#684 Redundant Connection — Medium — Graphs (12/13)

💻 算法 / Algorithms — #684 Redundant Connection 🟡

🧩 图遍历模式 (12/13) — building on the BFS/DFS template from Day 101


题目 / Problem

🔗 LeetCode #684 🟡 Medium

📹 NeetCode Solution

给定一个 n 个节点的无向图,最初是一棵树(无环)。有一条额外的边被加入,使得图中存在一个环。找出并返回这条多余的边。

Given an undirected graph that was originally a tree, find the one extra edge that creates a cycle. Return it.


真实类比 / Real-World Analogy

想象公司组织架构图(树结构)。某人同时汇报给两个老板 — 这就产生了一个"环"。你需要找出哪条汇报关系是多余的(后加入的)。

Company org chart: normally a tree. Someone reports to two managers — that creates a cycle. Find the redundant reporting relationship.


这道题 vs 模板的不同 / How It Differs from Base Template

普通 BFS/DFS 探索整个图;这道题需要增量检测环:

  • 每次加入一条边,检查两端节点是否已连通
  • 已连通 → 这条边就是多余的
  • 最优解:Union-Find(并查集),不是纯 BFS/DFS

Union-Find 解法 / Solution

class Solution:
    def findRedundantConnection(self, edges: list[list[int]]) -> list[int]:
        n = len(edges)
        parent = list(range(n + 1))  # parent[i] = i initially
        rank = [1] * (n + 1)

        def find(x):
            # Path compression: flatten the tree as we find root
            while parent[x] != x:
                parent[x] = parent[parent[x]]  # halving
                x = parent[x]
            return x

        def union(x, y):
            rx, ry = find(x), find(y)
            if rx == ry:
                return False  # already connected → redundant edge!
            # Union by rank: attach smaller tree under larger
            if rank[rx] < rank[ry]:
                rx, ry = ry, rx
            parent[ry] = rx
            rank[rx] += rank[ry]
            return True

        for u, v in edges:
            if not union(u, v):
                return [u, v]
        return []

执行追踪 / Trace

edges = [[1,2],[1,3],[2,3]] 初始: parent = [0,1,2,3] union(1,2): find(1)=1, find(2)=2 → different → merge → parent[2]=1 union(1,3): find(1)=1, find(3)=3 → different → merge → parent[3]=1 union(2,3): find(2)=find(1)=1, find(3)=find(1)=1 → SAME! → return [2,3]

复杂度 / Complexity

  • Time: O(n · α(n)) — α是反阿克曼函数,近似O(1)
  • Space: O(n)

举一反三 / Pattern Block Connections

题目用到的图技术
#200 Number of IslandsDFS/BFS flood fill
#207 Course ScheduleDFS cycle detection (directed)
#261 Graph Valid TreeUnion-Find / DFS
#684 Redundant ConnectionUnion-Find 增量
#127 Word Ladder (next!)BFS shortest path
关键洞察:Union-Find 擅长增量连通性检测;BFS/DFS 适合一次性探索

Quiz

{"question":"In Union-Find, what does 'path compression' do?","options":["Removes edges from the graph","Makes every node point directly to root during find()","Compresses the graph into fewer nodes","Sorts nodes by their rank"],"correct_index":1}

📚 References

🧒 ELI5

想象一群小朋友玩"找朋友"游戏。Union-Find 就像给每个小朋友一个队长。两人握手时,先检查他们是否已经是同一队的——是的话,这次握手就多余了!

🗣️ Day 116 — Soft Skills Synthesis

Expert Level | Synthesis: Engineering Culture & Influence at Scale

🗣️ 软技能 / Soft Skills — Staff Engineer 的影响力公式

题目 / Fresh Scenario

场景: 你是 Staff Engineer。公司决定将三个独立团队合并成一个平台团队,三个 EM 都有自己的技术栈偏好,一半工程师反对合并。你被要求在 6 周内完成统一架构设计并推动落地。你怎么做?

You're a Staff Engineer. Three teams are being merged. Each EM has different tech stack preferences. Half the engineers oppose the merger. You have 6 weeks to deliver a unified architecture.


STAR 框架分析

Situation: 技术意见分歧 + 组织变革阻力 + 硬性 deadline

Task: 不靠权威,靠影响力推动技术共识

Action — 分四步:

  1. 先倾听,再提案 — 一对一与每个 EM 和 Senior Engineer 聊,了解核心诉求(不是表面立场)
  2. 找共同敌人 — 把讨论从"我的技术栈 vs 你的"转向"共同面临的运维痛点"
  3. RFC 流程 — 写 RFC(Request for Comment),公开征集意见,让所有人都有发声机会
  4. 小胜快赢 — 第2周做一个小的 PoC,用数据说话,降低"这是空想"的疑虑

Result: 通过透明流程和数据驱动,6周内达成80%共识,剩余20%通过试点验证解决


❌ Bad vs ✅ Good

❌ 常见错误✅ 正确做法
直接发邮件宣布方案RFC + 异步讨论,给时间消化
把分歧升级给 VP先在工程师层解决,VP 是最后手段
只关注技术同时关注人的诉求(职业发展、ownership)
追求100%共识70%共识 + 清晰的决策机制更实际

Senior → Staff 的跨越 / The Leap

Senior: 影响本团队技术决策

Staff: 影响跨团队、跨组织的技术方向

关键能力差异:写 > 说(Staff 靠文档影响力),间接 > 直接(通过他人落地)


Key Takeaways

  • 影响力 = 倾听 × 透明 × 数据,不是职位
  • RFC 是 Staff Engineer 的核心工具
  • 组织变革中,"赢得人心"比"赢得技术辩论"更重要

📚 References

🧒 ELI5

当一群小朋友争论玩什么游戏时,最聪明的做法不是大声说"听我的!",而是先问每个人最不想要什么,然后找到大家都能接受的方案。

🤖 Day 116 — AI Synthesis

Expert Level | Deep Dive: The Inference Paradox & Agentic Cost Reality

🤖 AI — 推理悖论:Token 越便宜,账单越贵?

"Inference Paradox" — 2026 年 AI 成本的反直觉现实


新闻背景 / News Context

据 Gartner 分析师报告(来源:Computerworld):

Token 成本到2030年将下降95%,但智能体工作流的推理成本将在2028年前上涨5倍以上。

这就是"推理悖论":单价越低,但你用得越多,总账反而更贵。

Per Gartner analysts: token costs will drop 95% by 2030, but inference costs for agentic workflows will rise more than 5x through 2028. The "inference paradox."


为什么会这样?/ Why?

1990年代: 打印机墨盒模式 价格↓ → 打印量↑ → 总成本↑ 2026年 AI 版本: Token 价格↓ → Agent 做更多步骤(multi-hop reasoning) → 更多工具调用(search, code exec, memory) → 更长上下文窗口(1M tokens) → 总 token 消耗量 >>> 价格降幅 → 月账单 ↑

连接已学概念 / Synthesis Across Topics

之前学过的概念在推理成本中的体现
KV Cache (Day 46)长上下文 = 大 KV Cache = 显存瓶颈
RAG (Day 16)每次查询 = embedding + retrieval + generation
Agents/ReAct (Day 26)每个 tool call = 额外 LLM 调用
Quantization (Day 44)降低单次推理成本的关键杠杆
Context Windows (Day 34)1M token 窗口 ≠ 免费

实战:计算 Agent 真实成本 / Real Cost Calculation

# Agent cost estimator
def estimate_agent_cost(
    steps: int,
    avg_input_tokens: int,
    avg_output_tokens: int,
    input_price_per_1m: float,   # e.g., 3.0 for claude-sonnet
    output_price_per_1m: float,  # e.g., 15.0
) -> dict:
    input_cost = (steps * avg_input_tokens / 1_000_000) * input_price_per_1m
    output_cost = (steps * avg_output_tokens / 1_000_000) * output_price_per_1m
    total = input_cost + output_cost
    
    return {
        "total_tokens": steps * (avg_input_tokens + avg_output_tokens),
        "input_cost_usd": round(input_cost, 4),
        "output_cost_usd": round(output_cost, 4),
        "total_cost_usd": round(total, 4),
    }

# Typical research agent: 10 steps, 8K input, 1K output each
result = estimate_agent_cost(
    steps=10,
    avg_input_tokens=8_000,
    avg_output_tokens=1_000,
    input_price_per_1m=3.0,
    output_price_per_1m=15.0,
)
print(result)
# {'total_tokens': 90000, 'input_cost_usd': 0.24,
#  'output_cost_usd': 0.15, 'total_cost_usd': 0.39}
# ~$0.39 per agent run × 1000 runs/day = $390/day 💸

降本策略 / Cost Reduction Strategies

  1. 模型路由 — 简单步骤用小模型,复杂推理用大模型
  2. Prompt 缓存 — 系统提示缓存(Claude/OpenAI 均支持,最高90%折扣)
  3. 早停 — 检测到足够答案时立即停止 agent 循环
  4. 批处理 — 非实时任务走 Batch API(通常50%折扣)

📚 References

🧒 ELI5

就像自助餐越来越便宜,但你越来越能吃,结果总花费反而更多。AI token 价格下降,但 AI agent 做的事越来越多,账单还是涨了。