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

🏗️ 系统设计 / System Design — Day 108 (Synthesis)

一次请求的解剖 / Anatomy of a Production Request: 10 Systems in 100ms

综合回顾 / Synthesis Review — Expert Level

当用户在手机上点击"发送",接下来 100ms 内发生了什么?这是一个把我们过去几个月学到的所有系统设计知识串联起来的机会。

When a user taps "Send" on their phone, what happens in the next 100ms? This is your chance to connect every system design concept we've learned.


📍 完整请求链路 / The Complete Request Journey

User Phone │ ▼ [1] DNS Resolution (Anycast → nearest PoP) │ ~5ms (cached) or ~50ms (cold) ▼ [2] CDN / Edge (Cloudflare, Fastly) │ Static assets served here. Cache-hit = done in <10ms. │ Cache-miss → forward to origin ▼ [3] Load Balancer (L4/L7, e.g. AWS ALB) │ Health checks, sticky sessions, weighted routing ▼ [4] API Gateway (Kong, AWS APIGW) │ Auth (JWT verify), rate limiting, request validation ▼ [5] Rate Limiter (Token Bucket / Sliding Window) │ Redis-backed. 429 if exceeded. ▼ [6] App Server (Kubernetes Pod) │ Business logic. Check cache first! ▼ [7] Cache (Redis / Memcached) │ Cache hit → return immediately (~1ms) │ Cache miss → query DB ▼ [8] Database (Primary + Read Replica) │ Read from replica, write to primary │ Indexed queries: ~5-20ms ▼ [9] Distributed Tracing (Jaeger / OpenTelemetry) │ trace_id propagated through ALL hops ▼ [10] Monitoring / Alerting (Datadog / Prometheus) Metrics: latency p50/p95/p99, error rate, saturation

🔗 各层关键设计决策 / Key Design Decisions at Each Layer

1. DNS + CDN

  • Anycast routing → 用户被路由到最近的 PoP (Point of Presence)
  • CDN 缓存静态资源 (HTML, JS, images);API calls 通常不缓存
  • TTL 设置很重要:太长→部署慢,太短→DNS 压力大

2. Load Balancer

  • L4 (TCP level) vs L7 (HTTP level) — L7 更智能但开销更高
  • 算法:Round Robin, Least Connections, IP Hash (sticky sessions)
  • 健康检查:每 10s 一次,3次失败则摘除节点

3. API Gateway + Rate Limiter

  • 将横切关注点 (auth, rate limit, logging) 从业务代码剥离
  • Rate limiter 需要用 Redis 实现分布式限流,单机限流没有意义
  • 为什么不在 LB 层做 rate limit? → LB 无法识别用户身份

4. Cache 策略

  • Read-through: App 层透明,缓存代为查 DB
  • Write-through: 写 DB 同时写缓存,一致性好但写慢
  • Write-behind (Write-back): 先写缓存,异步写 DB,快但有丢失风险
  • 今天最常用:Cache-aside (Lazy loading)

5. Database

  • 主从分离:写主库,读从库
  • 连接池:不要每次请求新建连接 (pgbouncer, HikariCP)
  • 慢查询日志 → 找到未加索引的查询

⚡ 延迟预算 / Latency Budget (Target: <100ms p99)

LayerBudgetOptimization
DNS0ms (cached)Long TTL for stable services
CDN5msEdge cache, HTTP/3
LB + Gateway2msKeep it lightweight
Rate Limiter1msRedis pipelining
App Logic10msAvoid N+1 queries
Cache Hit1msRedis in same VPC
Cache Miss + DB30-50msIndexes, read replicas
Total~70ms30ms buffer for tail latency

🔴 常见陷阱 / Common Architectural Mistakes

  1. 跳过 CDN → 把静态资源请求打到 origin,浪费带宽和计算
  2. 单点 Redis → 缓存挂了整个系统崩溃,要用 Redis Cluster 或 Sentinel
  3. 在 app server 做 auth → 每个 service 都要重新实现,应该在 API Gateway 统一处理
  4. 不传递 trace_id → 出了问题无法跨服务追踪
  5. 忘记熔断器 → 下游服务超时会让 app server 线程耗尽 (thread pool exhaustion)

💡 面试中如何讲这个 / How to Present This in Interviews

Senior/Staff 级别面试官最欣赏的不是"你知道所有组件",而是:

  • 你知道为什么每层存在(职责分离)
  • 你能讨论权衡(CDN 带来复杂性,但值得)
  • 你关心延迟预算(100ms 是用户感知的临界点)
  • 你考虑故障模式(每层挂掉会发生什么)

The key signal for senior+ interviews: can you reason about which layer owns which concern and what breaks when each layer fails?


📚 References

  • https://www.cloudflare.com/learning/cdn/what-is-a-cdn/
  • https://www.nginx.com/blog/introduction-to-microservices/
  • https://aws.amazon.com/architecture/well-architected/

🧒 ELI5

想象你去麦当劳点汉堡:收银员(LB)分配任务→厨师检查食材架(Cache)→如果没有去仓库取(DB)→包装员验证订单(API Gateway)→监控员确保质量(Monitoring)。每个人各司其职,整个流程才能在 2 分钟内完成。
Imagine ordering at McDonald's: cashier (LB) routes your order → cook checks the ingredient rack (Cache) → if empty, fetches from storage (DB) → wrapper validates the order (API Gateway) → quality monitor checks everything (Monitoring). Everyone has one job — that's why it works fast.

💻 算法 / Algorithms — Day 108

🧩 图遍历模式 (6/13) — Pacific Atlantic Water Flow

在 Day 101 的模板基础上进阶 / Building on the BFS/DFS template from Day 101

这道题的特别之处:不是"从起点出发找终点",而是反向思维 — 从两个大洋的边界逆流而上,找能同时到达两个大洋的格子。

What makes this different: instead of flowing downhill from cells to ocean, we reverse the direction — BFS/DFS uphill from both ocean boundaries, find cells reachable from both.


🔗 题目链接 / Links


🌊 真实场景类比 / Real-World Analogy

想象一个地形图:左上角是太平洋,右下角是大西洋。雨水从高处流向低处,最终流入大洋。哪些格子的雨水同时能流进两个大洋?

这就像找"双重流域分水岭"— 那些既属于太平洋流域、又属于大西洋流域的高地。

Imagine a terrain map: Pacific is top-left/left/top edges, Atlantic is bottom-right/right/bottom edges. Water flows downhill. Which cells can reach both oceans?


💡 核心洞察 / Key Insight: 逆流思维

正向思维(难): 从每个格子 DFS,看能不能同时到达两个海岸 → O(m×n×(m×n)) 太慢

逆向思维(优):

  1. 从太平洋边界出发,BFS 逆流向上(只走不低于当前高度的格子)→ 标记所有能流入太平洋的格子
  2. 从大西洋边界出发,同理
  3. 两个集合的交集就是答案

Naive: DFS from every cell to check both oceans → O(m²n²)

Smart: BFS backward from ocean boundaries → O(mn)


🐍 Python 解法 / Solution

from collections import deque
from typing import List

def pacificAtlantic(heights: List[List[int]]) -> List[List[int]]:
    if not heights:
        return []
    
    rows, cols = len(heights), len(heights[0])
    
    def bfs(starts):
        """BFS from boundary, going uphill (reverse flow)"""
        visited = set(starts)
        queue = deque(starts)
        
        while queue:
            r, c = queue.popleft()
            for dr, dc in [(0,1),(0,-1),(1,0),(-1,0)]:
                nr, nc = r + dr, c + dc
                if (0 <= nr < rows and 0 <= nc < cols
                        and (nr, nc) not in visited
                        and heights[nr][nc] >= heights[r][c]):  # uphill!
                    visited.add((nr, nc))
                    queue.append((nr, nc))
        return visited
    
    # Pacific: top row + left column
    pacific_starts = [(r, 0) for r in range(rows)] + [(0, c) for c in range(cols)]
    # Atlantic: bottom row + right column
    atlantic_starts = [(r, cols-1) for r in range(rows)] + [(rows-1, c) for c in range(cols)]
    
    pacific_reachable = bfs(pacific_starts)
    atlantic_reachable = bfs(atlantic_starts)
    
    # Intersection = can reach both
    return [[r, c] for r, c in pacific_reachable & atlantic_reachable]

🔍 执行追踪 / Trace (3×3 example)

heights = [ [1, 2, 2], [3, 2, 3], [2, 4, 5] ] Pacific starts: (0,0),(1,0),(2,0),(0,1),(0,2) Atlantic starts: (0,2),(1,2),(2,2),(2,0),(2,1) Pacific BFS (uphill from left/top): → visits: (0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2) almost all Atlantic BFS (uphill from right/bottom): → starts at (2,2)=5, can go to (2,1)=4, (1,2)=3, etc. Intersection → cells reachable from both Result: [[0,2],[1,2],[1,1],[2,0],[2,1],[2,2]]

⏱️ 复杂度 / Complexity

TimeSpace
BFS×2O(m×n)O(m×n)
vs NaiveO(m²n²)O(mn)

🔄 模板变体对比 / Template Variation vs Previous Problems

ProblemStart PointDirectionGoal
#200 IslandsAny unvisited landAll 4 dirs (same height)Count components
#994 Rotting OrangesAll rotten cellsBFS outwardMin time
#417 Pacific AtlanticBoth ocean boundariesUphill (≥ current)Intersection of two BFS

关键变体 / Key twist: 两次独立 BFS + 求交集。这个"从边界逆流"的技巧在很多矩阵题里都会出现!


举一反三 / Related Problems in This Block

  • #130 Surrounded Regions (Day 109): 同样用"从边界出发"思路,标记不被围的 'O'
  • #207 Course Schedule (Day 110): 图的有向性,拓扑排序检测环
  • 逆向BFS 是一个通用技巧:当正向太慢时,考虑从目标反推

📚 References

  • https://leetcode.com/problems/pacific-atlantic-water-flow/editorial/
  • https://neetcode.io/problems/pacific-atlantic-water-flow
  • https://en.wikipedia.org/wiki/Drainage_basin

🧒 ELI5

想象地图上有两片海。从每片海的海岸线开始,逆着水流方向(往高处走),把能到达的格子都涂色。太平洋涂蓝色,大西洋涂红色。最后找紫色格子(蓝+红)就是答案!

Imagine coloring from each ocean's shoreline, going uphill. Pacific turns cells blue, Atlantic turns them red. Cells that get colored purple (both) are your answer!

🗣️ 软技能 / Soft Skills — Day 108 (Synthesis)

如何在压力下展示系统思维 / Demonstrating Systems Thinking Under Pressure

综合场景 / Synthesis Scenario — Staff Engineer Level

🎯 场景 / The Scenario

面试官问 / Interviewer asks:
"我们的核心支付流程每天有 5% 的事务失败,工程师们认为是数据库问题,产品认为是前端 bug,运维认为是网络抖动。作为新上任的 Staff Engineer,你怎么处理这个局面?"
"Our core payment flow has a 5% transaction failure rate daily. Engineers blame the database, product thinks it's a frontend bug, ops suspects network flakiness. As a newly promoted Staff Engineer, how do you handle this?"

❌ 初级工程师的答案 / Junior Answer

"我会让大家开个会讨论,然后投票决定先查哪个方向。"

"I'd call a meeting, have everyone share their theories, and we'd vote on which direction to investigate first."

为什么不够好: 没有结构,没有数据驱动,容易陷入政治博弈而不是解决问题。


✅ Staff 级别的答案框架 / Staff-Level Framework

Step 1: 先建立共同事实基础 (Before the debate)

"在我们讨论原因之前,我需要确认:
- 这 5% 是什么时间段的?全天均匀分布还是有峰值?
- 错误类型是什么?timeout?4xx?5xx?
- 最近有什么变更?(代码、配置、流量)"

目的: 把争论从"我的直觉 vs 你的直觉"转向"数据说明了什么"

Step 2: 并行调查,不是串行 (Parallel investigation)

同时开三条线:
① 数据库团队:查慢查询日志,看 5% 失败时段的 DB 指标
② 前端团队:查 JS error log,失败是在 submit 前还是 submit 后?
③ 运维团队:查网络延迟监控,失败时是否有 packet loss spike

给出明确时间盒:2小时内各出一页数据报告

Step 3: 相关性分析 (Correlation, not assumption)

把三条线的数据放在同一时间轴上: - 如果 DB 慢查询 和 支付失败 完全重叠 → DB 是根因 - 如果前端错误发生在 network call 之前 → 前端 bug - 如果所有指标都正常但失败率高 → 第三方支付 API 问题(被遗漏的假设!)

Step 4: 短期 vs 长期 (Decouple mitigation from fix)

短期(今天):
- 给支付加重试逻辑(idempotency key 确保安全重试)
- 监控告警:失败率 >2% 立即通知

长期(这周):
- 找到根因,彻底修复
- 加分布式追踪(trace_id 贯穿全链路),避免下次猜谜

🎖️ Senior/Staff 关键能力展示 / What This Shows Interviewers

  1. 不被政治裹挟 — 用数据而不是职位/声量决定方向
  2. 系统性思维 — 想到被所有人遗漏的第三方 API 假设
  3. 并行而非串行 — 不让组织陷入"等一个团队查完再查下一个"
  4. 解耦缓解与根治 — 先保用户体验,再慢慢修复
  5. 提升可观测性 — 解决问题的同时让下次更容易解决

💬 关键台词 / Phrases That Land Well

  • "Let's align on the facts before we align on the solution."(先对齐事实,再对齐方案)
  • "I want to run these investigations in parallel to avoid 3 days of serial blame."(并行调查,避免串行甩锅)
  • "What's our mitigation plan while we find the root cause?"(找根因的同时怎么保住用户体验?)

📚 References

  • https://www.atlassian.com/incident-management/postmortem/blameless
  • https://sre.google/sre-book/postmortem-culture/
  • https://charity.wtf/2020/11/14/the-engineer-staff-engineer-gap/

🧒 ELI5

三个人争论"为什么房间里有水":一个说管道漏了,一个说窗户没关,一个说屋顶破了。聪明的人先拿手机看天气预报,再检查三个地方,而不是让大家吵架。

Three people arguing about why the room is wet: one blames pipes, one blames the window, one blames the roof. The smart person checks the weather forecast first, then inspects all three — instead of letting everyone argue.

🤖 AI — Day 108 (Synthesis + News)

AI 新闻速递 / AI News Roundup — August 5, 2026


📰 本周大事 / This Week's Top Stories

1. 🤖 Claude 证明87年数学猜想

Anthropic 的 Claude Fable 5 模型据报道发现了 Jacobian 猜想(一个87年未解的数学难题)的反例,引发数学界震动。

Anthropic's Claude Fable 5 reportedly discovered a counterexample to the Jacobian conjecture — an 87-year-old unsolved math problem — sending shockwaves through the math community.

📎 Source: https://www.aiapps.com/blog/ai-news-august-breakthroughs-launches-trends-cant-miss/


2. 💰 GPT-5.6 价格暴降 80%

OpenAI 将其 GPT-5.6 Luna 模型价格削减 80%,降至每百万 token 仅 $0.20,标志着 LLM 进入"大宗商品化"阶段。谷歌同步跟进价格战。

OpenAI slashed GPT-5.6 Luna pricing by 80% to $0.20/1M input tokens. Google followed suit. LLMs are becoming commodities — the real competition is now on context, latency, and integration.

📎 Source: https://buttondown.com/agent-k/archive/llm-daily-august-05-2026/


3. 🌍 EU AI Act 透明度义务正式生效

2026 年 8 月 2 日,《欧盟 AI 法案》透明度条款正式实施。凡向欧盟市场提供 AI 系统的全球厂商,均须满足信息披露要求,违者面临巨额罚款。

The EU AI Act's transparency obligations took effect August 2, 2026. Any AI provider placing systems on the EU market or whose AI outputs are used in the EU must comply — globally. Non-compliance triggers significant fines.

📎 Source: https://www.cooley.com/news/insight/2026/2026-08-03-eu-ai-act-transparency-obligations-take-effect-2-august-2026


4. 🤖 AI Agent 全面落地

  • Google: 将 Gemini 集成进 Android,取代 Google Assistant;推出 Gemini Spark(云端常驻 agent,据报道 $99.99/月)
  • Anthropic: 推出 Claude Cowork,桌面端 multi-step agent,据报道 $20/月
  • ChatGPT: 据报道周活跃用户约 10 亿

Agents are no longer demos — they're shipping products. The race is now about distribution + reliability, not just raw capability.

📎 Source: https://www.aiapps.com/blog/ai-news-august-breakthroughs-launches-trends-cant-miss/


🔍 工程师视角 / Engineer's Take

这周的新闻有一个共同主题:AI 正在脱离"实验室玩具"阶段。

  1. 价格战 → API 成本下降对开发者是利好,但对 AI 公司的商业模式是压力
  2. Agent 商品化 → 真正的护城河在于数据、分发渠道、垂直领域集成
  3. 监管落地 → EU AI Act 会推动整个行业向透明度和可解释性投资
  4. 数学突破 → AI 辅助科研的速度在加快,不只是写代码

The through-line: AI is commoditizing fast. The question for engineers: what layer do you build on, and how do you add value that's not easily replicable by the next model version?


📚 References

  • https://www.aiapps.com/blog/ai-news-august-breakthroughs-launches-trends-cant-miss/
  • https://buttondown.com/agent-k/archive/llm-daily-august-05-2026/
  • https://www.cooley.com/news/insight/2026/2026-08-03-eu-ai-act-transparency-obligations-take-effect-2-august-2026
  • https://simonwillison.net/2026/Aug/4/new-release-of-llm/

🧒 ELI5

AI 这周的新闻就像:苹果手机越来越便宜(价格战)、手机助手越来越聪明能自己干活(Agent)、政府开始管手机说明书要写清楚功能(EU法规)、而且手机竟然帮数学家解出了87年没解开的题目。厉害的是:这全是同一周发生的。

This week's AI news is like: smartphones getting way cheaper (price war), phone assistants getting smart enough to do your chores (agents), governments saying you must write clear manuals (EU regs), and one phone solved an 87-year-old math problem. The wild part: all in one week.