CodingArchitectureAdvanced45 minSaves 1 hour

Designing Idempotent Payments API Write Endpoints

Fintech backend engineers design idempotent write endpoints for payment APIs. This prevents duplicate transactions, ensuring data consistency and reliability using idempotency keys and replay semantics.

Fintech and payments backend engineers design idempotent write endpoints for payments APIs. This prompt covers integrating idempotency keys, defining replay semantics, and specifying resource models and error schemas, ensuring transaction safety and preventing duplicate processing.

READY-TO-USE PROMPT

Copy Prompt

prompt.txt
As an experienced API Designer and Payments Architect, your objective is to define a set of idempotent write endpoints for a payments processing API. The design must prioritize transaction safety, data consistency, and developer experience.

### Context

You_are developing a core payments API that handles sensitive financial transactions such as creating charges, initiating refunds, or processing payouts. In a distributed system, network failures or client retries can lead to duplicate requests. Idempotency is crucial to ensure that these repeated requests do not result in unintended multiple executions or incorrect state changes. The API must clearly define how clients submit idempotent requests and how the server processes and responds to them.

The API should be designed for high availability and resilience, serving a global user base. Assume the underlying payment processing logic can be complex and potentially asynchronous.

### Task

Design the idempotent write endpoints for a payments API. Your design must include the following components:

1.  **API Specification (REST or GraphQL):** Define the specific write endpoints (e.g., `POST /charges`, `POST /refunds`, `POST /payouts`). For each endpoint, specify:
    *   HTTP method and path (for REST) or mutation name (for GraphQL).
    *   Request body structure, including the placement and format of the `Idempotency-Key` (for REST) or equivalent field (for GraphQL).
    *   Response structures for success, idempotent replay, and errors.
    *   Supported headers (e.g., `Idempotency-Key`, `Content-Type`).

2.  **Idempotency Key Strategy:**
    *   Define the format and generation requirements for the `Idempotency-Key`.
    *   Explain how the server uses this key to detect and handle duplicate requests.
    *   Specify the lifecycle of an idempotency key (e.g., how long it's considered valid for replay).

3.  **Replay Semantics and Responses:**
    *   Describe the server's behavior upon receiving a duplicate request with an active idempotency key.
    *   Specify the HTTP status codes (for REST) or error codes (for GraphQL) and response bodies for successful replays (e.g., returning the original successful response).
    *   Address scenarios where the original request failed but the key is replayed.

4.  **Resource Model:**
    *   Define the key resource objects involved (e.g., `Charge`, `Refund`, `Payout`) and their relevant fields, especially those impacted by idempotency (e.g., `status`, `idempotency_key_status`).
    *   Illustrate how the state of these resources changes through the idempotent process.

5.  **Error Schema:**
    *   Define a consistent error response structure for the API.
    *   Include specific error types related to idempotency (e.g., `idempotency_key_mismatch`, `idempotency_key_expired`, `invalid_idempotency_key`).

6.  **Versioning Policy:**
    *   Propose a clear versioning strategy for the API, considering how changes to idempotency mechanisms or endpoint signatures would be handled.

7.  **Examples:**
    *   Provide concrete request and response examples for:
        *   A successful initial request for `{{transaction_type}}` (e.g., a charge).
        *   A successful replay of the same `{{transaction_type}}` request.
        *   A failed initial request for `{{transaction_type}}` followed by a successful replay attempt (if applicable in your design).

### Constraints

*   **API Style:** Choose either RESTful HTTP API or GraphQL. Explicitly state your choice.
*   **Tone:** The design documentation should be principled, versioning-aware, and developer-empathetic.
*   **Clarity:** Ensure all definitions are clear, unambiguous, and practical for implementation by backend engineers.
*   **Security:** Briefly consider the security implications of idempotency keys (e.g., uniqueness, non-predictability).

### Output Format

Present your design in a structured, markdown-formatted document, including:

*   **API Specification:** Detailed endpoint definitions.
*   **Idempotency Key Strategy:** Explanation and guidelines.
*   **Replay Semantics:** Server behavior and response examples.
*   **Resource Model:** Schema definitions for affected resources.
*   **Error Schema:** Standardized error responses with idempotency-specific errors.
*   **Versioning Policy:** Proposed strategy.
*   **Examples:** Illustrated request/response flows.

Estimated results

DifficultyAdvanced
Setup time45 min
Time saved1 hour
Best modelsChatGPT, Gemini, Claude
Best audienceFintech, Payments

Editor's note

Why this prompt matters

Building reliable financial systems requires meticulous attention to detail, especially when handling transactions in distributed environments. Network glitches, client-side retries, or even user double-clicks can inadvertently trigger duplicate requests, leading to erroneous charges or refunds. For backend engineers working on payments APIs, ensuring that every write operation is executed exactly once, regardless of how many times the request is sent, is a fundamental challenge.

This workflow addresses the critical need for idempotency in payments API design. It guides engineers through defining robust write endpoints that prevent unintended side effects from repeated requests. By establishing clear strategies for idempotency keys, replay semantics, and consistent error handling, the design ensures data integrity and provides a predictable experience for both the API consumer and the underlying financial system.

Fintech teams should reach for this workflow when architecting new payment processing services or refactoring existing ones where transaction safety and consistency are paramount. It provides a structured approach to designing endpoints for operations like creating charges, processing refunds, or initiating payouts, ensuring that each transaction is handled with precision and resilience.

Anatomy

Prompt engineering breakdown

Role

As an experienced API Designer and Payments Architect

Context

You are developing a core payments API that handles sensitive financial transactions such as creating charges, initiating refunds, or processing payouts. Idempotency is crucial to ensure that repeated requests do not result in unintended multiple executions or incorrect state changes.

Goal

Define a set of idempotent write endpoints for a payments processing API. The design must prioritize transaction safety, data consistency, and developer experience.

Constraints

API Style (RESTful HTTP API or GraphQL), Tone (principled, versioning-aware, developer-empathetic), Clarity, Security implications (uniqueness, non-predictability).

Output format

Structured, markdown-formatted document, including: API Specification, Idempotency Key Strategy, Replay Semantics, Resource Model, Error Schema, Versioning Policy, Examples.

Why this structure works

The structured approach works by first employing role priming, establishing the persona of an experienced API Designer and Payments Architect to set the expected level of expertise. Explicit constraints guide the model on API style, tone, clarity, and security, ensuring the output meets specific non-functional requirements. Finally, a detailed structured output format, broken down into seven distinct components, ensures a comprehensive and organized design document suitable for direct implementation by backend engineers.

Pick your version

Prompt variations

BeginnerWorks with any model

For learning the basics of idempotent API design without deep technical details, focusing on a single transaction type.

prompt.txt
As an API Designer, outline a basic idempotent write endpoint for a payments API. Focus on creating a `POST /charges` endpoint. Explain what an idempotency key is and how it helps prevent duplicate charges. Describe how the server should respond if the same request is sent twice with the same key. Include a simple request and response example for creating a charge and for a repeated, idempotent charge using a `{{transaction_id}}`. Your output should be a clear, concise explanation suitable for someone new to payment API design, using REST.
ProfessionalBest with claude

When a comprehensive, detailed API design document is required for implementation by experienced backend engineers.

prompt.txt
As an expert API Designer and Payments Architect, your task is to design idempotent write endpoints for a payments API. Focus on ensuring transaction safety, data consistency, and a strong developer experience. Provide a detailed API specification (REST or GraphQL) for endpoints like `POST /charges`, including `Idempotency-Key` handling in requests and responses. Define a clear Idempotency Key Strategy, covering key format, server processing, and lifecycle. Outline Replay Semantics, specifying server behavior and HTTP/error codes for successful replays. Describe the Resource Model for `Charge`, `Refund`, `Payout` objects, showing state changes. Develop a consistent Error Schema, including idempotency-specific errors like `idempotency_key_mismatch`. Propose an API Versioning Policy. Conclude with concrete request and response examples for initial success and idempotent replay for a `{{transaction_type}}`.
Short VersionWorks with any model

For quick ideation or to generate a high-level overview of idempotent endpoint design.

prompt.txt
Quickly outline idempotent write endpoints for a payments API. Focus on a RESTful approach, specifying a `POST /{{resource}}` endpoint that accepts an `Idempotency-Key` in the request header or body. Describe the server's behavior upon receiving a duplicate request with the same key, ensuring it returns the original success response without re-executing. Provide a concise example of an initial successful request and a subsequent idempotent replay for a `{{transaction_type}}`, highlighting how the system prevents unintended multiple transactions. Keep the explanation to a single paragraph.
EnterpriseBest with gemini

For designing payment APIs within regulated industries where compliance, security, and auditability are paramount.

prompt.txt
As a Lead API Architect and Payments Risk Specialist, design a highly resilient and compliant set of idempotent write endpoints for a critical payments API. Your design must ensure transaction safety, data consistency, and adherence to regulatory standards (e.g., PCI DSS, GDPR where applicable). Define API specifications (REST or GraphQL) for core transaction types like `POST /charges`, including `Idempotency-Key` placement and robust validation. Detail an Idempotency Key Strategy that covers secure key generation, extended lifecycle for audit purposes, and clear data retention policies. Outline Replay Semantics with specific responses for both successful replays and scenarios where the original request failed but a replay is attempted, ensuring state consistency and auditability. The Resource Model must clearly show `idempotency_key_status`, `transaction_status`, and links to audit logs. Propose a comprehensive Error Schema with specialized errors for idempotency failures, compliance violations, or security anomalies. Finally, establish an API Versioning Policy that facilitates controlled evolution and addresses regulatory changes, providing concrete request/response examples for `{{transaction_type}}` demonstrating secure, auditable idempotent behavior.

What you'll get

Expected output

API Specification: POST /charges

  • Endpoint: POST /v1/charges
  • Description: Initiates a new payment charge.
  • Headers:

* Content-Type: application/json * Idempotency-Key: <UUIDv4> (Required) - A client-generated unique identifier for the request.

  • Request Body Example:

``json { "amount": { "value": "100.00", "currency": "USD" }, "source": { "type": "card", "token": "tok_visa" }, "description": "Order #12345 payment", "metadata": { "customer_id": "cust_abc" } } ``

  • Response (201 Created - Success):

``json { "id": "ch_xyz789", "amount": { "value": "100.00", "currency": "USD" }, "status": "succeeded", "created_at": "2023-10-27T10:00:00Z" } ``

  • Response (200 OK - Idempotent Replay): Returns the original successful response, without re-processing.

``json { "id": "ch_xyz789", "amount": { "value": "100.00", "currency": "USD" }, "status": "succeeded", "created_at": "2023-10-27T10:00:00Z" } ``

  • Response (400 Bad Request - Idempotency Key Mismatch): If the Idempotency-Key exists but the request body differs.

``json { "code": "idempotency_key_mismatch", "message": "Idempotency key '...' used with a different request payload." } ``

  • Response (4xx/5xx - Original Failure Replay): Returns the original error response if the initial attempt failed.

``json { "code": "card_declined", "message": "The payment card was declined." } ``

Idempotency Key Strategy

The Idempotency-Key must be a client-generated UUIDv4, included in the HTTP header. The server stores this key alongside the full request payload and the final response. Upon receiving a request with an Idempotency-Key, the server first checks if the key exists. If it does, it validates if the incoming request body exactly matches the stored payload. A mismatch results in a 400 Bad Request. Keys remain valid for replay for 24 hours to accommodate client retry logic and network transient errors. After 24 hours, the key may expire, and a new request with the same key could be processed as a distinct operation.

Replay Semantics

When a duplicate request with an active Idempotency-Key is received:

  1. Original Succeeded: The server retrieves and returns the stored 201 Created response with a 200 OK status. This confirms the operation's prior completion.
  2. Original Failed: The server returns the *original error response* (e.g., 400 Bad Request, 500 Internal Server Error) and its corresponding status code, preventing re-execution of a known-to-fail operation.
  3. Original Pending: For long-running operations, the server might return a 202 Accepted or 409 Conflict while the original request is still processing, prompting the client to poll for the final status.

Resource Model

  • Charge: Represents a financial debit. Key fields include id, amount, currency, status (succeeded, failed, pending), source (payment method details), and created_at.

Under the hood

Why this prompt works

This prompt succeeds by employing several targeted techniques. Firstly, the explicit role assignment as an "experienced API Designer and Payments Architect" directs the model to adopt a specific persona, ensuring the output is authoritative and aligned with the domain expertise expected by fintech backend engineers. This grounds the response in practical, industry-specific knowledge rather than generic API design principles.

Secondly, the detailed "Context" section is critical. It establishes the challenging environment of distributed financial transactions, network failures, and the need for high availability and resilience. This contextual grounding prevents abstract solutions, compelling the model to consider real-world operational complexities and design for robustness.

Furthermore, the "Task" section uses a structured, numbered list that acts as a strong constraint. By breaking down the design into specific components like API Specification, Idempotency Key Strategy, and Replay Semantics, it ensures comprehensive coverage. Each point contains granular requirements, such as defining Idempotency-Key format and lifecycle, or specifying HTTP status codes for replay scenarios. This level of detail pushes the model to generate concrete, implementable design elements rather than high-level concepts. Explicitly asking to "prioritize transaction safety, data consistency, and developer experience" also guides the model's design choices, ensuring a balanced and practical outcome for a developer-empathetic audience.

Model fit

Best AI models for this prompt

Claude

Claude models excel at handling complex, multi-part instructions and generating highly structured, detailed output. Its ability to maintain context over longer interactions makes it suitable for iterating on intricate API design elements like idempotency keys and error schemas, ensuring a coherent and principled overall design. See the full Claude hub for deeper guidance.

ChatGPT

ChatGPT models are proficient in generating clear, well-commented code and structured documentation. They follow specific output formats reliably and can produce practical examples for API requests and responses, which is essential for illustrating idempotency logic and replay semantics effectively. See the full ChatGPT hub for deeper guidance.

Gemini

Gemini models are particularly strong in their ability to reason through complex technical specifications and produce accurate, relevant code snippets or API definitions. Their capacity to follow detailed constraints makes them effective for designing versioning policies and specific error handling for idempotent operations. See the full Gemini hub for deeper guidance.

When to use

  • Designing new financial transaction APIs (e.g., charges, refunds, payouts).
  • Migrating existing payment systems where network instability or client retries are frequent.
  • Developing client-side SDKs for payments that require safe, automatic retry mechanisms.
  • Implementing webhook handlers or event processing systems that may receive duplicate events.
  • Integrating with third-party payment gateways that mandate idempotent request handling for critical operations.

When not to use

  • For read-only API endpoints (e.g., GET requests), as HTTP GET is inherently idempotent.
  • For non-critical data updates where occasional duplicate processing has no significant business impact.
  • When designing internal, single-service operations where retry logic guarantees no re-execution.
  • For high-volume, low-value logging or analytics endpoints where idempotency overhead is unnecessary.

Get more from it

Pro tips

  • 1

    Generate idempotency keys client-side using cryptographically secure UUIDs to prevent collisions and enhance request integrity.

  • 2

    Implement an explicit expiry for idempotency keys (e.g., 24 hours) to prevent indefinite storage and optimize database performance.

  • 3

    Store the initial request's full response alongside the idempotency key to ensure consistent replay responses, even for original failures.

  • 4

    Design idempotent operations to be atomic, ensuring the entire transaction succeeds or fails as a single, indivisible unit.

  • 5

    Clearly document the idempotency key lifecycle and server behavior for different replay scenarios to improve developer understanding.

  • 6

    Utilize a distributed cache (e.g., Redis) for rapid idempotency key lookup, reducing latency compared to direct database queries.

  • 7

    Validate idempotency key format and uniqueness early in the request pipeline to reject malformed or conflicting requests efficiently.

Don't ship this

Common mistakes

  • Not persisting the complete original response with the idempotency key.

    Fix — Store the full successful response, including headers and body, to return an identical replay and avoid inconsistent client state.

  • Using predictable or short idempotency keys, risking collisions.

    Fix — Generate long, globally unique, cryptographically random UUIDs to minimize collision risk and enhance request security.

  • Failing to define a clear expiry policy for stored idempotency keys.

    Fix — Implement a fixed duration (e.g., 24 hours) after which keys expire, preventing indefinite storage and resource bloat.

  • Not handling concurrent requests for the same idempotency key.

    Fix — Use a distributed lock mechanism to serialize processing for a given key, preventing race conditions and duplicate transaction execution.

  • Returning a generic error on replay after an original request failure.

    Fix — Return the original failure response on replay to accurately inform the client of the initial outcome, avoiding misleading success messages.

  • Applying idempotency key mechanisms to inherently idempotent read operations.

    Fix — Idempotency is for write operations; HTTP GET requests are naturally idempotent and do not require specific key handling or storage.

People also ask

Frequently asked questions

Q.How long should an idempotency key remain valid on the server?

Typically, 24 hours is sufficient for most payment transactions, accommodating common network retries. Longer durations might be needed for very slow, asynchronous processes, but this should be balanced with storage and performance considerations.

Q.What if a client sends a different request body with an active idempotency key?

The server should detect this as an 'idempotency_key_mismatch' error. This indicates client misuse, and the server should reject the request to prevent unintended state changes and ensure data consistency.

Q.Can this idempotency design be applied to non-payment APIs?

Yes, the core principles are broadly applicable to any API where duplicate write requests could cause issues, such as order processing, inventory updates, or user account creation. Adjust resource names and specific error codes as needed.

Q.How does implementing idempotency affect API performance?

Idempotency introduces a small overhead for key storage and lookup. This impact is mitigated by using an efficient distributed cache for keys and optimizing database writes for the stored responses.

Q.Should the idempotency key be placed in the request body or a header?

For REST APIs, a header (Idempotency-Key) is generally preferred. It keeps the request body clean and semantically separates idempotency control from the core resource data. GraphQL typically uses a dedicated input field.

Q.What HTTP status code should be returned for a successful replay of an idempotent request?

Return the *original* HTTP status code and body. If the initial request resulted in 201 Created, a replay should also return 201 Created with the original resource representation, confirming the operation's completion.

Version 1.0Last reviewed July 20, 2026
Reviewed by PromptInFlow Editorial Team