All notes

An Idempotency Key Is a State Machine

Bind request identity, input fingerprints, processing state and replayed results to one business operation.

English edition, edited for length. Read the complete Chinese original.

After the user submitted the order, the network connection was lost. He didn’t know if the order had already been created on the server, so he tried again. The client doesn’t need a “never retry” mechanism; instead, it needs to be able to repeat the same request without creating a second order. While a request ID stored in the cache seems to solve the problem, it often misses three crucial windows: process crashes, parameter changes, and concurrent requests.

Assume that order creation occurs within a relational database, and the client generates a stable, idempotent key for each purchase intent. When the purchase content changes, a new key should be generated. However, for the same purchase intent, timeout retries must continue to use the original key. This agreement should be formalized in the interface contract, and not left to individual clients to guess.

The Only True Competitive Advantage is Uniqueness

Create idempotent records that include tenant, operation type, key, request fingerprint, status, associated result, and expiration time. The unique constraint should cover the tenant and operation scope to prevent different users from accidentally using the same key, which would lead to conflicts.

CREATE UNIQUE INDEX request_key_unique
ON request_keys (tenant_id, operation, request_key);

Upon receiving the request, attempt to insert the record. If successful, the record is granted execution privileges. If there is a conflict, the existing state is read. Do not query for existence before inserting; there is still a competitive window between the two queries. Also, do not use browser-generated keys for user authentication; a key should not grant the right to read others’ orders.

Different parameters mean you can’t pretend to be successful.

When a user initiates a purchase of item A on the first attempt, the server should reject the subsequent request for item B. Otherwise, the client might receive an outdated order that is completely inconsistent with the current interface, making it difficult to identify and resolve the error.

The request for a fingerprint should be generated from validated business fields, rather than directly hashing the raw text. The order of fields, default values for optional fields, and meaningless whitespace can result in different text with the same meaning. It is possible to first normalize fields such as quantity, product, and currency, and then use a stable serialization to create a summary. Tracking fields that change with retries but do not alter the business intent must be excluded.

Normalization itself also has its limits. Don’t arbitrarily convert email addresses, names, or product codes to lowercase unless the business explicitly recognizes them as equivalent. It’s best to also preserve the original, “fingerprint” versions to facilitate explanations of historical data after interface upgrades.

Assume that the old client omits the currency, and the server defaults to Chinese Yuan. If the new client explicitly sends Chinese Yuan, whether this represents the same intent should be determined by the normalization rules. Whether the quantity string and numbers are allowed to be converted should also be validated through input verification, preventing the fingerprint function from making loose conversions. The normalized object should only contain fields that change the business result. Stable serialization and summarization should use mature tools to avoid unexpected differences caused by object traversal, number representation, or changes in default values.

After the fingerprint rule upgrade, the original rule version is retained in the history records. To retry, first find the record and then interpret or apply the compatible strategy according to the corresponding version, avoiding false positives from all old requests that would conflict with the new rules. If the upgrade is not compatible, the interface version and the promised window must be clearly defined. Randomness of keys helps reduce collisions, but does not guarantee a unique business intent. Database constraints and scope determine the outcome of the competition.

Do not store the entire request body, which has not been validated, in a single idempotent table. The results of replaying a request need to store a limited set of stable fields or business result identifiers. Personal information and payment data should be minimized as needed. The idempotent layer is a reliability component and should not be a permanent log repository for replicating every sensitive request. Access logs are still authorized, and users cannot read the results of other users’ keys.

Achieving Success: Writing Success and Business Data in the Same Transaction

If the order table and idempotent records are in the same database, the simplest solution is to acquire the eligibility, create the order, and save the result identifier within a transaction. Upon successful submission, all retries will return the same order. If the transaction is rolled back, the eligibility record will also be rolled back, and subsequent requests can be re-executed.

Long-running external calls are not suitable for holding database transactions. For example, if a request also needs to call a payment platform, the design must include handling the “in progress” status, external operation identifiers, and recovery tasks. The status can be “pending,” “in progress,” “completed,” or “failed and retryable,” but each transition must specify who has the authority to perform the action and who takes over after a failure.

If there’s only a “processing” state without a recovery process, a single process can permanently block the key. Setting a lease allows takeover, but the old executor might still be able to resume running, so downstream processes must also support idempotent operations or use mechanisms like fencing tokens to reject expired executors. Distributed boundaries cannot be resolved by a single local lock.

When a second request is made concurrently, the system detects that the first request is already in progress. It can then implement one of the following strategies:

  • Limited Waiting: Briefly pause the second request.
  • Return Processing Status: Indicate that the first request is being processed and provide a status update.
  • Provide Query Address: Offer the client a way to retrieve the results of the first request.

The response contract specifies whether the client should continue to poll, when to retry, and how to use the same key. It cannot indefinitely block all requests with the same key, nor can it return fabricated success results. The “Status Confirmation” message is more accurate than simply indicating failure and prompting the client to retry, especially when the result is unknown.

To successfully transfer a lease agreement, it’s necessary to verify the external operational facts. After the first executor initiates a payment and then pauses, the second executor takes over. It’s not possible to directly re-initiate the payment. If the supplier supports the same idempotent key, the same operation can continue. If the operation identifier can be queried, reconciliation should be performed first. If neither is available, manual exception handling should be initiated instead of assuming failure. A reliable system allows for clear identification of uncertain states, while blind automation can exacerbate losses.

The “fencing token” mechanism allows downstream components that support it to reject older executors, but this capability is not necessarily available in standard HTTP-based upstream components. The versioning mechanism itself does not guarantee atomicity; instead, the actual receiver must verify the version. Furthermore, single-process mutual exclusion does not solve issues related to deployment restarts or concurrent access from multiple instances. Each guarantee defines its own scope, preventing the wrapping of local atomicity into a single, system-wide operation.

The results of a replay do not equal the side effects of a replay.

Retrying can return the original order identifier and a stable response, but it should not resend welcome emails, re-publish events, or re-charge. By bundling the event intent and order information into a transaction and then having an independent delivery process handle it, it will be easier to recover than calling multiple services directly before returning the response.

Even in cases of failure, it’s important to categorize the cause. Parameter validation failures typically don’t require long-term key storage; clear business rejections can be saved for stable results; and network timeouts don’t necessarily mean external operations have failed, so you can’t simply clear the records and re-execute. It’s crucial to clarify in the interface whether to retain the initial results or to re-read the current order each time, otherwise users might misinterpret historical responses as the current status.

The first order creation returns “pending payment,” but the order is completed a few hours later. Idempotent re-creation can return the initial creation result, or, based on the contract, the current status of the same order. However, this must be explicitly stated. Replaying the original response helps maintain the stability of the API semantics, while querying the current status is more suitable for displaying the latest business facts. Do not mix fields from the old response with fields from the new object without clear indication.

After a lost response, the client uses the same key to confirm, allowing the server to return the original order identifier. Subsequently, the latest status is obtained through resource querying. This design ensures idempotency for the creation operation and separate responsibilities for resource status changes. Notifications, auditing, and inbox events are still generated only by the initial business transaction, and replaying does not re-trigger them. The number of interface refreshes should not be a side effect.

Whether an erroneous result is saved also depends on the business definition. Legitimate but exhausted purchase intents can be permanently rejected, or alternatively, future attempts can be allowed, but the latter should typically use a new intent key. If an error occurs during business execution and is rejected, it is not necessary to create a persistent record, but rate limiting still applies. Network and external uncertainties cannot be simplified into immediately deletable failures; retaining recovery evidence is essential for reconciliation.

The Expiry Time Determines the Scope of the Commitment

Unlike cache invalidation and operational failure, a stale response doesn’t necessarily mean the underlying data is incorrect. The old response format might require conversion, but the business logic remains valid. When retrieving historical results, the system should provide compatible feedback based on the version, rather than re-executing the action to generate a new format. The state machine needs to clearly define where to verify the authoritative result when the cache is missing.

When performing the cleanup task, avoid processing records that are still in progress, and use controlled bulk deletion. Do not directly enter names, email addresses, or ID information in the keys. Also, when accessing logs, avoid duplicating complete sensitive requests and responses solely for troubleshooting, as this would unnecessarily expand the scope of privacy exposure.

Repeating the key clearing process may re-introduce business objects, and the clearing window must match the longest retry duration for the client, queue, and compensating task. High-risk operations can allow the business table to store permanent operation identifiers, while short-term idempotent records only cache the response. This ensures that clearing the cache does not compromise the uniqueness of the business, but it requires clearly defining the scope and consistency of the two layers. It is important to note that deleting records to unlock requests should not ignore the possibility that old external operations may still complete.

The task of clearing and deleting records, along with uncertain records, should be performed in batches while retaining summary metrics. However, expiration does not necessarily mean that all records can be deleted unconditionally. Clear policies regarding legal and auditing requirements, as well as privacy and capacity, are necessary. User identifiers and fingerprints are not automatically anonymized and may be associated with user behavior, access, and retention. Storage budgets should be defined as design inputs and should not be secretly altered after deployment by shortening the commitment period.

Base observations on actual operations, not the number of requests

Five identical requests can correspond to one order and four retries. The number of successful requests does not equal the number of business creations. To understand the behavior of the caller, it is necessary to record the first execution, retry, parameter conflict, processing failure, and recovery failure. The key and user identifier are not used as an unlimited metric label; controlled logs are used to locate related identifiers, and aggregated metrics are counted by operation category.

When the conflict rate increases, it’s likely that the client continues to use the same key for each edit. An increase in the retransmission rate may be due to network instability. Delays in processing could be caused by issues with leases or external reconciliation. Different causes require different actions, and cannot be solved with a single “clear idempotent table” approach. Observable states and limited recovery allow the interface to be verified by operations, rather than simply stating “prevent duplication” in the design documentation.

Choosing a Recovery Branch Starting from a Response Loss

The client submits a key, K. The server completes the order transaction, and then the network disconnects. The client then resubmits the same key and parameters, and the server reads the completed record and returns the same order. The number of business creations remains the same. In contrast, if the first transaction is rolled back on submission, the record does not exist, and the second transaction can successfully create the order. The client sees only the result of the first failed attempt, but the server’s persistent state determines the different branches, and cannot be inferred from timeout messages.

The third scenario is when the server calls an external payment provider but does not receive a confirmation result. The status cannot be directly changed to “normal failure” and the eligibility cleared, as the payment may have been successful. Keep the external operation identifier and first query the supplier’s facts or continue using its explicitly supported idempotent protocol. If these capabilities are missing, proceed to manual confirmation. The “unknown” status is a genuine expression of the system’s lack of information, not a problematic field that needs to be eliminated through more automatic retries.

The tests independently control pre-submission anomalies, post-submission response loss, and external confirmation loss, checking the number of orders, operation records, and supplier counts. Concurrent requests with the same key should cover both waiting and completion competition, and the processing instance will not create a second instance. Interface tests assert business state, not just the number of 200 responses. A successful response may come from replaying, and does not necessarily indicate a new business operation.

Standardized objects should have a clearly defined equivalence relationship.

Whether two items with the same SKU in the shopping cart are merged, whether the quantity string is allowed, and whether omitting the currency is equivalent to an explicit default currency are all determined within the input contract. After validation, a standard business object is created, and the sequence is stabilized before generating a fingerprint. Tracking parameters and client time typically do not change the purchase intent and do not generate a fingerprint. The quantity, price, or currency of the item may change the result, and these cannot be removed to avoid conflicts.

Normalization is not about “making all inputs as similar as possible.” Product codes may have specific capitalization rules, and monetary values have their own precision rules. Similarly, blank names cannot be arbitrarily collapsed. The equivalence relationship should be expressed as positive and negative examples: semantically similar inputs should result in the same fingerprint, while different business inputs should result in different fingerprints. Collisions in the summarization algorithm and errors in normalization represent different risks. A mature summarization algorithm cannot correct errors caused by incorrectly deleting business fields.

The rules are upgraded and saved, and retries of old records are explained according to their committed form. When a new client adds optional fields, it’s necessary to determine if this changes the business semantics. If it does, a new operation version may be required, rather than maintaining compatibility with the default. Retries within the old committed window should not suddenly conflict, and should not unconditionally accept different payloads for compatibility. Version migration requires clear rejection and recovery paths.

How to Avoid Permanent Occupation of Qualification Records During Processing

After the executor creates a state and then crashes, another executor takes over and checks the persistent progress and external facts. The expiration of a lease only indicates that recovery is possible, but it does not prove that the previous executor has stopped. Any downstream processes that rely on a fence must actually reject the old operation. Only local records of the generation guarantee remote interfaces. When a third party does not have this capability, it is necessary to stabilize the external idempotent key or query result to take on another part of the recovery responsibility.

Limited waiting and state queries for the same key also require a budget. Clients can receive the query address and suggested polling frequency, and the query still verifies the user and their scope of operation. To avoid placing keys in public URLs and then logging or accessing external sources, even though identifiers are not credentials, they may be associated with private actions. A large number of repeated requests cannot indefinitely occupy connections, and both replay and queries have limited flow and volume control.

For failed conversions that can be retried, it’s crucial to clearly define who has the authority to initiate them. If input validation hasn’t been performed, creating long-lived records can lead to storage pressure, and if all exceptions are cleared, external success might be lost. Based on the execution stage, the business should define different policies for rejecting requests, rolling back databases, and handling external unknowns. It’s more important to give the state machine actual recovery actions than to constantly add new failure states.

The “Save Response” and “Query Current Resource” are two interfaces.

The order was initially created as “pending payment” but has since been completed. Re-creating the order should return the original promised result, while resource queries should return the current status. If you choose to re-create the current status, this should also be clearly documented in the API documentation, and the same order ID should be maintained. Do not combine historical amounts, current status, and the new generation time into a single, versionless object. Users need to know whether they are confirming the original operation or viewing the current resources.

The results record only stores necessary and stable fields and business identifiers. Sensitive data should not be fully copied. Access to the results is still authorized, even if the visitor provides the correct key, but it does not allow reading other tenants’ data. After changing account permissions, the visible fields are treated according to the security agreement and cannot bypass the current resource confidentiality requirements by simply “replaying the original response.” Reliability and permissions are hard boundaries that must be designed together.

Clearing the response cache should not compromise business uniqueness.

Clients, offline queues, and manual compensation may resend the same operation after a longer period. After short-term response records are deleted, the stable operation identity in the business table can continue to prevent repetition, but it requires a true unique constraint and reliable querying. The two-layer retention policy together indicates the commitment: how long the response can be repeated, and whether the business intent is permanently unique. It is not possible to silently shorten the retention period to allow old requests to be charged again.

Records in “In Progress,” “Unknown Result,” and “Recovering” states are not deleted according to standard task deletion procedures. Cleanup uses limited batches, retaining necessary counts and exception classifications, and does not copy all keys in the logs. Data capacity, audit policies, and privacy policies jointly determine the lifecycle, and hash fingerprints may also be associated with users, but are not automatically anonymized. Administrators unlock operations first reconcile the data, preventing the system from falsely appearing as if no changes have occurred through deletion.

Analyzing the Number of Transmission Occurrences by Observation Type and Business Facts

The five identical requests could be counted separately for each of the following categories: creation, replay (three times), and processing. An increase in conflicts may indicate a client-side error persisting with the key, while an unknown state may mean that the vendor’s query is unavailable. The alert provides specific recovery actions, without requiring the clearing of all records for a unified solution. The article only describes the acceptance plan and dependencies, without fabricating a perfectly successful outcome that has already been achieved, when no real database or vendor integration tests have been performed.

A Set of Tests That Should Fail

When submitting the same key with the same parameters, only one order will be created. Submitting the same key with different parameters must be rejected. After a submitter completes the submission, the response is lost, and the retry must return the created result. If the execution crashes, the recovery process cannot be permanently suspended, and it cannot be repeatedly called on downstream processes. Re-test the behavior before and after key expiration to ensure that the documentation promises align with the actual behavior.

These tests demonstrate a protocol with defined boundaries. Adding the Idempotency-Key field to the interface is simply an entry point for the protocol, not the protocol itself.

The tests should use real database unique constraints to simulate two connections inserting simultaneously. When the same key has different parameters, the system should return a detectable conflict, and not return the results of others. After deployment or process restart, the state should still be recoverable. Finally, the downstream system should confirm success while the local system marks failure. The next time, perform reconciliation on the same operation without repeating side effects. Once these windows are covered, you can determine where the idempotent guarantee holds and where manual intervention is required.

The client must also persistently store the intent and key before sending. The mobile app generates K and sends the request; if the response doesn’t arrive, it exits. If the app is restarted but only the shopping cart is saved, losing K, it generates K2, and the server treats it as a new intent. When testing by closing and then restoring the app, the system should continue using K for the pending intent. The user must explicitly modify the item and confirm the new purchase to generate a new key. The “Try Again” and “Buy Another” buttons on the interface require different actions and cannot be solely determined by the backend.

References