Interview Bank
328 questions total; 1 shown with current filters.
CourseAllFrom Frontend Engineer to Agent Engineer in 30 DaysPrompt Engineering From Scratch in 5 DaysMastering Claude: From Conversation to Claude Code in 5 DaysMastering Codex and the OpenAI Agents SDK in 5 DaysMCP in 7 Days: Wire Tools Into Any AgentAgent Skills in 7 Days: Turn Experience Into Reusable CapabilityContext Engineering in 5 DaysRAG in 14 Days: From Retrieval to Trustworthy AnswersBuild an AI Short-Drama Production Pipeline With Agents in 14 Days
Tag
All#fencing-token1#evaluation13#cost11#reliability11#agent-skills7#security6#idempotency5#streaming5#system-design5#prompt-injection4#architecture3#observability3
126 more tagsShow fewer tags
#agent-loop2#api-design2#chunking2#cost-tradeoff2#debugging2#distributed-systems2#error-handling2#hybrid-search2#llm-as-judge2#multi-agent2#multi-hop2#oauth2#operations2#pipeline-design2#prompt-caching2#rag2#recall2#retrospective2#retry2#scheduling2#sse2#tool-permissions2#trade-offs2#access-control1#agentic-rag1#agents-sdk1#analytics1#architecture-review1#behavioral1#budget-control1#caching1#cancellation1#checkpointing1#circuit-breaker1#citation-verification1#client1#client-integration1#coding-agent1#compaction1#compliance1#concurrency1#confused-deputy1#context-engineering1#contextual-retrieval1#copyright1#correctness1#cost-control1#customer-support1#data-quality1#database1#deployment1#distribution1#embedding-migration1#error-propagation1#escalation1#evidence1#faithfulness1#fallback1#feedback-loop1#filter-pushdown1#filtering1#framework-design1#graph-rag1#guardrails1#handoff1#image-generation1#integration1#iterative-scan1#json-parsing1#labeling1#latency1#latency-budget1#least-privilege1#long-context1#long-session1#long-term-memory1#mcp1#message-bus1#methodology1#model-migration1#multi-tenancy1#notifications1#ocr1#offline-testing1#project-storytelling1#protocol-versions1#quality1#query-rewriting1#rate-limiting1#reconnect1#refusal1#replay1#reproducibility1#rerank1#resume1#retrieval1#risk-assessment1#rollout1#routing1#runtime1#safety1#scaling1#self-introduction1#split-brain1#state-management1#state-persistence1#statelessness1#stdio-transport1#storytelling1#subagent1#subagents1#subscriptions1#test-strategy1#thresholds1#timezone1#token-accounting1#tool-design1#tool-schema1#tools1#trust-boundary1#ux1#verification1#versioning1#workflow-design1#workflow-engine1#zero-downtime1
From Frontend Engineer to Agent Engineer in 30 Days
D10 Sharding and Leases: Hashing userId → shard, SET NX + TTL + Lua Renewal, Per-User Ordering, Handoff
What happens when two workers both believe they hold the same shard lease (split brain), and how do you mitigate it?两个 worker 同时认为自己持有同一个 shard 的租约(脑裂)会造成什么后果,怎么规避?
Common in ChinaCommon overseasDeep dive#split-brain#fencing-token#reliabilityHow to reason about it · think before answering
- The scoring criterion here is explicit: does your answer contain the sentence 'a Redis lease alone cannot give absolute mutual exclusion'. Anyone who says SET NX plus a TTL makes it safe gets probed until they run out of answers.
- Start with how split brain arises, and use the common case: not a crash, but a holder that merely froze for five seconds — a full GC, a noisy neighbour saturating the host CPU, cgroup throttling. It wakes up still believing it holds shard 68, keeps processing the in-flight message and keeps writing, while the lease expired and was taken. Add the second layer: Redis replication is asynchronous, so a failover can lose the last few milliseconds of writes and let two workers both win SET NX.
- Then the consequences, expressed in business terms rather than 'inconsistent data': two messages from one user processed concurrently means out-of-order replies, a corrupted context window, and unique(run_id, seq) violations that silently drop a message. Worst is reordered or duplicated side effects — swap 'cancel the order' with 'move the delivery date' and you cancel an order the user wanted to keep.
- The key shift: since you cannot rule out that timeline on the Redis side, the goal is not to prevent split brain but to make the second writer's writes fail — push conflict detection and rejection down to the layer that actually causes side effects.
- Give three mitigations by value. First, a self-kill rule in the worker: after two consecutive renewal failures, or when the last success is older than two thirds of the TTL, stop processing and clear the held set — cheapest, and it bounds the 'I think I still hold it' window to two renewal periods. Second, fencing tokens: take a monotonically increasing number (Redis INCR) when acquiring, store it in the lease value, attach it to every side-effecting operation, and have the downstream accept only numbers not lower than the highest it has seen — in a database that is one conditional update. The revived predecessor carries a stale number and is rejected. Third, re-validate the lease immediately before each write inside the same script or transaction, which shrinks the window without closing it.
- Expect the follow-up: where does fencing break down? It needs downstream cooperation. Databases do conditional updates, but a third-party endpoint (SMS, payments) will not compare your token, so you fall back to idempotency keys that make duplicate execution harmless rather than impossible. True mutual exclusion means moving to a consensus-backed system such as etcd or ZooKeeper session leases, paying in write latency and operational complexity.
分析过程 · 先想清楚再作答
- 这题的判分点非常明确:答案里有没有出现「单靠 Redis 租约做不到绝对互斥」。说「用了 SET NX 加 TTL 就安全了」的人,会被追问到答不上来。
- 先讲脑裂是怎么发生的,而且要举那个最常见的场景——不是进程崩溃,是持有者只卡了 5 秒:一次 full GC、宿主机 CPU 被邻居打满、容器被 cgroup 限流。它醒过来时内存里还写着「我持有 shard 68」,继续处理手上那条消息、继续写库,而 Redis 里的租约早已到期并被别人抢走。再补一层:Redis 主从复制是异步的,切主时可能丢掉最后几毫秒的写入,于是两个 worker 都能 SET NX 成功。
- 然后讲后果,而且要落到业务上而不是停在「数据不一致」:同一个用户的两条消息被两个进程并发处理,回复乱序、上下文错乱、messages 表的 unique(run_id, seq) 撞约束导致落库失败;最严重的是有副作用的工具被重排或重复执行——「取消订单」和「改配送日期」顺序反了,结果是取消了一个用户本来想留下的订单。
- 关键的认知转折:既然无法在 Redis 一侧排除这条时间线,正确的思路就不是「让脑裂不发生」,而是「让第二个人的写入落不了地」——把冲突的检测与拒绝推到真正产生副作用的那一层。
- 三条手段按性价比给出。一是 worker 自己的自杀规则:连续两次续约失败、或距上次成功续约超过 TTL 的三分之二,立刻停止处理并清空持有集合——最便宜,把「我以为我还持有」的窗口从无限压到两个续约周期。二是 fencing token:抢租约时从一个单调递增计数器取号(Redis 的 INCR)写进租约值,之后所有有副作用的操作都带上它,下游只接受不比见过的最大号小的写入,落到数据库上就是一句条件更新;醒过来的前任拿的是旧号,写入直接被拒。三是每次写之前重新校验租约,并把校验与写入放进同一段脚本或同一个事务——这只缩小窗口,不消除。
- 可预期的追问:fencing 的局限在哪?答「它需要下游配合」。数据库能做条件更新所以好使,但下游是第三方接口(发短信、扣款)时你没法让对方帮你比号,这时只能退回幂等键,把重复执行变成无害,而不是让它不发生。真要绝对互斥就得换到有共识协议的系统(etcd、ZooKeeper 的会话租约),代价是写入延迟和运维复杂度。
Key points
- A Redis lease alone cannot guarantee mutual exclusion: a frozen holder that revives, and asynchronous replication losing writes on failover, are both unavoidable
- State consequences in business terms: out-of-order replies, corrupted context, unique-constraint violations dropping messages, and reordered or duplicated side effects
- The goal is to make the second writer's writes fail — push conflict detection to the side-effecting layer instead of hoping split brain never happens
- Three mitigations: a worker self-kill rule on repeated renewal failure, fencing tokens enforced as conditional updates, and re-validating the lease immediately before writing
- Fencing needs downstream cooperation; against third-party endpoints fall back to idempotency keys, and true mutual exclusion means a consensus system like etcd or ZooKeeper
答题要点
- 单靠 Redis 租约做不到绝对互斥:持有者被冻结再醒来、以及主从异步复制丢写,这两条时间线排除不掉
- 后果要落到业务:同用户回复乱序、上下文错乱、唯一约束冲突丢消息,最严重是有副作用的工具被重排或重复执行
- 思路是「让第二个人的写入落不了地」,把冲突检测推到产生副作用的那一层,而不是指望脑裂不发生
- 三条手段:worker 自杀规则(续约连续失败就放手)、fencing token(写入时带单调号做条件更新)、写前重新校验租约
- fencing 需要下游配合;下游是第三方接口时只能退回幂等键,要绝对互斥就得换 etcd / ZooKeeper 这类有共识协议的系统