Part 03 · Web এর ভাষা
Idempotency and Safe Operations
কোন request দুবার পাঠালেও ক্ষতি নেই, আর খারাপ network এ এটা কেন জরুরি।
⏱ 1 ঘণ্টা · Station 37 / 153
Charged twice for one ride
ঢাকায় একজন rider trip শেষ করে "Pay 500 taka" তে tap করলো। জ্যামে বসে phone এ 4G signal দুর্বল। Request server এ পৌঁছালো, card charge হলো, server ফেরত পাঠালো "201 paid"। কিন্তু সেই response আর পৌঁছায়নি, এক second এর জন্য signal চলে গিয়েছিল। 10 second পর app এর HTTP library timeout দিলো, আর তাকে যা বলা ছিল তাই করলো: retry। Server দেখলো একদম নতুন একটা payment request, আবার charge করলো। Rider দেখলো দুইটা 500 টাকার charge, তারপর আসলো one-star review।
সাধারণ অর্থে কেউ কোনো bug লেখেনি। Network ঠিক তাই করেছে যা network করে (Module 2, lesson 10): একটা message হারিয়ে ফেলেছে। Client ঠিক তাই করেছে যা client এর করা উচিত: retry করেছে। সমস্যা হলো, operation টা আবার করা safe ছিল না।
এই lesson দুইটা property নিয়ে, যেগুলো ঠিক করে একটা request ক্ষতি ছাড়া retry করা যাবে কিনা: safe (কিছুই বদলায় না) আর idempotent (দুইবার করলে আর একবার করলে effect একই)। আর সেই কৌশল নিয়ে, যেটা একটা payment কেও idempotent বানায়: idempotency key।
The problem: a timeout doesn't tell you what happened
Client timeout পেলে তিনটা জিনিস হতে পারে, আর client এদের আলাদা করে বুঝতে পারে না:
| আসলে কী হয়েছে | Server এর state | না বুঝে retry করলে কী হয় |
|---|---|---|
| Request server এ পৌঁছায়ইনি | বদলায়নি | কাজটা করে, ঠিক আছে |
| Server এখনো কাজ করছে | বদলাতে যাচ্ছে | কাজটা দুইবার হতে পারে |
| Server কাজ শেষ করেছে, response হারিয়ে গেছে | বদলে গেছে | কাজটা আবার করে |
Read এর জন্য তিনটাতেই retry করা ঠিক আছে। "email set করো [email protected]" এর জন্য তিনটাই একই state এ শেষ হয়। কিন্তু "500 টাকা charge করো" বা "100 credit যোগ করো" এর বেলায় শেষ দুইটা বিপদ। তাই কোনো client, proxy বা job queue একটা request retry করার আগে কাউকে জানতে হবে: এই operation আবার করা কি safe?
Think of a lift button
তুমি lift এর call button চাপলে। কিছু হচ্ছে না মনে হলো, তাই আরো পাঁচবার চাপলে। Lift তবুও একবারই আসে। "Lift কে 3 তলায় ডাকো" চাপা হলো idempotent: প্রথম চাপে কাজ হয়, বাকিগুলো কিছুই বদলায় না।
এবার ভাবো একটা vending machine, যেখানে "B4" এর প্রতিটা চাপে এক packet chips পড়ে আর 50 টাকা কাটে। Machine ধীর মনে হলো বলে পাঁচবার চাপলে খরচ 250 টাকা। ওই button idempotent না।
Idempotency key vending machine কে lift button বানিয়ে দেয়। তুমি order এ একটা unique ticket number লিখে দাও। Machine ticket number মনে রাখে। একই ticket আবার আসলে শুধু প্রথমবারের receipt দেখিয়ে দেয়।
Analogy টা কোথায় খাটে না। Lift button স্বভাবতই idempotent। Payment না। Server এটাকে idempotent বানায় কোন key গুলো দেখেছে সেটা মনে রেখে। এই memory store করতে হয়, সব server এর মধ্যে share করতে হয়, আর সব retry cover করার মতো লম্বা সময় রাখতে হয়।
The building blocks
- Safe মানে request server এর state বদলায় না: GET, HEAD, OPTIONS। Crawler, prefetcher আর cache এগুলো ইচ্ছামতো পাঠায়। (Log লেখা বা view গোনা ঠিক আছে, কারণ client কোনো বদল চায়নি।)
- Idempotent মানে N বার পাঠালে একবার পাঠানোর মতোই state থাকে। GET, HEAD, PUT আর DELETE definition অনুযায়ীই idempotent।
PUT /users/1/email "[email protected]"একটা value set করে, আবার set করলে কিছু বদলায় না।DELETE /orders/7মুছে ফেলে, আবার delete করলেও মোছাই থাকে। - State একই, response একই না। প্রথম DELETE হয়তো
204দেবে, দ্বিতীয়টা404। তবুও এটা idempotent, কারণ দুই ক্ষেত্রেই order টা নেই। - POST আর PATCH default ভাবে idempotent না।
POST /paymentsপ্রতিবার নতুন payment বানায়।PATCHদুই রকমই হতে পারে:{"status":"paid"}একটা value set করে (idempotent),{"op":"increment","by":100}না। - পারলে operation টাকেই idempotent করে design করো। "100 যোগ করো" এর বদলে "balance 600 set করো"। "পরের order ship করো" এর বদলে "order 7 কে shipped mark করো"। Blind insert এর বদলে upsert (
INSERT ... ON CONFLICT DO NOTHING)। - বাকিগুলোর জন্য idempotency key। Client প্রতিটা উদ্দেশ্য করা operation এর জন্য একটা unique key (একটা UUID) বানায়, আর
Idempotency-Keyএর মতো একটা header এ পাঠায়। Server রাখে key → request এর fingerprint + response। একই key আবার আসলে store করা response পায়, কাজ আবার হয় না। - Key কে একই request cover করতে হবে। একই key যদি আলাদা body নিয়ে আসে (500 এর বদলে amount 900), সেটা client এর bug। Reject করো (
422)। আলাদা request এর জন্য চুপচাপ পুরনো উত্তর ফেরত দিও না। - একসাথে আসা duplicate। প্রথম চেষ্টা চলতে চলতেই retry আসতে পারে। কাজ করার আগেই key store করো (status "in progress", unique constraint দিয়ে protected), আর duplicate কে
409দাও অথবা অপেক্ষা করাও।
একটা client DELETE /orders/7 পাঠায়। Server delete করে 204 দেয়, কিন্তু response হারিয়ে যায়। Client retry করে। দ্বিতীয় DELETE এর কী করা উচিত?
Behind the scenes: a payment with a key
POST /payments, হারানো response, safe retry
ধাপ 1/5 App এই payment এর জন্য একটা key বানায়
পাঠানোর আগে app বানায় Idempotency-Key: k-81f2, আর pending payment এর সাথে রেখে দেয়। তাই এই payment এর প্রতিটা retry একই key use করে।
- key
- k-81f2
- amount
- 500
The picture to keep in your head
প্রতিটা request তিনটা label এর একটা পায়, আর label ঠিক করে কে এটা retry করতে পারবে।
- Safe (GET, HEAD, OPTIONS): কিছুই বদলায় না। যে কেউ যেকোনো সময় আবার করতে পারে।
- Idempotent (PUT, DELETE, আর ঠিকমতো design করা PATCH): আবার করলে একই state এ শেষ হয়। Timeout এ নিশ্চিন্তে retry করো।
- কোনোটাই না (POST, increment, "পরের কাজটা করো"): আবার করলে কাজটা আবার হয়। Retry করো শুধু idempotency key দিয়ে, নাহলে একদমই না।
Try it: safe to retry?
Retry করবে, নাকি না?
retry
Code from first principles
একটা payment server, যেটা idempotency key মনে রাখে। তার সামনে একটা network, যেটা প্রথম response হারিয়ে ফেলে। Client timeout পেলে retry করে, ঠিক আসল HTTP library গুলোর মতো। তারপর একই key আলাদা amount দিয়ে আবার use করা হয়। শেষে একটা "set" operation আর একটা "add" operation, প্রতিটা দুইবার করে call করা হয়।
package main
import (
"fmt"
"strings"
)
// A payment server that remembers idempotency keys: key -> the request it came with + the answer.
type saved struct{ request, response string }
type server struct {
charges []string
total int
keys map[string]saved
}
func newServer() *server { return &server{keys: map[string]saved{}} }
func (s *server) pay(key string, amount int) string {
request := fmt.Sprintf("POST /payments amount=%d", amount)
if key != "" {
if old, ok := s.keys[key]; ok {
if old.request != request {
return "422 key already used for a different request"
}
return old.response + " (replayed)" // same request again: same answer, no new charge
}
}
id := fmt.Sprintf("pay_%d", len(s.charges)+1)
s.charges = append(s.charges, id)
s.total += amount
response := "201 " + id
if key != "" {
s.keys[key] = saved{request, response}
}
return response
}
// The network loses the first response: the server did the work, the client never hears back.
// The client does what every HTTP library does on a timeout: it tries again.
func payWithRetry(s *server, key string, amount int) string {
tries := []string{}
for attempt := 1; attempt <= 3; attempt++ {
resp := s.pay(key, amount)
if attempt == 1 {
tries = append(tries, "try 1 timeout")
continue
}
tries = append(tries, fmt.Sprintf("try %d %s", attempt, resp))
break
}
return strings.Join(tries, ", ")
}
func main() {
s := newServer()
r := payWithRetry(s, "", 500)
fmt.Printf("no key: %s -> charges %v, %d taka\n", r, s.charges, s.total)
s = newServer()
r = payWithRetry(s, "k-81f2", 500)
fmt.Printf("key k-81f2: %s -> charges %v, %d taka\n", r, s.charges, s.total)
fmt.Printf("same key, amount=900: %s -> charges %v\n", s.pay("k-81f2", 900), s.charges)
// Methods that are idempotent by design: the second call leaves the same state as the first.
email := ""
put := func(v string) string { email = v; return email } // PUT /users/1/email: set to a value
fmt.Printf("PUT email twice: %s, %s (same state)\n", put("[email protected]"), put("[email protected]"))
credits := 0
add := func(n int) int { credits += n; return credits } // POST /users/1/credits: add to it
fmt.Printf("add 100 twice: %d, %d (changed twice)\n", add(100), add(100))
}// A payment server that remembers idempotency keys: key -> the request it came with + the answer.
function newServer() {
return { charges: [], total: 0, keys: new Map() };
}
function pay(s, key, amount) {
const request = `POST /payments amount=${amount}`;
if (key && s.keys.has(key)) {
const old = s.keys.get(key);
if (old.request !== request) return "422 key already used for a different request";
return old.response + " (replayed)"; // same request again: same answer, no new charge
}
const id = `pay_${s.charges.length + 1}`;
s.charges.push(id);
s.total += amount;
const response = "201 " + id;
if (key) s.keys.set(key, { request, response });
return response;
}
// The network loses the first response: the server did the work, the client never hears back.
// The client does what every HTTP library does on a timeout: it tries again.
function payWithRetry(s, key, amount) {
const tries = [];
for (let attempt = 1; attempt <= 3; attempt++) {
const resp = pay(s, key, amount);
if (attempt === 1) {
tries.push("try 1 timeout");
continue;
}
tries.push(`try ${attempt} ${resp}`);
break;
}
return tries.join(", ");
}
const list = (a) => "[" + a.join(" ") + "]";
let s = newServer();
let r = payWithRetry(s, "", 500);
console.log(`no key: ${r} -> charges ${list(s.charges)}, ${s.total} taka`);
s = newServer();
r = payWithRetry(s, "k-81f2", 500);
console.log(`key k-81f2: ${r} -> charges ${list(s.charges)}, ${s.total} taka`);
console.log(`same key, amount=900: ${pay(s, "k-81f2", 900)} -> charges ${list(s.charges)}`);
// Methods that are idempotent by design: the second call leaves the same state as the first.
let email = "";
const put = (v) => (email = v); // PUT /users/1/email: set to a value
console.log(`PUT email twice: ${put("[email protected]")}, ${put("[email protected]")} (same state)`);
let credits = 0;
const add = (n) => (credits += n); // POST /users/1/credits: add to it
console.log(`add 100 twice: ${add(100)}, ${add(100)} (changed twice)`);use std::collections::HashMap;
// A payment server that remembers idempotency keys: key -> the request it came with + the answer.
struct Server {
charges: Vec<String>,
total: u32,
keys: HashMap<String, (String, String)>,
}
impl Server {
fn new() -> Self {
Server { charges: vec![], total: 0, keys: HashMap::new() }
}
fn pay(&mut self, key: &str, amount: u32) -> String {
let request = format!("POST /payments amount={}", amount);
if !key.is_empty() {
if let Some((old_request, old_response)) = self.keys.get(key) {
if *old_request != request {
return "422 key already used for a different request".to_string();
}
return format!("{} (replayed)", old_response); // same request again: same answer, no new charge
}
}
let id = format!("pay_{}", self.charges.len() + 1);
self.charges.push(id.clone());
self.total += amount;
let response = format!("201 {}", id);
if !key.is_empty() {
self.keys.insert(key.to_string(), (request, response.clone()));
}
response
}
}
// The network loses the first response: the server did the work, the client never hears back.
// The client does what every HTTP library does on a timeout: it tries again.
fn pay_with_retry(s: &mut Server, key: &str, amount: u32) -> String {
let mut tries = vec![];
for attempt in 1..=3 {
let resp = s.pay(key, amount);
if attempt == 1 {
tries.push("try 1 timeout".to_string());
continue;
}
tries.push(format!("try {} {}", attempt, resp));
break;
}
tries.join(", ")
}
fn list(a: &[String]) -> String {
format!("[{}]", a.join(" "))
}
fn main() {
let mut s = Server::new();
let r = pay_with_retry(&mut s, "", 500);
println!("no key: {} -> charges {}, {} taka", r, list(&s.charges), s.total);
let mut s = Server::new();
let r = pay_with_retry(&mut s, "k-81f2", 500);
println!("key k-81f2: {} -> charges {}, {} taka", r, list(&s.charges), s.total);
let again = s.pay("k-81f2", 900);
println!("same key, amount=900: {} -> charges {}", again, list(&s.charges));
// Methods that are idempotent by design: the second call leaves the same state as the first.
let mut email = String::new();
let mut put = |v: &str| { email = v.to_string(); email.clone() }; // PUT /users/1/email: set to a value
let (a, b) = (put("[email protected]"), put("[email protected]"));
println!("PUT email twice: {}, {} (same state)", a, b);
let mut credits = 0;
let mut add = |n: i32| { credits += n; credits }; // POST /users/1/credits: add to it
let (a, b) = (add(100), add(100));
println!("add 100 twice: {}, {} (changed twice)", a, b);
}class Server:
"""A payment server that remembers idempotency keys: key -> the request it came with + the answer."""
def __init__(self):
self.charges = []
self.total = 0
self.keys = {}
def pay(self, key, amount):
request = f"POST /payments amount={amount}"
if key and key in self.keys:
old_request, old_response = self.keys[key]
if old_request != request:
return "422 key already used for a different request"
return old_response + " (replayed)" # same request again: same answer, no new charge
id = f"pay_{len(self.charges) + 1}"
self.charges.append(id)
self.total += amount
response = "201 " + id
if key:
self.keys[key] = (request, response)
return response
def pay_with_retry(s, key, amount):
"""The network loses the first response: the server did the work, the client never hears back.
The client does what every HTTP library does on a timeout: it tries again."""
tries = []
for attempt in range(1, 4):
resp = s.pay(key, amount)
if attempt == 1:
tries.append("try 1 timeout")
continue
tries.append(f"try {attempt} {resp}")
break
return ", ".join(tries)
def lst(a):
return "[" + " ".join(a) + "]"
s = Server()
r = pay_with_retry(s, "", 500)
print(f"no key: {r} -> charges {lst(s.charges)}, {s.total} taka")
s = Server()
r = pay_with_retry(s, "k-81f2", 500)
print(f"key k-81f2: {r} -> charges {lst(s.charges)}, {s.total} taka")
print(f"same key, amount=900: {s.pay('k-81f2', 900)} -> charges {lst(s.charges)}")
# Methods that are idempotent by design: the second call leaves the same state as the first.
state = {"email": "", "credits": 0}
def put(v): # PUT /users/1/email: set to a value
state["email"] = v
return state["email"]
def add(n): # POST /users/1/credits: add to it
state["credits"] += n
return state["credits"]
print(f"PUT email twice: {put('[email protected]')}, {put('[email protected]')} (same state)")
print(f"add 100 twice: {add(100)}, {add(100)} (changed twice)")import java.util.*;
public class Main {
// A payment server that remembers idempotency keys: key -> the request it came with + the answer.
static class Server {
List<String> charges = new ArrayList<>();
int total = 0;
Map<String, String[]> keys = new HashMap<>();
String pay(String key, int amount) {
String request = "POST /payments amount=" + amount;
if (!key.isEmpty() && keys.containsKey(key)) {
String[] old = keys.get(key);
if (!old[0].equals(request)) return "422 key already used for a different request";
return old[1] + " (replayed)"; // same request again: same answer, no new charge
}
String id = "pay_" + (charges.size() + 1);
charges.add(id);
total += amount;
String response = "201 " + id;
if (!key.isEmpty()) keys.put(key, new String[]{request, response});
return response;
}
}
// The network loses the first response: the server did the work, the client never hears back.
// The client does what every HTTP library does on a timeout: it tries again.
static String payWithRetry(Server s, String key, int amount) {
List<String> tries = new ArrayList<>();
for (int attempt = 1; attempt <= 3; attempt++) {
String resp = s.pay(key, amount);
if (attempt == 1) {
tries.add("try 1 timeout");
continue;
}
tries.add("try " + attempt + " " + resp);
break;
}
return String.join(", ", tries);
}
static String list(List<String> a) { return "[" + String.join(" ", a) + "]"; }
static String email = "";
static int credits = 0;
static String put(String v) { email = v; return email; } // PUT /users/1/email: set to a value
static int add(int n) { credits += n; return credits; } // POST /users/1/credits: add to it
public static void main(String[] args) {
Server s = new Server();
String r = payWithRetry(s, "", 500);
System.out.println("no key: " + r + " -> charges " + list(s.charges) + ", " + s.total + " taka");
s = new Server();
r = payWithRetry(s, "k-81f2", 500);
System.out.println("key k-81f2: " + r + " -> charges " + list(s.charges) + ", " + s.total + " taka");
System.out.println("same key, amount=900: " + s.pay("k-81f2", 900) + " -> charges " + list(s.charges));
// Methods that are idempotent by design: the second call leaves the same state as the first.
System.out.println("PUT email twice: " + put("[email protected]") + ", " + put("[email protected]") + " (same state)");
System.out.println("add 100 twice: " + add(100) + ", " + add(100) + " (changed twice)");
}
}Output (পাঁচটা language এই একই):
no key: try 1 timeout, try 2 201 pay_2 -> charges [pay_1 pay_2], 1000 taka
key k-81f2: try 1 timeout, try 2 201 pay_1 (replayed) -> charges [pay_1], 500 taka
same key, amount=900: 422 key already used for a different request -> charges [pay_1]
PUT email twice: [email protected], [email protected] (same state)
add 100 twice: 100, 200 (changed twice)
Output টা পড়ি:
- Key ছাড়া: try 1 এ
pay_1charge হয়েছে, কিন্তু client শুধু timeout দেখেছে। Try 2 তে charge হয়েছেpay_2। দুইটা charge, এক ride এর জন্য 1000 টাকা। Server কোনো ভুল করেনি। দুইটা request যে একই উদ্দেশ্যের, সেটা জানার কোনো উপায় তার ছিল না। - Key
k-81f2সহ: try 2 পেয়েছে201 pay_1 (replayed), হুবহু একই payment id। একটা charge, 500 টাকা। Client যে উত্তরটা miss করেছিল, সেটাই পেয়ে গেলো। - একই key, amount 900:
422। Key টা আলাদা একটা request এ use হয়েছিল, তাই server ভান না করে refuse করেছে। - PUT দুইবার:
[email protected], [email protected]। Value set করা idempotent, দ্বিতীয় call কিছুই বদলায়নি। - Add দুইবার:
100, 200। Code দেখতে একই রকম, কিন্তু idempotent না। এমন operation এর জন্যই key লাগে, অথবা নতুন design ("credits 100 set করো")।
Production এ "key মনে রাখা" অংশটা সাধারণত database এর একটা unique constraint। তাই একই key নিয়ে দুইটা server race করলেও দুইজনই কাজটা করতে পারে না। এখানে আসল PostgreSQL 16 এ:
$ psql -q -e < idem.sql
CREATE TABLE payments (id serial PRIMARY KEY, idem_key text UNIQUE, amount int);
INSERT INTO payments (idem_key, amount) VALUES ('k-81f2', 500) ON CONFLICT (idem_key) DO NOTHING RETURNING id;
id
----
1
(1 row)
INSERT INTO payments (idem_key, amount) VALUES ('k-81f2', 500) ON CONFLICT (idem_key) DO NOTHING RETURNING id;
id
----
(0 rows)
SELECT count(*) AS charges, sum(amount) AS taka FROM payments;
charges | taka
---------+------
1 | 500
(1 row)
- প্রথম insert ফেরত দিয়েছে
id 1: key নতুন ছিল, payment row তৈরি হয়েছে। - দ্বিতীয় insert ফেরত দিয়েছে
0 rows:ON CONFLICT (idem_key) DO NOTHINGদেখেছে key আগে থেকেই আছে, তাই skip করেছে। Application বুঝে যায় এটা repeat, আর save করা response ফেরত দেয়। 1 | 500: request যতবারই আসুক, charge একটা।
Real engineering
- তোমার client এর retry policy জানো। অনেক HTTP client, SDK, proxy আর service mesh timeout বা connection error এ retry করে। বেশিরভাগ default ভাবে শুধু idempotent method retry করে। নিশ্চিত করো তোমারটাও তাই করে, আর key ছাড়া কখনো POST auto-retry করে না।
- যে endpoint কিছু বানায়, টাকা সরায়, message পাঠায় বা job শুরু করে, সবগুলোতে
Idempotency-Keyheader নাও। Stripe, PayPal আর Adyen সবাই এভাবে কাজ করে। Header টা standard করার জন্য একটা IETF draft ও আছে। - Key কে result সহ store করো, কাজের সাথে একই transaction এ। Payment commit হলো কিন্তু key হলো না (বা উল্টোটা), তাহলে retry ভেঙে যায়। Client যতক্ষণ retry করতে পারে, অন্তত ততক্ষণ key রাখো (প্রায়ই 24 ঘণ্টা), তারপর expire করো।
- Request এর fingerprint নাও (method, path আর body এর hash), আর একই key আলাদা fingerprint নিয়ে আসলে reject করো।
- চলমান অবস্থায় আসা duplicate সামলাও, key তে unique constraint আর একটা status column দিয়ে। প্রথমটা চলতে চলতে duplicate আসলে
409 Conflictদাও (Retry-Afterসহ)। - Consumer কেও idempotent বানাও। Message queue "at least once" deliver করে (Module 8), তাই একই event দুইবার আসতে পারে। Process হওয়া event id record করো, অথবা handler কে "add" না বানিয়ে "set" বানাও।
When it breaks
একটা failure বেছে নাও
same cart, two orders, 3 seconds apart
Think before you read on
Idempotency key টা client কেন বানাবে, server কেন না? Server key দিয়ে দিলে কি সহজ হতো না?
Reveal
Key টা প্রথম request পাঠানোর আগেই থাকতে হবে, কারণ পুরো উদ্দেশ্যই হলো request টা retry হয়ে ফিরে আসলে তাকে চিনতে পারা। Server key বানালে সেটা response এ পাঠাতো, আর ঠিক response টাই তো হারিয়ে যায়। তখন client key না জেনেই retry করতো, আর server দেখতো নতুন একটা request। তাই client key বানায় (একটা random UUID ই যথেষ্ট), যে operation করতে চাইছে তার সাথে save করে রাখে, আর প্রতিটা চেষ্টায় একই key পাঠায়। Server-side একটা বিকল্প হলো দুই ধাপের flow (POST /payment-intents দিয়ে একটা id নাও, তারপর confirm করো)। এটা কাজ করে, কারণ একটা intent বানানো আবার করলে ক্ষতি নেই।
Check yourself
1. Safe আর idempotent এর পার্থক্য কী?
Answer
Safe মানে request server এর state বদলায় না (GET, HEAD, OPTIONS)। Idempotent মানে আবার করলেও একবার করার মতো state থাকে (safe method গুলো, সাথে PUT আর DELETE)। সব safe method idempotent, কিন্তু সব idempotent method safe না।
2. দ্বিতীয় call 404 দিলেও কি DELETE idempotent থাকে?
Answer
হ্যাঁ। Idempotency server এর state নিয়ে, হুবহু একই response নিয়ে না। একটা বা দুইটা DELETE এর পর resource টা নেই।
3. Idempotency key কীভাবে double charge আটকায়?
Answer
Client একটা operation এর প্রতিটা চেষ্টায় একই unique key পাঠায়। Server প্রথমবার key টা result সহ save করে, আর repeat হলে কাজ আবার না করে save করা result ফেরত দেয়।
4. পরিচিত একটা key আলাদা body নিয়ে আসলে server এর কী করা উচিত?
Answer
Reject করা (যেমন 422)। Key একটা নির্দিষ্ট request কে চেনায়। আলাদা request এর জন্য পুরনো result দিলে client এর bug লুকিয়ে যাবে।
Your challenge: handle the in-progress duplicate
Server টা এমনভাবে বাড়াও, যাতে প্রথম চেষ্টা চলতে চলতে duplicate আসতে পারে:
payকে ভাগ করোstart(key, amount)আরfinish(key)এ।startkey টা statusin_progressদিয়ে claim করে।finishcharge করে, response save করে, আর statusdoneকরে।startযদি এমন key দেখে যেটাin_progress, ফেরত দাও409 still processing।doneহলে save করা response আবার দাও।- Simulate করো:
start(k1), তারপর একটা duplicatestart(k1), তারপরfinish(k1), তারপর তৃতীয়start(k1)।
Run করার আগে predict করো: তিনটা উত্তর কী হবে, আর charge কয়টা?
তুমি সফল যখন output হবে started, 409 still processing, তারপর 201 pay_1 (replayed), ঠিক একটা charge সহ। আর in_progress check সরিয়ে দিলে duplicate একটা দ্বিতীয় charge বানাবে।
The mental model
Network response হারায়, আর timeout পাওয়া client বুঝতে পারে না কাজটা হয়েছে কিনা, তাই retry করে। Safe request (GET, HEAD, OPTIONS) কিছুই বদলায় না; idempotent গুলো (PUT, DELETE, value set করা PATCH) যতবারই চলুক একই state এ শেষ হয়। বাকি সবকিছুর জন্য client প্রতিটা উদ্দেশ্য করা operation এ একটা idempotency key পাঠায়, আর server key, request এর fingerprint আর response store করে, কাজের সাথে atomically, repeat এ save করা উত্তর আবার দেয়। যেখানে পারো, operation কে "add" না বানিয়ে "set" বানাও।
Station stamp
Chapter শেষ করো
পড়া শেষ হলে Complete চাপো, progress save হবে। XP শুধু Pro তে — Pro থাকলে এই chapter এ +10 XP পেতে।
Pro নিয়ে XP পাও →