Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 42 ยท Core Data Types

Strings and Counters

Learn Redis strings: SET options (NX, XX, EX, GET), APPEND, GETRANGE, atomic INCR counters, MSET and MGET, binary safety and size limits, with live examples.

The string is the simplest and most used Redis type. A key holds one value, and that value is a sequence of bytes: text, a number, a JSON document, a serialized object or even a small image. You will use strings for caches, flags, locks, tokens and counters long before you need anything fancier, and several other types are built on the same ideas.

This lesson covers the everyday commands, the options of SET that replace older commands, atomic counters, and the limits to remember. Real Redis syntax appears in read-only blocks. The runnable examples use the JavaScript MiniRedis emulator introduced in What Is Redis?, extended with the string commands and a fake clock so expiry is deterministic. It models the command semantics, not the network or real performance.

SET and GET

SET key value stores a value, replacing whatever was there, even if the old value had a different type. GET key returns it, or nil if the key does not exist.

TEXT
127.0.0.1:6379> SET site "tutorials"
OK
127.0.0.1:6379> GET site
"tutorials"
127.0.0.1:6379> SET site "docs"
OK
127.0.0.1:6379> GET site
"docs"

A plain SET also removes any expiry the key had. That surprises people the first time, and there is an option to keep it (below). Commands that only modify a value in place, such as APPEND and INCR, leave the expiry untouched.

SET options

Instead of many separate commands, modern Redis puts options on SET:

Option Meaning
NX Only set if the key does not exist.
XX Only set if the key does exist.
EX seconds / PX milliseconds Set a time to live.
EXAT / PXAT Expire at an absolute Unix timestamp.
KEEPTTL Keep the existing expiry instead of clearing it.
GET Return the old value (or nil) while setting the new one.

Without GET, SET replies OK when it wrote the value, or nil when an NX or XX condition prevented it. With GET it replies with the old value either way. The older commands SETNX, SETEX, PSETEX and GETSET still work, but SET covers all of them.

SET does it all

NX Only if the key is missing.
XX Only if the key already exists.
EX / PX Expire after seconds or milliseconds.
GET Hand back the old value.

Combine them, such as SET lock id NX EX 30.

1 / 2

SET key value NX EX 30 is the building block of simple locks: one command checks that nobody holds the lock and writes the owner with an expiry, so two clients can never both win. Queues, locks and leaderboards builds on it.

Try it: SET options, MSET and wrong types

The emulator keeps a fake clock in milliseconds. Setting redis.now forward is how this lesson "waits" for a lock to expire without sleeping. The script also shows that one command can store or read many keys at once, and that using a string command on another type fails with WRONGTYPE.

JS SET options with a fake clock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output from top to bottom. The second SET lock with NX returns (nil), so only the first caller owns the lock. After the clock jumps 31 seconds, the key is gone and TTL returns -2. MSET writes all pairs in one atomic step, and MGET returns one answer per key in order, using nil for a missing key. Sending many keys in one command saves network round trips, which matters far more than CPU for most applications (see pipelining).

Working with text: APPEND, STRLEN, GETRANGE

Because values are byte strings, Redis has commands to treat them as text without fetching them.

  • APPEND key suffix adds to the end (creating the key if needed) and returns the new length.
  • STRLEN key returns the length in bytes.
  • GETRANGE key start end returns a slice. Both ends are inclusive, and negative numbers count from the end, so -1 is the last byte.
  • SETRANGE key offset value overwrites part of the string, padding with zero bytes if the offset is beyond the end.
TEXT
127.0.0.1:6379> APPEND log "boot;"
(integer) 5
127.0.0.1:6379> APPEND log "ready;"
(integer) 11
127.0.0.1:6379> GETRANGE log 0 3
"boot"
127.0.0.1:6379> GETRANGE log -6 -2
"ready"

APPEND is a cheap way to build a small log or buffer on the server, but a string that grows without limit becomes a very large single value, so cap it or use a list or stream instead.

Atomic counters

If a string holds a number written in base 10, you can change it with the counter commands. They read the value, add to it and store the result in one atomic step:

Command Effect
INCR key / DECR key Add or subtract 1.
INCRBY key n / DECRBY key n Add or subtract n.
INCRBYFLOAT key x Add a decimal number.

A missing key counts as 0, so the first INCR returns 1. Each command returns the new value, which is what you want: it tells you your own count without a second read. Integer commands work on 64-bit signed integers, and going past the range returns an error instead of wrapping around. A value that is not a valid integer (text, spaces, 1.5) also returns an error.

Because commands run one at a time, a thousand clients calling INCR page:views at once always produce exactly one thousand increments. Do not replace this with GET plus SET in your application: two clients can read the same number and one update is lost. That is the core mistake What Is Redis? demonstrated.

Try it: text commands and counters

JS Counters, text slices and errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A few lines deserve attention. GETRANGE log 100 200 returns an empty string, not an error, because out-of-range slices are clamped. STRLEN word is 6, not 5: the letter รฉ takes two bytes in UTF-8, and Redis measures bytes, not characters (the emulator measures bytes here on purpose, although its slicing commands use plain characters, so keep slicing examples to ASCII). The counter that reached the 64-bit maximum refuses to go further, and the key is left unchanged.

Binary safety, encodings and limits

Redis strings are binary safe: they are length-prefixed byte arrays, not C strings, so a value may contain any byte, including zero and \r\n. A string can hold up to 512 MB, and so can a key name, though keys should stay short. Redis does not interpret your bytes, which means you choose the text encoding and any serialization format (JSON, MessagePack, Protobuf) in your application.

Redis chooses an internal representation for you. Numbers that fit in a 64-bit integer are stored compactly as integers, short strings use a compact layout, and larger ones a plain buffer. You rarely need to think about this, but it explains why small values are very cheap. OBJECT ENCODING key shows the choice, and Memory limits and eviction covers memory in depth.

A value can be 512 MB, but you should not do that. Every command reads or writes the whole value, a huge string blocks other clients while it moves, and replication and persistence copy it as well. Keep values small (kilobytes, not megabytes) and split large payloads into chunks or store them elsewhere.

Common patterns and mistakes

  • Cache entries: SET cache:product:7 "<json>" EX 300 stores a serialized value for five minutes.
  • Flags and tokens: short strings with an expiry, such as email verification codes.
  • Counters and IDs: INCR generates unique, ever-increasing IDs without a lock.
  • Mistake: forgetting that SET clears the TTL. Use KEEPTTL or reset the expiry yourself when you overwrite a value that should still expire.
  • Mistake: read-modify-write. If one command (INCR, APPEND, SETRANGE) does the job, use it.
  • Mistake: counting with floats in strings you also read with INCR. Pick one numeric style per key.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does SET lock owner-2 NX EX 30 reply with if the key lock already exists?

    NX means set only if the key does not exist. When the condition fails, SET replies nil and leaves the existing value alone.
  2. 2. Which command safely produces unique, increasing IDs from many clients at once?

    INCR reads, adds and writes in one atomic step and returns the new value, so no two clients receive the same number.
  3. 3. What does GETRANGE greeting 0 3 return for the value hello world?

    GETRANGE end positions are inclusive, so indexes 0 through 3 give four bytes: hell.
  4. 4. What happens to a key's expiry when you run a plain SET on it?

    SET replaces the value and clears the time to live. KEEPTTL preserves it; INCR and APPEND never touch it.
  5. 5. What is the maximum size of a Redis string value?

    A string may be up to 512 MB, but values that big hurt latency, replication and memory. Keep values small.

Summary

  • A Redis string is a binary-safe byte sequence up to 512 MB, used for caches, flags, tokens and counters.
  • SET takes options (NX, XX, EX, PX, KEEPTTL, GET) that replace SETNX, SETEX and GETSET; a plain SET clears the expiry.
  • MSET and MGET handle many keys in one command; string commands on other types fail with WRONGTYPE.
  • APPEND, STRLEN, GETRANGE and SETRANGE work on bytes, and range ends are inclusive.
  • INCR, DECR, INCRBY and INCRBYFLOAT are atomic, create missing keys as 0 and error on non-numbers or 64-bit overflow.

Next, control how long keys live in Keys, Expiry and TTL.