逐日AI

面试题库

共 328 题,当前筛选 5 题。

30 天从前端工程师到 Agent 工程师

D8 为什么 Gateway/Worker 分离;Postgres 表设计(sessions/runs/messages)+ Drizzle

  • 消息总线是至少一次投递,同一条消息被重复投递时,怎么保证不会产生两条 run?With at-least-once delivery, how do you guarantee a redelivered message does not create two runs?
    国内高频海外高频深入#idempotency#database#reliability

    分析过程 · 先想清楚再作答

    1. 这题在考幂等的落点在哪一层。凡是答「在代码里先查一下有没有,没有再插入」的,基本当场结束——因为那正是这题想筛掉的答案。
    2. 先把前提摊开:重复不是意外。总线是至少一次语义、客户端会超时重发、用户会手抖双击,同一句话到达两次是必然事件。所以设计目标不是「避免重复到达」,而是「重复到达时结果相同」。
    3. 然后给推导:幂等需要一个由请求内容决定的键。随机 UUID 每次都不同,等于没有幂等;正确取法是把会话 id、客户端消息 id、消息内容拼起来做哈希,客户端没有消息 id 时退用内容加一个粗粒度时间窗。
    4. 结论落在存储层:在 runs 表的这一列上加唯一约束,插入写成「冲突就什么都不做」,返回零行时回查那条已有的 run,把同一个 runId 返回给用户。两次请求、一条 run、一个 runId。
    5. 解释为什么「先查后插」不行,这是本题的分水岭:两个 Gateway 实例可以同时查、同时发现没有、同时插入,这两步之间有一个应用层拦不住的时间窗;它窄到压测复现不出来,上线后每天漏几条。**幂等的最终裁判必须是数据库的唯一约束**,应用层的判断只是为了少一次插入尝试。
    6. 可以预期的追问:那消费侧的重复执行呢?答:唯一约束保证了只有一条 run,但 Worker 可能重复拿到同一条 run,所以状态迁移也要带条件更新(只有当前状态是 pending 时才能改成 running),并且用一个显式的迁移白名单挡住「已完成的 run 被推回运行中」这种会覆盖用户已收到回复的情况。

    How to reason about it · think before answering

    1. This question is about which layer idempotency lives in. Anyone who answers 'check whether it exists, then insert' has usually just failed it — that is exactly the answer being screened out.
    2. State the premise: duplicates are not accidents. The bus is at-least-once, clients retry on timeout, users double-click. The same message arriving twice is certain, so the goal is not to prevent duplicates but to make duplicates produce the same result.
    3. Then derive the key: idempotency needs a key derived from request content. A random UUID differs every time and buys nothing; hash the session id, the client message id and the message body together, falling back to content plus a coarse time bucket when the client has no id.
    4. Land it in storage: put a unique constraint on that column in the runs table, write the insert as on-conflict-do-nothing, and when it returns zero rows read back the existing run and return the same run id. Two requests, one run, one id.
    5. Explain why check-then-insert fails, which is the whole point: two gateway instances can query, both see nothing, and both insert. The window between the two statements cannot be closed in application code, it is too narrow to reproduce under load tests, and it leaks a few bad rows every day in production. The database's unique constraint has to be the final arbiter; the application-level check only saves a wasted insert.
    6. Expect the follow-up: what about duplicate execution on the consumer side? The unique constraint gives you one run, but a worker can still receive it twice, so status changes need conditional updates (move to running only if the current status is pending) plus an explicit transition whitelist that blocks a finished run from being pushed back to running and overwriting a reply the user already saw.

    答题要点

    • 重复投递是必然事件,设计目标是「重复到达时结果相同」,不是「避免重复」
    • 幂等键必须由请求内容决定:会话 id 加客户端消息 id 加内容做哈希,随机 UUID 等于没有幂等
    • 在 runs 的幂等键列上建唯一约束,插入用「冲突就什么都不做」,零行时回查已有 run 返回同一个 runId
    • 先查后插在并发下必然出双份,两条语句之间的时间窗应用层拦不住,幂等的最终裁判是数据库唯一约束
    • 消费侧还要用条件更新加状态迁移白名单,避免同一条 run 被重复执行或把已完成的回复覆盖掉

    Key points

    • Redelivery is certain, so the goal is identical outcomes on duplicates, not preventing duplicates
    • The idempotency key must be derived from request content — session id plus client message id plus body, hashed; a random UUID buys nothing
    • Put a unique constraint on that column, insert with on-conflict-do-nothing, and read back the existing run when zero rows return
    • Check-then-insert races under concurrency; the window between the statements cannot be closed in application code, so the unique constraint must be the final arbiter
    • On the consumer side add conditional status updates and a transition whitelist so a finished run is never re-run or overwritten
  • sessions / runs / messages 这三张表你会怎么设计主键与索引?为什么不用自增主键?How would you design primary keys and indexes for sessions, runs and messages, and why avoid auto-increment ids?
    国内高频海外高频进阶#database#schema-design#idempotency

    分析过程 · 先想清楚再作答

    1. 这题看着像八股,其实每一个选择背后都有一个具体约束。判断标准是:你能不能为每个决定说出「不这么做会发生什么」。
    2. 先讲为什么是三张表而不是一张:粒度不同。会话是长期容器,一次执行有生命周期且可能失败重来,消息是不可变事实。少了「一次执行」这一层,你就没有地方回答「这次跑完没有」「该不该重试」「这轮花了多少钱」。
    3. 主键选文本型的应用侧 id(UUID 或 ULID),理由是接入层必须在写库之前就把 id 放进 202 响应体返回给客户端;自增主键要等数据库插完才知道值,那次往返就被卡在用户的等待路径上,而且多实例无法预分配。附带好处是将来分库分表不用重编号。
    4. 索引按查询路径建,不按直觉建:按用户拉会话列表要 sessions 的 user_id 索引,按会话拉历史要 messages 的 session_id 索引,外键列本身要索引否则删除父行会全表扫。多余的索引不是免费的,每个都让写入变慢。
    5. 两条唯一约束才是这套设计的灵魂:runs 的幂等键唯一,挡住重复投递;messages 的「run id 加序号」复合唯一,既保证同一次执行的输出顺序稳定,又让断线重连可以按序号幂等回放。序号要从 0 开始、连续、不跳号,否则续传就找不到断点。
    6. 可以预期的追问:ULID 和 UUIDv4 选哪个?答 ULID 或 UUIDv7——它们按时间有序,插入时集中在 B 树右端,不像 UUIDv4 那样随机分布导致页分裂和缓存命中率下降。这个细节能直接体现你关心过写入性能。

    How to reason about it · think before answering

    1. It looks like a trivia question, but every choice sits on a concrete constraint. The test is whether you can say what breaks if you choose otherwise.
    2. Start with why three tables rather than one: the grains differ. A session is a long-lived container, a run has a lifecycle and can fail and be retried, a message is an immutable fact. Without the run layer there is nowhere to answer 'did this finish', 'should we retry', or 'what did this turn cost'.
    3. Use text primary keys generated in the application (UUID or ULID), because the gateway must put the id into the 202 response before the row is written. Auto-increment ids are only known after the insert, which parks a round trip in the user's wait path and cannot be pre-allocated across instances. A bonus is that sharding later needs no renumbering.
    4. Index by query path, not by instinct: sessions need an index on user_id to list a user's conversations, messages need one on session_id to load history, and foreign key columns need indexes or deleting a parent row triggers a full scan. Extra indexes are not free — each one slows writes.
    5. The two unique constraints carry the design: a unique idempotency key on runs blocks duplicate delivery, and a composite unique on run id plus sequence in messages both fixes output ordering for one run and lets a reconnect replay idempotently by sequence. The sequence must start at zero and never skip, otherwise resume cannot find the cut point.
    6. Expect the follow-up: ULID or UUIDv4? Choose ULID or UUIDv7 — they are time-ordered so inserts land at the right edge of the B-tree, whereas random UUIDv4 scatters writes, splits pages and hurts cache hit rates. Mentioning this shows you have watched write performance.

    答题要点

    • 三张表对应三种粒度:会话是长期容器、run 是一次有生命周期的执行、message 是不可变事实;少了 run 就无法回答是否跑完、该不该重试、花了多少钱
    • 主键用应用侧生成的文本 id,因为 Gateway 要在写库之前把 runId 放进 202 响应里,自增主键必须等插入完成且无法跨实例预分配
    • 索引按实际查询路径建:sessions 的 user_id、messages 的 session_id、以及外键列;多余索引会拖慢写入
    • 两条唯一约束是灵魂:runs 的幂等键唯一挡重复投递,messages 的「run id 加序号」复合唯一保证保序与幂等回放
    • id 优先选 ULID 或 UUIDv7 这类时间有序的方案,避免随机 UUID 造成的页分裂与缓存失效

    Key points

    • Three tables for three grains: a long-lived session, a run with a lifecycle, and immutable messages; without runs you cannot answer completion, retry or cost questions
    • Application-generated text ids, because the gateway must return the run id in the 202 before the write, and auto-increment ids cannot be pre-allocated across instances
    • Index the real query paths — user_id on sessions, session_id on messages, plus foreign key columns; extra indexes slow writes
    • Two unique constraints carry the design: a unique idempotency key on runs, and a composite unique on run id plus sequence in messages for ordering and idempotent replay
    • Prefer time-ordered ids such as ULID or UUIDv7 over random UUIDv4 to avoid page splits and cache misses

D9 Redis Streams 消息总线:XADD/XREADGROUP/XACK/XAUTOCLAIM、consumer group、毒消息

  • 什么是 at-least-once?既然消息会被重复投递,业务上到底要怎么保证幂等?What is at-least-once delivery, and given that messages get redelivered, how do you actually make the business side idempotent?
    国内高频海外高频深入#message-bus#idempotency#reliability

    分析过程 · 先想清楚再作答

    1. 这题是本章最容易被追到底的一道。绝大多数人能说出「至少一次,所以业务要幂等」,然后就没有下文了——面试官等的恰恰是下文:幂等具体落在哪一行代码上。答不出具体落点,前半句就是背的。
    2. 先解释为什么消费不掉这个重复:写业务和销号是两个系统的两次写(比如 Postgres 加 Redis),处理完成到 XACK 之间必然存在一个可以崩溃的窗口,崩在那里消息就会被重投。这个窗口只能变小,不能消失,所以 exactly-once 不是总线给你的语义。
    3. 由此得到一句可以直接说出口的结论:exactly-once 是消费端幂等做出来的**效果**,不是中间件提供的**能力**。Kafka 的事务能在「读 Kafka 写 Kafka」的闭环里做到,一旦下游是数据库或第三方 API 就又退回至少一次。
    4. 然后给具体落点,两道闸门要分清各自挡什么:第一道是 runs 表 idempotency_key 上的唯一约束,配 insert on conflict do nothing,挡的是**客户端重复提交**——冲突时接入层直接返回已有的 runId,连总线都不投第二遍;第二道是 messages 表的 unique(run_id, seq),同样 on conflict do nothing,挡的是**同一条总线消息被执行两遍**,就算两个消费者真的同时跑完,用户也只会看到一条回复。中间还可以加一道便宜的短路:捞到消息先看 run 是不是已经 done,是就直接补一个 XACK 走人——但那是省钱的优化,正确性靠的是那两个唯一约束。
    5. 接着讲最容易做错的一步:幂等键怎么取。它必须能从「同一个意图」稳定推出来。客户端每次重试都新生成一个 uuid 是最常见的错法,那每次都是新意图,唯一约束一次都命中不了,闸门形同虚设。正确做法是客户端生成一次、重试复用同一个值,服务端兜底可以用「会话 id 加消息内容哈希加秒级时间戳」。
    6. 可以预期的追问:不可逆的副作用怎么办,比如发一次退款?答:把外部调用也变成带幂等键的(大多数支付网关都支持 idempotency key 头),并且先在本地库里落一条「已发起」记录再调用,用同一个键去重;实在不支持的接口就只能靠本地状态机加人工对账,这时要主动说出「这类操作我会把它挪出重试路径」。

    How to reason about it · think before answering

    1. This is the question that gets probed hardest. Most candidates say 'at-least-once, so make the business idempotent' and stop — but the follow-up is exactly what matters: which line of code enforces it.
    2. Explain why the duplicate cannot be removed: committing the business write and acking are two writes to two systems (say Postgres and Redis), so there is always a crash window between finishing the work and XACK. The window can shrink but not disappear, which is why exactly-once is not something the bus gives you.
    3. That yields a sentence worth saying out loud: exactly-once is an effect produced by consumer-side idempotency, not a capability provided by the broker. Kafka transactions achieve it inside a read-Kafka-write-Kafka loop, but the moment the sink is a database or third-party API you are back to at-least-once.
    4. Now name the concrete guards and what each one blocks. First, a unique constraint on runs.idempotency_key with insert ... on conflict do nothing, which blocks duplicate submissions: on conflict the gateway returns the existing run id and never publishes a second bus message. Second, unique(run_id, seq) on the messages table, also on conflict do nothing, which blocks duplicate execution: even if two consumers finish the same run simultaneously the user sees one reply. A cheap short-circuit can sit in between — read the run first and just re-ack if it is already done — but that saves money; correctness comes from the two constraints.
    5. Then the step people get wrong: deriving the key. It must be reproducible from the same intent. Generating a fresh uuid on every retry is the classic mistake, because every retry becomes a new intent and the constraint never fires. The client should mint the key once and reuse it across retries; a server-side fallback can hash session id plus message body plus a second-resolution timestamp.
    6. Expect: what about irreversible side effects such as issuing a refund? Push the idempotency key into the external call (most payment gateways accept an idempotency key header), and record an 'initiated' row locally before calling so the same key deduplicates. For APIs with no such support, fall back to a local state machine plus reconciliation, and say plainly that you would move such operations off the automatic retry path.

    答题要点

    • at-least-once:消息至少被处理一次、可能多次,因为业务提交和 XACK 是两个系统的两次写,中间的崩溃窗口消不掉
    • exactly-once 是消费端幂等做出来的效果,不是中间件的能力;下游只要是数据库或第三方 API 就退回至少一次
    • 闸门一:runs.idempotency_key 唯一约束 + on conflict do nothing,挡客户端重复提交,冲突时不再投递总线消息
    • 闸门二:messages 表 unique(run_id, seq) + on conflict do nothing,挡同一条消息被执行两遍,用户只会看到一条回复
    • 幂等键必须从同一个意图稳定推导,客户端重试要复用同一个值;每次重试新生成 uuid 等于没有幂等
    • 不可逆副作用要把幂等键透传给外部接口,并先落一条本地记录再调用

    Key points

    • At-least-once means a message is processed one or more times, because the business commit and the XACK are two writes to two systems with an unavoidable crash window
    • Exactly-once is an effect of consumer-side idempotency, not a broker feature; any database or third-party sink puts you back at at-least-once
    • Guard one: a unique constraint on runs.idempotency_key with on conflict do nothing blocks duplicate submissions and skips publishing a second bus message
    • Guard two: unique(run_id, seq) on messages with on conflict do nothing blocks duplicate execution, so the user sees exactly one reply
    • The idempotency key must be derivable from the same intent and reused across retries; minting a new uuid per retry defeats the whole mechanism
    • For irreversible side effects, pass the idempotency key through to the external API and record an initiated row locally before calling

D11 run 状态机、输出流回传、按 runId 保序、SSE 等待者、30s 打断合并

  • 流式接口的客户端断线重连后,怎么做到既不丢片段也不重复?After a streaming client reconnects, how do you deliver every missed chunk exactly once — no gaps, no duplicates?
    国内高频海外高频深入#sse#idempotency#reconnect

    分析过程 · 先想清楚再作答

    1. 「不丢」和「不重复」要分开答。只答一半的人很多:说了从库里补发(不丢),却没说重叠部分怎么去重(不重复)。
    2. 推导链很短:客户端知道自己最后收到的编号 → 它重连时把这个编号带回来 → 服务端从下一号开始给 → 前提是编号连续不跳号。所以能不能重连,取决于当初有没有把序号设计成从 0 开始、连续、单调。序号一旦是时间戳或随机 id,这条链第一步就断了。
    3. 然后给三步实现和各自的坑:第一步换算,带回来的是「最后收到」的那一号,要加一,少加一重复一帧、多加一丢一个字,这是整段逻辑里唯一的算术也最常写错;第二步先从持久化里回放缺的部分,因为库里一定是全的;第三步再接上还在流动的那条流,两边必然重叠,靠「小于当前指针的一律丢弃」去重——幂等回放的全部秘密就是这一次比较。
    4. 这里要点出为什么必须双写:片段既进流也进库。只有流,重连时早期片段已被消费掉;只有库,就得轮询查库,首字延迟从几十毫秒涨到几百毫秒。代价是写放大,一次回答几百个片段就是几百行,生产里按批落库(每几十个片段或每两百毫秒一次)。
    5. 对齐一下协议细节:浏览器原生的事件源会自动把上次的编号放进重连请求头带回来;但大模型接口通常要用 POST,原生事件源只能发 GET,所以真实前端多是手写解析,重连时要自己把编号带上——这个细节能证明你真接过前端。
    6. 可以预期的追问:回放要保留多久?必须给两个边界——保留期(逐片段的行只对最近若干小时的执行保留,之后归档成一整条完整回复并删掉碎行)和回放上限(一次重连最多回放多少片段,超了就一次性发完整文本而不是逐字重演)。不定这两条,那张表会变成全库最大且 99% 的行写完十秒后再没人读。

    How to reason about it · think before answering

    1. Answer 'no gaps' and 'no duplicates' separately. Plenty of candidates cover only the first — they backfill from storage but never say how the overlap is deduplicated.
    2. The chain is short: the client knows the last id it received, it sends that id back on reconnect, the server resumes from the next one — and all of that requires contiguous, monotonic numbering. Whether resumption is possible at all was decided when you chose the sequence scheme; timestamps or random ids break the chain at step one.
    3. Then the three steps and their individual traps. Convert: the client reports the last id it *received*, so add one — off by minus one repeats a frame, off by plus one drops a character, and this is the only arithmetic in the whole flow and the most commonly wrong line. Replay: read the missing range from durable storage, which is always complete. Attach: resume the live stream, whose overlap with the replay is guaranteed, and drop anything below the cursor. That single comparison is all there is to idempotent replay.
    4. Explain why the dual write is mandatory: chunks go both to the stream and to the table. Stream only, and the early chunks are gone by reconnect time; table only, and you are polling the database, pushing time-to-first-token from tens to hundreds of milliseconds. The cost is write amplification — hundreds of rows per answer — so production batches the writes, every few dozen chunks or every couple hundred milliseconds.
    5. Get the protocol detail right: the browser's native event source replays the last id in a request header for you, but model endpoints generally need POST while that API only issues GET, so real frontends hand-roll the parser and must resend the id themselves. Mentioning this proves you have actually wired up the client side.
    6. Expect: how long do you keep replayable data? Give two bounds — a retention window (per-chunk rows only for runs from the last few hours, then collapsed into one complete message) and a replay cap (beyond N chunks, send the full text once instead of re-enacting it character by character). Without both, that table becomes the largest in the database while 99% of its rows are never read again after ten seconds.

    答题要点

    • 重连的前提是序号从 0 开始、连续、单调;序号是时间戳或随机 id 就无法续传
    • 客户端带回来的是「最后收到」的那一号,服务端要加一再开始,这是唯一的算术也最容易错
    • 先从库里回放缺的片段(库一定是全的),再接上还在流动的流,重叠部分靠「小于当前指针一律丢弃」去重
    • 片段必须双写:流服务当前挂着的连接,库服务等一下才回来的人;代价是写放大,生产里按批落库
    • 必须定保留期与回放上限:过期的执行归档成一整条完整回复,超长回放直接一次性发完整文本

    Key points

    • Resumption requires a contiguous, monotonic sequence starting at 0; timestamps or random ids make it impossible
    • The client reports its last received id, so the server resumes from that id plus one — the single most error-prone line
    • Replay the gap from durable storage first, then attach the live stream, discarding anything below the cursor to dedupe the overlap
    • Dual-write every chunk: the stream serves currently attached connections, the table serves clients that come back later; batch the writes in production
    • Set a retention window and a replay cap — archive old runs into one complete message and send full text instead of re-enacting long replays

D13 cron 调度(中心调度→stream 投递)+ 成本计量(token→USD 台账、usage report)

  • 怎么保证一个 cron 任务不会被重复投递或重复执行?幂等键应该怎么构造?How do you keep a cron job from being published or executed twice, and how should the idempotency key be built?
    国内高频海外高频深入#idempotency#scheduling#distributed-systems

    分析过程 · 先想清楚再作答

    1. 题眼在「投递」和「执行」是两件事。很多人只答一半:要么只说消费组保证一条消息一个消费者(那只挡住了执行侧的重复),要么只说加锁(那只挡住了投递侧,还挡不干净)。完整答案要说清两侧各自的重复来源,以及一个能同时兜住的兜底。
    2. 先拆重复的来源:投递侧的重复来自多个调度器实例、调度器重启后的补发重放、以及消息总线本身的至少一次语义;执行侧的重复来自 Worker 处理到一半崩溃后消息被 XAUTOCLAIM 转交给别人。这两类重复用不同手段挡效率完全不同。
    3. 再给核心结论:不要用分布式锁去做互斥,用数据层的唯一约束做去重。原因是锁只能提供「大概率互斥」——租约到期而前任进程其实只是 GC 卡住的那一瞬间,两个调度器都会认为自己持有,各发一次;而唯一约束是在最终落库那一步判断的,无论上游发了几次,任务表里只会多一行。能在唯一约束上解决的问题,不要升级成分布式协调问题。
    4. 然后回答幂等键怎么构造,这是最容易翻车的一步:键必须是「任务 id 加计划触发的那一分钟」,绝不能用当前时刻。两个调度器实例的时钟不可能对齐到毫秒,一个在 09:00:00.120 醒来、另一个在 09:00:00.480 醒来,用 now 算出来的键不一样,去重完全失效。把秒和毫秒截掉之后,无论谁在这一分钟里的哪一刻醒来,算出的键都是同一个字符串。落到代码上就是 insert 加 on conflict do nothing,冲突说明已经有人建过这次执行,直接 ack 掉不执行。
    5. 补一句作用范围:这套只保证「同一个触发点只产生一次执行」,不保证「执行内部的副作用只发生一次」。如果这次执行要发短信、要扣款,那些副作用还得各自带自己的幂等键,因为 Worker 可能在发完短信之后、写完状态之前崩掉。这一层区分是加分项。
    6. 可以预期的追问:那漏发怎么办?答宁可多发不可少发——调度器启动时回看最近 N 分钟逐分钟重放,重复投递被幂等键吃掉。at-least-once 加幂等是分布式系统里最省心的一组搭配,反过来先追求 exactly-once 再补幂等,通常两头都做不好。

    How to reason about it · think before answering

    1. The hinge is that publishing and executing are two separate problems. Most candidates answer half: either only the consumer group (which stops duplicate execution) or only a lock (which stops duplicate publishing, and imperfectly). A complete answer names the duplicate sources on both sides plus one backstop that covers both.
    2. Enumerate the sources: duplicate publishes come from multiple scheduler instances, from replay after a scheduler restart, and from the bus's own at-least-once semantics. Duplicate executions come from a worker crashing mid-processing and the message being reclaimed by another consumer. The two need different treatment.
    3. State the core conclusion: do not reach for a distributed lock, use a uniqueness constraint in the data layer. A lease only gives you probable mutual exclusion — in the instant when the TTL expires while the previous holder is merely stuck in GC, both schedulers believe they hold it and both publish. A uniqueness constraint is evaluated at the final insert, so no matter how many times upstream published, the table gains exactly one row. Do not escalate a problem solvable by a constraint into a distributed coordination problem.
    4. Then the key construction, which is where people fail: the key must be the task id plus the scheduled minute, never the current instant. Two scheduler clocks never align to the millisecond; one wakes at 09:00:00.120 and the other at 09:00:00.480, so keys built from now differ and dedup collapses. Truncate seconds and milliseconds and every instance computes the same string for that minute. In code this is an insert with on conflict do nothing; a conflict means the execution already exists, so ack the message and skip.
    5. Scope it honestly: this guarantees one execution per trigger point, not that side effects inside the execution happen once. If the run sends an SMS or charges a card, those side effects need their own idempotency keys, because the worker can crash after sending and before writing status. Making that distinction earns points.
    6. Expect: what about missed triggers? Prefer over-publishing to under-publishing — replay the last N minutes at startup and let the idempotency key absorb duplicates. At-least-once plus idempotency is the easiest combination in distributed systems; chasing exactly-once first and adding idempotency later usually achieves neither.

    答题要点

    • 投递重复和执行重复是两件事:前者来自多调度器实例、重启重放和总线的至少一次语义,后者来自 Worker 崩溃后消息被转交
    • 用数据层唯一约束去重,不要用分布式锁互斥:租约过期而前任还活着的瞬间两个调度器都会各发一次,而唯一约束在落库那一步只放行一条
    • 幂等键必须是任务 id 加计划触发的那一分钟,不能用当前时刻——两个实例的醒来时刻永远不同,用 now 会让去重完全失效
    • 落到代码上是 insert 加 on conflict do nothing,冲突就直接 ack 不执行
    • 这只保证一个触发点一次执行,执行内部的发短信、扣款等副作用要各自带幂等键;宁可多发不可少发,靠 at-least-once 加幂等兜底

    Key points

    • Duplicate publishing and duplicate execution are separate: the former comes from multiple schedulers, restart replay and at-least-once delivery; the latter from a crashed worker's message being reclaimed
    • Dedupe with a database uniqueness constraint rather than a distributed lock: when a lease expires while the holder is only GC-stalled, both schedulers publish, whereas the constraint admits exactly one row
    • Build the key from the task id plus the scheduled minute, never the current instant — instances never wake at the same millisecond, so a now-based key defeats dedup entirely
    • In code this is an insert with on conflict do nothing; on conflict, ack the message and skip execution
    • This guarantees one execution per trigger, not once-only side effects — SMS or payments inside the run need their own keys; prefer over-publishing and let at-least-once plus idempotency absorb it