APPEND and STRLEN
Wordcraft keeps a tiny text log of each player's recent results: won,won,lost,. Rewriting the whole log after every game means reading it, changing it in the app and sending it all back. Redis can simply add to the end of the string, and measure it, without the value ever leaving the server.
The rule
APPEND grows the string and replies with its length; STRLEN only measures.
APPEND key text adds text to the end of the string at key and replies with the new length in bytes, not with the text. If the key does not exist, APPEND creates it, exactly like SET.
STRLEN key replies with the length of the string in bytes. A missing key has length 0, not (nil).
127.0.0.1:6379> APPEND log:asha "won,"
(integer) 4
127.0.0.1:6379> APPEND log:asha "won,"
(integer) 8
127.0.0.1:6379> APPEND log:asha "lost,"
(integer) 13
127.0.0.1:6379> STRLEN log:asha
(integer) 13
127.0.0.1:6379> GET log:asha
"won,won,lost,"
127.0.0.1:6379> STRLEN log:nobody
(integer) 0Bytes, not letters. Redis strings are byte sequences, so lengths are counted in bytes. Plain English letters are one byte each, but many characters take more in UTF-8: STRLEN of "café" is 5, because é takes two bytes.
Numbers count as text. After SET coins:asha 120, STRLEN coins:asha replies 3, the number of digits, and APPEND coins:asha 0 turns it into "1200". Handy to know, dangerous to do by accident.
Like GET, both commands only work on strings; on a hash or list they reply with a WRONGTYPE error.
The shortcut
Keep a running length: start at the current length (0 if missing), add the byte length of each appended piece, and that sum is every reply.
Start
log:ravidoes not exist, so the length is 0.
Remember to count the commas: they are bytes too, and missing them is the most common slip.
A common use is a compact log or a growing buffer, but keep an eye on size: APPEND never trims, so a string you append to forever keeps growing. If you only need the most recent entries, a list with a length cap (you will meet LTRIM later) is usually a better fit.
Drills
Answer fast — trust the rule.
note does not exist. What does APPEND note "hi" reply?
note holds "hi". What does APPEND note " there" reply?
What does STRLEN missing:key reply?
coins:tom holds "90". After APPEND coins:tom 5, what does INCR coins:tom reply?
Remember
- APPEND grows the string and replies with its length; STRLEN only measures.
- Keep a running length in bytes, and count the commas and spaces.
- Numbers are text to APPEND: appending a digit changes the number.
