Redis atomic writes
Concurrency bugs are usually invisible until they become expensive.
One of the most practical lessons I learned is simple: whenever a key should be set once, or a lock key should be acquired by only one worker, use Redis NX.
Without NX, concurrent workers can overwrite each other and create write skew. The system still “works,” but state becomes inconsistent in subtle ways.
The Rule I Follow Now
If the operation is “first writer wins” or “acquire lock if free,” I treat NX as mandatory. I also pair lock keys with expiration so stale locks do not live forever after process crashes.
For set-once records, same principle: use NX so only the first write succeeds. No NX, no guarantee.
What I Considered (Briefly)
I considered plain SET, database constraints and transactions, and full distributed lock algorithms. Plain SET is unsafe under concurrency because last-writer-wins is not the behavior we want. Database constraints can give strong correctness, but they are sometimes heavier than needed for simple cross-worker coordination. Full lock algorithms are useful for complex critical sections, but often overkill for short set-once or lock-if-free cases. For many practical cases, Redis SET with nx: true is the smallest safe step.
Important Caveat About Locks
Using NX for locking is reliable only when you have a single-node Redis instance.
With replication, writes are propagated asynchronously. A primary can accept a lock write, fail before replication catches up, and then a replica can be promoted without that lock key. At that point, another worker can acquire what looks like a free lock, and you can end up with two workers in the same critical section.
So for strict distributed lock correctness, another alternatives like Redlock might be more appropriate—although there’s still criticism against Redlock
Conclusion
I now treat NX as a default in concurrency-sensitive Redis writes (e.g, locks).
It is a tiny option with a big impact: fewer race conditions, fewer hidden state issues, and behavior that matches intent.