Skip to main content
Back to all insights
Payment Gateway เว็บพนัน2026-11-30·13 min read

Idempotent Payout Engine: Stopping Double Withdrawals on a Gambling Payment Gateway

An engineering deep-dive for teams running a Payment Gateway for gambling sites: how retries, timeouts, queue redeliveries and double-clicks create duplicate transfers, and how merchant_ref_id, a state machine and ledger reconciliation prevent them.

Reviewed by the SF PayGate Payment Engineering & Reconciliation Desk · Updated December 2026

Idempotent Payout Engine: Stopping Double Withdrawals on a Gambling Payment Gateway

Summary

Double withdrawals almost always come from the merchant side sending the same intent twice without realising it, not from the gambling payment gateway misbehaving. The fix is to generate merchant_ref_id before the call, persist it, reuse it on every retry and govern the record with a state machine. SF PayGate treats a unique merchant_ref_id as the idempotency key on POST /api/v1/payouts, and a regular reconciliation against your ledger catches whatever remains.

01Why a duplicate payout costs more than it looks

A withdrawal is the one side of a gambling platform where money genuinely leaves your account. Pay-ins can be disputed, queried and matched after the fact; a completed payout cannot be recalled by pressing a button. Because push-payment rails such as PromptPay or bank transfer have no card-style chargeback, a duplicate transfer to a player becomes a manual recovery exercise that rarely returns the full amount.

Picture a Friday-night spike. A player requests 3,000 THB, the page hangs, and they tap the button twice more. If your backend creates a fresh payout command for every request it receives, 9,000 THB leaves the platform, even though the player's balance may have been debited only once or twice depending on how a race condition played out. Each small leak is easy to miss, and together they turn month-end into a hunt.

This article is written for the engineer who has to make a gambling payment gateway integration safe on the merchant side. It describes only behaviour that SF PayGate documents; anything beyond that, such as the exact shape of a response to a repeated key, should be confirmed in the sandbox and the current docs before launch.

02Four ways a duplicate transfer is born

The first is the timeout. The HTTP request reaches the gateway, but the response does not make it back in time. Your code concludes that the call failed even though the other side may have accepted it, and if the retry path builds a new command with a new identifier, two transfers follow. This is the most common scenario because unknown is not the same as failed.

The second is queue redelivery. Most queues guarantee at-least-once delivery, so a worker that is restarted or slow to acknowledge causes the same message to reach another worker. If that worker does not check the record's state before calling the gateway, it calls twice. The third is the human double-click: a player tapping twice, or two back-office operators pressing Approve on the same row within a second of each other.

The fourth is the manual fix. An agent sees a payout stuck in an in-between state and creates a new one by hand without verifying whether the original went through. The common thread is that nothing in the system holds a permanent identity for the intent to withdraw. Giving that intent an identity is exactly what an idempotency key is for.

03Why the quick fixes fall short

The first reflex is to disable the button after one click. That helps with double-clicks but does nothing for timeouts, queue redelivery or two operators, because all of those happen server-side. Front-end protection is a thin courtesy layer, not the control that keeps money safe.

The second reflex is an in-memory lock, or a rule such as block the same player and amount within 60 seconds. Locks held in one process are useless once you run several instances or workers. Time-window rules fail in both directions: they reject legitimate requests, such as a player who intentionally withdraws 1,000 THB twice, and they pass genuine duplicates that arrive just outside the window.

The sturdier approach binds each intent to a single identifier that survives every retry layer, then lets both your database and the gateway use that identifier to refuse or merge repeats. In the SF PayGate API that identifier is merchant_ref_id.

04merchant_ref_id: doing the idempotency key properly

According to the documentation, POST /api/v1/payouts requires a unique merchant_ref_id, which acts as the idempotency key. Using it well comes down to three habits. Generate the value before you call the API rather than during it. Persist it in your database together with the ledger hold, in the same transaction. Reuse the identical value on every retry of that payout.

Create the value once per withdrawal request, for example a ULID or UUID with a prefix for your system. Do not derive it from the current time during a retry, and do not compute it from player and amount alone, because a player is entitled to legitimately withdraw the same amount twice. A database unique constraint on the column gives you a second line of defence on your own side.

What happens when the gateway receives a key it has already seen? The documented contract is that merchant_ref_id must be unique and acts as the idempotency key. The precise response format for a repeated key is something to confirm in the sandbox and in the Smart Payouts API documentation. So write your handler to be independent of any particular message: whatever the outcome of a repeated call, the next action is always to look up the payout by the same id.

05Sandbox walkthrough: when a player taps withdraw and the connection times out

To help engineering and finance teams verify idempotency side by side, the table below traces a single simulated Sandbox withdrawal of 5,000 THB (`WD-SBX-0912`) where the merchant server experiences a network timeout on the first call and automatically retries with the exact same `merchant_ref_id`.

Even though the merchant worker sends two HTTP requests to `POST /api/v1/payouts`, both the SF PayGate Dashboard and the immutable financial ledger record exactly one payout and one fee deduction, matching the player's single wallet hold.

Time (Sim)System EventWhat the Player SeesGateway Dashboard StateActual Ledger Debits
20:10:01Player confirms 5,000 THB withdrawal; backend persists WD-SBX-0912 + holdWithdrawal submitted (5,000 THB held)Not yet received0 debits (merchant hold only)
20:10:02Worker sends attempt #1 to POST /api/v1/payouts; client socket times out at 5sProcessing withdrawal — please waitWD-SBX-0912 accepted & queued (1 record)0 debits (awaiting bank clearing)
20:10:12Worker retries attempt #2 with identical merchant_ref_id WD-SBX-0912Processing withdrawal (same request, no duplicate row)Deduplicated against existing WD-SBX-09120 debits (single active payout)
20:10:19Bank transfer completes; signed webhook delivered and acknowledged HTTP 2005,000 THB withdrawal completedCOMPLETED (1 payout: 5,000 THB + 50 THB fee)Exactly 1 debit (-5,050 THB net in Ledger)
Illustrative Sandbox trace (`WD-SBX-0912`, 5,000 THB withdrawal)

06A state machine for every withdrawal

An idempotency key does little if the record's status can change without rules. Define a state machine and make every transition atomic, for example an UPDATE with WHERE state = 'CREATED' followed by a check on the affected row count. If the count is zero, another worker won the race, and the current worker must stop.

The table below is a merchant-side model. The state names are ours, not gateway status codes, so you will map them to the statuses in callbacks and query responses yourself. The important design choice is that SUCCEEDED and FAILED are terminal and are not reopened. If a player genuinely needs a second attempt, create a new withdrawal with a new key through an approval step that has an owner.

StateMeaningWho may change itNext
CREATEDRequest stored and funds held in your ledger; gateway not yet calledWithdrawal intake serviceSENT
SENTA worker has claimed the send; the outcome of the call may be unknownThe worker that won the claimPROCESSING or FAILED
PROCESSINGGateway accepted the instruction; awaiting result or step resultsCallback receiver / reconcilerSUCCEEDED or FAILED
SUCCEEDEDTransfer confirmed; the hold becomes a final debitCallback receiver / reconcilerTerminal
FAILEDFailure confirmed; the held amount is releasedCallback receiver / reconcilerTerminal
Merchant-side payout state machine

07A safe payout handler in TypeScript/Node

The code below is pseudo-code to show the structure, not an official SDK; field names for the destination should follow the documentation. Three points matter. The key and the ledger hold are created in one transaction. The queue carries only the payoutId, not an amount or a new key. And a worker must claim the state atomically before it touches the gateway.

Note also how a timeout is handled: the record stays in SENT and is rechecked later with the same key, and nothing in that path mints a new identifier. Remember the signing rule as well. You call /api/v1/payouts, but the HMAC-SHA256 signature over the raw body uses the path /v1/payouts, because the leading /api is stripped before verification.

// Pseudo-code (TypeScript / Node). Adapt names to your own stack.
// States: CREATED -> SENT -> PROCESSING -> SUCCEEDED | FAILED

async function requestWithdrawal(playerId: string, amountThb: number) {
  // 1) Validate against the documented THB limits before anything else
  if (amountThb < 100 || amountThb > 45000 || amountThb % 100 !== 0) {
    throw new Error("INVALID_AMOUNT");
  }

  // 2) Generate the key ONCE, and persist it together with the ledger hold,
  //    inside a single database transaction.
  const payoutId = "wd_" + newUlid();
  await db.transaction(async (tx) => {
    await tx.ledger.holdFunds(playerId, amountThb, payoutId);
    await tx.payouts.insert({ payoutId, playerId, amountThb, state: "CREATED" });
  });

  // 3) Enqueue by payoutId only. The job carries no amount and no new key.
  await queue.publish("payout.send", { payoutId });
  return { payoutId };
}

// Consumer: safe to run twice, or to run concurrently
async function sendPayout({ payoutId }: { payoutId: string }) {
  // Atomic claim: only one worker can move CREATED -> SENT
  const claimed = await db.payouts.transition(payoutId, "CREATED", "SENT");
  if (!claimed) {
    // Already sent (or finished). Do not call the gateway with a new key.
    return;
  }

  const row = await db.payouts.get(payoutId);
  const body = JSON.stringify({
    merchant_ref_id: row.payoutId,   // same key on every retry
    amount: row.amountThb,
    // ...destination fields as documented in /docs/payouts-smart
  });

  try {
    // Sign the raw body; sign the path without the leading /api
    await gateway.post("/api/v1/payouts", body, sign("/v1/payouts", body));
    await db.payouts.transition(payoutId, "SENT", "PROCESSING");
  } catch (err) {
    if (isTimeoutOrNetworkError(err)) {
      // Outcome unknown. Keep SENT, retry later with the SAME payoutId,
      // and let the reconciler look it up. Do not mint a new key here.
      await queue.publishDelayed("payout.recheck", { payoutId }, 30);
      return;
    }
    if (isDefiniteRejection(err)) {
      await failAndRelease(payoutId, String(err));
      return;
    }
    throw err; // unknown error class: surface it, do not guess
  }
}

// Webhook handler: verify HMAC-SHA256 on the RAW body first
async function onPayoutCallback(rawBody: Buffer, signature: string) {
  if (!verifyHmac(rawBody, signature)) return httpStatus(401);
  const evt = JSON.parse(rawBody.toString("utf8"));

  await db.transaction(async (tx) => {
    const seen = await tx.webhookEvents.insertIfAbsent(evt.eventId ?? hash(rawBody));
    if (!seen) return;                       // duplicate delivery, already applied
    await applyStepOrFinalState(tx, evt);    // terminal states are not reopened
  });
  return httpStatus(200); // only after the data is durably stored
}

08Smart Withdraw: split execution and step callbacks

SF PayGate's Smart Withdraw can split the execution of a payout into steps and report each step in HMAC-SHA256 signed webhook callbacks. This matters to your design because a single payout may generate more than one callback, and you may see intermediate states before the final one.

The practical consequence is not to treat the first callback as the final answer. Store step results against the single merchant_ref_id, and mark the payout SUCCEEDED only when the end condition described in the documentation is met. If a step fails, confirm with the query API and your ledger before releasing the hold.

For illustration, suppose a player withdraws 45,000 THB, the per-order ceiling. Your receiver has to cope with callbacks arriving out of order or twice, so compare each against the stored state before updating, and check the documentation for the constraints that apply to each payout.

09Reconciling payouts against the ledger

Even with a careful design, run a reconciler on a schedule. It selects payouts that have sat in SENT or PROCESSING longer than a threshold, then uses the query API, available around the clock, or the dashboard to check each by its original merchant_ref_id. The answer closes the record through the same state machine rules.

Each day, compare three data sets: your payout table, your internal ledger (holds and final debits), and the gateway's reporting. What you must not find is one withdrawal request with more than one transfer behind it, or money out with no request behind it. Raise anything odd through POST /api/me/issues and keep the request_id for reference.

By month-end, reconciliation should be confirmation rather than investigation. When daily comparisons run, the residual differences are small and explainable. SF PayGate pairs an immutable financial ledger with on-demand treasury settlement and keeps financial records separate from security audit logs, which helps when tracing events, and your own ledger should be append-only for the same reason.

10Failure modes and the right response

The table summarises the situations that cause trouble most often. One principle runs through every row: unknown must not be treated as failed, and every remedy loops back to the original key.

ScenarioSymptomWhat goes wrongCorrect handling
HTTP timeoutNo response receivedA new command with a new key is createdStay in SENT; check with the same key
Queue redeliveryTwo workers receive the same messageGateway called without a state checkAtomic claim before sending
Double-click / two operatorsNear-simultaneous duplicate requestsTwo debits and two payout rowsApprove the existing row; unique constraint
Repeated webhookSame callback arrives several timesBalance debited or released twiceDeduplicate; do not reopen a terminal state
Out-of-order callbackIntermediate state after final resultFinal result is overwrittenCompare with stored state before updating
Manual resendAn agent presses send againNew key created without checking the originalCheck status first; require an approver
Payout failure modes

11Pre-launch test checklist

Run every item in the sandbox first, and remember that good tests simulate failure, not just the happy path. The reviewer should be someone other than the author of the code, to avoid shared blind spots.

Keep the documented boundaries in mind too. A THB withdrawal is 100 to 45,000 per order and must be a multiple of 100, so validate on your side before sending and also handle a rejection from the gateway.

  1. 1Tap withdraw ten times quickly: exactly one payout row and one ledger hold must result.
  2. 2Simulate a timeout after sending and confirm the retry reuses the same merchant_ref_id.
  3. 3Deliver one queue message to two workers at once and verify only one claims it.
  4. 4Replay the same webhook, then shuffle the order, and verify the ledger changes only once.
  5. 5Send a wrong HMAC or an altered body and confirm it is rejected.
  6. 6Take your endpoint offline briefly, then bring it back, and confirm repeated callbacks leave a correct state.
  7. 7Run the reconciler against a payout stuck in SENT and confirm it closes via the original key.
  8. 8Try amounts such as 99, 150 and 45,100 THB and confirm they are rejected before reaching the gateway.
  9. 9Rehearse opening a case through POST /api/me/issues and recording the request_id.

12Who this suits, and compliance responsibilities

The approach suits any platform with meaningful withdrawal volume or several channels that can trigger payouts, because the cost of a clean state model is lower than the cost of chasing a duplicate transfer. If you process only a handful per day, still do it, but start small: a payouts table with a unique constraint on merchant_ref_id and a basic state machine.

SF PayGate supports push payments only: PromptPay QR, Thai bank transfer, Hong Kong FPS and USDT on TRC20. Cards are not supported, so there are no card-network chargebacks, although transfer disputes or bank holds are handled as tracked cases with a request_id under the written merchant agreement.

Merchants are responsible for their own licensing and for complying with the rules of the markets they operate in. SF PayGate reviews merchants before going live, and scams, phishing, fake investment and Ponzi operations are prohibited on the network under a 100% prohibition policy. To begin, request onboarding access and evaluate in the sandbox, which does not require a live domain.

Frequently asked questions

What is merchant_ref_id and why does it matter?
It is the identifier your platform assigns to each withdrawal. It must be unique and acts as the idempotency key for POST /api/v1/payouts. Generating it before the call, persisting it and reusing it on retries keeps a repeated request from turning into a new transfer.
After a timeout, should I resend with a new key?
No. A timeout means the outcome is unknown, not that the call failed. Keep the record in SENT, and retry or check status with the same key until you have a confirmed result.
What does the gateway return when the same key is sent twice?
The documentation states that merchant_ref_id must be unique and acts as the idempotency key. Confirm the exact response format in the sandbox and on the Smart Payouts page, and design your handler so every outcome leads to a status lookup by the same id.
Can a repeated webhook cause a double debit?
It can if your handler does not deduplicate. The gateway retries until it receives HTTP 200, so store an event id or body hash and do not reopen a terminal state. Verify the HMAC-SHA256 signature on the raw body before processing anything.
How is Smart Withdraw different for my integration?
Smart Withdraw can split execution into steps and report each in a signed callback. Your receiver therefore needs to accept several callbacks per payout and close the record only when the final result described in the documentation is reached.
How often should I reconcile?
Run a short-interval job for payouts stuck in SENT or PROCESSING, and compare against your ledger daily. That way month-end becomes confirmation rather than investigation, and anything unusual can be raised with POST /api/me/issues.

ENGINEERING & MARKET INSIGHTS

Related guides

All guides