Idempotency in Bet and Win APIs: Preventing Duplicate Transactions

A casino wallet API is exposed to retries from remote game servers, intermediary gateways, load balancers, queues, and internal workers. A caller may send a bet, fail to receive the acknowledgment, and send it again. The wallet cannot conclude that the first attempt failed merely because the network response disappeared. If every retry creates a fresh debit, the player is overcharged. If a win is repeated as a fresh credit, the player is overpaid.

Idempotency means that repeating the same business instruction has the same intended financial effect as executing it once. It does not mean every request is successful, that the network delivers messages exactly once, or that two unrelated bets with identical amounts should collapse into one. The design must distinguish a new economic operation from another attempt to communicate an existing operation.

The HTTP specification defines idempotent methods in terms of repeated intended server effects, but financial POST endpoints are not magically idempotent. They need a business-level key, atomic storage, strict payload comparison, and repeatable outcomes. This article focuses on wallet-side bet and win mutation safety; broader retry timing and circuit-breaker policy belongs in a separate integration reliability guide.

Why retries create duplicate financial requests

Imagine a provider sends BET for round R-91, transaction T-201, amount 5.00 EUR. The wallet commits a debit and journal entry, but its process crashes before the HTTP response reaches the provider. The provider sees a timeout. If it retries as the same economic operation, the correct wallet behavior is to report the earlier result. A naive handler that only checks the latest balance will debit again and produce a second valid-looking journal row.

Lost response followed by repeat-safe retry
Figure 1. The first request may commit even when its acknowledgment is lost; the retry must resolve the same outcome.

Retries arise for other reasons too: a message broker redelivers after consumer restart, a proxy retries connection establishment, the provider replays a historical batch, or two gateway instances receive equivalent callbacks concurrently. An API can pass single-threaded tests yet fail under a race where two handlers both check “key not found” before either inserts a record. Duplicate detection must be part of the same atomic commitment as the financial effect.

Distinguish three identifiers. A network attempt ID changes on each delivery. A round ID groups game lifecycle activity and may contain several legitimate financial operations. A financial transaction ID identifies the economic operation being booked. Deduplicating by round alone can accidentally suppress a valid separate win or partial bet. Deduplicating by HTTP request ID that changes on retry does not protect money. Contract review must explicitly determine the provider’s stable transaction reference.

Idempotency-key design and scope

A reliable idempotency key is unique within a documented business namespace and remains stable through retries, routing, and deployment. A useful conceptual scope is (operator, provider, operation_type, provider_transaction_reference) when the contract guarantees uniqueness of that reference within those dimensions. Some providers reuse identifiers across tenants or transaction types; others provide globally unique IDs. Choose the narrowest safe namespace grounded in the actual contract rather than copying a generic formula.

Idempotency identity compared with round and network attempt IDs
Figure 2. Multiple delivery attempts map to one financial instruction, while a round may contain several distinct instructions.

Store the key with a fingerprint of immutable business fields—such as player mapping, currency, integer-minor-unit amount, transaction type, and original reference where relevant. On a repeated key, compare the payload against the original business meaning. If the key matches but the amount or player changes, return a conflict and alert; do not replay a success response for a different instruction. Fields such as request timestamp or tracing identifier may vary by attempt without changing the economic intent, so the fingerprint must be defined carefully.

Key retention is a business requirement, not simply a cache tuning parameter. A transaction reference may be replayed days or months later during dispute resolution or provider recovery. If deduplication records expire earlier than the allowed replay window, an old callback can post again. Some systems retain an immutable transaction ID in the ledger permanently and use a faster auxiliary table for recent calls. Document the archival and lookup behavior so an ancient replay is still detectable.

The identity namespace also protects against cross-provider collisions. T-7 from provider A must not automatically collide with T-7 from provider B, but the same provider must not be allowed to reuse T-7 for a different player without detection. Do not trust a raw tenant identifier from an unauthenticated message to choose its own namespace. Resolve the authenticated provider and operator context before deduplication.

Atomicity, storage and race handling

The central invariant is: for one valid logical financial transaction, the authoritative ledger records at most one committed economic effect. Implement that with an atomic database operation where deduplication ownership, balance validation, journal posting, and durable result storage are committed together, or with an equivalent transactional mechanism. A standalone Redis SETNX before a database write can prevent concurrent work temporarily, but it does not on its own solve a crash between the cache claim and the ledger commit.

Atomic claim, ledger commit and durable result
Figure 3. The deduplication result and accounting journal must not diverge when a process crashes.

One pattern is a unique database constraint on the scoped business key. The first transaction wins the insert, checks all financial preconditions, posts the journal entries, and records the final business outcome. A concurrent request either waits for the first transaction to commit or observes a conflict and then loads the committed result. If the first transaction aborts, the key claim must not remain in a state that falsely reports a booking. The exact locking and isolation strategy depends on the database and contention profile.

Another pattern uses a durable IN_PROGRESS state with a lease or ownership token, but it requires careful recovery. What happens when the worker loses its lease after committing the ledger but before recording completion? The system must be able to locate the authoritative journal by immutable business key and reconstruct the outcome. Do not let lease expiry alone authorize a second posting. Treat the ledger’s committed identity and a uniqueness constraint as the final protection.

Here is an illustrative transaction outline, not production SQL:

BEGIN TRANSACTION
  resolve authenticated provider/operator scope
  insert financial_operation(key, fingerprint, state=PENDING)
    subject to unique(scope, key)
  validate player, currency, amount, available funds and policy
  write balanced ledger postings with the operation_id
  update financial_operation(state=COMMITTED, result=...)
  insert outbox event for the committed operation
COMMIT

On a uniqueness collision, the handler reads the existing operation, compares fingerprints, and returns the correct repeated result or a conflict. A failed balance check may create a durable rejected outcome under the agreed key, but the contract must specify whether a rejected transaction can later be retried as the same business instruction. Do not automatically convert a historical rejection into a successful debit without an explicit policy.

In-progress, failed and completed repeat responses

Design the response model around authoritative business states rather than transport status alone. A committed transaction can be replayed with the same durable result even if the original HTTP response was lost. A permanently rejected transaction can repeat the same rejection where the contract requires it. An operation still being processed may require a documented IN_PROGRESS response or bounded wait. A true unknown outcome demands a lookup or reconciliation path, not speculation based on a timeout.

Response decision tree for first, repeated, and conflicting requests
Figure 4. Repeated keys resolve to existing outcomes; altered payloads are conflicts, not retries.

An API should not report success until the contract’s claimed financial state is durable. If accepted means merely placed on a queue, make that explicit and keep the operation status query available. A provider expecting synchronous wallet booking must not be misled by an asynchronous acceptance response. Similarly, a generic HTTP 500 can occur after commit; an automatic retry should use the original financial key and should never manufacture a replacement key to “make it work.”

Record separate metrics for retry attempts, idempotent replays, key conflicts, in-progress age, unknown outcomes, and actual ledger postings. High retry volume may indicate a slow dependency; high duplicate postings indicates a correctness failure. Alert on any key collision involving mismatched economic fields, unexpected replay after retention boundaries, or financial journal entry without a corresponding operation identity.

Safe refunds and rollback semantics

A refund is a new financial instruction linked to an original transaction, not a deletion of history. Give that refund its own stable operation identity, and enforce rules on which original debit can be reversed, how much is refundable, whether partial refunds are legal, and whether a previous refund already consumed that amount. Duplicate delivery of the same refund must not credit the player twice. A second distinct valid partial refund should not be incorrectly suppressed by deduplicating only on the original bet ID.

Two refunds and the remaining reversible amount
Figure 5. Each reversal has its own key and a link to the original; total credited correction cannot exceed contractual limits.

Suppose a 10.00 bet can be partially refunded. Provider instruction REV-1 refunds 4.00, leaving 6.00 potentially refundable. An identical retry of REV-1 returns the already committed result without another credit. A new instruction REV-2 for 6.00 may be valid if the provider contract permits a separate partial refund. A third instruction for another 2.00 must be rejected or investigated because it would exceed the original reversible amount. This example assumes the simplified refund model and excludes game-specific settlement netting.

Some providers define rollback as reversing an entire round, including winnings; others only reverse the bet. Map these rules explicitly before applying accounting corrections. Keep the original transaction, reversal references, authorization decision, and any downstream event in the audit trail. A refund repeated after a deployment or provider migration still needs to resolve the same history and operator/provider namespace.

Concurrency tests and failure scenarios

Test that the financial invariant holds under real concurrency, durable restarts, and partial failure. Unit tests for a deduplication helper are necessary but insufficient. Use integration tests with the actual database uniqueness, isolation, retry middleware, and event-outbox mechanism. For each scenario, assert both the API response and the journal entry count and amounts.

Scenario Expected financial effect Evidence to verify
Identical bet sent twice sequentially Exactly one debit One unique operation key and journal group
Identical bet sent concurrently Exactly one debit Unique constraint or equivalent atomic protection
Committed bet, response lost Exactly one debit after retry Returned result points to original journal ID
Same key, changed amount No second debit; conflict raised Stored fingerprint and security/audit event
Different bets in one round Two legitimate debits if contract allows Different transaction identities, same round
Win repeated after long delay Exactly one credit Durable identity retained beyond replay window
Duplicate partial refund One refund credit One refund key tied to original debit
New refund exceeds remaining amount No excessive credit Aggregate reversal limit enforced atomically
Process fails before commit No partial ledger effect Transaction rollback and safe replay
Process fails after commit, before event publish One ledger effect and recoverable outbox event Outbox persisted in same commit

Consider fault injection at every boundary: before acquiring the key, after acquiring it, before ledger posting, after posting but before commit, after commit but before HTTP response, and during event publication. Add clock skew, provider retry storms, request reordering, failover, and restore from backup. Verify that restoring an old application binary does not undermine persisted uniqueness guarantees or key parsing logic.

Idempotency is not a best-effort optimization. It is an accounting property that must remain true when messages are duplicated and infrastructure fails. Choose stable business identities, verify their scope, commit outcomes atomically, retain evidence for expected replay horizons, and test with the final ledger as the oracle. That is the difference between an API that usually handles retries and a wallet that cannot silently charge a player twice for one transaction.

Further reading

Editorial note: The examples apply general HTTP and distributed-systems principles to a conceptual wallet design. Actual replay periods, refund rules, and transaction namespaces must come from the provider/operator contract and accounting policy.

Scroll to Top