惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Troy Hunt's Blog
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
F
Full Disclosure
Recorded Future
Recorded Future
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
博客园_首页
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Hacker News: Front Page
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
博客园 - 司徒正美
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Cloudbric
Cloudbric
PCI Perspectives
PCI Perspectives
有赞技术团队
有赞技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
量子位
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tailwind CSS Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
P
Proofpoint News Feed
N
News and Events Feed by Topic
罗磊的独立博客
T
Threat Research - Cisco Blogs
Schneier on Security
Schneier on Security
T
Tor Project blog
IT之家
IT之家
M
MIT News - Artificial intelligence
S
Security @ Cisco Blogs
O
OpenAI News
AI
AI
S
Securelist
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
月光博客
月光博客
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Idempotency Keys: What Most Tutorials Don't Tell You
Thea · 2026-04-29 · via DEV Community

Every payment flow has a silent enemy: the network. Requests time out, connections drop, users panic, and click twice. What happens to your system when the same charge arrives more than once?
I used to think idempotency keys were one of those "nice-to-have backend things."
You know the kind you tell yourself you'll fix later. That thinking is dangerous.
When it comes to payments, idempotency isn't a feature; it's what prevents duplicate charges and inconsistent state.

The Problem: "The Double Tap"

Imagine this:

  1. A user clicks "Pay"
  2. The network is slow, or their Wi-Fi drops
  3. They click "Pay" again
  4. Your API receives two identical requests

If you're not handling this correctly:

  • The user gets charged twice
  • Your database ends up in a weird state
  • You lose user trust instantly

This doesn't require a bug. It's normal behavior in distributed systems.

What Is Idempotency?

In simple terms:

You can send the same request multiple times, but it will be processed only once.

Every retry with the same key should return the same result as the first successful request.

Important edge case: idempotency ≠ caching

It's tempting to think:

"If something fails, just return the same failure."

But it's not that simple.

  • If the request never reached your server logic, a retry should proceed normally
  • If the request may have started processing, you must rely on stored state, not assumptions
  • If an external system (like a payment provider) already processed the charge, a retry must not trigger it again

Idempotency protects against duplicate processing, not against retrying genuinely unprocessed requests.

The Key: Idempotency-Key

To make this work, every payment intent needs a unique identifier.
This key must be generated once per intent (not per click) and reused across retries.

// ❌ WRONG: New key on every click
// const handlePay = () => {
//   const key = crypto.randomUUID();
// }

// ✅ RIGHT: One key per payment intent
const idempotencyKey = crypto.randomUUID(); // generate when checkout loads

fetch('/api/payments/charge', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Idempotency-Key': idempotencyKey
  },
  body: JSON.stringify(payload)
});

Enter fullscreen mode Exit fullscreen mode

Where does the key live on the client?

"Generated once" means you need to persist it across retries.
Good options:

  • React state or a ref (single-page flow)
  • sessionStorage (if reloads are possible)
  • A server-generated key passed into the checkout session

The key should be tied to the intent, not the button click.

🔒 Security note: Idempotency keys can reveal payment patterns (e.g., same key on retry = something went wrong). Always send them over HTTPS, and avoid logging full keys in plaintext in production logs; hash or truncate if needed.

The Server Side: Where the Real Work Happens

Sending the header does nothing unless your backend actually uses it.
Here's the core logic:

async function handleChargeRequest(req, res) {
  const key = req.headers['idempotency-key'];

  if (!key) {
    return res.status(400).json({ error: 'Idempotency-Key header is required' });
  }
  const existing = await keyStore.get(key);

  // 🚨 Same key must always mean the same intent
  if (existing) {
    const currentSignature = extractBusinessSignature(req.body);
    const storedSignature = existing.businessSignature;

    if (currentSignature !== storedSignature) {
      return res.status(409).json({
        error: 'Idempotency key reused with different payment details'
      });
    }
    return res.status(existing.statusCode).json(existing.body);
  }

  // Process the payment
  const result = await paymentProvider.charge(req.body);
  const statusCode = result.success ? 200 : 400;

  // Store every deterministic response (success or known failure)
  await keyStore.set(key, {
    statusCode,
    body: result,
    businessSignature: extractBusinessSignature(req.body)
  });
  return res.status(statusCode).json(result);
}

// Only include immutable business fields - never timestamps, request IDs, or metadata
function extractBusinessSignature(payload) {
  return JSON.stringify({
    amount: payload.amount,
    currency: payload.currency,
    customerId: payload.customerId,
  });
}

Enter fullscreen mode Exit fullscreen mode

If the payment provider returns a failure (e.g., 402 or 500), you should store that response just like a success. Otherwise, a retry might reprocess the same key and produce a different result, breaking idempotency.

The only exception is when the result is unknown (e.g., network timeout or provider unavailable). In those cases, the client should retry with the same key, and your system should check the provider state before deciding what to return.

The Real Danger: Concurrency

Here's where most implementations break.
Two identical requests can arrive at the same time:

  • both check "key not found"
  • both proceed
  • both charge the user

Game over.

The fix

You need a database-level unique constraint on the idempotency key.
This is what actually makes sure only one request wins.

CREATE TABLE idempotency_keys (
  key TEXT PRIMARY KEY,
  response JSONB,
  status_code INT,
  business_signature TEXT,
  created_at TIMESTAMP DEFAULT NOW()
);

Enter fullscreen mode Exit fullscreen mode

In production, the key should be inserted with a unique constraint before processing the payment to avoid race conditions.

If two requests try to insert the same key:

  • one succeeds
  • the other fails → and must fetch the stored result

Without this, your idempotency is not reliable.

Don't use SQL?

The unique constraint is ideal, but here are alternatives:

  • Redis: SET key value NX EX ttl (atomic create-if-not-exists)
  • MongoDB: unique index on idempotencyKey
  • DynamoDB: conditional write with attribute_not_exists(idempotencyKey)

Whatever you use, the operation must be atomic. A check-then-insert pattern will always have a race condition.

Fake Idempotency (Very Common)

A lot of systems look correct, but aren't.
Examples:

  • checking the key but not storing the response
  • storing the key but not handling concurrency
  • using in-memory storage in a distributed system

This creates a false sense of safety, which is worse than having none.

Key Expiration: The Gotcha Nobody Mentions

Idempotency keys shouldn't live forever.
A typical approach:

  • keep them for ~24 hours
  • clean up old entries

Why?

  • prevents unlimited storage growth
  • gives you a safe retry window

After expiration, the same key can be treated as new. This is fine only if the original session has ended (for example, the user abandoned checkout).

⚠️ Be careful: if a key expires while a payment is still processing (rare, but possible), a retry could create a duplicate. Set expiration long enough to cover your processing time and retry window. 24 hours is usually safe for most payment flows.

The Full Flow

CHECKOUT LOADS
      ↓
Generate idempotency key (once)
      ↓
User clicks "Pay"
      ↓
POST /charge (Idempotency-Key)
      ↓
SERVER: Key exists? ── YES → return stored response ✓
      │
      NO
      ↓
Try to insert key (unique constraint)
      │
      ├─ success → process payment → store result
      │
      └─ fail → fetch existing result
      ↓
Return response

Enter fullscreen mode Exit fullscreen mode

A Quick Note on HTTP Methods

GET requests are intended to be idempotent; calling them multiple times should not change server state.
Idempotency keys are mainly for POST and PATCH - basically, anything that changes state.

Idempotency Beyond Payments

This isn't just about payments. The same idea applies to:

  • email sending (avoid duplicates)
  • webhook handling (providers retry delivery)
  • message queues (at-least-once delivery)
  • database writes (deduplication)

Anywhere you need exactly-once behavior on unreliable networks, idempotency is your tool.

How to Test It (Because Trust, But Verify)

💡 Pro tip: Don't just hope it works, prove it.
In your tests, send the same idempotency key twice:

test('idempotent charge: second request returns cached result', async () => {
  const key = 'test_order_123';
  const payload = { amount: 2000, currency: 'USD', customerId: 'cus_abc' };

  // First request — processes payment
  const res1 = await request(app).post('/charge')
    .set('Idempotency-Key', key)
    .send(payload);

  // Second request — should return cached result, NOT call payment provider again
  const res2 = await request(app).post('/charge')
    .set('Idempotency-Key', key)
    .send(payload);
  expect(res2.body).toEqual(res1.body);
  expect(paymentProviderMock.charge).toHaveBeenCalledTimes(1); // 🔑 critical check
});

Enter fullscreen mode Exit fullscreen mode

If your mock gets called twice, your idempotency is leaking. Fix it before prod.

Quick Checklist

Before shipping a payment flow:

  • [ ] Key generated once per intent
  • [ ] Key persisted across retries
  • [ ] Backend checks key before processing
  • [ ] Response is stored and reused
  • [ ] Payload consistency is validated
  • [ ] Database enforces a unique constraint
  • [ ] Key store is shared across instances
  • [ ] Expiration policy is defined

If one of these is missing, it's not done.


TL;DR

Client sends the same key. The server enforces a unique constraint. Store every result (success or failure). Return stored result on retry.
Miss any of these? You don't have idempotency. You have hope.
The double tap is coming. Be ready for it.