Online gambling payments

Building an Online Casino Cashier: Idempotency Keys, Webhooks and a Double-Entry Ledger

The money core of a casino cashier is small and unforgiving. These are the patterns that stop double charges, double payouts and balances nobody can explain.

By VyaPayPublished 8 min read

A casino cashier needs three things to keep money straight: an idempotency key on every deposit and withdrawal so a retry can't charge or pay twice, webhooks treated as the record of what the processor actually did, and a double-entry ledger in which every balance is the sum of its postings. Add a hold before each payout and a daily reconciliation, and cashier bugs show up in a report instead of a support ticket.

An idempotency key is a unique value a client sends with a request so the server can recognise a retry of the same operation and return the original result instead of performing it again. In a casino cashier, it is what stops a deposit or withdrawal that timed out from charging or paying the player a second time when the app retries.

Why every deposit and withdrawal needs an idempotency key

Because the network between a phone and your cashier will drop responses, and the client can't tell a request that failed from one that succeeded without an answer. Mobile apps retry. Players tap twice. A load balancer gives up while the processor is still working. Without a key, each retry is a new charge or a new payout.

Generate the key once per player intent (this deposit, this withdrawal), not once per HTTP attempt, and send the same key on every retry of that intent. On the server, store the key with a hash of the request and the result:

CREATE TABLE idempotency_keys (
  player_id     BIGINT NOT NULL,
  key           TEXT NOT NULL,
  operation     TEXT NOT NULL,          -- 'deposit' or 'withdrawal'
  request_hash  TEXT NOT NULL,
  status        TEXT NOT NULL,          -- 'in_progress' or 'done'
  response      JSONB,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (player_id, key)          -- scope keys to the player
);
def handle_withdrawal(req):
    h = sha256(canonical_json(req.body))
    row, created = insert_or_get(req.player_id, req.idempotency_key, "withdrawal", h)
    if row.request_hash != h:
        return error(422, "key reused with a different request")
    if row.status == "done":
        return row.response               # replay: same answer, no second payout
    if not created:
        return error(409, "request already in progress")
    result = reserve_and_pay(req)         # ledger hold, then provider call
    mark_done(req.player_id, req.idempotency_key, result)
    return result

Three details matter. Reject a reused key with a different body; that is a client bug, not a retry. Return 409 for a request still in flight rather than starting a second one. And pass your key, or one derived from it, to your payment provider if it accepts one, so a retry between your server and the provider is deduplicated as well.

How retries interact with Visa's decline rules

An idempotent replay isn't a new attempt; a decline is a result to keep. If the processor answered with a decline, replaying the same key should return that decline, not send a fresh authorization. A genuinely new attempt gets a new key and is subject to Visa's reattempt rules.

Visa's current rulebook sorts declines into categories. Category 1 means the issuer will never approve, and the transaction must not be reattempted. Categories 2 (can't approve at this time), 3 (data quality) and 4 (generic) allow reattempts, up to 20 attempts in 30 days. Vendor blogs still quote 15; the 24 October 2026 rules say 20.

def may_reattempt(card_ref, decline_category, now):
    if decline_category == 1:
        return False                      # issuer will never approve
    recent = count_attempts(card_ref, since=now - timedelta(days=30))
    return recent < 20

Ask your acquirer how attempts are grouped for counting; the sketch counts per card. Store the decline category on every attempt so the check has something to read.

Webhooks are the record; your API call is a request

The synchronous response tells you what the processor thought at that moment. Webhooks tell you what happened afterwards: captures, settlements, reversals, disputes, payout confirmations and failures. Build the cashier so that a webhook can move state on its own, because some events arrive with no API call from you at all.

Verify every webhook before acting on it. The exact header names and the string that gets signed come from your provider's documentation; the sketch below assumes an HMAC over a timestamp and the raw body:

def verify(raw_body: bytes, sig: str, ts: str, secret: bytes) -> bool:
    if abs(time.time() - int(ts)) > 300:
        return False                      # stale: treat as a possible replay
    expected = hmac.new(secret, ts.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig)
  • Use the raw body. Re-serialised JSON may not match the signature byte for byte.
  • Deduplicate on the event id. Providers can redeliver the same event. Insert the event id into a unique column before processing and skip on conflict.
  • Expect events out of order. A settlement can arrive before the capture you were waiting for. Apply state transitions only when they move forward, and park events whose prerequisite hasn't arrived.
  • Acknowledge fast, process after. Return 2xx once the event is stored, then process it from a queue, so slow work doesn't trigger redelivery.

A double-entry ledger for player balances

Keep balances as the sum of immutable postings, never as a column you update. Every money movement is a journal entry with two or more postings that net to zero, and a player's balance is the sum of postings to that player's account. When something looks wrong, the history is the explanation.

CREATE TABLE journal_entries (
  id           BIGSERIAL PRIMARY KEY,
  kind         TEXT NOT NULL,           -- deposit, wager, settle_win, withdrawal_hold, payout, ...
  external_ref TEXT UNIQUE,             -- provider transaction or event id
  created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE postings (
  entry_id     BIGINT NOT NULL REFERENCES journal_entries(id),
  account      TEXT NOT NULL,           -- e.g. 'player:42:cash', 'pending_withdrawals:42'
  amount       BIGINT NOT NULL          -- minor units; debits positive, credits negative
);
-- enforce sum(amount) = 0 per entry_id in the write path or a deferred constraint
EventDebitCredit
Card deposit capturedProcessor receivablePlayer cash
Wager placedPlayer cashWagers in play
Wager settles as a winWagers in play; house resultsPlayer cash
Wager settles as a lossWagers in playHouse results
Withdrawal requestedPlayer cashPending withdrawals
Payout confirmedPending withdrawalsPayout clearing
Payout failedPending withdrawalsPlayer cash
ACH deposit returnedPlayer cashProcessor receivable

The external reference column does double duty: it ties each entry to the provider's record for reconciliation, and its unique constraint stops the same webhook from posting twice. Deposit entries also give you a clean count of deposits per player across every method, which a per-day deposit limit depends on; Colorado's reported rules for sportsbooks are covered in enforcing gambling deposit limits and credit-card bans in your cashier.

Reserve, then pay out

Move the money out of the player's available balance before you call the payout, not after it confirms. The "withdrawal requested" entry above does that. If the process crashes between the ledger write and the provider call, the money sits in pending withdrawals where a sweeper job can find it, instead of in the player's balance where it could be wagered or withdrawn again.

Model payouts as their own entry type, separate from refunds. Visa's §5.8.18.3 says gambling winnings paid to a cardholder must never be processed as a refund or credit of the deposit, so a code path that "refunds" a deposit to pay out a balance is a rules problem as well as an accounting one. Instant payouts to eligible debit cards are push-to-debit transactions; how operators run them is in instant withdrawals for online casinos and sportsbooks.

A payout call that times out is unknown, not failed. Query its status with the same idempotency key, or wait for the webhook, before releasing the hold.

Reconciling the ledger against settlement

Once a day, match three records: your ledger, the processor's settlement report, and the bank deposits that fund it. Every break falls into one of a few types.

  • In the ledger, not in settlement. A deposit you credited that never settled, or a payout you marked paid that the provider doesn't show.
  • In settlement, not in the ledger. A webhook you missed or failed to process.
  • Amount mismatch. Fees, partial captures, currency rounding or a bug.
  • Late reversals. ACH returns and card disputes that arrive days or weeks after you credited the player.

ACH deserves its own line in the report. Nacha's long-standing return-rate thresholds are 0.5% for unauthorized returns, 3.0% for administrative returns and 15% overall, and a return can land after you've let the player use the money. Track rates by deposit cohort; the deposit side is covered in ACH deposits for online casinos and Nacha's return limits.

If you're building on VyaPay, VyaLynk is the direct API for card-present, card-not-present, ACH and eCheck, sandbox access is available for developers, and VyaCloud tokenization keeps card data off your servers. The patterns in this post are provider-neutral. To talk through a cashier build for a licensed operator, get in touch with the team.

Frequently asked questions

Should the client or the server generate the idempotency key?

The client, at the moment the player commits to the action, so every retry from that device carries the same key. Your server then generates or derives its own key for the call to the payment provider.

How long should idempotency keys be kept?

Longer than any retry window in your stack, including the provider's own. Keeping completed keys for days rather than minutes costs little storage and covers clients that retry after an app restart.

Can I store a balance column instead of a ledger?

You can cache one for fast reads, but derive it from the postings and rebuild it when they disagree. A balance you update in place has no history, so nobody can explain how it got there when a player or an auditor asks.

Sources

Talk to the team that underwrites you

Tell us about your licenses, your markets and your volume. You'll be talking to the people who run VyaPay's processor and make its risk decisions.

or call 833-4-VYAPAY

Let’s meet up!

Tell us about your business and someone from our team will reach out.