Learn about idempotency and how idempotency keys prevent negative results from accidental duplicate requests.
Build Basics

Idempotency

Learn about idempotency and how idempotency keys prevent unintended results from accidental duplicate requests.

What is idempotency? Permalink Get a link to this section

An API call or operation is idempotent if it has the same result no matter how many times it is applied. That is, an idempotent operation provides protection against accidental duplicate calls causing unintended consequences.

For example, suppose CreatePayment did not require idempotency and you make a successful CreatePayment request (Square successfully processes the payment). However, your connection fails before you receive success confirmation from Square. You do not know what happened to your request and therefore you make the request again, charging the customer twice.

Square supports idempotency by allowing API operations to provide an idempotency key (a unique string) to protect against accidental duplicate calls that can have negative consequences.

In the case of the preceding CreatePayment example:

  • If you make the same CreatePayment request with the same idempotency key again, the endpoint knows it is a duplicate request. It does not take the payment again. Instead of getting an error, the endpoint returns the response as the first successful CreatePayment response.

  • If you use the same idempotency key but change the CreatePayment request (for example, specify a different payment amount), you get an error indicating that you used the idempotency key previously. Note that this behavior might vary depending on the API.

Idempotency keys can be anything, but they need to be unique. Virtually all popular programming languages provide a function for generating unique strings. You should use one of these language calls.

LanguageRecommended function
RubySecureRandom.uuid
PHPuniqid
JavaUUID.randomUUID
Pythonuuid
C#Guid.NewGuid
Node.jscrypto.randomUUID

Additional Square API patterns Permalink Get a link to this section

There are other Square API patterns. For more information, see Common Square API Patterns.

Related topics Permalink Get a link to this section

If you need more assistance, contact Developer Support or ask for help in the Developer Forums.