{"id":13853,"date":"2026-11-24T20:21:24","date_gmt":"2026-11-24T14:51:24","guid":{"rendered":"https:\/\/pheonixsolutions.com\/blog\/?p=13853"},"modified":"2026-11-24T20:21:29","modified_gmt":"2026-11-24T14:51:29","slug":"api-idempotency-keys","status":"publish","type":"post","link":"https:\/\/pheonixsolutions.com\/blog\/api-idempotency-keys\/","title":{"rendered":"API Idempotency Keys: How to Stop Duplicate Requests in 7 Steps"},"content":{"rendered":"\n<h2 id=\"introduction\" class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A customer taps &#8220;Pay&#8221;. The network is slow, so the app times out and tries again. The first request did reach your server, so now there are two payments. The same thing happens with orders, bookings, and text messages. The customer only asked once, but your API did the work twice.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Retries are normal. Mobile networks drop, load balancers time out, and good client libraries retry on purpose. The answer is not to stop retries. The answer is to make them safe. That is what an <strong>idempotency key<\/strong> does.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this guide, we explain what API idempotency keys are, and how to add them to your API in seven simple steps, with PHP and MySQL examples you can adapt to any stack.<\/p>\n\n\n\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\"><h2>On This Page<\/h2><nav><ul><li class=\"\"><a href=\"#introduction\">Introduction<\/a><\/li><li class=\"\"><a href=\"#what-is-an-idempotency-key\">What Is an Idempotency Key?<\/a><\/li><li class=\"\"><a href=\"#why-api-idempotency-keys-matter\">Why API Idempotency Keys Matter<\/a><\/li><li class=\"\"><a href=\"#which-http-methods-need-idempotency-keys\">Which HTTP Methods Need Idempotency Keys?<\/a><\/li><li class=\"\"><a href=\"#how-to-add-api-idempotency-keys-in-7-steps\">How to Add API Idempotency Keys in 7 Steps<\/a><\/li><li class=\"\"><a href=\"#idempotency-responses-at-a-glance\">Idempotency Responses at a Glance<\/a><\/li><li class=\"\"><a href=\"#common-idempotency-mistakes-to-avoid\">Common Idempotency Mistakes to Avoid<\/a><\/li><li class=\"\"><a href=\"#conclusion\">Conclusion<\/a><\/li><li class=\"\"><a href=\"#faqs\">FAQs<\/a><\/li><li class=\"\"><a href=\"#related-articles\">Related Articles<\/a><\/li><li class=\"\"><a href=\"#official-documentation\">Official Documentation<\/a><\/li><li class=\"\"><a href=\"#talk-to-our-api-experts\">Talk to Our API Experts<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 id=\"what-is-an-idempotency-key\" class=\"wp-block-heading\">What Is an Idempotency Key?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">An operation is <em>idempotent<\/em> when doing it many times has the same effect as doing it once. An idempotency key is a unique value that the client sends with a request, usually in an <code>Idempotency-Key<\/code> header. The server remembers the key. If the same key arrives again, the server returns the saved result instead of doing the work a second time.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>POST \/v1\/payments HTTP\/1.1\nContent-Type: application\/json\nIdempotency-Key: 7f3c91ab-44e2-4c8e-9a0b-2f6d1c3e8b17\n\n{\"amount\": 4999, \"currency\": \"INR\", \"customer_id\": 314}<\/code><\/pre>\n\n\n\n<h2 id=\"why-api-idempotency-keys-matter\" class=\"wp-block-heading\">Why API Idempotency Keys Matter<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No double charges.<\/strong> A retried payment request returns the first payment, not a new one.<\/li>\n\n\n\n<li><strong>No duplicate messages.<\/strong> A retried send does not text the same person twice.<\/li>\n\n\n\n<li><strong>Safe automatic retries.<\/strong> Clients can retry timeouts and 5xx errors without fear.<\/li>\n\n\n\n<li><strong>Simpler client code.<\/strong> The client does not need to check &#8220;did that work?&#8221; before it retries.<\/li>\n<\/ul>\n\n\n\n<h2 id=\"which-http-methods-need-idempotency-keys\" class=\"wp-block-heading\">Which HTTP Methods Need Idempotency Keys?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Some HTTP methods are already idempotent by design. <code>POST<\/code> is the one that usually needs help.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Method<\/th><th>Idempotent by default?<\/th><th>Needs a key?<\/th><\/tr><\/thead><tbody><tr><td>GET<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>PUT<\/td><td>Yes, it replaces the whole resource<\/td><td>Usually no<\/td><\/tr><tr><td>DELETE<\/td><td>Yes, deleting twice leaves it deleted<\/td><td>Usually no<\/td><\/tr><tr><td>POST<\/td><td>No, each call can create something new<\/td><td>Yes<\/td><\/tr><tr><td>PATCH<\/td><td>Not always<\/td><td>Sometimes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 id=\"how-to-add-api-idempotency-keys-in-7-steps\" class=\"wp-block-heading\">How to Add API Idempotency Keys in 7 Steps<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Let the Client Create the Key<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The client creates a new random key for each new action, and reuses the same key only when it retries that action. A UUID v4 is the easiest choice. The key must come from the client, because only the client knows that two requests are &#8220;the same&#8221;.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Client side (JavaScript)\nconst key = crypto.randomUUID();\nawait fetch('\/v1\/payments', {\n  method: 'POST',\n  headers: { 'Content-Type': 'application\/json', 'Idempotency-Key': key },\n  body: JSON.stringify(payment),\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. Create a Table to Store Keys<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Store each key with the account that sent it, a hash of the request body, and the saved response. The unique index is the most important part. It is what stops two copies of the same request from both running.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE TABLE idempotency_keys (\n  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n  account_id     BIGINT UNSIGNED NOT NULL,\n  idem_key       VARCHAR(255)    NOT NULL,\n  request_hash   CHAR(64)        NOT NULL,\n  status         ENUM('processing','done') NOT NULL DEFAULT 'processing',\n  response_code  SMALLINT        NULL,\n  response_body  MEDIUMTEXT      NULL,\n  created_at     DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,\n  UNIQUE KEY uq_account_key (account_id, idem_key)\n);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3. Scope Keys to Each Client<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Always store the key together with the account or API client ID. Two different customers could send the same key by chance. They must never see each other&#8217;s responses.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Claim the Key Before Doing the Work<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Insert the key first, before you charge the card or send the message. If the insert fails because of the unique index, another request with the same key already exists. This makes the database do the hard work of handling two requests that arrive at the same moment.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\n$hash = hash('sha256', $rawBody);\n\ntry {\n    $stmt = $pdo-&gt;prepare(\n        'INSERT INTO idempotency_keys (account_id, idem_key, request_hash)\n         VALUES (:account, :idem_key, :hash)'\n    );\n    $stmt-&gt;execute(&#091;'account' =&gt; $accountId, 'idem_key' =&gt; $key, 'hash' =&gt; $hash]);\n} catch (PDOException $e) {\n    if ($e-&gt;errorInfo&#091;1] === 1062) {         \/\/ duplicate key\n        return replayOrReject($pdo, $accountId, $key, $hash);\n    }\n    throw $e;\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. Save the Response and Replay It<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">After the work is done, save the status code and body. When the same key comes back, return exactly the same response. Many APIs also add a header such as <code>Idempotent-Replayed: true<\/code>, which helps when debugging.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nfunction replayOrReject(PDO $pdo, int $accountId, string $key, string $hash): void\n{\n    $stmt = $pdo-&gt;prepare(\n        'SELECT request_hash, status, response_code, response_body\n           FROM idempotency_keys\n          WHERE account_id = :account AND idem_key = :idem_key'\n    );\n    $stmt-&gt;execute(&#091;'account' =&gt; $accountId, 'idem_key' =&gt; $key]);\n    $row = $stmt-&gt;fetch();\n\n    if ($row&#091;'request_hash'] !== $hash) {\n        jsonResponse(422, &#091;'error' =&gt; 'Idempotency key reused with a different request']);\n    }\n    if ($row&#091;'status'] === 'processing') {\n        jsonResponse(409, &#091;'error' =&gt; 'A request with this key is still in progress']);\n    }\n\n    header('Idempotent-Replayed: true');\n    http_response_code((int) $row&#091;'response_code']);\n    echo $row&#091;'response_body'];\n    exit;\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">6. Reject the Same Key with a Different Body<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If a client sends the same key with a different amount or a different phone number, something is wrong in the client. Do not guess. Return an error, such as <code>422<\/code>, and do nothing. That is why we store a hash of the request body.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">7. Expire Old Keys<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keys do not need to live forever. Most APIs keep them for 24 hours to a few days, which covers any normal retry window. A small cron job keeps the table small:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>DELETE FROM idempotency_keys\n WHERE created_at &lt; NOW() - INTERVAL 24 HOUR\n LIMIT 10000;<\/code><\/pre>\n\n\n\n<h2 id=\"idempotency-responses-at-a-glance\" class=\"wp-block-heading\">Idempotency Responses at a Glance<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Situation<\/th><th>What the API does<\/th><th>Status code<\/th><\/tr><\/thead><tbody><tr><td>New key<\/td><td>Runs the request and saves the result<\/td><td>201 or 200<\/td><\/tr><tr><td>Same key, same body, finished<\/td><td>Returns the saved response<\/td><td>Same as the first<\/td><\/tr><tr><td>Same key, still processing<\/td><td>Asks the client to wait and retry<\/td><td>409 Conflict<\/td><\/tr><tr><td>Same key, different body<\/td><td>Rejects the request<\/td><td>422<\/td><\/tr><tr><td>No key on a POST that requires one<\/td><td>Rejects the request<\/td><td>400<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 id=\"common-idempotency-mistakes-to-avoid\" class=\"wp-block-heading\">Common Idempotency Mistakes to Avoid<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Checking before inserting.<\/strong> A <code>SELECT<\/code> followed by an <code>INSERT<\/code> has a race window. Use a unique index and let the insert decide.<\/li>\n\n\n\n<li><strong>Global keys.<\/strong> Always scope keys to the account, or customers may see each other&#8217;s data.<\/li>\n\n\n\n<li><strong>Saving the key after the work.<\/strong> If the server crashes in the middle, the retry runs the work again. Claim the key first.<\/li>\n\n\n\n<li><strong>Caching 5xx errors forever.<\/strong> If the first attempt failed because of a temporary error, remove the key or let the client retry with the same key.<\/li>\n\n\n\n<li><strong>Generating keys on the server.<\/strong> The server cannot tell two retries apart from two real requests. The client must send the key.<\/li>\n<\/ul>\n\n\n\n<h2 id=\"conclusion\" class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Networks fail, and clients will retry. Idempotency keys turn those retries from a risk into a safety net. With one table, one unique index, and a few lines of code, your API can stop double charges, duplicate orders, and repeated messages. Pair them with clear <a href=\"https:\/\/pheonixsolutions.com\/blog\/rest-api-status-codes\/\">REST API status codes<\/a>, and clients will always know what happened.<\/p>\n\n\n\n<h2 id=\"faqs\" class=\"wp-block-heading\">FAQs<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. What is an idempotency key in an API?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is a unique value the client sends with a request, usually in the Idempotency-Key header. The server uses it to recognise a retry and return the first result instead of doing the work again.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Which header should I use for idempotency keys?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Idempotency-Key is the common choice. It is used by major payment APIs and is being standardised by the IETF HTTP API working group.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. How long should I keep idempotency keys?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">24 hours is a common default. Keep them at least as long as your clients might retry a request.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Do GET requests need idempotency keys?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. GET, PUT, and DELETE are idempotent by design. Idempotency keys are mainly for POST requests that create something.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5. What should happen if two requests with the same key arrive at the same time?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Only one should run. A unique database index makes the second insert fail, and the API returns 409 Conflict until the first request finishes.<\/p>\n\n\n\n<h2 id=\"related-articles\" class=\"wp-block-heading\">Related Articles<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pheonixsolutions.com\/blog\/rest-api-status-codes\/\">REST API Status Codes: 12 HTTP Codes Every Backend Developer Should Use Right<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/pheonixsolutions.com\/blog\/designing-a-cashfree-payment-integration-module-for-a-web-application\/\">Designing a Cashfree Payment Integration Module for a Web Application<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/pheonixsolutions.com\/blog\/understanding-graphql-a-beginners-guide-to-modern-api-design\/\">Understanding GraphQL: A Beginner&#8217;s Guide to Modern API Design<\/a><\/li>\n<\/ul>\n\n\n\n<h2 id=\"official-documentation\" class=\"wp-block-heading\">Official Documentation<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/datatracker.ietf.org\/doc\/draft-ietf-httpapi-idempotency-key-header\/\" target=\"_blank\" rel=\"noreferrer noopener\">IETF Draft: The Idempotency-Key HTTP Header Field<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.rfc-editor.org\/rfc\/rfc9110.html#name-idempotent-methods\" target=\"_blank\" rel=\"noreferrer noopener\">RFC 9110: Idempotent Methods<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/docs.stripe.com\/api\/idempotent_requests\" target=\"_blank\" rel=\"noreferrer noopener\">Stripe API: Idempotent Requests<\/a><\/li>\n<\/ul>\n\n\n\n<h2 id=\"talk-to-our-api-experts\" class=\"wp-block-heading\">Talk to Our API Experts<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Duplicate payments and repeated orders cost money and trust. At <a href=\"https:\/\/pheonixsolutions.com\/web-development\/\">Pheonix Solutions<\/a>, our backend developers build APIs that handle retries, high traffic, and failures safely.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can help you with:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pheonixsolutions.com\/web-development\/\">Web and API development<\/a>, including payment and messaging APIs with safe retries.<\/li>\n\n\n\n<li><a href=\"https:\/\/pheonixsolutions.com\/devops-cloud\/\">DevOps and cloud services<\/a> to run your APIs reliably at scale.<\/li>\n\n\n\n<li><a href=\"https:\/\/pheonixsolutions.com\/software-maintenance-and-support\/\">Software maintenance and support<\/a> to find and fix duplicate-request bugs in existing systems.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Seeing duplicate orders or double charges? <a href=\"https:\/\/pheonixsolutions.com\/contact\/\">Talk to our API experts<\/a> and make every retry safe.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn what API idempotency keys are and how to add them in 7 steps with PHP and MySQL, so retries never cause double charges, duplicate orders or repeated messages.<\/p>\n","protected":false},"author":540,"featured_media":13849,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_hide_featured_image":false,"_jetpack_featured_image_duplicate_dismissed":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[1022],"tags":[],"class_list":["post-13853","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-architecture","psol-cat-web-architecture"],"jetpack_publicize_connections":[],"jetpack_shortlink":"https:\/\/wp.me\/phn2x7-3Br","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/pheonixsolutions.com\/blog\/wp-content\/uploads\/2026\/11\/api-idempotency-keys-featured.jpg","_links":{"self":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/13853","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/users\/540"}],"replies":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/comments?post=13853"}],"version-history":[{"count":3,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/13853\/revisions"}],"predecessor-version":[{"id":13862,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/13853\/revisions\/13862"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/media\/13849"}],"wp:attachment":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/media?parent=13853"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/categories?post=13853"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/tags?post=13853"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}