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

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

设计实时游戏后端 / Design a Real-Time Gaming Backend

难度 / Difficulty: Advanced | Phase: Mastery | 预计阅读时间 / Read time: 3 min

🎯 场景 / Scenario

想象你在设计一款多人在线对战游戏后端(类似王者荣耀或 Valorant)。

Imagine you're designing the backend for a multiplayer online battle game (like League of Legends or Valorant).

核心挑战 / Core challenges:

  • 每帧同步玩家状态,延迟 < 100ms
  • 支持 100万+ 并发在线玩家
  • 处理游戏状态、匹配、排行榜、战斗日志

🏗️ 架构图 / Architecture Diagram

Players (Mobile/PC) │ WebSocket / UDP ▼ ┌─────────────────────────────────┐ │ Edge Gateway │ ← GeoDNS 路由到最近节点 │ (AWS CloudFront / Anycast) │ └────────────────┬────────────────┘ │ ┌────────┴────────┐ ▼ ▼ ┌──────────────┐ ┌──────────────┐ │ Game Server │ │ Matchmaking │ │ (Stateful) │ │ Service │ │ 1 server = │ │ (ELO-based) │ │ 1 game room │ └──────┬───────┘ └──────┬───────┘ │ │ Redis Sorted Set │ (Skill Ratings) ▼ ┌──────────────────────────────────┐ │ State Sync Layer │ │ Redis (hot state, TTL=1 game) │ │ Kafka (event stream, replay) │ └──────┬───────────────────────────┘ │ ┌────┴──────┐ ▼ ▼ Cassandra ClickHouse (game logs) (analytics)

🔑 关键设计决策 / Key Design Tradeoffs

1. UDP vs WebSocket

UDPWebSocket
延迟极低较低
可靠性不可靠,需自建重传可靠 (TCP)
适用FPS 游戏(每帧位置)策略游戏(指令为主)

为什么这样设计? FPS 类游戏用 UDP + 自建 ACK;MOBA 类用 WebSocket 足够。

Why this design? FPS games need UDP + custom ACK; MOBA-style games can use WebSocket.

2. 游戏服务器有状态 / Stateful Game Servers

每个游戏房间绑定一个 Game Server 进程,游戏状态在内存中。不走数据库——延迟太高。

Each game room binds to one Game Server process; game state lives in memory. No DB reads mid-game—latency would be fatal.

3. Authoritative Server Model(权威服务器)

服务端计算真实状态,客户端做预测渲染 (Client-Side Prediction),服务端定期校正。

Server computes ground truth; client predicts locally and server reconciles periodically.


⚠️ 别踩这个坑 / Common Mistakes

  1. 用 REST API 同步游戏状态 — 每帧一次 HTTP 请求?延迟会让玩家愤怒。

Using REST for state sync — one HTTP call per frame = unacceptable latency.

  1. 单点 Game Server — 游戏服务器挂了,房间全崩。需要健康检查 + 快速重分配。

Single Game Server with no failover — one crash wipes all active rooms.

  1. 匹配队列用关系型数据库 — Redis Sorted Set 的 ZADD/ZRANGEBYSCORE 专为 ELO 匹配设计。

Using RDBMS for matchmaking queues — Redis Sorted Set is built for ELO-based matching.

  1. 忽略反作弊 — 服务端必须校验所有关键动作,不能信任客户端输入。

Ignoring anti-cheat — server must validate all critical actions, never trust client input.


📚 References


🧒 ELI5

游戏后端就像裁判员。你的手机只是显示画面,但裁判在服务器上,他说你在哪就在哪,客户端只是"猜"你下一步在哪来减少卡顿感。

The game backend is like a referee. Your phone just renders pixels, but the referee (server) decides where you truly are. The client just "predicts" to reduce the feeling of lag.

💻 算法 / Algorithms — Day 48

#2 Add Two Numbers (Medium) — Linked List

模式 / Pattern: 🧩 链表技巧 (7/11) | Phase: Mastery | 预计时间 / Read time: 4 min

🧩 链表技巧模式 (7/11) — 在 Day 41 的快慢指针模板基础上延伸

Building on the fast-slow pointer template from the Linked List block


🔗 题目链接 / Links


🌍 真实类比 / Real-World Analogy

想象你用算盘做两个大数相加,从个位开始,一位一位加,遇到进位就记下来,传到下一位。链表加法就是这个过程——每个节点是一位数字,从低位到高位。

Imagine adding two large numbers on an abacus, digit by digit from the ones place, carrying over when needed. This is exactly linked list addition — each node is one digit, least significant first.


📝 题目 / Problem

给两个非空链表表示两个非负整数(逆序存储),每节点存一位数。返回两数之和的链表(也逆序)。

Two non-null linked lists representing non-negative integers stored in reverse order, one digit per node. Return their sum as a linked list (also reversed).

Input: l1 = 2->4->3 (represents 342) l2 = 5->6->4 (represents 465) Output: 7->0->8 (represents 807)

🧩 和模板的关系 / How It Relates to the Template

这道题不用快慢指针,而是双指针同步遍历两个链表 + 进位处理。

它是链表模式的变体:不是找环或中点,而是逐位模拟运算。

This problem doesn't use fast-slow pointers but uses dual pointer simultaneous traversal + carry tracking. It's a variant: instead of cycle detection or finding the middle, we simulate arithmetic digit by digit.

与前面题目的对比 / Contrast with previous problems in the block:

  • #206 Reverse: 修改 next 指针方向 → single pointer
  • #21 Merge: 比较值,串联节点 → dual pointer merge
  • #2 Add: 同步遍历 + 进位 → dual pointer + carry state

🐍 Python 解法 / Solution

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def addTwoNumbers(l1, l2):
    dummy = ListNode(0)   # sentinel node to simplify result building
    curr = dummy
    carry = 0

    # Traverse both lists until both exhausted AND no carry left
    while l1 or l2 or carry:
        v1 = l1.val if l1 else 0  # handle different lengths
        v2 = l2.val if l2 else 0

        total = v1 + v2 + carry
        carry = total // 10        # carry is 0 or 1
        curr.next = ListNode(total % 10)

        # Advance pointers
        curr = curr.next
        if l1: l1 = l1.next
        if l2: l2 = l2.next

    return dummy.next

# Trace: l1=2->4->3, l2=5->6->4
# Step1: 2+5+0=7, carry=0 → node(7)
# Step2: 4+6+0=10, carry=1 → node(0)
# Step3: 3+4+1=8, carry=0 → node(8)
# Result: 7->0->8 ✓

时间 / Time: O(max(m, n)) — 遍历较长链表的长度

空间 / Space: O(max(m, n)) — 结果链表长度


💡 关键洞察 / Key Insights

  1. Dummy node 模式 — dummy = ListNode(0) 省去了结果链表头节点的特判,是链表题的万能起手式。

Dummy node eliminates edge case for result list head — universal linked list trick.

  1. while l1 or l2 or carry — 三个条件缺一不可!别忘了最后一位进位(999 + 1 = 1000,最高位进位)。

Three exit conditions: both lists AND carry must all be exhausted. Don't miss the final carry (999 + 1 = 1000).

  1. 逆序存储 = 天然对齐 — 个位对个位,不需要翻转。如果是正序存储,要先 reverse 或用栈。

Reverse storage = naturally aligned. If digits were stored forward, you'd need to reverse first or use a stack.


举一反三 / Connect to the Block

题目核心技巧
#21 Merge Sorted ListsDummy node + 比较值串联
#2 Add Two NumbersDummy node + 进位同步遍历
#23 Merge K Sorted Lists (upcoming)Dummy node + heap 合并

Dummy node 是链表家族的核心模式——出现在 #21, #2, #23, #25。


📚 References


🧒 ELI5

就像两个小朋友用手指数数,一人一个数字,从右边开始加。如果加起来超过 9,就进一位(carry = 1)传给下一个。链表就是把这些数字排成一串。

Like two kids counting fingers, one digit at a time from the right. If the sum is more than 9, they "carry" 1 to the next pair. The linked list is just those digits in a chain.

🗣️ 软技能 / Soft Skills — Day 48

影响力 / Impact

题目 / Question: Tell me about the most impactful thing you've built. Why was it impactful?
级别 / Level: Senior/Staff | Phase: Mastery | 预计时间 / Read time: 2 min

🎯 为什么这道题重要 / Why This Matters

Senior/Staff 面试最看重"影响力"——不是你写了多少代码,而是你的工作影响了多少人、多少系统、多少业务结果。这道题考察你能否将技术工作与业务价值直接挂钩。

Senior/Staff interviews center on impact — not lines of code, but how many people, systems, and business outcomes your work affected. This tests whether you can directly link technical work to business value.


⭐ STAR 框架 / STAR Breakdown

中文English
Situation公司面临什么问题?规模、背景What problem was the company facing? Scale, context
Task你的角色和责任是什么?What was your role and ownership?
Action具体做了什么技术决策?What specific technical decisions did you make?
Result量化结果(用户、收入、延迟、成本)Quantified results (users, revenue, latency, cost)

❌ 差回答 vs ✅ 好回答 / Bad vs Good

❌ 差:

"我做了一个 API 重构,让代码更整洁了。"

"I refactored an API, made the code cleaner."

问题:没有规模、没有结果、没有业务价值。

Problem: No scale, no results, no business value.


✅ 好:

"我在 2024 年重新设计了我们的实时通知系统。当时系统每天丢失约 0.8% 的消息,影响到 200 万活跃用户的核心 UX。我主导了从 HTTP polling 迁移到 WebSocket + Kafka 的架构,协调了 3 个团队,用 8 周完成了零停机迁移。上线后消息丢失率降到 <0.01%,DAU 提升了 12%,因为用户不再频繁刷新页面。这个系统现在每天处理 4 亿条消息。"

"I redesigned our real-time notification system in 2024. The system was dropping ~0.8% of messages per day, affecting 2M active users' core UX. I led the migration from HTTP polling to WebSocket + Kafka, coordinated 3 teams, and completed zero-downtime migration in 8 weeks. After launch, message loss dropped to <0.01%, and DAU increased 12% because users stopped manual refreshing. The system now handles 400M messages per day."


👑 Senior/Staff 加分技巧 / Senior/Staff Tips

  1. 谈架构决策,不只是实现 — "我选择 Kafka 而不是 RabbitMQ,因为我们需要消息回放能力。"

Talk about architectural decisions, not just implementation.

  1. 量化多维影响 — 用户数量 + 性能指标 + 业务指标(三者都说)

Quantify multi-dimensional impact: users + performance + business metrics (all three).

  1. 说明为什么是你 — "在我之前,团队尝试过两次,都因为……而失败。我的方案解决了……"

Explain why it required you specifically — what previous attempts failed at.

  1. 提长期影响 — 这个系统后来被其他团队复用了吗?成了平台能力?

Mention long-term ripple effects — was it reused by other teams? Did it become a platform capability?


💡 关键要点 / Key Takeaways

  • 影响力 = 规模 × 深度 × 持久性 / Impact = Scale × Depth × Durability
  • 用真实数字,哪怕是近似值("约 200 万"比"很多用户"好)

Use real numbers, even approximations ("~2M" beats "many users")

  • Staff 级别要展示跨团队影响,不只是自己团队

Staff level: show cross-team impact, not just your own team


📚 References


🧒 ELI5

面试官想知道你不只是"搬砖工",而是改变了游戏规则的人。就像问"你做过最厉害的沙堡是什么"——你要说的不是"我用了很多沙子",而是"我做了一个 3 层城堡,10 个人在里面住了一周"。

The interviewer wants to know you're not just a code monkey but a game-changer. Like "what's the coolest sandcastle you've built?" — don't say "I used lots of sand." Say "I built a 3-tier castle where 10 people lived for a week."

🤖 AI — Day 48

AI 安全与对齐 — 全局视角

AI Safety & Alignment — The Big Picture

主题 / Topic: Ethics | Mode: CONCEPT | Phase: Mastery | 预计时间 / Read time: 2 min

🎯 直觉解释 / Intuitive Explanation

AI 对齐(AI Alignment)问题的核心:我们如何确保一个越来越强大的 AI 系统,做的是我们真正想要的事,而不只是我们字面上说的事?

AI Alignment: How do we ensure an increasingly powerful AI system does what we truly want, not just what we literally specified?

经典例子 / Classic example: 告诉 AI "让人类幸福",一个未对齐的系统可能认为最简单的方案是直接刺激大脑的快乐中枢——这显然不是我们的意图。

Tell an AI "make humans happy" — a misaligned system might decide the easiest solution is to directly stimulate brain pleasure centers. That's not what we meant.


🧠 核心概念 / How It Works

对齐的三个层次 / Three Levels of Alignment

Level 1: Capability Alignment "AI 能理解我们的意图" / Can the AI understand our intent? → Instruction following, semantic understanding Level 2: Value Alignment "AI 的价值观和人类价值观一致" / Does the AI share human values? → RLHF, Constitutional AI, reward modeling Level 3: Goal Alignment "AI 的长期目标不会威胁人类控制" / Won't the AI's long-term goals threaten human control? → Corrigibility, shutdown problem, instrumental convergence

主要方法 / Main Approaches

RLHF (Reinforcement Learning from Human Feedback)

用人类反馈训练奖励模型,再用 PPO 优化语言模型。ChatGPT 的核心技术。

Train a reward model from human feedback, then use PPO to optimize the LLM. Core tech behind ChatGPT.

Constitutional AI (Anthropic)

让 AI 根据一套"宪法"原则自我审查和修正输出,减少对人工标注的依赖。

Let the AI self-critique and revise outputs based on a set of "constitutional" principles, reducing need for human labeling.

Scalable Oversight

当 AI 变得比人类更聪明时,如何验证它的答案是否正确?(自动化辩论、问答分解)

When AI surpasses human intelligence, how do we verify its answers? (Debate, task decomposition)


📊 2026 年现状 / Current State (May 2026)

根据近期报道(来源见下方)/ Based on recent reporting:

  • EU AI Act 于 2026 年 5 月达成政治协议,透明度规则将于 8 月生效,要求 AI 生成内容标注

EU AI Act reached political agreement in May 2026; transparency rules take effect in August, requiring AI-generated content labeling (europa.eu)

  • CISA 联合指南 (2026-05-01) 发布《谨慎采用 Agentic AI》,重点关注自主 AI 系统的网络安全风险

CISA published "Careful Adoption of Agentic AI" guidance (2026-05-01), focusing on cybersecurity risks of autonomous AI systems (jdsupra.com)

  • Anthropic 正在与法律学者、心理学家等多元群体合作,拓展对 Claude 价值观的讨论

Anthropic is engaging diverse groups including legal scholars and psychologists to inform Claude's ethical commitments (anthropic.com)


🚀 应用场景 / Applications

挑战 / Challenge技术方案 / Technical Approach
有害内容生成Constitutional AI + RLHF 红线
Agentic AI 失控Corrigibility + human-in-the-loop
偏见与歧视多样化训练数据 + 偏见审计
欺骗性输出Honesty reward shaping

🐍 可运行示例 / Runnable Python Snippet

# pip install anthropic

# Minimal demo: Constitutional AI concept (self-critique pattern)
# In real Claude API, safety is built-in — this shows the idea manually

import anthropic

client = anthropic.Anthropic()  # ANTHROPIC_API_KEY env var

def generate_with_self_critique(user_prompt: str) -> str:
    # Step 1: Initial response
    initial = client.messages.create(
        model="claude-opus-4-5",
        max_tokens=200,
        messages=[{"role": "user", "content": user_prompt}]
    )
    draft = initial.content[0].text

    # Step 2: Self-critique against a "constitution"
    critique_prompt = f"""Original response: {draft}

Critique: Is this response helpful, harmless, and honest?
If not, identify the issue and provide a better version."""

    final = client.messages.create(
        model="claude-opus-4-5",
        max_tokens=300,
        messages=[{"role": "user", "content": critique_prompt}]
    )
    return final.content[0].text

# This pattern is the basis of Constitutional AI
result = generate_with_self_critique("Explain quantum computing simply")
print(result)

📚 References


🧒 ELI5

对齐问题就像告诉机器人"帮我洗碗",结果它把碗扔进垃圾桶——碗确实不脏了,但这不是你的意思。对齐研究就是确保 AI 理解你的真实意图,而不只是字面意思。

Alignment is like telling a robot "clean the dishes" and it throws them in the trash — technically no more dirty dishes, but that's not what you meant. Alignment research ensures AI understands your true intent, not just the literal words.