Prompt
how to use atomic increments in Redis
Latest observation
Oct 25, 2026
OpenAI APIWeb search: off
To do atomic increments in Redis, use the built-in INCR / INCRBY commands. These are atomic, meaning Redis guarantees the operation happens as one indivisible step, even with multiple clients.
Basic usage
Increment by 1
INCR counter
Increment by a custom amount
INCRBY counter 5
Decrement
DECR counter
DECRBY counter 3
Example
If counter does not exist:
INCR counter
Redis will create it and set it to 1.
If you run:
INCRBY counter 10
it becomes 11.
In code
Python (redis-py)
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
value = r.incr("counter")
print(value)
value = r.incrby("counter", 5)
print(value)
Node.js (ioredis)
const Redis = require("ioredis");
const redis = new Redis();
(async () => {
let value = await redis.incr("counter");
console.log(value);
value = await redis.incrby("counter", 5);
console.log(value);
})();
Important notes
- The key must contain an integer value.
- If the key does not exist, Redis treats it as
0. - These commands are atomic by design, so you usually do not need transactions for a simple counter.
If you need more complex atomic logic
Use:
- Lua scripts (
EVAL) for multiple operations that must be atomic together - Transactions (
MULTI/EXEC) for grouped commands, though they are not the same as a full compare-and-swap mechanism
If you want, I can also show:
- how to do atomic increments with expiration, or
- how to implement a distributed rate limiter with Redis.