Skip to content

Designing Idempotent Apis & Exactly-Once Semantics In Distributed Systems

1) Problem Clarification / Làm rõ khái niệm

EN

Clients retry requests due to:

  • network failure
  • timeout
  • unknown response status

Without protection, retries can cause:

  • double payment
  • duplicate booking
  • duplicate message

Idempotent API ensures same result no matter how many retries.

VI

Client thường retry vì:

  • mạng lỗi
  • timeout
  • không biết server đã xử lý chưa

Retry có thể gây:

  • thanh toán hai lần
  • double booking
  • duplicate message

API idempotent đảm bảo kết quả như nhau dù gọi nhiều lần.

2) Definitions / Định nghĩa

EN

✔ Idempotent Operation = calling multiple times gives same effect

✔ Exactly-once semantics = operation guaranteed executed once (logically)

VI

✔ Idempotent = gọi bao nhiêu lần cũng ra kết quả như 1 lần

✔ Exactly-once = thực thi đúng 1 lần (về mặt logic, thực tế có thể nhiều lần nhưng bù trừ)

3) Why Needed? / Tại sao cần?

EN

  • unreliable networks
  • retry logic
  • microservice hop failures
  • asynchronous messaging

VI

Cần vì:

  • mạng không ổn định
  • client retry
  • microservice chain fail
  • async messaging

4) Architectural Patterns for Idempotency / Pattern idempotency

EN

Techniques:

  1. Client-provided idempotency key
  2. Server-generated transaction IDs
  3. Operation deduplication via storage
  4. Result caching to return previous response

VI

Cách thực hiện:

  1. Client cung cấp idempotency key
  2. Server sinh transaction id
  3. Lưu record để check duplicate
  4. Cache kết quả để trả lại khi retry

5) Implementation Example: Payment API

EN

Store an entry:

idempotency:<key> = status, result

When request arrives:

  • if existing → return stored result
  • else process & store result & lock state

VI

Lưu entry:

idempotency:<key>

Request đến:

  • tồn tại → trả result cũ
  • không tồn tại → xử lý + lưu result

6) Idempotency State Machine / Máy trạng thái

EN

States:

  • PROCESSING
  • SUCCESS
  • FAILED
  • UNKNOWN

Retries reconcile into SUCCESS or FAILED state.

VI

State:

  • PROCESSING
  • SUCCESS
  • FAILED
  • UNKNOWN

Retry phải update vào state cuối.

7) Exactly-Once Messaging Semantics / Exactly-once trong messaging

EN

Kafka / SQS approach:

  1. write message
  2. process message
  3. commit offset after success
  4. on retry, skip duplicates

VI

Kafka/SQS:

  1. write message
  2. process
  3. commit offset
  4. retry check duplicate và skip

8) Anti-Duplicate Techniques / Kỹ thuật chống duplicate

EN

  • Deduplication key store
  • hash-based fingerprint
  • sequence number per user/device
  • optimistic concurrency (CAS)

VI

Kỹ thuật:

  • dedup key store
  • fingerprint hash
  • sequence number
  • optimistic CAS

9) Distributed Locking / Lock phân tán

EN

To enforce exactly-once:

  • Redis Redlock
  • DB row locking
  • Zookeeper locks

But locking introduces contention → use minimally.

VI

Lock phân tán:

  • Redis Redlock
  • lock row DB
  • Zookeeper

Nhưng lock tạo contention → chỉ dùng khi cần.

10) Statlessness vs Idempotency / Stateless vs Idempotent

EN

Stateless app cannot remember previous results → store idempotency state externally (Redis, DB)

VI

App stateless không nhớ gì → cần storage ngoài (Redis/DB) để giữ state idempotency.

11) Failure Modes & Risk Handling / Trường hợp lỗi

EN

  • partial failure → client retries → must return same result
  • network timeout → must not double charge
  • duplicate message for async queue → dedupe worker logic

VI

Lỗi:

  • partial fail → client retry → phải trả kết quả như cũ
  • timeout mạng → không được charge 2 lần
  • duplicate message → worker phải dedupe

12) Observability Metrics / Metric giám sát

EN

  • idempotency hit rate
  • retry success vs failure
  • stale key retention
  • latency spikes due to lock contention

VI

Theo dõi:

  • tỷ lệ hit idempotency
  • retry success/failure
  • TTL key tồn
  • latency khi lock contention

13) Practical System Example / Ví dụ thực tế

EN

Stripe, PayPal, banking gateways enforce idempotency to avoid double charging.

DynamoDB and Redis used as idempotency stores.

VI

Stripe/PayPal/bank yêu cầu idempotency để tránh charge 2 lần.

Họ dùng DynamoDB/Redis để lưu state idempotency.

14) Future enhancements / Nâng cấp

EN

  • automatic expiration of idempotency keys
  • queryable error reconciliation
  • ML-based fraud analytics on retry behavior

VI

  • TTL key tự động
  • reconciliation UI
  • phân tích retry bằng ML để phát hiện fraud
Published inAll

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *