KNOWLEDGE WALLET & TRANSACTIONS

Wallet API Idempotency: Preventing Duplicate Debits

A wallet can debit a bet correctly and still receive the same instruction again after a timeout. Learn how stable transaction IDs, immutable request fields, database uniqueness, atomic posting and provider-specific duplicate responses keep retries from charging twice.

How to use this guide

This is a reference integration model, not a specification for CASINO-AGG or any particular provider. Actual request formats, party responsibilities and settlement rules depend on the agreed API contract.

Idempotency means one financial effect, not one delivery

A provider sends a debit request for a wager. The wallet posts the stake, but the network connection drops before the provider receives the answer. A retry arrives, possibly on another server worker. Without a durable way to recognize the original instruction, the wallet may subtract the same stake twice. Idempotency is the property that repeating the same intended financial operation does not create a second monetary effect. It does not mean the network physically delivered the message only once.

The distinction matters because an HTTP request, a casino game round and an accounting operation are not interchangeable. Two separate bets may use the same game round, while a single wager can trigger several attempts to deliver one debit instruction. The wallet must recognize the latter as retries and the former as separate valid instructions. A simplistic rule such as one transaction per round could silently reject legitimate play, especially where one round covers multiple wagers or players.

The target is at-most-one committed debit for one authenticated, uniquely identified instruction, plus a way to discover its outcome. This is a testable claim, unlike global exactly-once delivery across systems. AWS's guidance on idempotent APIs emphasizes stable client-request identities and equivalent results for equivalent repeated intent. The precise identity and response contract for a casino wallet still come from its approved provider integration specification.

Scope of this guide

Examples describe recommended integration controls and public documentation from third parties. They are not claims about CASINO-AGG's deployed code, supported providers, financial guarantees or contractual partnerships. Validate transaction semantics against the signed integration contract before implementation.

Define a stable business key and an immutable payload

The best idempotency identity is a provider-defined transaction reference that remains unchanged when a sender retries the same intended debit. A random HTTP trace ID generated on every attempt cannot perform that job. A session token also cannot substitute for the money instruction: sessions expire, can be refreshed and may cover many bets. Depending on the contract, an internal uniqueness key may need the provider, operator or tenant, environment, operation type and the documented reference scope. Never assume an unqualified transaction string is globally unique across all integrations.

Field or identityUse in duplicate handlingCommon error
Provider transaction referencePrimary business identity when contract guarantees stabilityGenerating a new value for each retry
Operator, provider and environmentSeparate financial and testing namespacesLetting a sandbox or another brand collide with production
Operation typeKeep debit, credit and reversal meanings explicitTreating a win or refund as a duplicate bet
Player, amount and currencyImmutable comparison attributes of the intended postingAllowing an old ID to authorize a different amount or account
Round, bet and session referencesContext and correlation according to contractAssuming a round or session is one unique debit
Internal wallet posting IDAudit trail and reconciliation linkReplacing the provider's retry identity with an internal-only ID

Persist a normalized fingerprint of the immutable financial meaning: authorized tenant and player, debit or credit type, amount in exact units, currency, and provider-required bet or round relation. Normalize according to a documented schema, not raw JSON byte order or incidental fields such as timestamps and trace IDs. A retry with the same key and same meaning may return its recorded outcome. The same key with a changed amount, currency or account is an identity conflict and must never be silently accepted as a harmless retry.

Some providers prescribe which fields form the duplicate identity and whether a shared reference spans several callback methods. That contract overrides a generic composite-key example. Preserve the original signed request and normalized interpretation where retention and privacy requirements permit, so a dispute can distinguish a genuine retransmission from a conflicting new instruction.

Stop the concurrent double-debit race inside the database

Checking for an existing transaction and then inserting a new one is not sufficient if those steps are unprotected. Two workers can both observe that no record exists and both begin debiting the same account. Put a database-enforced unique constraint on the agreed business identity, and make reservation of that identity, balance authorization, ledger posting and final outcome one coherent transaction boundary. The winning worker establishes the financial result; the other worker resolves the existing record rather than posting a second debit.

01Authenticate and normalize

Verify sender authority, resolve the wallet account and calculate the canonical business identity and immutable attributes.

02Reserve the unique identity

Use a database-enforced uniqueness rule so competing workers cannot both own the same intended debit.

03Serialize account changes

Lock or atomically condition the authoritative balance when applying a legitimate debit alongside other independent bets.

04Commit posting and result

Persist one ledger effect and the definitive operation state in a transaction with appropriate durability.

05Resolve every retry

Compare immutable fields and return or query the original committed, declined or still-pending outcome under the provider contract.

A database unique key prevents two postings with one identity, but it does not by itself prevent overspending by two genuinely different bets. Balance updates also require concurrency control. For an InnoDB-based design, MySQL documents transaction isolation and locking reads; the exact indexes, lock order, deadlock recovery and isolation level must be chosen for the deployed schema. A failed unique insert, deadlock or worker crash is a state-resolution event, not permission to debit a second time outside the transaction.

Avoid sending a final success before the database commits. If a service instead acknowledges an accepted pending operation, that must be an explicit protocol state with durable ownership and later status resolution. Timeouts around commit are ambiguous from the sender's perspective; the next attempt must interrogate the stable operation identity rather than guess whether the balance changed.

Persist an operation state that survives worker crashes

An idempotency cache containing only a response string is rarely enough for a financial wallet. The wallet needs a durable record connecting the request identity, immutable attributes, ledger entry and final business outcome. It also needs a strategy for a worker that dies between receiving a request and completing it. State names can vary; the conceptual lifecycle below is intended for design review, not as a mandatory public API.

Illustrative stateFinancial meaningSafe retry behavior
RECEIVEDValid request identity recorded but no final decisionOne authorized worker may resume or investigate
PENDINGProcessing owned or awaiting a dependencyDo not create another concurrent debit; query or wait
COMMITTEDExactly one debit recorded in the authoritative ledgerReturn documented prior success or duplicate result
REJECTEDDefinitive business refusal, such as insufficient funds at decision timeReturn the recorded refusal for the same immutable intent
REVIEW_REQUIREDOutcome or cross-system evidence is unresolvedFreeze accidental reposting and escalate or reconcile

The critical distinction is between a final business result and a transient infrastructure error. An insufficient-funds decision can be an immutable refusal for that particular transaction identity, if the provider contract requires it. A database connection failure before any durable decision is not a confirmed monetary rejection. Likewise, a gateway returning HTTP 500 after the ledger committed does not prove the debit failed. Store the actual transition evidence and define how stuck pending operations become recoverable without changing their identity.

A recovery process should use compare-and-set ownership, leases with fencing, or equivalent coordination if workers can restart. A timeout on a lease does not erase a committed ledger entry. All paths that claim success, rejection or reversal must consult the same authoritative operation and account records. A partial external acknowledgment is evidence for investigation, not an instruction to reconstruct the money movement from browser logs.

Return the duplicate response defined by each provider

Idempotent financial effect does not imply that every provider expects the same HTTP status or JSON body. The receiver has to know whether a duplicate must return the original transaction details, a specific error code or an equivalent success envelope. VeliGames' public wallet documentation illustrates an HTTP 409 duplicate-transaction response. Tom Horn Gaming documents a provider-specific duplicate reference code and fields tied to the original transaction. These are examples of different contracts, not alternatives the operator can choose arbitrarily.

  • Map a first successful debit to the provider's specified final acknowledgment only after the internal posting is durable.
  • For a byte-for-byte or semantically equivalent retry, resolve the original transaction ID and documented response semantics.
  • For reuse of an old identity with changed immutable financial parameters, return the contract-defined conflict and record the discrepancy.
  • For an unresolved pending instruction, use a supported pending or retryable response only if the integration explicitly defines it.
  • Preserve the response's currency, amount, transaction references and wallet balance meaning exactly as required by that provider.

A wallet cannot safely copy the behavior of an unrelated payments API. Stripe's public API idempotency guidance illustrates stable request keys and describes caching the initial result for a specific API version, including some unsuccessful responses. Casino wallet contracts may handle duplicate success, failure and status lookup differently. Build an adapter-level response matrix for each provider and test it against signed-off examples, including a lost acknowledgment and a conflict with the same reference.

Treat a timeout as unknown until the ledger proves otherwise

Imagine a debit of 10 units. The operator commits the debit and is about to return success, but its connection to the provider closes. The provider sees a timeout. If the next request uses a new business ID, the wallet may legitimately consider it another bet and debit 10 again. The correct recovery is to reuse the original provider transaction identity and ask the authoritative wallet state what happened. RFC 9110's discussion of retries explains why a transport failure is not evidence that a non-idempotent request had no effect.

01First attempt

Provider sends one signed debit instruction under stable business ID T-100.

02Unknown response

The wallet may have committed, declined or not reached a durable decision when the connection fails.

03Same-identity retry

The provider resends T-100 with equivalent immutable financial attributes, not a newly invented T-101.

04Durable resolution

The wallet finds the existing state or safely resumes an uncommitted reservation without a second posting.

05Bounded escalation

After the agreed retry budget, use status inquiry and financial reconciliation rather than unlimited duplicate attempts.

Retries should have bounded counts, backoff and jitter to avoid magnifying an outage. A provider's callback retry schedule and status API take precedence over a generic policy. If neither side can prove the outcome, mark the instruction for investigation while protecting its original identity. Do not report a successful debit merely to quiet retries, and do not report permanent failure merely because the caller stopped waiting.

Keep transaction identities longer than the retry window

Idempotency cannot work after the unique identity record has disappeared. Choose a retention period from the actual integration's retry promises, late financial callbacks, possible corrections, reconciliation cycle and required audit trail. A balance posting may need long-lived provenance even when a high-speed response cache expires. If an old identity is purged and later reused, an innocent replay can be mistaken for a new stake. Plan retention and archival before the first wallet migration.

Stripe documents an illustrative policy in which its service can prune idempotency keys after at least 24 hours. That is not a universal safe lifetime for casino money instructions and should never become a copied default. A casino provider might retry or settle events on a different schedule, and operational disputes may surface much later. Where policy permits pruning hot storage, retain a durable tombstone or indexed historical identity that still prevents financial replay through the same namespace.

RecordWhy it must remain accessibleArchival caution
Business identity and payload fingerprintRecognize old retries and changed-parameter conflictsDo not release an old ID for immediate financial reuse
Ledger posting and balance evidenceProve whether money actually movedKeep immutable references even after cache eviction
Provider response or result mappingReproduce contract-compliant duplicate handlingStore safely without leaking secrets or personal data
Correction and reconciliation linksExplain a later reversal or mismatched provider reportPreserve history across reporting and retention boundaries

Retention policies must also respect privacy, access control and legal obligations applicable to the operator; those requirements differ by jurisdiction and contract. A compact protected identifier index can sometimes outlive detailed request payloads. Reconcile the design with the provider's maximum reuse and retry horizon, and test a replay after simulated archival, not just five seconds after the first successful bet.

Protect the available balance against different valid bets

Suppose a player has 15 units. Two distinct, authorized bets for 10 arrive simultaneously under different valid transaction IDs. An idempotency key for each bet correctly treats them as different operations, so duplicate protection alone does not stop both services from reading 15 and trying to spend 20. The wallet must serialize balance decisions or apply an atomic conditional update with its accounting rules. One debit may succeed and the other may be declined, depending on the contract and available balance at commit time.

An append-only ledger and an available balance projection need a defined consistency model. It should be impossible for a committed debit and the reported balance to disagree merely because an asynchronous view lagged during authorization. If the implementation uses database locks, choose stable lock order to reduce deadlocks and ensure transactional rollback on failure. If it uses optimistic compare-and-set, retry only the balance calculation for the same original operation identity. MySQL's InnoDB documentation explains isolation and lock behavior, but does not replace application-specific wallet invariants.

  • Use exact monetary units and an explicit currency; floating-point approximations are unsuitable for an authoritative amount comparison.
  • Apply funds checks to the same account and balance version that the ledger debit will commit against.
  • Separate provider duplicate recognition from competition between two legitimate transaction identities.
  • Keep bonuses, reserved funds, cash and restricted balances distinct whenever the actual wallet contract requires it.
  • Verify that a deadlock retry or worker failover never regenerates the provider's business operation identity.

Check sender authenticity even when an ID looks familiar

An already-seen transaction ID is not an authorization token. A malicious client could guess a reference or replay a captured callback with changed amount or player fields. Verify the required signature or credential, tenant scope, operation permissions and account mapping before sharing original financial details or returning a duplicate acknowledgment. OWASP's webhook security guidance separates sender authentication, replay resistance and idempotent processing because these controls cover different failure modes.

Signature timestamps, nonces or delivery-event IDs may help reject stale network messages, but they do not necessarily identify a unique monetary instruction. If every retry has a fresh signed delivery ID, treating that delivery ID as the wallet debit key would defeat financial idempotency. Conversely, using only the financial ID without signature checks can leak account information or allow forged status probes. Validate each layer independently and preserve the meaning of retries authorized by the provider contract.

  • Keep production and testing credentials in separate namespaces and prevent cross-tenant transaction lookups.
  • Reject reuse of a valid transaction reference when the authenticated owner or immutable amount differs.
  • Redact secrets, signatures, raw tokens and unnecessary player data from operational logs.
  • Restrict audit and status endpoints, including those used to investigate duplicate responses.
  • Log signature failures and semantic-ID conflicts separately from expected insufficient-funds outcomes.

Reconcile partial failures without rewriting the original debit

A local database transaction can make the operator's reservation and ledger posting atomic. It cannot atomically commit a remote provider's database at the same time without additional distributed coordination. The wallet may have a confirmed debit while the provider still believes it timed out, or the provider may record a bet while the operator believes the callback was rejected. This gap is a normal distributed-systems risk, not proof of a duplicate debit, and it needs status inquiry and reconciliation evidence.

Keep an immutable mapping between provider instruction, internal posting, player, amount, currency, business time and final state. Where asynchronous notifications are necessary, a transactional outbox or comparable durable handoff can link local financial commitment to subsequent delivery, while an inbox identity can suppress repeated inbound events. Neither technique guarantees a remote consumer has acted; design explicit acknowledgment, retry and exception handling. Compare both sides' authoritative trails rather than reconstructing settlement from client telemetry.

A refund or rollback is a separate, authorized compensating monetary instruction with its own unique identity and an explicit relation to the original debit. Do not delete, overwrite or silently reverse the first posting merely because a callback was repeated. Repeating the rollback must itself be idempotent. If a cancellation arrives before the original operation can be found, follow the documented hold, query or rejection path; blindly crediting money would create a different risk. Detailed reversal patterns belong to the next article in this series.

A balanced ledger is necessary but not sufficient

A local ledger can be internally consistent while disagreeing with a provider's accepted wager history. Correctness requires a traceable one-to-one mapping of authorized business instructions, durable postings, compensations and any unresolved external differences.

Prove duplicate safety with a realistic acceptance matrix

A successful test must measure monetary effects, not just whether two API calls returned HTTP 200. Capture the provider operation ID, authenticated scope, payload fingerprint, internal ledger ID, resulting balance, exact response and commit time. Exercise concurrency and failures by pausing workers at database reservation, commit and acknowledgment boundaries. Confirm the final account total and the absence of extra postings from authoritative records.

Test scenarioExpected financial and operational evidence
Same signed debit ID sent twice sequentiallyOne ledger debit; documented duplicate or equivalent prior response
Same ID from two concurrent workersOne committed debit despite the race; loser resolves original state
Same ID with changed player, currency or amountNo second posting; authenticated conflict recorded
Two different valid bet IDs for one playerBoth evaluated as distinct bets with atomic balance authorization
Response lost after database commitRetry obtains original outcome without another debit
Worker dies before commitNo ghost success; reservation recovered or safely failed
Retry after cache expiration or archivePersistent identity prevents a historical duplicate posting
Invalid signature using a known transaction IDNo financial disclosure or change; security failure recorded
Duplicate rollback or refundOne authorized compensation, linked to original operation
Provider report differs from internal wallet trailMismatch flagged with IDs, amounts and investigation owner

Monitor duplicate-request rates, identity conflicts, stuck pending states, ledger-commit failures, database contention, callback latency, retry exhaustion and unreconciled differences. A high duplicate rate can be a provider transport issue, while changed-payload conflicts may indicate a serious protocol or security problem. Do not log raw credentials or full sensitive wallet payloads simply to make dashboards more detailed; preserve minimal, controlled evidence instead.

Release gate

Do not approve a live wallet integration solely on ordinary debit and win happy paths. Require evidence of one posting under concurrent retries, correct provider-specific duplicate responses, timeout recovery, balance serialization, safe rollback identity and a reproducible reconciliation report.

KNOWLEDGE

Sources & further reading

This guide draws on primary technical references and official guidance. Regulatory applicability depends on jurisdiction and implementation.

  1. AWS Builders' Library — Making retries safe with idempotent APIs
  2. AWS Well-Architected — Make mutating operations idempotent
  3. MySQL 8.4 Reference Manual — Transaction Isolation Levels
  4. MySQL 8.4 Reference Manual — Locks Set by Different SQL Statements
  5. Stripe API — Idempotent requests
  6. VeliGames Documentation — Wallet API
  7. Tom Horn Gaming — Withdraw / Bet Request
  8. OWASP — Webhook Security Cheat Sheet
  9. RFC 9110 — HTTP Semantics
  10. AWS Well-Architected — Control and limit retry calls
  11. OWASP — Logging Cheat Sheet