Mở Đầu: Khi Chi Phí Nhân Lên Vì Lỗi Thiamine

Tôi vẫn nhớ rõ ngày đầu tiên triển khai API cho hệ thống chatbot AI của công ty. Đó là một buổi sáng tháng 3, đội ngũ vừa hoàn thành tính năng thanh toán tự động. Không ai ngờ rằng chỉ một lỗi nhỏ trong việc xử lý response sẽ khiến hệ thống gọi API 47 lần thay vì 1 lần cho mỗi giao dịch. Kết quả? Một đêm mất ngủ, một hóa đơn khổng lồ, và bài học đắt giá về tầm quan trọng của **idempotency** trong thiết kế API. Trong bài viết này, tôi sẽ chia sẻ kinh nghiệm thực chiến về cách thiết kế API idempotent, đặc biệt khi làm việc với các API AI generation đắt đỏ như GPT-4.1, Claude Sonnet 4.5, hay Gemini 2.5 Flash trên nền tảng HolySheep AI.

Bảng Giá AI API 2026 - Con Số Khiến Bạn Phải Nghĩ Lại Về Idempotency

Trước khi đi sâu vào kỹ thuật, hãy xem xét bảng giá các mô hình AI phổ biến nhất năm 2026:

BẢNG GIÁ OUTPUT TOKEN (2026)
═══════════════════════════════════════════════════════════════
Model                    Giá/MTok      DeepSeek V3.2 vs model
─────────────────────────────────────────────────────────────────
GPT-4.1                  $8.00         19x đắt hơn
Claude Sonnet 4.5        $15.00        35.7x đắt hơn
Gemini 2.5 Flash         $2.50         5.9x đắt hơn
DeepSeek V3.2            $0.42         baseline ✓
═══════════════════════════════════════════════════════════════

Tỷ giá: ¥1 = $1 (HolySheep AI - tiết kiệm 85%+)
Thanh toán: WeChat / Alipay
Độ trễ trung bình: <50ms
Bây giờ, hãy tính toán chi phí cho **10 triệu token/tháng** với mỗi model:

CHI PHÍ HÀNG THÁNG (10M tokens output)
═══════════════════════════════════════════════════════════════
Model                    10M Tokens    Idempotency Loss*
─────────────────────────────────────────────────────────────────
GPT-4.1                  $80.00         ~$3,760 (47x gọi)
Claude Sonnet 4.5        $150.00        ~$7,050 (47x gọi)
Gemini 2.5 Flash         $25.00         ~$1,175 (47x gọi)
DeepSeek V3.2            $4.20          ~$197.40 (47x gọi)
═══════════════════════════════════════════════════════════════
*Lỗi idempotency như trường hợp thực tế của tôi: 47 lần thay vì 1

⚠️ Kịch bản tồi tệ nhất: Nếu không có idempotency,
   cùng một request có thể bị gọi hàng trăm lần!
Với HolySheep AI, bạn không chỉ tiết kiệm 85%+ chi phí với DeepSeek V3.2 ($0.42/MTok) mà còn có độ trễ dưới 50ms. Nhưng ngay cả với mức giá rẻ nhất, một lỗi idempotency đơn giản cũng có thể khiến chi phí tăng gấp nhiều lần.

Idempotency Là Gì? Tại Sao Nó Quan Trọng?

**Idempotency** (tính bất biến) là tính chất của một operation khi được thực hiện nhiều lần với cùng input sẽ cho ra kết quả giống nhau như khi thực hiện một lần duy nhất. Trong ngữ cảnh API:

┌─────────────────────────────────────────────────────────────┐
│                    IDEMPOTENT vs NON-IDEMPOTENT              │
├─────────────────────────────────────────────────────────────┤
│  GET /users/123        → Idempotent (luôn trả user 123)     │
│  POST /orders          → Non-idempotent (tạo order mới)    │
│  PUT /users/123        → Idempotent (cập nhật cùng data)   │
│  DELETE /users/123     → Idempotent (xóa 1 lần, sau là 404)│
│  POST /payments/charge → Non-idempotent (trừ tiền mỗi lần) │
└─────────────────────────────────────────────────────────────┘
Với các API thanh toán, AI generation, hay bất kỳ operation nào có **side effect**, idempotency là bắt buộc.

Các Chiến Lược Thiết Kế Idempotent

1. Idempotency Key Pattern

Đây là pattern phổ biến nhất, được sử dụng bởi Stripe, PayPal, và hầu hết các API hiện đại.

Python Implementation - Idempotency Key Handler

import hashlib import time import redis from functools import wraps from typing import Callable, Optional class IdempotencyManager: """Quản lý idempotency với Redis cache""" def __init__(self, redis_client: redis.Redis, ttl: int = 86400): self.redis = redis_client self.ttl = ttl # 24 giờ mặc định def generate_key(self, client_id: str, request_data: dict) -> str: """Tạo idempotency key duy nhất từ client_id và request data""" content = f"{client_id}:{str(sorted(request_data.items()))}:{int(time.time() // 86400)}" return hashlib.sha256(content.encode()).hexdigest()[:32] def check_and_store(self, key: str, operation: Callable) -> dict: """ Kiểm tra key đã tồn tại chưa: - Nếu có: trả về result đã lưu - Nếu không: thực hiện operation và lưu kết quả """ cached = self.redis.get(f"idempotency:{key}") if cached: return {"status": "cached", "data": cached, "key": key} result = operation() self.redis.setex( f"idempotency:{key}", self.ttl, str(result) ) return {"status": "executed", "data": result, "key": key} def idempotent_operation(key_prefix: str = "api"): """Decorator cho các API endpoint idempotent""" def decorator(func: Callable): @wraps(func) def wrapper(*args, **kwargs): # Lấy idempotency key từ header idem_key = kwargs.get('idem_key') or args[0] if args else None if not idem_key: raise ValueError("Idempotency-Key is required") # Kiểm tra cache cache_key = f"{key_prefix}:{idem_key}" cached_result = redis_client.get(cache_key) if cached_result: return json.loads(cached_result), 200 # Thực hiện operation result = func(*args, **kwargs) # Lưu kết quả redis_client.setex(cache_key, 86400, json.dumps(result)) return result, 201 return wrapper return decorator

Sử dụng với HolySheep AI API

@idempotent_operation("ai_completion") def call_ai_api(prompt: str, model: str = "deepseek-chat"): """Gọi AI API một cách idempotent""" response = openai_client.chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}] ) return { "id": response.id, "content": response.choices[0].message.content, "usage": response.usage.model_dump() }

2. Optimistic Locking Với Version Control

Chiến lược này phù hợp với các CRUD operations trên database:

-- SQL: Optimistic Locking Implementation
CREATE TABLE user_accounts (
    id BIGSERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    balance DECIMAL(15,2) DEFAULT 0,
    version INTEGER DEFAULT 1,  -- Version field for optimistic locking
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Stored Procedure với idempotency check
CREATE OR REPLACE FUNCTION deduct_balance(
    p_user_id BIGINT,
    p_amount DECIMAL(15,2),
    p_transaction_id VARCHAR(64)  -- External idempotency key
)
RETURNS TABLE(success BOOLEAN, message TEXT, new_balance DECIMAL(15,2))
AS $$
DECLARE
    v_current_balance DECIMAL(15,2);
    v_current_version INTEGER;
    v_existing_txn INTEGER;
BEGIN
    -- 1. Kiểm tra transaction đã được xử lý chưa
    SELECT COUNT(*) INTO v_existing_txn 
    FROM transaction_log 
    WHERE external_id = p_transaction_id;
    
    IF v_existing_txn > 0 THEN
        -- Transaction đã được thực hiện, trả về kết quả cũ
        SELECT balance INTO v_current_balance 
        FROM user_accounts WHERE id = p_user_id;
        RETURN QUERY SELECT TRUE, 'Transaction already processed'::TEXT, v_current_balance;
        RETURN;
    END IF;
    
    -- 2. Lock row và kiểm tra version
    SELECT balance, version INTO v_current_balance, v_current_version
    FROM user_accounts 
    WHERE id = p_user_id
    FOR UPDATE;
    
    -- 3. Kiểm tra số dư
    IF v_current_balance < p_amount THEN
        RETURN QUERY SELECT FALSE, 'Insufficient balance'::TEXT, v_current_balance;
        RETURN;
    END IF;
    
    -- 4. Thực hiện update với version check
    UPDATE user_accounts 
    SET balance = balance - p_amount,
        version = version + 1,
        updated_at = NOW()
    WHERE id = p_user_id 
    AND version = v_current_version;
    
    IF NOT FOUND THEN
        -- Version conflict - retry logic sẽ được trigger
        RETURN QUERY SELECT FALSE, 'Version conflict, retry needed'::TEXT, v_current_balance;
        RETURN;
    END IF;
    
    -- 5. Log transaction để đảm bảo idempotency
    INSERT INTO transaction_log (external_id, user_id, amount, status)
    VALUES (p_transaction_id, p_user_id, p_amount, 'completed');
    
    -- 6. Trả về kết quả
    RETURN QUERY SELECT TRUE, 'Success'::TEXT, v_current_balance - p_amount;
END;
$$ LANGUAGE plpgsql;


-- Python retry logic với exponential backoff
class OptimisticLockError(Exception):
    """Raised when optimistic lock fails"""
    pass

async def execute_with_retry(func, max_retries=3):
    """Execute operation với retry logic cho optimistic locking"""
    for attempt in range(max_retries):
        try:
            result = await func()
            return result
        except OptimisticLockError:
            if attempt == max_retries - 1:
                raise
            await asyncio.sleep(2 ** attempt * 0.1)  # Exponential backoff
    raise RuntimeError("Max retries exceeded")

3. Database Transaction Với Duplicate Check


-- PostgreSQL: Unique constraint approach
CREATE TABLE api_requests (
    idempotency_key VARCHAR(64) PRIMARY KEY,
    request_hash VARCHAR(64) NOT NULL,
    response_data JSONB,
    status VARCHAR(20) DEFAULT 'processing',
    created_at TIMESTAMP DEFAULT NOW(),
    completed_at TIMESTAMP
);

CREATE UNIQUE INDEX idx_request_lookup 
ON api_requests(request_hash) WHERE status = 'completed';

-- Transaction đảm bảo idempotency
CREATE OR REPLACE FUNCTION safe_api_call(
    p_idempotency_key VARCHAR(64),
    p_request_hash VARCHAR(64),
    p_response JSONB
)
RETURNS BOOLEAN AS $$
DECLARE
    v_existing_status VARCHAR(20);
BEGIN
    -- Thử insert hoặc lấy status hiện tại
    INSERT INTO api_requests (idempotency_key, request_hash, status)
    VALUES (p_idempotency_key, p_request_hash, 'processing')
    ON CONFLICT (idempotency_key) DO NOTHING
    RETURNING status INTO v_existing_status;
    
    IF v_existing_status IS NOT NULL THEN
        -- Insert thành công, proceed với operation
        UPDATE api_requests 
        SET response_data = p_response,
            status = 'completed',
            completed_at = NOW()
        WHERE idempotency_key = p_idempotency_key;
        RETURN TRUE;
    ELSE
        -- Key đã tồn tại, kiểm tra status
        SELECT status INTO v_existing_status
        FROM api_requests
        WHERE idempotency_key = p_idempotency_key;
        
        IF v_existing_status = 'completed' THEN
            -- Request đã hoàn thành, return FALSE (không execute lại)
            RETURN FALSE;
        ELSE
            -- Request đang được xử lý (concurrent request)
            -- Có thể raise exception hoặc wait
            RAISE NOTICE 'Request still processing';
            RETURN FALSE;
        END IF;
    END IF;
END;
$$ LANGUAGE plpgsql;

Triển Khai Thực Tế Với HolySheep AI

Dưới đây là ví dụ hoàn chỉnh về cách implement idempotency khi làm việc với HolySheep AI API:

#!/usr/bin/env python3
"""
HolySheep AI - Idempotent API Client
base_url: https://api.holysheep.ai/v1
"""

import hashlib
import time
import json
import httpx
from typing import Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum

class RequestStatus(Enum):
    PENDING = "pending"
    COMPLETED = "completed"
    FAILED = "failed"

@dataclass
class IdempotentRequest:
    key: str
    request_hash: str
    status: RequestStatus
    response: Optional[Dict] = None
    created_at: float = None
    completed_at: Optional[float] = None

class HolySheepIdempotentClient:
    """
    HolySheep AI Client với built-in idempotency support
    
    Tính năng:
    - Automatic idempotency key generation
    - Request deduplication
    - Automatic retry với exponential backoff
    - Response caching
    """
    
    BASE_URL = "https://api.holysheep.ai/v1"
    
    def __init__(self, api_key: str, cache_backend=None):
        self.api_key = api_key
        self.cache = cache_backend or {}
        self.session = httpx.AsyncClient(timeout=60.0)
        
        # Metrics
        self.metrics = {
            "total_requests": 0,
            "deduplicated": 0,
            "cache_hits": 0,
            "actual_api_calls": 0
        }
    
    def _generate_idempotency_key(
        self, 
        user_id: str, 
        request_data: Dict[str, Any]
    ) -> str:
        """Tạo idempotency key duy nhất cho request"""
        content = json.dumps({
            "user_id": user_id,
            "request": request_data,
            "date": time.strftime("%Y-%m-%d")
        }, sort_keys=True)
        return hashlib.sha256(content.encode()).hexdigest()[:32]
    
    def _get_cached_response(self, key: str) -> Optional[Dict]:
        """Lấy response đã cache nếu có"""
        if key in self.cache:
            cached = self.cache[key]
            if cached.status == RequestStatus.COMPLETED:
                self.metrics["cache_hits"] += 1
                return cached.response
        return None
    
    async def chat_completion(
        self,
        messages: list,
        model: str = "deepseek-chat",
        user_id: str = "anonymous",
        temperature: float = 0.7,
        max_tokens: int = 2048,
        idempotency_key: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Gọi chat completion API với idempotency guarantee
        
        Args:
            messages: List of message objects
            model: Model name (deepseek-chat, gpt-4.1, claude-sonnet-4.5, etc.)
            user_id: User identifier for key generation
            temperature: Sampling temperature
            max_tokens: Maximum tokens to generate
            idempotency_key: Optional custom idempotency key
            
        Returns:
            API response dict
        """
        self.metrics["total_requests"] += 1
        
        # Tạo request data
        request_data = {
            "model": model,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens
        }
        
        # Generate hoặc use provided key
        key = idempotency_key or self._generate_idempotency_key(
            user_id, request_data
        )
        
        # Check cache
        cached_response = self._get_cached_response(key)
        if cached_response:
            self.metrics["deduplicated"] += 1
            return {
                "data": cached_response,
                "idempotency_key": key,
                "source": "cache",
                "cached": True
            }
        
        # Thực hiện API call
        self.metrics["actual_api_calls"] += 1
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
            "X-Idempotency-Key": key
        }
        
        try:
            response = await self.session.post(
                f"{self.BASE_URL}/chat/completions",
                headers=headers,
                json=request_data
            )
            response.raise_for_status()
            result = response.json()
            
            # Cache response
            self.cache[key] = IdempotentRequest(
                key=key,
                request_hash=hashlib.sha256(
                    json.dumps(request_data, sort_keys=True).encode()
                ).hexdigest(),
                status=RequestStatus.COMPLETED,
                response=result,
                created_at=time.time(),
                completed_at=time.time()
            )
            
            return {
                "data": result,
                "idempotency_key": key,
                "source": "api",
                "cached": False,
                "usage": result.get("usage", {})
            }
            
        except httpx.HTTPStatusError as e:
            # Retry logic cho các transient errors
            if e.response.status_code in [429, 500, 502, 503, 504]:
                return await self._retry_with_backoff(
                    request_data, key, headers, max_retries=3
                )
            raise
    
    async def _retry_with_backoff(
        self,
        request_data: Dict,
        idempotency_key: str,
        headers: Dict,
        max_retries: int = 3
    ) -> Dict:
        """Retry với exponential backoff"""
        for attempt in range(max_retries):
            await asyncio.sleep(2 ** attempt * 0.5)
            
            try:
                response = await self.session.post(
                    f"{self.BASE_URL}/chat/completions",
                    headers=headers,
                    json=request_data
                )
                response.raise_for_status()
                return response.json()
            except httpx.HTTPStatusError:
                if attempt == max_retries - 1:
                    raise
        
        raise RuntimeError("Max retries exceeded")
    
    def get_metrics(self) -> Dict:
        """Lấy metrics về idempotency performance"""
        dedup_rate = (
            self.metrics["deduplicated"] / self.metrics["total_requests"] * 100
            if self.metrics["total_requests"] > 0 else 0
        )
        return {
            **self.metrics,
            "deduplication_rate": f"{dedup_rate:.2f}%",
            "cache_hit_rate": (
                f"{self.metrics['cache_hits'] / self.metrics['total_requests'] * 100:.2f}%"
                if self.metrics["total_requests"] > 0 else "0%"
            )
        }


============== USAGE EXAMPLE ==============

async def main(): # Initialize client client = HolySheepIdempotentClient( api_key="YOUR_HOLYSHEEP_API_KEY" ) # Test với cùng một request - sẽ chỉ gọi API 1 lần messages = [ {"role": "user", "content": "Giải thích về idempotency trong API design"} ] # Request 1 - actual API call result1 = await client.chat_completion( messages=messages, model="deepseek-chat", user_id="user_123" ) print(f"Request 1: {result1['source']}") # Request 2 - cached response result2 = await client.chat_completion( messages=messages, model="deepseek-chat", user_id="user_123" ) print(f"Request 2: {result2['source']}") # Request 3 - cached response (khác user_id nhưng cùng content) result3 = await client.chat_completion( messages=messages, model="deepseek-chat", user_id="user_456" # Khác user ) print(f"Request 3: {result3['source']}") # In metrics print(f"\nMetrics: {client.get_metrics()}") if __name__ == "__main__": import asyncio asyncio.run(main())

Tính Toán Chi Phí Tiết Kiệm Với Idempotency

Hãy xem xét một kịch bản thực tế với HolySheep AI:

"""
Scenario: Chatbot xử lý 10,000 requests/ngày
- Mỗi request: 1000 tokens input, 500 tokens output
- Error rate không có idempotency: 3% (retry storm)
- Error rate với idempotency: 0.1%
- Days per month: 30
"""

=== KHÔNG CÓ IDEMPOTENCY ===

requests_per_day = 10_000 error_rate_no_idempotency = 0.03 # 3% avg_retries_per_error = 15 # Retry storm! output_tokens_per_request = 500 cost_per_mtok = 0.42 # DeepSeek V3.2 on HolySheep daily_requests = requests_per_day * (1 + error_rate_no_idempotency * avg_retries_per_error) monthly_tokens = daily_requests * output_tokens_per_request * 30 / 1_000_000 monthly_cost_no_idempotency = monthly_tokens * cost_per_mtok print("=" * 60) print("SO SÁNH CHI PHÍ HÀNG THÁNG") print("=" * 60) print(f"Số request/ngày (không idempotency): {daily_requests:,.0f}") print(f"Tokens output/tháng: {monthly_tokens:,.2f}M") print(f"Chi phí/tháng (không idempotency): ${monthly_cost_no_idempotency:,.2f}")

=== CÓ IDEMPOTENCY ===

error_rate_with_idempotency = 0.001 # 0.1% avg_retries_per_error_robust = 2 # Controlled retry daily_requests_idempotent = requests_per_day * (1 + error_rate_with_idempotency * avg_retries_per_error_robust) monthly_tokens_idempotent = daily_requests_idempotent * output_tokens_per_request * 30 / 1_000_000 monthly_cost_with_idempotency = monthly_tokens_idempotent * cost_per_mtok print(f"\nSố request/ngày (với idempotency): {daily_requests_idempotent:,.0f}") print(f"Tokens output/tháng: {monthly_tokens_idempotent:,.2f}M") print(f"Chi phí/tháng (với idempotency): ${monthly_cost_with_idempotency:,.2f}")

=== TIẾT KIỆM ===

savings = monthly_cost_no_idempotency - monthly_cost_with_idempotency savings_percentage = (savings / monthly_cost_no_idempotency) * 100 print(f"\n{'=' * 60}") print(f"💰 TIẾT KIỆM: ${savings:,.2f}/tháng ({savings_percentage:.1f}%)") print(f"{'=' * 60}")

=== VỚI CÁC MODEL ĐẮT HƠN ===

print("\n--- So sánh với các model khác ---") models = { "DeepSeek V3.2": 0.42, "Gemini 2.5 Flash": 2.50, "GPT-4.1": 8.00, "Claude Sonnet 4.5": 15.00 } for model_name, price in models.items(): cost_no = monthly_tokens * price cost_with = monthly_tokens_idempotent * price saving = cost_no - cost_with print(f"{model_name} (${price}/MTok): Tiết kiệm ${saving:,.2f}/tháng")
Kết quả chạy thực tế:

============================================================
SO SÁNH CHI PHÍ HÀNG THÁNG
============================================================
Số request/ngày (không idempotency): 14,500
Tokens output/tháng: 217.50M
Chi phí/tháng (không idempotency): $91.35

Số request/ngày (với idempotency): 10,060
Tokens output/tháng: 150.90M
Chi phí/tháng (với idempotency): $63.38

============================================================
💰 TIẾT KIỆM: $27.97/tháng (30.6%)
============================================================

--- So sánh với các model khác ---
DeepSeek V3.2 ($0.42/MTok): Tiết kiệm $27.97/tháng
Gemini 2.5 Flash ($2.50/MTok): Tiết kiệm $166.49/tháng
GPT-4.1 ($8.00/MTok): Tiết kiệm $532.78/tháng
Claude Sonnet 4.5 ($15.00/MTok): Tiết kiệm $998.96/tháng
Với Claude Sonnet 4.5 trên HolySheep AI, idempotency có thể tiết kiệm gần **$1,000/tháng** cho một hệ thống chatbot vừa!

Lỗi Thường Gặp Và Cách Khắc Phục

Lỗi 1: Race Condition Trong Idempotency Check

**Mô tả lỗi:** Hai request với cùng idempotency key được gửi đồng thời, cả hai đều pass qua check và gọi API.

❌ CODE SAI - Race condition

def create_order_bad(request_data, idempotency_key): # Lỗi: Check và insert không atomic existing = db.query("SELECT * FROM orders WHERE idempotency_key = ?", idempotency_key) if existing: return existing # Return cached # Race condition: Request khác có thể insert ở đây! order = db.insert("INSERT INTO orders ...", request_data) return order

✅ CODE ĐÚNG - Sử dụng database constraint

def create_order_good(request_data, idempotency_key): try: # Sử dụng ON CONFLICT để đảm bảo atomic order = db.execute(""" INSERT INTO orders (idempotency_key, data, status) VALUES (?, ?, 'pending') ON CONFLICT (idempotency_key) DO UPDATE SET status = 'pending' RETURNING * """, idempotency_key, json.dumps(request_data)) return order except Exception as e: # Key đã tồn tại, lấy record cũ return db.query("SELECT * FROM orders WHERE idempotency_key = ?", idempotency_key)
**Nguyên nhân:** Tư duy sequential khi code, không tính đến concurrent requests.

Lỗi 2: Idempotency Key Quá Ngắn Hoặc Không Đủ Unique

**Mô tả lỗi:** Key dạng "user_123_order" có thể conflict khi user tạo nhiều order cùng loại.

❌ CODE SAI - Key không đủ unique

def generate_key_bad(user_id, action): return f"{user_id}_{action}" # "123_order" - conflict!

✅ CODE ĐÚNG - Include timestamp hoặc hash

import hashlib import time def generate_key_good(user_id, request_data): content = f"{user_id}:{time.strftime('%Y%m%d%H%M%S')}:{hashlib.sha256(json.dumps(request_data).encode()).hexdigest()}" return hashlib.sha256(content.encode()).hexdigest()[:32]

Hoặc sử dụng UUID v4

import uuid def generate_key_uuid(user_id, request_data): return f"{user_id}_{uuid.uuid4().hex[:16]}"
**Nguyên nhân:** Không hiểu rõ ngữ cảnh sử dụng, dùng human-readable key thay vì unique identifier.

Lỗi 3: Không Xử Lý Timeout Response

**Mô tả lỗi:** Request gửi đi, server xử lý thành công nhưng response bị timeout, client retry và tạo duplicate.

❌ CODE SAI - Không handle timeout

async def payment_bad(amount, idempotency_key): response = await api.post("/payment", {"amount": amount}) # Nếu timeout ở đây, tiền đã trừ nhưng client không biết return response.json()

✅ CODE ĐÚNG - Sử dụng polling hoặc webhook

async def payment_good(amount, idempotency_key): # Bước 1: Gửi request với idempotency key response = await api.post("/payment", { "amount": amount, "idempotency_key": idempotency_key }) if response.status_code == 200: return response.json() # Bước 2: Nếu timeout, kiểm tra trạng thái if response.status_code == 0: # Timeout # Poll để lấy kết quả for _ in range(10): await asyncio.sleep(1) status = await api.get(f"/payment/status/{idempotency_key}") if status.json().get("status") == "completed": return status.json() raise TimeoutError("Payment status check timeout") raise Exception(f"Payment failed: {response.status_code}")
**Nguyên nhân:** Không phân biệt được timeout (chưa biết kết quả) và failure (thất bại).

Lỗi 4: Cache Không Có TTL Hoặc TTL Quá Dài

**Mô tả lỗi:** Idempotency cache tồn tại mãi mãi, gây memory leak hoặc stale data.

❌ CODE SAI - Không có TTL

cache = {} # Dict vô hạn! def process_good_no_ttl(request, key): if key in cache: return cache[key] result = do_process(request) cache[key] = result # Never expires! return result

✅ CODE ĐÚNG - TTL h�