Video in progress
This code oversells tickets under load. Where is the bug, and how do you fix it?
public boolean buy(long eventId) {
String key = "tickets:" + eventId;
int left = Integer.parseInt(redis.opsForValue().get(key));
if (left <= 0) {
return false;
}
redis.opsForValue().decrement(key);
orderService.create(eventId);
return true;
}
Checking with GET and then DECR are separate commands, and in between other requests also see "1 left". The check and the decrement must be a single atomic operation: check the result of DECR, a Lua script, or WATCH.
📖 Answer
Each command is atomic, but a sequence of them is not. When 1 ticket is left, 50 threads GET and see 1, all of them decrement, and the remainder is -49.
The simplest fix is to decrement first and then look at the result:
Long left = redis.opsForValue().decrement(key);
if (left == null || left < 0) {
redis.opsForValue().increment(key); // put it back
return false;
}
This works, but a negative value is briefly visible. The clean version is Lua:
local left = tonumber(redis.call('GET', KEYS[1]) or '0')
if left <= 0 then return -1 end
return redis.call('DECR', KEYS[1])
One more problem remains: the ticket was decremented in Redis, but if orderService.create throws an exception, the count doesn't come back. You need to put it back with INCR in a catch, or write the reservation with a TTL and release it automatically if the order isn't confirmed.
And finally, Redis here is a fast "gate". The final truth is in the DB: UPDATE event SET sold = sold + 1 WHERE id = ? AND sold < capacity, and if 0 rows are updated, reject.
Sign up to mark studied questions and save your progress.