Strings and counters

Redis · Essentials · 8 min

Strings are the most used type: cached values, flags, tokens and counters.

A Redis string is a binary-safe value up to 512 MB: text, a serialized JSON document, an image, or a number. SET key value writes it, GET key reads it, and MGET/MSET handle several keys in one round trip.

SET has options that make it far more than an assignment:

  • EX 60 or PX 60000 sets an expiry in seconds or milliseconds,
  • NX only sets if the key does not exist, XX only if it does,
  • GET returns the old value while setting the new one.

SET lock:report token NX EX 30 is the building block of simple locks and idempotency keys: exactly one client succeeds.

If a string holds an integer, INCR, INCRBY, DECR and INCRBYFLOAT change it atomically and return the new value; a missing key counts as 0. This makes counters (page views, rate limits, id generators) trivial and race-free. APPEND, STRLEN, GETRANGE and SETRANGE work on raw bytes.

Storing objects as serialized JSON strings is fine when you always read and write the whole object. When you need to update individual fields, a hash (next lesson) or the JSON data type is a better fit.

Example

redis-cli SET page:home:views 0          # OK
redis-cli INCR page:home:views           # (integer) 1
redis-cli INCRBY page:home:views 10      # (integer) 11
redis-cli SET session:abc '{"user":42}' EX 3600   # OK
redis-cli TTL session:abc                # (integer) 3600
redis-cli SET lock:job1 worker-a NX EX 30   # OK
redis-cli SET lock:job1 worker-b NX EX 30   # (nil)  already held
redis-cli MGET page:home:views lock:job1    # 1) "11"  2) "worker-a"
redis-cli INCR session:abc
# (error) ERR value is not an integer or out of range

Remember

  • Strings hold any bytes up to 512 MB
  • SET supports EX/PX expiry and NX/XX conditions
  • INCR and friends are atomic counters; missing keys start at 0
  • MGET/MSET batch several keys in one round trip

Watch out for

  • Doing GET, adding 1 in the app and SET-ing back instead of INCR, which loses updates under concurrency.

Check yourself

  1. What does SET k v NX return when k already exists?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: redis.io/docs/latest/develop/data-types/strings/