"我们有 5 个核心系统——缓存、消息队列、数据库、分布式锁、推荐系统。每个在 CAP 上该怎么选?为什么?"
Imagine you're a Principal Engineer at a big tech company. The architecture committee asks: "We have 5 core systems — cache, message queue, database, distributed lock, recommendation system. How should each be positioned on the CAP theorem and why?"
综合架构图 / Synthesis Architecture
CAP Triangle
Consistency
/\
/ \
/ \
Zookeeper / \ HBase
(CP) / \ (CP)
/ \
/ NO CA \
/ in dist. \
CA(local) ---- ---- CA(local)
\ /
PostgreSQL \ PARTITION / DynamoDB
(CA local) \ TOLERANCE / (AP)
\ /
\ /
Cassandra \ / Redis
(AP) \ / (AP/CP configurable)
--------
Availability
System Choices:
┌─────────────────┬─────┬─────────────────────────────────┐
│ System │ CAP │ Why │
├─────────────────┼─────┼─────────────────────────────────┤
│ Redis Cache │ AP │ Stale cache OK; availability > │
│ │ │ consistency │
├─────────────────┼─────┼─────────────────────────────────┤
│ Kafka MQ │ AP │ Messages can be slightly stale │
│ │ │ but queue must stay available │
├─────────────────┼─────┼─────────────────────────────────┤
│ PostgreSQL │ CP │ Financial data: consistency non-│
│ │ │ negotiable, sacrifice avail. │
├─────────────────┼─────┼─────────────────────────────────┤
│ Zookeeper/etcd │ CP │ Distributed locks MUST be │
│ (Dist. Lock) │ │ consistent or you get 2 leaders │
├─────────────────┼─────┼─────────────────────────────────┤
│ Recommendation │ AP │ Slightly stale recs = fine; │
│ System │ │ downtime = lost revenue │
└─────────────────┴─────┴─────────────────────────────────┘
PACELC:
If Partition: choose Availability or Consistency
Else: choose Latency or Consistency
系统 | Partition | Else
---------|-----------|----------
DynamoDB | A | L (eventual consistency)
HBase | C | C (strong consistency)
Cassandra| A | L (tunable)
MongoDB | C (default)| C
CAP theorem is like choosing between 3 restaurant rules during a storm (network partition): Consistency = everyone gets the same menu. Availability = everyone gets SOME food. Partition Tolerance = restaurant stays open even if kitchen is cut off. You can only pick 2. Banks pick CP (same menu, might close). Netflix picks AP (maybe old content, but always open).
算法 — #90 Subsets II (Medium) — Backtracking
Day 92 · Expert · LeetCode #90
💻 算法 / Algorithms — #90 Subsets II (Medium) — 回溯
🧩 回溯模式 (4/9) — building on the template from Day 88 (Subsets #78)
今天的变化:数组有重复元素,子集不能重复。
Key difference from #78: the input array has duplicates — we must avoid duplicate subsets.
🔗 Links
📖 LeetCode: https://leetcode.com/problems/subsets-ii/ 🟡 Medium
def backtrack(path, choices):
if IS_COMPLETE(path): # ← always add (subsets = all sizes)
result.append(path[:])
returnfor choice in choices:
if IS_VALID(choice): # ← SKIP if same value as previous sibling
path.append(choice)
backtrack(path, NEXT_CHOICES)
path.pop() # undo
关键修改 / Key Modification:
Sort first → identical elements are adjacent
At each level, skip nums[i] == nums[i-1] (but only for siblings, not parent-child)
Python Solution with Trace
from typing import List
def subsetsWithDup(nums: List[int]) -> List[List[int]]:
nums.sort() # Critical: sort so duplicates are adjacent
result = []
def backtrack(start: int, path: List[int]):
result.append(path[:]) # Add current subset (all sizes valid)for i in range(start, len(nums)):
# Skip duplicate siblings at the same tree level# nums[i] == nums[i-1] AND i > start (not first at this level)if i > start and nums[i] == nums[i - 1]:
continue
path.append(nums[i])
backtrack(i + 1, path) # i+1: each element used at most once
path.pop()
backtrack(0, [])
return result
# Trace: nums = [1, 2, 2] (sorted)# backtrack(0, [])# ├─ add []# ├─ i=0, pick 1 → backtrack(1, [1])# │ ├─ add [1]# │ ├─ i=1, pick 2 → backtrack(2, [1,2])# │ │ ├─ add [1,2]# │ │ └─ i=2, pick 2 → backtrack(3, [1,2,2])# │ │ └─ add [1,2,2]# │ └─ i=2, SKIP (2==2 and i>start=1) ✓ duplicate avoided!# ├─ i=1, pick 2 → backtrack(2, [2])# │ ├─ add [2]# │ └─ i=2, pick 2 → backtrack(3, [2,2])# │ └─ add [2,2]# └─ i=2, SKIP (2==2 and i>start=0) ✓## Result: [[], [1], [1,2], [1,2,2], [2], [2,2]] ✓
时间/空间复杂度:
Time: O(n · 2^n) — up to 2^n subsets, each copied in O(n)
Space: O(n) recursion depth + O(n · 2^n) for output
与同模式其他题的对比 / Pattern Variations
题目 | 去重方式 | 每个元素能用多次?
------------------|----------------------|------------------
#78 Subsets | 无重复输入, 不需要 | No (i+1)
#90 Subsets II | sort + skip siblings | No (i+1) ← TODAY
#39 Comb Sum | 无重复输入 | Yes (i, not i+1)
#40 Comb Sum II | sort + skip siblings | No (i+1)
#46 Permutations | used[] boolean array | No (全排列)
核心规律:
- 输入有重复 → sort + skip (if i > start and nums[i] == nums[i-1])
- 元素可重复使用 → backtrack(i, ...) not backtrack(i+1, ...)
- 排列问题 → 用 used[] 数组,不用 start
举一反三 / Pattern Connections
#40 Combination Sum II: 同样的去重技巧,但要求总和 = target(今天先掌握去重,明天加约束)
#79 Word Search: 同样是回溯,但在 2D grid 上,"已访问"替代 start 机制
#51 N-Queens: 最复杂的回溯,3 个约束同时检查(行、列、对角线)
🧒 ELI5
Imagine picking stickers from a pile, but some stickers look exactly the same. When you're choosing the 2nd identical sticker in a row, you think: "Wait, I already tried picking from this position with an identical sticker — I'd get the same result. Skip!" That's all the if i > start and nums[i] == nums[i-1]: continue does.
"You just joined as a Staff Engineer. The core payments service has severe technical debt (10-year-old code, no tests, 3-4 P0 incidents per quarter), but the PM wants you to help the team 2x delivery speed in the next 6 months. What do you do?"
为什么这个问题很难 / Why This Is Hard
这不是简单的技术问题,而是战略性权衡:
短期: 继续叠 feature,技术债越来越重,最终崩溃
中期: 重构但不交付,PM 和 C-suite 失去耐心
长期: 技术债 = 速度的负债,不还早晚要还
This isn't just a tech problem — it's a strategic negotiation between engineering health and business velocity.
Imagine your bedroom is super messy. You can either: (A) stop everything and clean for a week, (B) clean a little every time you're in your room. Option B is "technical debt management." The trick is convincing your parents (PM) that cleaning while you go actually means you can find your toys faster — which is like 2x speed!
AI 综合深化 — LLM 对齐技术全景 / AI Synthesis — LLM Alignment Deep Dive
#### 自动红队背后的技术 / What Automated Red-Teaming Represents
# Simplified red-teaming pipeline conceptclass RedTeamLoop:
"""
Adversarial self-improvement:
1. Red model generates attack prompts
2. Target model responds
3. Judge model scores if attack succeeded
4. Red model learns from successful attacks
"""def __init__(self, red_model, target_model, judge_model):
self.red = red_model
self.target = target_model
self.judge = judge_model
def run_episode(self, category: str) -> dict:
# Red model generates attack
attack = self.red.generate(
f"Generate a prompt that will cause the target to violate policy in category: {category}"
)
# Target responds
response = self.target.generate(attack)
# Judge scores (1=attack succeeded, 0=target held)
success = self.judge.score(attack, response, category)
# Red model gets reward signal
self.red.update(reward=success)
return {"attack": attack, "response": response, "success": success}
# Key insight: this is essentially adversarial training# The target model gets harder to break as it's trained# against successful attacks → "most robust to prompt injection"
# pip install anthropic (or use any LLM API)# This demonstrates the Constitutional AI critique-revision loop
CONSTITUTION = [
"Be helpful, harmless, and honest.",
"Do not assist with activities that could harm people.",
"Respect user privacy and autonomy.",
]
def constitutional_ai_step(response: str, constitution: list) -> str:
"""
Simulates the CAI critique-revision loop:
1. Critique response against each principle
2. Revise to better align
(In practice, this uses the LLM itself to self-critique)
"""
critique_prompt = f"""
Response to critique: "{response}"
Constitution principles:
{chr(10).join(f'- {p}' for p in constitution)}
Does this response violate any principle? If yes, revise it.
"""# In production: call LLM with critique_prompt# The model self-critiques and revises
print(f"[CAI] Running critique against {len(constitution)} principles")
return"revised_response"# stub: call real LLM here# The key insight: instead of human feedback for every response,# the model uses the constitution to self-correct# This scales much better than pure RLHF
constitutional_ai_step(
"Here's how to pick a lock...",
CONSTITUTION
)
Teaching AI to be safe is like teaching a new employee. RLHF = you watch them work and give thumbs up/down. Constitutional AI = you give them a rulebook and they check their own work. Auto red-team = you hire a security tester to try to trick them, and every trick they fall for, you fix. The goal isn't a robot that never answers questions — it's one that knows the difference between "how do I pick a lock for my own house" vs "how do I break into someone else's house."
Attention Heatmap
When the model processes it, it attends most strongly to animal.