🔢
Lesson 2 of 4 · Atomic Counters
Counting without race conditions
Redis makes counting atomic — correct under any load, no locks needed.
🔴 The problem with normal databases

Imagine 50,000 users click "Like" at the exact same moment. A normal counter works like this: read the current count → add 1write it back.

Under heavy traffic, two requests can read the same value before either writes back. Both write "count + 1" — and one like is silently lost. This is called a race condition.

4
times this page has been loaded — every single one counted correctly
💻 What Redis did when you loaded this page
redis> INCR demo:counter:visits
→ 4 ← the new value, returned atomically
INCR is one single operation, not three steps.
Redis guarantees no two calls get the same value — ever.
Run this 1 million times concurrently → every number 1–1,000,000 appears exactly once.
🧪 Try it: adjust stock level

This shows INCRBY and DECRBY — same atomic guarantee, different amounts.

Stock 100 / 100 units
redis> DECRBY demo:counter:stock 10
→ 90 ← new value after selling 10
redis> INCRBY demo:counter:stock 25
→ 125 ← new value after restocking 25
💡 The key insight — atomicity

INCR is a single CPU instruction inside Redis — not "read, then add, then write." That's what atomic means: it cannot be interrupted mid-way. No matter how many concurrent requests hit Redis, each gets a unique, correct count.

🌍 Where you've seen this

YouTube view counts, Instagram likes, Stripe API usage meters, Steam concurrent player counts. Any number that goes up (or down) under heavy traffic is a candidate for Redis counters.