Inventory counters
Maintain a remaining quantity, such as available inventory, where each operation consumes one unit.
Redis · Module
Decrements the integer value stored at a key by one and returns the updated value. If the key is missing, Redis starts from zero.
DECR subtracts one from the integer represented by a key's string value and returns the resulting integer. A missing key starts at zero, while a wrong type, non-integer string, or value outside the signed 64-bit range causes an error.
DECR key| Name | Type | Description |
|---|---|---|
key | key | Name of the key whose integer value is decremented. |
Integer reply: the value of the key after decrementing it.
import { createClient } from "redis";
const client = createClient();
await client.connect();
await client.set("stock", "10");
const remaining = await client.decr("stock");
console.log(remaining); // 9
await client.quit();Connects to Redis, initializes a string integer, decrements it once, and prints the resulting value.
Maintain a remaining quantity, such as available inventory, where each operation consumes one unit.
Track a number of available permits or slots and atomically reserve one.
Reduce a retry, quota, or pending-work counter by one per processed item.
DECR decrements the integer value stored at a key by one and returns the new value. If the key is absent, Redis treats its initial value as zero.
Follow-up: What happens with a non-numeric string? Redis returns an error because the stored string cannot be represented as an integer.
The command runs in O(1) time. It performs a single integer update and returns the resulting value.
Follow-up: How would you decrement by an arbitrary amount? Use DECRBY with the key and the desired decrement.
DECR accepts one required argument, the key name. The key's value must represent a signed 64-bit integer, otherwise Redis returns an error.
Follow-up: What reply should a client expect? An integer reply containing the value after decrementing.
DECRBYINCRINCRBYSETGET