DEV Community

Cover image for Payment Status Polling in Node.js When Webhooks Go Missing
Jafar on Payments
Jafar on Payments

Posted on

Payment Status Polling in Node.js When Webhooks Go Missing

A customer completes a payment in their bank's app, but your checkout still says "pending". A deployment, blocked endpoint or signature verification bug has stopped the webhook reaching your order system, leaving staff unsure whether to release the order or ask for payment again.

You can rely on webhooks, use payment status polling, combine webhooks with a fallback poller, or run scheduled checks for unresolved payments. The approach here uses webhooks first, a short server-side poller when confirmation is late, and a later reconciliation sweep.

This guide is for Node.js developers running checkouts for UK businesses.

Choose How Your Checkout Gets Confirmation

Each approach has a place, but they leave different gaps:

  • Webhooks only: payment updates arrive without repeated requests, but a missed delivery can leave your local order pending.
  • Polling only: repeatedly checking a payment status using the payment request ID can recover the result, but careless loops waste requests.
  • Webhooks with fallback polling: use the payment webhook payload for normal updates, then query unresolved requests after a grace period.
  • Scheduled reconciliation: revisit unresolved records after the checkout's polling window closes.

The status endpoint is documented for integrations without webhooks. Using it as a fallback is an integration design choice: both paths must feed the same order update logic.

Keep the polling credentials on your server. The browser can display your own order status without holding the payment API key or keeping the recovery process alive.

Step 1: Give Both Paths One Way to Finish

Start with the database operation, before writing the polling loop. An idempotent operation produces the same result when repeated, so duplicate confirmation cannot dispatch the same order twice.

The API reference doesn't document an idempotency header, so implement duplicate protection in your application.

Create a finishOrder(paymentRequestId, status) function that runs a database transaction. It should:

  1. Find the payment attempt using its stored payment request ID.
  2. Change its state only if it is still unresolved.
  3. For COMPLETED, insert a fulfilment job with a unique business key.
  4. Commit the state change and job together.

That stored job is an outbox record: a durable instruction for a worker to process. Give the downstream fulfilment operation the same duplicate protection, because workers can also repeat work.

FAILED finishes that payment attempt, without dispatching anything. If the customer retries, track the new attempt separately rather than overwriting the failed request's identity.

Do not rely on an in-memory flag or a read followed by an unconditional write. The database must decide which competing update wins.

Step 2: Receive Webhooks Without Losing Work

Verify the signature using the signing version configured for your integration. Create a signing secret in the dashboard first: the signature header is only sent after that secret exists. Use the newer V2 signature, because the older V1 check does not cover refund status or amount.

After verification, save the event durably before returning a successful response. A worker can then validate the update, call finishOrder, and cancel any active poller for that request.

The Standard Webhooks specification treats a 2xx response as successful delivery (Standard Webhooks specification). Responding before durable acceptance risks losing the update if your process stops immediately afterwards.

That specification also recommends retaining the same event ID across retries. This provider's payment webhooks have no event id or type field and no webhook ID, so deduplicate on payment ID plus status. Keep payment-level duplicate protection too: a poll result and a webhook are different inputs describing the same payment.

For this provider, return a 2xx response after durable acceptance, and also for webhook events you do not use. An error response, a timeout or a failed connection triggers a retry, so return an error only when you want a retry. The provider retries only about 5 times a few seconds apart and then stops; use webhooks as recommended in the webhook introduction, with polling as the backstop.

Step 3: Build a Bounded Fallback Poller

Persist the request ID, environment and expiry when creating the payment. Schedule the fallback as durable work, so a deployment cannot erase the recovery task.

The following core loop deliberately separates provider details from scheduling. readPayment is your adapter around the documented endpoint; it normalises responses into pending, not-started, final or retry.

It must preserve the distinction between a payment status and a transport problem. Network failures and temporary HTTP errors belong in the retry path, while authentication or malformed-response problems should raise an operational alert.

import { setTimeout as sleep } from "node:timers/promises";

const active = new Map();

export function cancelPoller(paymentRequestId) {

  active.get(paymentRequestId)?.abort();

}

export async function pollPayment({

  payment,

  policy,

  store,

  readPayment,

  finishOrder

}) {

  const id = payment.paymentRequestId;

  if (active.has(id)) return;

  const controller = new AbortController();

  const signal = controller.signal;

  active.set(id, controller);

  const deadline =

    payment.expiresAt + policy.expiryMarginMs;

  const remaining = deadline - Date.now();

  if (remaining <= 0) {

    active.delete(id);

    return;

  }

  const expiryTimer = setTimeout(

    () => controller.abort(),

    remaining

  );

  let ceiling = policy.initialBackoffMs;

  let nextCheckAt = payment.createdAt + policy.graceMs;

  try {

    while (!signal.aborted) {

      if (Date.now() >= deadline) return;

      if (await store.isFinal(id)) return;

      const waitMs = Math.max(0, nextCheckAt - Date.now());

      if (Date.now() + waitMs >= deadline) return;

      await sleep(waitMs, undefined, { signal });

      if (await store.isFinal(id)) return;

      const result = await readPayment({

        paymentRequestId: id,

        env: payment.env,

        signal,

        deadline

      });

      if (result.kind === "final") {

        await finishOrder(id, result.status);

        return;

      }

      if (!["pending", "not-started", "retry"].includes(result.kind)) {

        throw new Error("Unexpected payment result");

      }

      const jitterMs = Math.floor(Math.random() * ceiling);

      const retryAt = result.retryAt ?? 0;

      nextCheckAt = Math.max(

        Date.now() + jitterMs,

        retryAt

      );

      ceiling = Math.min(

        policy.maxBackoffMs,

        ceiling * 2

      );

    }

  } catch (error) {

    if (error.name !== "AbortError") throw error;

  } finally {

    clearTimeout(expiryTimer);

    active.delete(id);

  }

}
Enter fullscreen mode Exit fullscreen mode

This is the polling control flow, with explicit integration adapters rather than guessed endpoint paths, authentication headers or response shapes. Validate the policy before starting: delays must be positive, and the expiry margin must be bounded.

Choose a short grace period and a capped backoff suitable for your checkout. No rate limit is documented in the supplied status reference, so absence of a published limit is not permission to poll continuously.

Random jitter spreads requests across time instead of making every waiting checkout retry together. The AWS explanation of exponential backoff and jitter shows why increasing delays alone can still leave requests clustered (AWS Architecture Blog, 2015, updated 2023).

Step 4: Handle Each Response Deliberately

The adapter is where payment semantics belong. Map the documented responses carefully:

  • PENDING: keep waiting within the polling window.
  • "Payment not initiated": keep waiting; the endpoint can return this message with HTTP 200 before the customer starts.
  • COMPLETED: validate the payment details and call finishOrder.
  • FAILED: finish the attempt without fulfilment; the customer must retry.
  • AUTHORIZED or CANCELLED: route to the separate saved-card capture workflow.

Those last statuses apply to saved-card payments with manual capture or capture before expiry. An authorisation is not proof that the order has been paid.

Before accepting completion, compare the request identity, amount and currency with the stored payment attempt. Use the returned transaction details to diagnose failures, rather than letting an unfamiliar response become a successful order.

If the endpoint returns HTTP 429, back off. When it supplies Retry-After, convert either its seconds value or HTTP date into the adapter's absolute retryAt timestamp, as defined by HTTP Semantics (IETF RFC 9110, 2022).

The adapter must also pass the abort signal to its HTTP client and bound each request by the remaining deadline. Otherwise, stopping the loop will not stop an outstanding network request.

Step 5: Cancel Locally and Coordinate Across Workers

Node's promise-based timer API accepts an AbortSignal and rejects a cancelled wait with AbortError (Node.js documentation). The loop uses that mechanism to stop sleeping when a verified webhook has finished the payment.

Call cancelPoller after the final database update commits. Cancelling on receipt of an unverified message could stop recovery without recording a trustworthy result.

The map only coordinates work within one Node.js process. With multiple workers, use a database lease or queue uniqueness rule to prevent duplicate pollers, and send cancellation to the worker holding the task.

Database checks remain necessary even with cancellation messages. A webhook can finish the payment just as a status request returns, so finishOrder must safely accept that race.

Step 6: Reconcile After Polling Stops

Reaching the deadline means the poller has stopped trying; it does not mean payment failed. Leave unresolved records available to a scheduled reconciliation worker and staff review.

Expired requests signalled by the separate EXPIRED_STATUS webhook are handled by the reconciliation job rather than mapped in finishOrder.

Faster Payments can sometimes take up to two hours, with longer delays outside working hours (Pay.UK, 2026). Keep that possibility separate from the payment request's expiry and your checkout's waiting window.

The scheduled worker should query unresolved attempts and use the same validation and completion function. Record when each attempt was last checked, and escalate persistent uncertainty instead of silently abandoning it.

Mistakes to Avoid

  • Polling from the browser: closing the tab stops recovery, and payment credentials must stay server-side.
  • Treating HTTP success as payment success: inspect the payment response, including "Payment not initiated".
  • Turning expiry into failure: a local deadline does not establish the payment outcome.
  • Dispatching from both handlers: route both through the transactional completion function.
  • Mixing environments: keep sandbox requests and production requests with their matching environment.
  • Restarting the grace period after every deployment: calculate it from the persisted creation time.

Checklist

  • Store the request ID, environment, creation time and expiry.
  • Verify signatures before accepting webhook updates.
  • Save events before acknowledging successful receipt.
  • Use one transactional completion function.
  • Apply capped backoff, jitter and any Retry-After.
  • Cancel waits and network requests.
  • Recover durable polling jobs after restarts.
  • Reconcile unresolved attempts later.

Conclusion

Payment status polling gives your checkout another route to confirmation when a webhook is late or missed. Start by making completion safe to repeat, then add bounded polling and scheduled reconciliation so an unanswered request never becomes an automatic instruction to charge again.

Top comments (0)