Idempotency

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

Link to section

What is idempotency?

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

For example, suppose CreatePayment didn't 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 don't 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's a duplicate request. It doesn't 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
Link to section

Additional Square API patterns

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

Link to section

See also