How to perform atomic increment and decrement operations using INCR and DECR?
Jun 25, 2025 am 12:01 AMINCR and DECR are commands used in Redis to increase or decrease atomic values. 1. The INCR command increases the value of the key by 1. If the key does not exist, it is created and set to 1. If it exists and is an integer, it will be incremented, otherwise it will return an error; 2. The DECR command reduces the value of the key by 1, which is similar in logic and is suitable for scenarios such as inventory management or balance control; 3. The two are only suitable for string types that can be parsed into integers, and you must ensure the correct data type before operation; 4. It is commonly used in concurrent scenarios such as API current limiting, event counting and shared counting in distributed systems, and can be combined with EXPIRE to achieve automatic reset temporary counters.
When you're working with Redis, atomic increment and decrement operations are handled cleanly using the INCR
and DECR
commands. These are simple but powerful tools for safely updating numeric values ??stored under a key, without worrying about race conditions.
Using INCR
to Atomically Increment a Value
The INCR
command increases the value of a key by 1. It's atomic, meaning even if multiple clients try to increment the same key at once, Redis ensures each operation is completed one after another, avoiding conflicts.
- If the key doesn't exist, Redis creates it and sets its value to 1.
- If the key exists and holds a string that can be interpreted as an integer, Redis increments it.
- If the stored value isn't a valid integer, Redis returns an error.
Example:
> SET counter 10 OK > INCR counter (integer) 11
This is commonly used for things like tracking page views, login counts, or API rate limiting.
Using DECR
to Atomically Decrement a Value
Just like INCR
, the DECR
command decreases the value of a key by 1 in a thread-safe way.
- If the key doesn't exist, Redis creates it and sets its value to -1.
- If the key contains a valid integer, Redis declines it.
- As with
INCR
, invalid data types will cause Redis to return an error.
Example:
> SET counter 10 OK > DECR counter (integer) 9
A common use case might be managing inventory levels or handling token balances where real-time accuracy matters.
Handling Edge Cases and Data Types
Both INCR
and DECR
work only with string keys that represent integers. You'll run into issues if you try to use them on other data types like lists or hashes.
If you're not sure what kind of data is stored under a key, check it first using GET
or wrap your logic in code that handles type errors gracefully.
Here are some gotchas:
- Redis strings have a size limit of 512MB, but when used as integers, they must fit within 64-bit signed integer ranges.
- Always validate input before passing it to
INCR
orDECR
from user input or external sources.
When to Use These Commands in Real Applications
These commands shine in scenarios where concurrency matters — for example:
- Rate limiting (eg, track how many times a user hits an API endpoint)
- Counting events (like likes, comments, or page visits)
- Managing shared counters across distributed systems
They eliminate the need for locking mechanisms because Redis handles synchronization internally.
You can also combine these commands with Redis' expiration system ( EXPIRE
) for temporary counters that reset automatically after a time window.
Basically that's it. Redis's INCR
and DECR
commands are simple but practical, and can save a lot of trouble in concurrent processing if used well.
The above is the detailed content of How to perform atomic increment and decrement operations using INCR and DECR?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Thread safety can be guaranteed by using atomic operations in C++, using std::atomic template class and std::atomic_flag class to represent atomic types and Boolean types respectively. Atomic operations are performed through functions such as std::atomic_init(), std::atomic_load(), and std::atomic_store(). In the actual case, atomic operations are used to implement thread-safe counters to ensure thread safety when multiple threads access concurrently, and finally output the correct counter value.

MySQL is a popular relational database management system (RDBMS) used to manage various types of data. In the database, an atomic operation refers to an operation that cannot be interrupted during execution. These operations are either all executed successfully or all fail, and only part of the operation is not executed. This is ACID (atomicity, consistency). , isolation, persistence) principle. In MySQL, you can use the following methods to implement atomic operations on the database. Transactions in MySQL

How to solve the cache consistency problem in C++ development In C++ development, the cache consistency problem is a common and important challenge. When threads in a multithreaded program execute on different processors, each processor has its own cache, and there may be data inconsistencies between these caches. This data inconsistency can lead to unexpected errors and undefined behavior of the program. Therefore, solving the cache consistency problem in C++ development is very critical. In C++, there are multiple ways to solve the cache coherency problem

In some of our previous articles related to the sync package, we should have also discovered that atomic operations are used in many places. Today let’s take an in-depth look at the principles, usage scenarios, usage, etc. of atomic operations in go.

When writing multi-threaded applications, it is very important to consider thread safety. Ensuring thread safety, enabling multiple threads to work together, and improving program running efficiency is an issue worthy of full consideration. Java provides many atomic operation functions, including the atomic integer operation function - AtomicInteger. AtomicInteger is an atomic class in Java that can implement atomic operations on an integer variable. The so-called atomic operation means that there can only be

Atomic operations ensure data consistency when multiple threads access shared variables concurrently, by executing a series of operations atomically. For example, the AtomicInteger class in Java provides atomic operations, allowing counters to be updated atomically, ensuring that counter values ??are always correct and consistent, thereby simplifying code and improving performance. However, atomic operations are not omnipotent. For complex concurrency scenarios, locks or other synchronization mechanisms still need to be used, and they are only applicable to basic data types. It is recommended to use concurrent collection classes for reference types.

Atomic operations are critical for managing shared memory in a multi-threaded environment, ensuring that accesses to memory are independent of each other. The C++ standard library provides atomic types, such as std::atomic_int, and member functions such as load() and store() for performing atomic operations. These operations are either performed in full or not at all, preventing data corruption caused by concurrent access. Practical cases such as lock-free queues demonstrate the practical application of atomic operations. Use fetch_add() to atomically update the head and tail pointers of the queue to ensure the atomicity and consistency of queue operations.

In computer science, concurrent programming is when a program can perform multiple tasks simultaneously. It is often used to fully utilize the computing power of multi-core processors and plays an important role in areas such as user interface, network communication, and database operations. However, concurrent programming also brings some challenges, the most important of which is how to ensure data consistency and program correctness when multiple threads access shared resources simultaneously. Java provides rich thread synchronization and mutual exclusion mechanisms to help developers solve challenges in concurrent programming. These mechanisms mainly include locks, atomic operations and the volatile keyword. Locks are used to protect shared resources. They allow one thread to monopolize a shared resource when accessing it, preventing other threads from accessing it at the same time, thus avoiding data inconsistency and program crashes.
