Ch 5 · Redis Strings and Numbers · Redis

Topic 5 of 5 in Redis — Complete Tutorial (Beginner) — 4 lessons.

String Operations and Counters

Work with string operations, counters, and atomic increments. Strings are the simplest Redis type, yet they power page-view counters, like buttons and rate limits. Each command runs as one indivisible step, so two users clicking at once cannot lose a count. You will meet INCR and DECR, the batch commands MSET and MGET, and SETNX, which only sets a key that does not exist yet.

String Operations and Counters in Code

The code runs a visitor counter up to 12 using INCR twice and INCRBY once, even though the value is stored as a string. Next, MSET and MGET handle three keys in one round trip. Watch APPEND grow a message and STRLEN measure it, then see SETNX return 1 when it creates a lock key and 0 if the key already exists.

Practice: String Operations and Counters

Put strings and counters to work in three small tasks. You will count page views, store and fetch several profile fields in one go, and create a simple lock that only one process can hold. A correct answer uses clear, namespaced key names and makes sure the lock expires by itself, so a crashed program cannot leave it stuck forever.

Solution & Challenge: String Operations and Counters

Compare your work with the worked solution, which counts home-page views, saves a profile with MSET, and takes a lock using SET with NX and EX so it expires after 30 seconds. The challenge asks you to build a rate limiter that allows a set number of requests per user each minute, using INCR to count and EXPIRE to reset.

All topics in Redis Beginner

  1. Redis Hashes
  2. Redis Introduction and Setup
  3. Redis Lists
  4. Redis Sets
  5. Redis Strings and Numbers