← Lessons

quiz vs the machine

Silver1080

Databases

Redis Strings and Counters

The simplest type doubles as an atomic counter.

4 min read · intro · beat Silver to climb

The Workhorse Type

The string is the most basic Redis value. It holds text, serialized JSON, or raw binary up to 512 MB. You set and read it with SET and GET, and you can attach an expiry so the key disappears automatically.

Strings shine as caches: store a rendered page or a database row under a key, set a time to live, and serve future reads from memory.

Atomic Counters

When a string holds a number, Redis can change it atomically:

  • INCR adds one and returns the new value.
  • INCRBY adds an arbitrary amount.
  • DECR subtracts one.

Because the increment happens on the server in a single step, two clients incrementing the same key never lose an update. This makes strings perfect for page view counts, IDs, and metrics without locks.

Useful Extras

  • SETNX sets a key only if it does not exist, the basis of simple locks.
  • SETEX sets a value with an expiry in one command.
  • APPEND grows a string in place.

A counter that must reset daily is just a key whose name includes the date, given a one day expiry.

Key idea

Redis strings store bytes and, when numeric, support atomic INCR and DECR, giving lock free counters and easy expiring caches.

Check yourself

Answer to earn rating on the learn ladder.

1. Why can two clients safely INCR the same key at once?

2. What does SETNX do?