A developer is writing code to increment a hit counter in Redis. Why does the following Python code contain a potential concurrency bug?

Python interview question for Advanced practice.

Answer

Race condition: Concurrent clients can read the same value and overwrite each other's increments. Use INCR.

Explanation

While Redis is single-threaded, the GET and SET are two separate network calls. If two clients GET '10' at the same time, they both calculate '11' and SET '11', losing one increment. The INCR command should be used to make the operation atomic on the server.

Related Questions