Backend Development 5 min read

Solving Redis Concurrent Key Competition: Distributed Lock with Timestamp and Message Queue Approaches

This article explains why Redis experiences key‑setting race conditions under high concurrency and presents two practical solutions—using a distributed lock with timestamps and serializing writes via a message queue—to ensure correct ordering and data consistency.

Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Solving Redis Concurrent Key Competition: Distributed Lock with Timestamp and Message Queue Approaches

In high‑concurrency scenarios, multiple Redis clients may attempt to set the same key simultaneously, leading to race conditions, cache penetration, and inconsistent data.

The problem arises because Redis operates as a single‑threaded NoSQL store without built‑in locking, so concurrent client operations can overwrite each other.

For example, if several clients write the value 1 to a key and then sequentially update it to 2 , 3 , 4 , the final order may become 4,3,2 instead of the intended 2,3,4 , resulting in an incorrect final value.

Solution 1: Distributed Lock + Timestamp

The overall scheme is to acquire a distributed lock before performing the SET operation, turning parallel reads/writes into serialized ones.

Implementation uses Redis’s SETNX command. For example:

SETNX lock.mikechen<current Unix time + lock timeout + 1>

If the command returns 1 , the client obtains the lock and can set the key; it releases the lock later with DEL lock.mikechen . If it returns 0 , another client holds the lock, so the client may retry or abort.

A timestamp is stored as the lock value; when a client acquires the lock it compares its timestamp with the existing one. If its timestamp is older, it skips the SET to avoid overwriting newer data.

Distributed locks can be built on various systems such as Zookeeper or Redis, but the core idea remains the same: a shared state indicates lock ownership.

Solution 2: Message Queue Serialization

When the request volume is very high, a message‑queue middleware can be used to serialize Redis SET operations. Each write request is placed into a queue and processed one‑by‑one, ensuring ordered execution.

This approach is a generic solution for high‑concurrency environments and works well when combined with other backend components.

Both methods aim to eliminate concurrent key‑setting conflicts and maintain data consistency in Redis‑based systems.

backendConcurrencyRedisMessage QueueDistributed Locktimestamp
Mike Chen's Internet Architecture
Written by

Mike Chen's Internet Architecture

Over ten years of BAT architecture experience, shared generously!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.