Idempotency: จ่ายเงินเดิม ส่งมาสองรอบ

network ทำของหายได้เสมอ client เลยต้องลองใหม่ บั๊กคือลองใหม่แล้วโดนตัดบัตรอีกรอบ มาดูการจ่าย ฿990 ครั้งเดียวเจอสี่ปัญหา แล้วดูว่าแบบไหนตัดเงินครั้งเดียวจริง ๆ

ระดับ: กลางดู 14 ขั้น · ~100 วินาทีลองทำ network พังเองจำ 3 คำถาม · 8 การ์ดเทียบ 4 แบบTypeScript · SQL · Python

สิ่งที่จะได้

  • อธิบายได้ว่าคำตอบหายแล้ว retry ทำให้ตัดเงินสองรอบยังไง และทำไมไม่ retry เลยก็ไม่รอด
  • ใช้ idempotency key หนึ่งอันต่อการจ่ายหนึ่งครั้ง ให้ retry ได้คำตอบเดิมที่เก็บไว้
  • จอง key ด้วย INSERT ลงตารางที่ key เป็น unique สองคำขอที่มาพร้อมกันก็ตัดเงินครั้งเดียว
  • ให้ worker ข้ามข้อความที่มาซ้ำได้ ด้วยการจด id ไว้ใน transaction เดียวกับงาน

สรุป 1 นาที

กดข้อไหน ภาพข้างล่างจะเล่นขั้นนั้นให้ดู

4เทียบทุกแบบ
ลองใหม่ ไม่มี keyจ่ายแล้ว แต่คำตอบหาย
แอป
API server
ledger (DB) · ฿990 ×0
POST /pay ฿990 → …
ขั้น 1 / 14 · กดทีละขั้น
0ครั้งที่ตัดเงิน
0request ที่แอปส่ง
–key ที่ใช้

ในภาพ การจ่าย ฿990 วิ่งจากมือถือ (หรือข้อความใน queue) ไปที่ server แล้วต่อไปที่ ledger แสงแต่ละดวงบนถนนคือข้อความหนึ่งอัน ดวงที่หยุดกลางทางเป็นสีแดงคือไปไม่ถึง และข้างถนนแต่ละเส้นเขียนข้อความล่าสุดที่ผ่านไว้ แผ่น ฿990 บนหลังคา ledger แต่ละแผ่นคือลูกค้าโดนตัดเงินหนึ่งครั้ง

ขั้นที่ 4 · ปล่อยทุกแบบวิ่งพร้อมกัน

เทียบทุกแบบ: Idempotency

การจ่าย ฿990 ครั้งเดียว เจอสี่ปัญหาเรียงกัน: request หาย คำตอบหาย กดสองที และ queue ส่งซ้ำ ดูว่าแต่ละแบบตัดเงินกี่ครั้ง ที่ถูกคือ ×1 ทุกช่อง

1/4 · request หายระหว่างทาง
ไม่ลองใหม่ส่งครั้งเดียว พลาดก็พลาด (at-most-once)ถูก (×1) 0 จาก 0

ใช้เมื่อ งานที่หายได้ไม่เป็นไร เช่น ส่งสถิติการใช้งาน

ไม่ควรใช้เมื่อ เงิน order และอะไรที่ลูกค้ารอผล

แบบจำลอง: ตัวเลขนับจาก ledger ใน sequence diagram ของแต่ละช่อง ไม่ได้วัดจากระบบจริง แต่ทุกแบบรันจริงในโค้ดด้านล่าง · กดช่องไหนก็ได้ ภาพใหญ่ด้านบนจะเปลี่ยนเป็นแบบนั้น พร้อมบอกว่าเหมาะกับงานแบบไหน

ส่งได้แค่ อาจหาย หรือ อาจซ้ำ

แบบได้แบบไหนพังตอน
ไม่ลองใหม่at most onceอะไรหายก็พลาด: เสียยอดขาย หรือตัดเงินแล้วแอปบอกว่าไม่สำเร็จ
ลองใหม่ ไม่มี keyat least onceคำตอบหาย หรือกดสองที: ตัดสองครั้ง
key เช็กก่อนแล้วจดครั้งเดียว ถ้ามาทีละตัวมาพร้อมกันสองตัว หรือดับระหว่างทำงานกับจด
key จองในขั้นเดียวผลเกิดครั้งเดียวลบ key ทิ้งทั้งที่ client ยังลองใหม่อยู่

exactly-once ต้องสร้างเอง

พอคำตอบหาย ผู้ส่งไม่มีทางรู้ว่าอีกฝั่งได้ข้อความแล้วหรือยัง ก็ต้องเลือกว่าจะเลิก (อาจหาย) หรือส่งใหม่ (อาจซ้ำ) ที่ขายกันว่า exactly-once คือส่งแบบ at-least-once แล้วให้ฝั่งที่รับทำงานเหมือนเดิมเมื่อเจอข้อความเดิมซ้ำ

ตั้งค่า อย่าบวกเพิ่ม

ใน HTTP, PUT กับ DELETE เป็น idempotent: ทำสองทีผลเท่าทำทีเดียว ถ้าทำได้ ให้งานเป็นการตั้งค่า (status = paid) แทนการบวกเพิ่ม (balance + 990) ถ้าทำไม่ได้ ใช้ key ที่ client สร้างหนึ่งอันต่อการกระทำหนึ่งครั้ง แล้วส่งอันเดิมทุกครั้งที่ลองใหม่

ในโค้ดจริง

server.ts
// A payment API that takes an Idempotency-Key, on a real node:http server. The client makes one key per payment and
// sends it with every retry; the server keeps the key with its answer. Here one response is dropped on purpose (the
// server closes the connection after the work, as a lost packet would), and the client retries.
// In one process, setting the key before the first await is the claim; with several servers it's a unique insert in
// the database (claim.sqlite.sql). Run: node server.ts   (Node 23.6+; on Node 22: node --experimental-strip-types server.ts)
import assert from "node:assert/strict";
import { createHash, randomUUID } from "node:crypto";
import { createServer, request } from "node:http";
import type { AddressInfo } from "node:net";

type Kept = { hash: string } & ({ state: "running" } | { state: "done"; code: number; body: string });
const ledger: { payment: string; amount: number }[] = [];
const keys = new Map<string, Kept>();
let dropNext = false; // the test's stand-in for a network that loses one response

const sha = (s: string) => createHash("sha256").update(s).digest("hex");
const charge = async (amount: number) => { await new Promise((r) => setTimeout(r, 30)); const payment = `p_${ledger.length + 1}`; ledger.push({ payment, amount }); return payment; };

const server = createServer((req, res) => {
  let raw = "";
  req.on("data", (c) => (raw += c));
  req.on("end", async () => {
    const send = (code: number, body: string) => {
      if (dropNext) { dropNext = false; req.socket.destroy(); return; } // the work is done, the answer never arrives
      res.writeHead(code, { "content-type": "application/json" }).end(body);
    };
    const key = req.headers["idempotency-key"], hash = sha(raw);
    if (typeof key === "string") {
      const kept = keys.get(key);
      if (kept && kept.hash !== hash) return send(422, `{"error":"this key was used for another request"}`);
      if (kept?.state === "running") return send(409, `{"error":"the first request with this key is still running"}`);
      if (kept?.state === "done") return send(kept.code, kept.body); // the stored answer, no second charge
      keys.set(key, { hash, state: "running" }); // claimed before any await
    }
    const payment = await charge(JSON.parse(raw).amount);
    const body = JSON.stringify({ payment });
    if (typeof key === "string") keys.set(key, { hash, state: "done", code: 201, body });
    send(201, body);
  });
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
const port = (server.address() as AddressInfo).port;

function post(amount: number, key?: string): Promise<{ code: number; body: string }> {
  return new Promise((ok, fail) => {
    const r = request({ host: "127.0.0.1", port, path: "/payments", method: "POST", headers: { "content-type": "application/json", ...(key ? { "idempotency-key": key } : {}) } }, (res) => {
      let b = ""; res.on("data", (c) => (b += c)); res.on("end", () => ok({ code: res.statusCode ?? 0, body: b }));
    });
    r.on("error", fail);
    r.end(JSON.stringify({ amount }));
  });
}
/** Retry on a lost answer or a 409, a little later each time, with the SAME key. */
async function pay(amount: number, key?: string) {
  for (let i = 0; ; i++) {
    try { const r = await post(amount, key); if (r.code !== 409) return r; } catch { /* no answer: try again */ }
    if (i === 4) throw new Error("gave up");
    await new Promise((r) => setTimeout(r, 20 * 2 ** i));
  }
}

dropNext = true;
await pay(990); // no key: the retry looks like a new payment
const withoutKey = ledger.length;

ledger.length = 0; dropNext = true;
const k1 = randomUUID();
const retried = await pay(990, k1);
const withKey = ledger.length;

ledger.length = 0;
const k2 = randomUUID();
const firstTry = await Promise.allSettled([post(990, k2), post(990, k2)]); // two taps, same key, same moment
const codes = firstTry.map((x) => (x.status === "fulfilled" ? x.value.code : 0)).sort();
const after = await pay(990, k2); // the 409 one comes back later
const twoAtOnce = ledger.length;

const otherAmount = await post(1990, k2);
server.close();

assert.equal(withoutKey, 2);
assert.equal(withKey, 1);
assert.equal(retried.code, 201);
assert.deepEqual(codes, [201, 409]);
assert.equal(twoAtOnce, 1);
assert.equal(JSON.parse(after.body).payment, "p_1");
assert.equal(otherAmount.code, 422);
console.log(`response lost, no key: charged ${withoutKey} · with a key: charged ${withKey}, the retry got the stored 201 · two at once: ${codes.join(" + ")}, charged ${twoAtOnce} · same key, other amount: ${otherAmount.code}`);
รัน: node server.ts (Node 23.6+ · Node 22 ใส่ --experimental-strip-types)ผลที่พิมพ์ออกมา: response lost, no key: charged 2 · with a key: charged 1, the retry got the stored 201 · two at once: 201 + 409, charged 1 · same key, other amount: 422

server กับ client ของ node:http จริง ตั้งใจทำคำตอบหายหนึ่งครั้ง ไม่มี key ก็ตัดซ้ำ มี key ครั้งที่ลองใหม่ได้ 201 ที่เก็บไว้ สอง request key เดียวกันพร้อมกันได้ 201 กับ 409 key เดิมแต่ยอดอื่นได้ 422 รันจริง ข้างล่างคือที่มันพิมพ์ออกมา

คำถามที่เจอบ่อย

idempotent แปลว่าอะไร

ทำสองทีได้ผลเท่าทำทีเดียว ตั้ง status = paid ซ้ำกี่ทีก็ paid แต่บวก 990 เข้ายอดสองทีก็ได้สองเท่า ใน HTTP, GET, PUT กับ DELETE ควรเป็น idempotent ส่วน POST ไม่ใช่

อ่าน: ตั้งค่า อย่าบวกเพิ่ม

ไม่ลองใหม่เลยก็จบ ไม่ได้เหรอ

request หายระหว่างทางก็เสียยอดขายไปเลย หรือแย่กว่านั้น ตัดเงินแล้วแต่คำตอบหาย แอปบอกลูกค้าว่าไม่สำเร็จ เน็ตพังบ้างเป็นเรื่องปกติ ยังไงก็ต้องลองใหม่ แค่ต้องทำให้การลองใหม่ปลอดภัย

idempotency key ทำงานยังไง

client สร้าง key สุ่มหนึ่งอันต่อการกระทำหนึ่งครั้ง ไม่ใช่ต่อการส่งหนึ่งรอบ แล้วส่ง key เดิมทุกครั้งที่ลองใหม่ เช่นใน header Idempotency-Key แบบที่ API ของ Stripe ใช้ server เก็บ key คู่กับคำตอบ key เดิมก็ได้คำตอบเดิมโดยไม่ทำงานซ้ำ

เช็กก่อนว่าเคยเห็น key ไหม แล้วค่อยจด ไม่พอเหรอ

ไม่พอตอนที่สองคำขอ key เดียวกันมาห่างกันไม่กี่ ms ทั้งคู่ถามว่าเคยเห็นไหม ทั้งคู่ได้คำตอบว่าไม่ ก็ตัดเงินทั้งคู่ ต้องจอง key ก่อนในขั้นเดียว ด้วย INSERT ลงตารางที่มี unique constraint database ให้ผ่านแค่ตัวเดียว

ระหว่างที่ตัวแรกยังทำงานอยู่ ตัวที่สองควรได้อะไร

ได้ 409 (Conflict) บอกให้กลับมาใหม่ทีหลัง พอตัวแรกเสร็จ การลองใหม่ก็ได้คำตอบที่เก็บไว้ ที่ห้ามเด็ดขาดคือให้มันทำงานเดิมซ้ำอีกรอบ

exactly-once delivery มีจริงไหม

บนเน็ตที่ข้อความหายได้ ไม่มี ผู้ส่งที่ไม่ได้ยินคำตอบต้องเลือกว่าจะเลิก (อาจหาย) หรือส่งใหม่ (อาจซ้ำ) ที่สร้างได้คือผลที่เกิดครั้งเดียว ส่งแบบ at-least-once แล้วให้ฝั่งรับข้ามของที่เคยทำไปแล้ว

อ่าน: exactly-once ต้องสร้างเอง

worker ของ queue จะข้ามข้อความที่เคยทำแล้วได้ยังไง

จด id ของข้อความลงตาราง processed ที่ id เป็น unique ใน transaction เดียวกับงานจริง ถ้า worker ดับก่อน ack แล้ว queue ส่งข้อความเดิมมาอีก มันจะชน unique key แล้วถูกข้ามไป

server ควรเก็บ idempotency key ไว้นานแค่ไหน

อย่างน้อยนานเท่าที่ client ยังอาจลองใหม่ ลบ key เร็วไป การลองใหม่ที่มาช้าจะดูเหมือนคำขอใหม่แล้วทำงานซ้ำ Stripe เก็บไว้อย่างน้อย 24 ชั่วโมง

บทต่อไป

Circuit breaker, retry และ timeoutระดับ: ลึก

ส่งซ้ำได้อย่างปลอดภัยแล้ว บทต่อไปคือ retry ตอนไหนและยังไง (backoff, jitter) และเมื่อไหร่ควรหยุดเรียก