← 2026-07-16 📂 All Days 2026-07-18 →

System Design — Day 93: 合成深度 / Synthesis Deep Dive

一致性模型全景:从 Redis 到 Spanner / Consistency Models: From Redis to Spanner

综合模式 — 跨越过去所涵盖的主题,进行 Expert 级别对比与深度分析

场景 / Scenario

想象你在设计一个全球金融平台,需要在三个地区运行(美国、欧洲、亚洲)。你的团队争论激烈:

  • 工程师 A 说:「用 Redis + 异步复制,简单快!」
  • 工程师 B 说:「不行,金钱数据必须强一致,用 Spanner!」
  • 工程师 C 说:「Cassandra 最终一致足够了吧?」

谁是对的?取决于你的一致性需求矩阵。

Imagine you're designing a global financial platform across 3 regions. Your team disagrees on consistency — who's right? It depends on your consistency requirements matrix.


一致性模型对比 / Consistency Model Comparison

强一致性 (Strong) ←→ 最终一致性 (Eventual) │ │ Spanner Cassandra DynamoDB CockroachDB Redis Cluster S3 Postgres (single) MongoDB Kafka Topics │ │ 💰 高延迟,高成本 💚 低延迟,低成本 ✅ 适合:金融、库存 ✅ 适合:用户档案、分析
线性一致性 (Linearizable):
  Every operation appears atomic at a single point in time.
  Read always sees latest write.
  Example: Spanner uses TrueTime API.

顺序一致性 (Sequential):
  All ops appear in some global order.
  Less strict than linearizable.

因果一致性 (Causal):
  Causally related ops maintain order.
  Example: "Reply after post" ordering.

最终一致性 (Eventual):
  Given enough time, all replicas converge.
  Example: DNS propagation, S3.

架构对比 / Architecture Comparison

[ Redis Sentinel ] [ Google Spanner ] Primary ──► Replica 1 Node 1 (US-East) └─► Replica 2 ◄──► Node 2 (EU-West) Node 3 (Asia-Pacific) Async replication Paxos consensus Failover ~30s TrueTime (GPS + atomic clocks) Eventual consistency External consistency (linearizable) Latency: <1ms local Latency: ~10ms cross-region Cost: 💚 cheap Cost: 💰 expensive

关键权衡 / Key Tradeoffs

维度Redis (Async)Postgres (Sync Replica)SpannerCassandra
一致性最终强(单区)线性(全球)最终/可调
可用性高中(主挂即降级)很高极高
延迟亚毫秒1-5ms10-100ms1-10ms
扩展性垂直+集群读扩展水平全球水平无限
成本低中极高中

决策框架 / Decision Framework:

if money_or_inventory: → Spanner / CockroachDB (global) → Postgres with synchronous replication (regional) elif user_profiles_or_feeds: → Cassandra / DynamoDB (eventual ok) elif session_cache: → Redis (speed > consistency) elif audit_log: → Kafka → cold storage (append-only wins)

别踩这个坑 / Common Mistakes

❌ 坑 1: 认为"最终一致"就是"不一致"

最终一致在窗口期(通常 ms~s)内可能读到旧数据,但最终会收敛。设计时要处理"读己写"场景。

❌ 坑 2: 忽视时钟漂移

分布式系统的"先后"是个难题。Spanner 用 GPS + 原子钟解决;你自己实现时要用逻辑时钟(Lamport / Vector Clock)。

❌ 坑 3: 强一致 ≠ 无 bug

即便 Spanner 保证线性一致,应用层的事务逻辑(转账的原子性)仍需正确设计。


📚 References

  • https://cloud.google.com/spanner/docs/true-time-external-consistency
  • https://cassandra.apache.org/doc/latest/cassandra/architecture/dynamo.html
  • https://jepsen.io/consistency — Jepsen consistency model hierarchy
  • https://martin.kleppmann.com/2015/05/11/please-stop-calling-databases-cp-or-ap.html

🧒 ELI5

把数据库想象成班级公告栏。强一致 = 老师每次改公告必须等全班同学都看到才算完成(慢但准)。最终一致 = 老师先改,等下课了大家陆续看到(快但有时滞后)。Spanner 是那种用原子钟确保全球每个黑板在同一秒更新的黑科技教室。

Think of a database like a school bulletin board. Strong consistency = the teacher waits until every student acknowledges the update before moving on (slow but precise). Eventual = teacher posts it and students gradually see it (fast but lagging). Spanner is the sci-fi classroom with atomic clocks ensuring every board globally updates at the exact same moment.

Algorithms — Day 75: #40 Combination Sum II (Medium) — Backtracking

🧩 回溯模式 (5/9) — building on the template from Day 72 (Subsets II, Day 88/89 for Subsets/Combination Sum)

今天是 Backtracking 模式块的第 5 题。对比 #39 Combination Sum,今天多了一个关键约束:候选数组有重复项,且每个元素只能用一次。

Today is problem 5/9 in the Backtracking block. Versus #39, the key difference: candidates have duplicates and each element can only be used once.


🔗 Links


现实类比 / Real-World Analogy

你有一堆零钱(可能有重复面值),想凑出一个精确金额,但每枚硬币只能用一次,且结果不能重复。

You have a pile of coins (with possible duplicates) and want to make exact change — but each coin can only be used once, and duplicate combinations aren't allowed.


问题 / Problem

Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [[1,1,6],[1,2,5],[1,7],[2,6]] Constraint: Each number in candidates may only be used once. Duplicates in candidates → but output must have no duplicate combinations.

与模版的映射 / Mapping to Template

def backtrack(path, choices):          # Template structure
    if IS_COMPLETE(path): ...          # sum(path) == target
    for choice in choices:
        if IS_VALID(choice): ...       # sum + choice <= target, skip dups
        path.append(choice)
        backtrack(path, NEXT_CHOICES)  # start+1 (not start!) — no reuse
        path.pop()

与 #39 的关键差异 / Key diff from #39 Combination Sum:

  • #39: candidates has no dups, each can be reused → recurse with start (same index)
  • #40: candidates has dups, each used once → recurse with start+1, AND skip dup siblings

Python 解法 + 注释 / Solution + Trace

def combinationSum2(candidates, target):
    candidates.sort()  # CRITICAL: sort to group duplicates together
    result = []

    def backtrack(start, path, remaining):
        if remaining == 0:
            result.append(path[:])  # found valid combination
            return
        for i in range(start, len(candidates)):
            # Skip duplicates at same tree level
            # "i > start" means: skip if same value as prev sibling
            # (i == start is fine — first occurrence at this level)
            if i > start and candidates[i] == candidates[i - 1]:
                continue
            if candidates[i] > remaining:
                break  # sorted → no point going further
            path.append(candidates[i])
            backtrack(i + 1, path, remaining - candidates[i])  # i+1: no reuse
            path.pop()

    backtrack(0, [], target)
    return result

# Trace for candidates=[1,1,2,5,6,7,10], target=8:
# Level 0: try 1 → [1]
#   Level 1: try 1(second) → [1,1]
#     Level 2: try 2 → [1,1,2], rem=4... try 5 → [1,1,5], rem=1... no
#              try 6 → [1,1,6], rem=0 ✅ FOUND [1,1,6]
#   Level 1: try 2 → [1,2]... eventually [1,2,5] ✅
#   Level 1: try 6 → [1,6], rem=1... [1,7] ✅
# Level 0: try 1(second) — SKIP (i>start and candidates[i]==candidates[i-1])
# Level 0: try 2 → [2]... [2,6] ✅

Complexity:

  • Time: O(2^n) — each element in or out
  • Space: O(n) — recursion depth (target / min_candidate)

与同模式块的对比 / Comparison Within Block

题目重复元素?可重用?递归调用去重方式
#78 SubsetsNoNoi+1N/A
#39 Combo SumNoYesi (same)N/A
#46 PermsNoNoexclude visitedN/A
#90 Subsets IIYesNoi+1skip candidates[i]==candidates[i-1]
#40 Combo Sum IIYesNoi+1skip candidates[i]==candidates[i-1]
**规律 / Pattern:** 只要有重复元素 → 先排序 → 同层跳过相同值。

举一反三 / Connect to Block

  • 下一题 #79 Word Search — 2D 棋盘上的 backtracking,不是数字,而是路径
  • #131 Palindrome Partitioning — 不是"数字求和"而是"字符串划分",但框架完全一样
  • 核心变化模式: 约束变了(不重用、不重复),但 选择→递归→撤销 三步不变

📝 Quiz

{"question":"In #40 Combination Sum II, why do we check `i > start` before skipping duplicate candidates?","options":["A) To allow the first occurrence at each recursion level","B) To ensure the list is sorted","C) To prevent index out of bounds","D) To handle negative numbers"],"correct_index":0}

📚 References

  • https://leetcode.com/problems/combination-sum-ii/
  • https://neetcode.io/problems/combination-target-sum-ii
  • https://leetcode.com/explore/featured/card/recursion-ii/472/backtracking/

🧒 ELI5

想象你在一堆糖果里挑糖,有两颗一样的草莓糖。你先把糖按口味排好,然后每次挑糖时,如果上一颗已经跳过同口味的了,这颗也跳过(不然会装出重复的袋子)。每颗糖只能装一次,装完不够再加,超了就换下一种口味。

Imagine picking candy from a bag, some duplicates. Sort the bag first. When at the same "level" of choosing, if you already skipped a strawberry candy, skip all subsequent strawberry candies too — otherwise you'd get duplicate bags. Each candy goes in once; if over the budget, stop trying heavier candies.

Soft Skills — Day 93: 综合挑战 / Synthesis Challenge

Staff-Level Scenario: 技术债务 vs 战略窗口 / Technical Debt vs Strategic Window

综合模式 — 跨越先前所有 behavioral 主题,提出一个 Staff/Principal 级别的复合场景

🎯 场景 / Scenario

你是一家 B2B SaaS 公司的 Staff Engineer。产品团队发现了一个 6 周的战略窗口:竞争对手宣布停止维护其核心产品,你们有机会快速上线一个功能来接纳那些流失的客户。
但问题是:你的核心服务有 严重技术债(无测试覆盖的意大利面条代码),任何快速改动都有较高的生产事故风险。上次"快速发布"造成了 4 小时的宕机。
CEO 要求 3 周内上线。你的团队说需要 8 周(2 周还债 + 6 周开发)。

You're a Staff Engineer at a B2B SaaS. Product found a 6-week strategic window — a competitor just sunsetted their product. But your core service has severe tech debt: any fast change risks an outage. Last "fast release" caused 4 hours of downtime. CEO wants 3 weeks. Your team says 8 weeks.

How do you handle this?


STAR 分解 / STAR Breakdown

Situation — 定义清楚,不要模糊

  • 明确量化风险:「上次快速发布造成了 4h 宕机,影响了 X 个企业客户,造成了 $Y 的信用损失」
  • 明确机会成本:「竞品停服后预估有 200+ 企业客户在找替代品,我们的赢单率当前约 30%」

Task — 你的角色定义

作为 Staff Engineer,你的任务不只是"写代码",而是:

  1. 技术决策架构师:提出可行路径,量化风险
  2. 业务翻译者:把"技术债"翻译成 CEO 听得懂的语言
  3. 对齐者:让产品、工程、CEO 对同一个现实有共识

Action — 具体做什么

第一步:不要立刻说"不行"

❌ 避免:「这个代码库太烂了,3 周不可能。」

✅ 改为:「让我花 48 小时做一个风险评估,再给你一个有据可依的答复。」

第二步:提出"菜单式"方案

方案 A (3周): 直接开发,不还债 → 风险:~60% 概率出现生产事故,发布后 3 个月要还债 → 商业影响:抓住窗口,但可能因事故损失新客户信任 方案 B (5周): 最小化还债 + 功能开发 → 只偿还关键路径上的债(不是所有债) → 风险:~20% 概率事故 → 商业影响:窗口末期上线,仍可抓住 ~70% 的机会 方案 C (8周): 完整还债 + 开发 → 错过窗口,但基础稳固 → 适合"我们不急这批客户"的判断

第三步:让业务做决策

你的工作是呈现选项和风险,不是代替 CEO 做商业决策。

Present the menu; let business own the decision.

第四步:无论选哪条,设立护栏

  • Feature flag + 逐步灰度放量
  • On-call 轮班,发布后 72 小时高警戒
  • 提前准备回滚 runbook

Result

  • 最终选方案 B,用 5 周上线
  • 关键路径代码有了 80% 测试覆盖
  • 发布顺利,无重大事故
  • 转化了 ~40 家新客户

❌ Bad vs ✅ Good 回答

❌ 弱回答: 「我解释了技术债的重要性,说服了 CEO 等 8 周。」

→ 问题:没展示商业意识,也没展示如何影响非技术决策者

✅ 强回答: 「我把风险量化成业务语言(事故概率 × 客户信任损失),提出了三个方案菜单,让产品和 CEO 做知情决策,并确保无论选哪个方案我们都有护栏。」


Senior/Staff Tips

  1. Tech debt is a business risk, not just a code quality issue. 学会用商业语言($、客户、风险概率)解释技术决策。
  2. "No" 是最后手段。 先问"怎么在约束下做到接近目标"。
  3. Options > Opinions. Staff+ 工程师提供选项+权衡,不是单一答案。
  4. Own the outcome, not just the code. 你对发布后 30 天的结果也负责。

Key Takeaways

  • 将技术债翻译为量化业务风险 → Translate tech debt into quantified business risk
  • 呈现选项菜单,赋予业务决策权 → Present options menu, empower business to decide
  • 无论选哪条路,都要设护栏 → Regardless of path chosen, always establish guardrails

📚 References

  • https://martinfowler.com/bliki/TechnicalDebt.html
  • https://www.staffeng.com/guides/staff-archetypes/
  • https://increment.com/teams/the-anatomy-of-a-risk/

🧒 ELI5

就像你妈妈说「明天要交作业,但你的书桌太乱找不到笔」。聪明的做法不是说「不行,要先整理 3 天书桌」,也不是「不管乱就写,可能写错地方」,而是「先把笔这一块整理好(最小化还债),然后写作业(发货),整理完整个书桌等下个周末」。

Like your desk being too messy to do homework. Don't spend 3 days cleaning first. Don't ignore the mess entirely. Just clean enough of the desk to find your pen — then do the homework.

AI — Day 93: AI 新闻速递 / AI News Roundup

📡 NEWS MODE — 2026年7月17日

🌏 本周 AI 三大动态 / Top 3 Stories This Week


1. 模型价格战:大模型全面降价 / The Great Model Price War

来源: https://llm-stats.com/ai-news · https://medium.com/@davidakpovi/ai-news-week-of-july-6-to-july-12-2026-f81a26c49c55

本月初,多家主要 AI 公司几乎同步发布新模型,引发业界称之为"Great Model Price War"(大模型价格战)的局面:

  • Grok 4.5(xAI/SpaceX,7月8日)
  • GPT-5.6(OpenAI,7月9日):三个变体 Sol / Terra / Luna;据报道 Luna 每百万输出 token 约 $6,较之前旗舰大幅降低
  • Kimi K3(Moonshot AI,7月16日):据报道是一个约 2.8T 参数的 MoE 稀疏模型,1M token 上下文窗口,承诺于 7月27日开源权重

为什么重要 / Why it matters:

价格竞争加速 AI 普及,对开发者和企业来说意味着 API 成本可能继续下降。但模型能力趋同后,下一个差异化可能是专业化(代码、医疗、多模态)而非规模。


2. 推理效率新突破:ICML 2026 "选择性激活稀疏" / Selective Activation Sparsity

来源: https://kersai.com/ai-breakthroughs-july-2026/ · https://skycrumbs.com/blog/ai-research-july-2026

ICML 2026 上有研究提出了 "selective activation sparsity" 训练方法:模型在推理时只激活与当前任务最相关的参数子集,而非全量激活所有神经元。据报道,该方法在部分基准上以更小的有效参数量达到大模型同级性能。

这与 MoE(Mixture of Experts)思想一脉相承,但在激活粒度上更细。对工程师来说的含义:未来模型在同等推理成本下可能更强,或同等能力下更便宜。


3. Google 品牌整合:NotebookLM → Gemini Notebook / Google Consolidates

来源: https://llm-stats.com/ai-news

Google 将旗下 NotebookLM 重命名为 Gemini Notebook,并集成了:

  • 安全的云端代码执行环境
  • 与 Gemini 应用和 Google 搜索的跨平台同步

此外,据泄露信息显示 Gemini 3.5 Pro 即将发布,据报道将支持 2M token 上下文窗口(如确认将是目前最长上下文之一)。


💡 工程师视角 / Engineer's Takeaway

趋势总结 / Trend Summary: 1. 价格 ↓ → API 调用成本继续下降,AI 产品 margin 逻辑改变 2. MoE / 稀疏激活 → 未来"大模型"不一定贵,效率是新竞争点 3. 生态整合 → 大厂在将 AI 工具深度绑定自有生态(Google Workspace, etc) 对你的影响: • 如果在做 AI 产品:重新评估 API 供应商定价 • 如果在做基础设施:长上下文窗口(2M+)改变 RAG 的设计逻辑 • 面试角度:被问到 MoE 架构时,能联系到 "sparse activation" 这个趋势加分

📚 References

  • https://llm-stats.com/ai-news
  • https://kersai.com/ai-breakthroughs-july-2026/
  • https://medium.com/@davidakpovi/ai-news-week-of-july-6-to-july-12-2026-f81a26c49c55
  • https://skycrumbs.com/blog/ai-research-july-2026

🧒 ELI5

AI 世界这周很热闹:大公司们在比谁的模型更便宜(就像手机降价大战),科学家们在研究让 AI 只"用部分大脑"完成任务(省电省钱),Google 把旗下工具名字统一叫 Gemini(就像苹果把所有东西都叫 Apple XXX)。

AI world this week: companies competing to see who can make models cheapest (like a smartphone price war), scientists figuring out how to use only part of the AI brain per task (efficiency), and Google renaming everything to Gemini (like Apple naming everything iPhone/iPad/iMac).