接口幂等怎么设计才能避免重复提交和重复扣款

我以前做支付和订单接口时吃过一次亏,前端按钮做了防抖,网关也有限流,但用户网络一抖,重试请求还是把同一笔业务打进来了。后来才明白,防抖只能减少重复点击,真正兜底还是后端幂等。 我现在做这类接口,会先定一个业务维度的幂等键。下单可以用 client_request_id 加用户 id,支付回调可以用平台交易号,库存扣减要绑定订单行,不能只拿时间戳或随机数糊弄。请求进来后先查幂等记录,有成功结果就直接返回原结果,有处理中状态就让客户端稍后查,不要让同一笔业务重新跑一遍。 数据库层也要配合。唯一索引、事务边界、状态机要提前想清楚,尤其是"已创建订单但支付未确认""支付成功但库存扣减失败"这种半路状态。幂等不是加一个字段就完事,真正难的是每一步失败后还能知道下一次重试该从哪里继续。

相关公开内容

  1. How to speed up CI builds without cutting test coverage tech-software-dev · experience · 1 条回复 2026-06-04T21:47:27.887Z
  2. The small API cleanup that saved us later tech-software-dev · experience · 2 条回复 2026-06-03T15:56:59.439Z
  3. Bentley System图形程序员入职分享 tech-software-dev · experience · 1 条回复 2026-05-17T00:10:43.701Z
  4. AI coding tools tuhought tech-software-dev · experience · 1 条回复 2026-05-18T02:00:51.998Z
  5. Interviewed for a GPU software engineer role at Sony. Key points: tech-software-dev · experience · 1 条回复 2026-05-20T04:14:38.658Z
  6. Recently interviewed with Autodesk for a graphics development internship. The manager round was casual tech-software-dev · experience · 1 条回复 2026-05-20T03:58:43.093Z
  7. miHoYo AIGC Algorithm Engineer: 3D Direction tech-software-dev · experience 2026-05-20T04:37:49.927Z
  8. 接老系统别一上来就重写 tech-software-dev · experience 2026-06-04T01:06:26.011Z
  9. Just had an interview for a rendering intern role at a well-known game company tech-software-dev · experience 2026-05-20T04:24:07.867Z
  10. Recently interviewed with Autodesk for a graphics intern role. The manager chat focused on tech-software-dev · experience 2026-05-20T04:20:22.396Z