Payment timed out. Should we release the stock?
DEV Community

Payment timed out. Should we release the stock?

Someone buys the last pair of headphones in our shop. We reserve them and ask the payment provider to authorize the purchase. Five seconds pass without a reply. Should we put the headphones back on sale?

I ran into a similar problem while working on an event-driven saga. I'll use checkout as the example here because the decision is easy to picture. If the provider declined the payment, we can release the headphones. If it approved the payment and the reply got lost, someone may already be counting on that last pair.

ResultFlow is a TypeScript library I built on top of neverthrow for composing workflows that can fail. If your functions already return neverthrow's Result or ResultAsync, you can use them directly in a flow. ResultFlow lets you decide which steps to retry, where to set a timeout, and when to run the workflow. Calling .run() returns a Promise that resolves to a regular neverthrow Result.

In this checkout, the interesting question is which steps a retry repeats. If a payment request times out, we can retry it with the same order ID. If saving the order fails because another worker updated it, we already have the payment approval. We only need to repeat the database work.

Start with the checkout

import { ResultFlow } from '@youldali/result-flow';
import { err, ok, type Result } from 'neverthrow';

type CheckoutStatus = 'confirmed' | 'pending';

function checkoutFlow(orderId: string): ResultFlow<CheckoutStatus, CheckoutError> {
  return ResultFlow.from(() => reserveStock(orderId))
    .chain(reservation => paymentFlow(orderId, reservation))
    .tap(status => console.info('Checkout status', { orderId, status }))
    .ifFailure(failure => console.error('Checkout failed', { orderId, failure }));
}

checkoutFlow(orderId) builds the workflow. Passing () => reserveStock(orderId) keeps the inventory call lazy. The shop only reserves the headphones when the flow runs.

From there, .chain() passes the reservation to paymentFlow. If the headphones are already out of stock, checkout skips payment and .ifFailure() logs the typed failure. The same callback also logs unexpected exceptions.

The inventory, payment, and database functions in this example belong to the application.

What happens if the payment times out?

function paymentFlow(
  orderId: string,
  reservation: Reservation,
): ResultFlow<CheckoutStatus, CheckoutError> {
  // The provider uses orderId as the idempotency key, so retries
  // refer to the same payment authorization.
  return ResultFlow.from(() => authorizePayment(orderId))
    .timeout({ ms: 5_000, onTimeout: () => 'payment-timeout' as const })
    .retryPolicy({
      maxRetries: 2,
      condition: error => error === 'payment-timeout',
    })
    .chain(authorization => confirmOrderFlow(orderId, authorization))
    .map<CheckoutStatus>(() => 'confirmed')
    .orElse(async (error): Promise<Result<CheckoutStatus, CheckoutError>> => {
      switch (error) {
        case 'payment-declined':
          await releaseStock(reservation.id);
          return err(error);
        case 'payment-timeout': {
          // Keep the stock reserved and queue a job to check
          // the existing payment with the provider.
          const scheduled = await schedulePaymentCheck(orderId, reservation.id);
          if (scheduled.isErr()) return err(scheduled.error);
          return ok('pending');
        }
        default:
          return err(error);
      }
    });
}

Suppose the provider approves the first request, but its reply gets lost. After five seconds, .timeout() produces a 'payment-timeout' error and .retryPolicy() makes another request. Both requests carry the same orderId as their idempotency key, so the provider can return the existing authorization. Because .timeout() comes before .retryPolicy(), each request gets its own five-second deadline.

A decline takes a shorter path. Only timeouts qualify for a payment retry, so 'payment-declined' reaches .orElse() immediately. We release the headphones, then return the decline. Here releaseStock returns Promise<void>. If it rejects, .ifFailure() logs the exception and .run() rejects with it.

If all three requests time out, we still don't know whether the provider approved the payment. schedulePaymentCheck queues a job to look up the existing payment later. In the meantime, the shop holds the reservation. Returning ok('pending') means the follow-up was successfully queued. If queuing fails, the caller gets that error instead.

What if payment succeeds but saving the order fails?

Suppose we load version 12 of the order. Before we save the confirmation, another worker updates the delivery instructions and saves version 13. The database rejects our stale write. What should we repeat?

function confirmOrderFlow(
  orderId: string,
  authorization: Authorization,
): ResultFlow<Order, ConfirmationError> {
  return ResultFlow.from(() => loadOrder(orderId))
    .chain(order => applyConfirmation(order, authorization))
    .chain(order => saveOrder(order))
    .retryPolicy({
      maxRetries: 2,
      condition: error => error === 'version-conflict',
    });
}

The retry starts at loadOrder. We load version 13, apply the payment approval we already received, and try the save again. This preserves the updated delivery instructions. If the other worker cancelled the order, applyConfirmation can return a different error and the retry stops.

The retry happens entirely inside confirmOrderFlow. By the time this function runs, authorizePayment has already succeeded. A database conflict can make us read and write the order again, but it never sends another request to the payment provider.

Run it

const result = await checkoutFlow('order-123').run();

result is a neverthrow Result<CheckoutStatus, CheckoutError>.

  • An Ok('confirmed') means the order confirmation was saved.
  • An Ok('pending') means the shop is holding the headphones and has queued a payment check.
  • A typed failure reaches the caller as an Err.

So when do we put the last pair back on sale? When the provider tells us it declined the payment. Five seconds of silence gives us a reason to retry. If the retries run out, we keep the headphones reserved until we know what happened.

ResultFlow on GitHub

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.