Video in progress

Strong Middle ⚡ Redis and caching

What is wrong with this balance withdrawal code, and how do you fix it with `WATCH`?

public boolean withdraw(String userId, long amount) {
    String key = "balance:" + userId;
    long balance = Long.parseLong(redis.opsForValue().get(key));
    if (balance < amount) return false;
    redis.opsForValue().set(key, String.valueOf(balance - amount));
    return true;
}

Between the GET and the SET, another request can change the balance: a lost update. WATCH observes the key, and if it changes before EXEC, the transaction is aborted and you try again.

📖 Answer

Two parallel requests both read balance = 100, both withdraw amount = 80, and the balance ends up at 20, but 160 has been paid out.

WATCH is an optimistic lock:

public boolean withdraw(String userId, long amount) {
    String key = "balance:" + userId;
    for (int attempt = 0; attempt < 5; attempt++) {
        List<Object> result = redis.execute(new SessionCallback<>() {
            @Override
            public List<Object> execute(RedisOperations ops) {
                ops.watch(key);
                long balance = Long.parseLong((String) ops.opsForValue().get(key));
                if (balance < amount) {
                    ops.unwatch();
                    return null; // not enough money
                }
                ops.multi();
                ops.opsForValue().set(key, String.valueOf(balance - amount));
                return ops.exec(); // an empty list if the key changed
            }
        });
        if (result == null) return false;
        if (!result.isEmpty()) return true;
        // someone wrote before us, so we retry
    }
    throw new IllegalStateException("Juda ko'p raqobat");
}

SessionCallback is required: WATCH, MULTI and EXEC have to be on a single connection, while plain redisTemplate calls may take a different connection from the pool each time.

For this case a Lua script is actually simpler: the check and the withdrawal happen in one atomic step and no retry loop is needed. WATCH aborts a lot under high contention. It's better to use it where contention is low and the logic is too complex to move to the server.