Maintaining inventory in Redis, using atomic addition and subtraction operations, can avoid inventory shortages, oversold and other anomalies caused by high concurrency.

Here is a Lua script that records the old and new values of an inventory operation while preserving atomicity:

local stock = tonumber(redis.call('get', KEYS[1]));
local delta = tonumber(ARGV[1]);
if (stock + delta < 0) then
   return ' ';
end;
return string.format('%d,%d', stock, redis.call('incrby', KEYS[1], delta));
Copy the code

The script queries the current inventory based on the key and then performs the quantity operation on the variable without actually changing the value of Redis. If the result of the operation is negative, return null, otherwise perform atomic addition and subtraction, and return the current inventory and the post-operation inventory.

Here’s an example:

The input parameters are the corresponding inventory key, and the amount to add or subtract, for example: GOODS_425, -10,

Represents a decrease of 10 in inventory for GOODS_425.

The return is a string, if empty, indicating that the user should be prompted to redo the operation when the operation will make the inventory negative.

Normal operations return the old and new values of the inventory operation separated by commas, “125,105”.