Redis Strings Tutorial | SET, GET, INCR Commands
# CHAPTER 4
Redis Strings and Basic Operations
1. Introduction
Welcome to the terminal. It is time to start caching data. The most foundational, essential building block of Redis is the String. Despite the name, a Redis String can hold text, serialized JSON, binary files, or integers. If you only ever learn how to use Redis Strings, you can still architect incredibly powerful caching layers. In this chapter, we will master the basic CLI commands required to insert, read, and manipulate string data.2. Learning Objectives
By the end of this chapter, you will be able to:-
Connect to the
redis-cli.
-
Execute the
SETandGETcommands.
-
Check if a key exists using
EXISTS.
-
Delete keys using
DEL.
-
Perform atomic integer math using
INCRandDECR.
3. The Holy Grail: SET and GET
The entire Key-Value paradigm is built on these two words. Open your terminal and typeredis-cli.
To insert data, use SET:
*(Redis responds: OK)*
To retrieve data, use GET:
*(Redis responds: "alice_smith")*
If you try to GET a key that hasn't been created yet, Redis returns (nil). (Nil is the Redis equivalent of Null).
4. Overwriting and Appending
What happens if you runSET on a key that already exists?
It instantly overwrites the old data. GET username will now return "bob_jones".
What if you want to add to the end of a string without destroying the original? Use APPEND:
*(Redis responds: "Hello World!")*
5. Managing Keys (EXISTS and DEL)
Before your application tries to fetch a massive block of data, it is good practice to check if the key even exists in RAM.*(Redis responds with an integer: 1 if it exists, 0 if it does not).*
To remove data from RAM and free up memory, use the Delete command:
*(Redis responds: 1 to confirm it deleted one key).*
6. Atomic Counters (INCR and DECR)
This is where Strings become magical. If a String contains a number, Redis can perform math on it natively.*(Redis responds: "101").*
To decrease a number, use DECR:
*(Redis responds: "100").*
To add a specific amount (like 50 points), use INCRBY:
7. Why INCR is "Atomic" (Real-World Use Case)
Imagine 10,000 users visit your website at the exact same millisecond. If you use MySQL to track page views, 10,000 users will runSELECT views, see the number 100, add 1, and run UPDATE views SET views = 101. The final total will be 101, which is mathematically disastrous. 10,000 hits were lost due to a "Race Condition."
INCR is an Atomic Operation. Because Redis is single-threaded, if 10,000 users trigger the INCR command at the same time, Redis queues them up in a single file line and executes them perfectly one-by-one in microseconds. The final result will be a mathematically perfect 10,100.
8. Mini Project: The Live Counter
Let's build the logic for a "Likes" button on a social media app.-
1.
redis-cli
- 2. Initialize the post's like count:
SET post:5499:likes 0
- 3. Three users click "Like" simultaneously:
INCR post:5499:likes
INCR post:5499:likes
INCR post:5499:likes
- 4. Fetch the final score to display on the frontend:
GET post:5499:likes *(Returns 3)*.
9. Common Mistakes
-
Spacing in values: If you type
SET mykey Hello World, Redis will throw a syntax error. Because there is a space, Redis thinks "World" is a separate command parameter. If your value contains spaces, you MUST wrap it in double quotes:SET mykey "Hello World".
10. Best Practices
-
MSET and MGET: If you need to set or get 5 keys at the same time, do not run
SET5 separate times. This creates "Network Latency" (the time it takes data to travel from the app to the database). UseMSET(Multiple Set) andMGETto do it all in one single round-trip connection.
MSET user1 "Alice" user2 "Bob"
MGET user1 user2
11. Exercises
- 1. What command do you use to retrieve the value associated with a specific key?
-
2.
If the key
scorecurrently holds the value"10", what command will instantly change the value to"15"using mathematical addition?
12. Redis Challenges
You run the commandINCR activeusers. However, you forgot to create the activeusers key first with the SET command. What will Redis do? Will it crash?
*(Answer: It will not crash. In Redis, if you call INCR on a key that does not exist, Redis is smart enough to assume the starting value is 0. It will automatically create the key and instantly increment it to 1).*
13. MCQ Quiz with Answers
A web application tracks product inventory using Redis. 50 users attempt to buy the last remaining laptop at the exact same millisecond. Why is utilizing the Redis DECR command mathematically safer than pulling the inventory count into the backend application, subtracting 1, and saving it back?
When utilizing the redis-cli, what is the correct syntax to store a string containing spaces?
14. Interview Questions
-
Q: Define an "Atomic Operation" in the context of Redis. Why is the
INCRcommand heavily favored by system architects for implementing rate-limiters and global counters?
-
Q: Explain the purpose of the
MGETcommand. How does fetching multiple keys simultaneously improve application performance compared to executingGETmultiple times?
15. FAQs
Q: Can I store a massive PDF file in a Redis String? A: Technically, yes. A Redis String can hold up to 512MB of binary data. However, storing large files in RAM is an incredibly expensive waste of server resources. Files should be stored on AWS S3, and you should only store the *URL link* to the file in Redis.16. Summary
You are now manipulating data in memory. By masteringSET, GET, and the atomic power of INCR, you possess the foundational skills required to build blazing-fast caching layers, API rate-limiters, and high-concurrency tracking systems.