Scrivio Interview library
DesignAdvanced7 min read · updated 13 November 2026

A gaming platform keeps in-game credit wallets in Redis Cluster, one key per player, for 40 million players. A new feature lets players gift credits to each other, and a transfer must never create or destroy credits.

The two players' keys sit in different slots, so one Lua script cannot update both. How would you design the transfer, and where should the source of truth for balances live?

Redis Cluster cannot update two arbitrary keys atomically, and tagging all wallets together would put 40 million players on one shard, so the transfer becomes a small saga keyed by a transfer id: one Lua script debits the sender and records the id in the sender's slot, a second credits the receiver and ignores ids it has already applied, and retries complete interrupted transfers. The source of truth is a durable ledger, for example a PostgreSQL table of transfers, with Redis balances as a fast projection that is reconciled against it, because a failover can lose acknowledged Redis writes.

Why this question is asked

A rule like a transfer must never create or destroy credits is a conservation law, and conservation laws are where eventually consistent systems get uncomfortable. Each wallet sits in its own slot, possibly on a different shard, so no single Redis operation covers both. Interviewers ask this design question to see whether we can build correctness out of idempotent steps, decide what happens between them, and choose a source of truth honestly, knowing that Redis replication can lose writes. In this answer, we will see why there is no atomic shortcut, design the ledger, write the two scripts, handle failures between the steps, and reconcile.

1Why There Is No Atomic Shortcut

In Redis Cluster, a transaction or a Lua script can only touch keys in one slot. Wallets are keyed per player, such as {p:17}:wallet and {p:99}:wallet, which fall into slots 12289 and 6246. One option would be to tag all wallets with one value, {wallets}, so every transfer is a single script. That puts 40 million players' balances, and every gift, on one shard, which then becomes the bottleneck of the whole game. Another idea, tagging pairs of players together, fails because any player may gift any other; we cannot know the pairs in advance, and one key can only be in one slot.

So the transfer must be made of separate steps, each atomic on its own, and the design must make the sequence correct.

2The Ledger Is the Source of Truth

Redis replication is asynchronous, so after a primary fails, the promoted replica may be missing writes that clients were told succeeded. For a game wallet that means a debit or credit can silently disappear. So the true balance is defined by a durable ledger: a relational table of transfers and credit movements in PostgreSQL, written with ordinary ACID transactions. Redis holds each player's balance as a fast projection, for reads on every screen and for quick checks, and it can be rebuilt from the ledger at any time.

A transfer starts as a row in the ledger with status PENDING and a unique transfer id. That row is the commitment: from now on, the system's job is to drive it to COMPLETED or COMPENSATED, never to lose it.

Step throughWhere each piece lives
  1. Game servicesrequest a gift, show balances
  2. Transfer coordinatorcreates transfer, runs steps, retries
  3. Redis Clusterwallet balances and applied transfer ids, per player slot
  4. PostgreSQL ledgertransfers and movements; defines the true balance

4 layers, from the top down. Step through them one at a time.

3The Two Idempotent Scripts

Each step runs as a Lua script in one player's slot. The debit script checks whether this transfer was already applied to the sender, checks the balance, debits it and records the transfer id, all atomically. The credit script does the same on the receiver's side, without a balance check. Recording the transfer id next to the wallet, in a key with the same tag, is what makes each step safe to repeat.

Java
-- debit.lua KEYS[1] = {p:17}:wallet KEYS[2] = {p:17}:applied ARGV = transferId, amount
if redis.call('HEXISTS', KEYS[2], ARGV[1]) == 1 then return 'ALREADY' end
local balance = tonumber(redis.call('GET', KEYS[1]) or '0')
if balance < tonumber(ARGV[2]) then return 'INSUFFICIENT' end
redis.call('DECRBY', KEYS[1], ARGV[2])
redis.call('HSET', KEYS[2], ARGV[1], 'debit')
return 'OK'
-- credit.lua KEYS[1] = {p:99}:wallet KEYS[2] = {p:99}:applied ARGV = transferId, amount
if redis.call('HEXISTS', KEYS[2], ARGV[1]) == 1 then return 'ALREADY' end
redis.call('INCRBY', KEYS[1], ARGV[2])
redis.call('HSET', KEYS[2], ARGV[1], 'credit')
return 'OK'
-- debit(tx-81, 50) with balance 120 -> OK, balance 70
-- debit(tx-81, 50) again (a retry) -> ALREADY, balance still 70
-- credit(tx-81, 50) twice -> OK, then ALREADY: credited once

The applied-ids hash grows with every transfer, so it needs trimming: keep ids for longer than the longest possible retry, for example 7 days, using per-field expiry (HEXPIRE, Redis 7.4 and later) or a periodic cleanup. Both keys of each script share the player's tag, so the script stays within one slot.

4Running the Saga and Handling Failures

The coordinator runs the steps in order and records progress in the ledger: PENDING, then DEBITED after the debit script returns OK or ALREADY, then COMPLETED after the credit. If the debit returns INSUFFICIENT, the transfer is marked REJECTED and nothing changed.

Failures between steps are the interesting part. If the service crashes after the debit, the transfer is DEBITED in the ledger but not credited: credits are temporarily out of circulation, but not destroyed. A sweeper finds transfers that have stayed PENDING or DEBITED for longer than, say, 30 seconds and retries the next step; because both scripts are idempotent, retrying is always safe. If a transfer cannot complete within a timeout, for example because the receiver's account was closed, the sweeper compensates, but carefully: a slow credit might still land later. So it first runs a small cancel script in the receiver's slot that records the transfer id as cancelled, unless the id is already there as credited, in which case the transfer is simply COMPLETED. Only after a successful cancel does it credit the sender back, recording tx-81:refund in the sender's applied hash so the refund also happens once, and mark the transfer COMPENSATED. Because the credit script checks the same hash, a late credit attempt then does nothing.

Step throughStates of one transfer
  1. PENDING in the ledgertransfer id created
  2. Debit script returns OK or ALREADY?
    YesDEBITEDNoREJECTED if INSUFFICIENT
  3. Credit script returns OK or ALREADY?
    YesCOMPLETEDNoSweeper retries
  4. Still failing after the timeout?
    YesCredit sender back: COMPENSATEDNoRetry later

4 steps in order. Play them, or step through them one at a time.

5Reconciling Redis With the Ledger

Because Redis can lose writes in a failover, and because bugs happen, we reconcile regularly. A job compares each Redis balance with the balance computed from the ledger, starting with players who had movements recently, and alerts on differences. A difference after a failover is corrected by rewriting the Redis balance from the ledger. The conservation rule can be checked globally too: the sum of all balances plus credits in DEBITED transfers must equal credits issued minus credits spent.

6Follow-up questions

How would you show the receiver a pending gift in the meantime?

From the ledger, or from a small pending list in the receiver's slot written when the transfer is created. The UI then shows the gift as arriving, with the amount, until the credit step completes and the transfer is COMPLETED. Usually that takes milliseconds, so most players never see it; after a failure, the pending state is honest instead of showing a balance that might change.

Why not do the whole transfer in PostgreSQL and only cache balances in Redis?

That is a good option and often the simplest: one ACID transaction debits and credits in the database, and Redis is updated afterwards. It costs more database writes per gift. The saga design keeps balance checks and updates fast in Redis while the ledger defines the truth; which fits better depends on gift volume and latency needs.

Can WAIT make the Redis steps durable enough?

WAIT reduces the chance of losing a write by waiting for replicas to acknowledge it, but it does not make failover lossless or turn Redis into a ledger. The reconciliation against the durable ledger is still needed.

7Conclusion

In this answer, we saw that Redis Cluster offers no atomic update across two arbitrary keys and that a global hash tag would put every wallet on one shard. We designed the transfer as a saga keyed by a transfer id, with an idempotent debit script that checks the balance and an idempotent credit script, a sweeper that retries or compensates stuck transfers, a durable ledger as the source of truth, and regular reconciliation of Redis balances against it.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start by accepting that Redis Cluster cannot update two arbitrary keys atomically. A script only works within one slot, tagging all wallets together would put 40 million players on one shard, and arbitrary pairs of players cannot be tagged in advance.

Then, if they want more

So the transfer becomes a small saga with an idempotent transfer record. First the transfer is written to a durable ledger, for example a PostgreSQL table, with a unique transfer id and status pending.

Then a Lua script in the sender's slot checks that the transfer id was not already applied, checks the balance, debits it and records the id next to the wallet, all atomically. A second script in the receiver's slot credits the amount and ignores ids it has already applied.

Because both steps are idempotent, the coordinator can retry them as often as needed, and the ledger records each state. A sweeper picks up transfers stuck between steps and retries them, and if a transfer cannot complete within a timeout, it credits the sender back as a compensation keyed by the same id.

Credits are therefore never created or destroyed, only briefly in flight. The ledger, not Redis, defines the true balance, because a Redis failover can lose acknowledged writes, so Redis balances are a fast projection that I reconcile against the ledger regularly, alerting on any difference and rebuilding from the ledger when needed.

About this answer

Last updated
13 November 2026
Versions it names
Redis 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "The two players' keys sit in different slots, so one Lua script cannot update both. How...": https://scrivio-interview-library.netlify.app/databases/redis-scaling/83bd54349e/