Prevents Double Payment Using Idempotent API

palwashakmalik

palwasha malik

Posted on June 14, 2024

Prevents Double Payment Using Idempotent API

Two brothers wanted to start a business but struggled to set up an online payment system. So, they decided to create their own service, calling it Stripe.

The Double Payment Problem

As Stripe's user base grew, they encountered issues with double payments, where users were accidentally charged twice for the same transaction. Here are the main reasons for this:

  1. Server Error The server might fail while processing a request, leaving the client unsure if the transaction was successful. Retrying could lead to double payment.

Image description

  1. Network Error The server processes the request, but a network failure prevents the response from reaching the client. Again, the client doesn't know if the request succeeded, so retrying might result in double payment.

Image description

Idempotent API

To solve this issue, Stripe developed an idempotent API, ensuring that a request can be safely retried multiple times without side effects. Here's how it works:

Image description

  1. Idempotency keys Each request includes a unique idempotency key (a UUID) in its HTTP header. This key is used to track if the request has already been processed. If the request is new, it gets processed and the key is stored. If the request has been processed before, the cached response is returned. Idempotency keys are stored in an in-memory database and are removed after 24 hours to reduce storage costs.
  2. Retrying Failed Requests

Image description

To prevent server overload, Stripe uses an exponential backoff algorithm with jitter. This means adding increasing delays with some randomness between retries to avoid overwhelming the server with simultaneous requests.
By implementing these strategies, Stripe effectively prevents double payments and ensures reliable transaction processing.

💖 💪 🙅 🚩
palwashakmalik
palwasha malik

Posted on June 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related