Redis 💾 and How Caching Makes Things Super Fast! 🚀

Redis 💾 and How Caching Makes Things Super Fast! 🚀

Introduction to Redis

Redis is a key-value pair database that stores data in memory. Because the data is stored in memory, it's great for caching things.


Understanding Caching

What is a cache, you ask?
It's usually frequently used data that is stored for faster retrieval.

For example, imagine you are a librarian, and you notice that people are frequently borrowing one particular book. Instead of going all the way to the back to get the book every time, you keep some copies near you—let's say 5. So whenever someone walks in and asks for that book, you give it to them.

This saves you energy and saves the customer time since it’s much faster. This is what caching is.


Storage and Expiry in Caching

But notice a few things here:

  1. Storage: You need some storage to keep the recently used books near you.

  2. Restocking: You brought, say, 5 copies of the book near your table. After 5 people have borrowed the book, you’ll need to restock.

These are important to understand.

Redis acts as the storage for cached data. It stores data as:

  • Key: "Name"

  • Value: "John"

This is called a key-value pair.

Now, just like the books, when all 5 are borrowed, you need to replenish your stock. In caching terms, this concept is called “expiry” or “Time to Live (TTL)”.


Practical Example of Caching

Let’s see an example:

Imagine a particular meme is going viral in a region on Instagram. Instagram would want to cache it (since many people are viewing it, similar to the librarian example).

But as the meme's virality decreases after a few weeks, it doesn’t make sense to keep it in the cache forever.

Here’s how we can handle this:

  1. Keep only the top 5 viral memes in the cache.

  2. Set an expiration time for the meme.


Let’s See How It’s Done in Redis

Now, shall we? 🚀


Installation

You can install Redis from the following link:
https://github.com/microsoftarchive/redis/releases

While installing, make sure to check the “Add to PATH” checkbox to make Redis commands accessible globally from the command line.

After installation, open Command Prompt (CMD) and run the following command:

redis-cli

This will open the Redis Command Line Interface (CLI), where you can interact with Redis.


Adding Books to the Library

Adding a Single Book

To add a book to the library, use the SET command:

SET BOOK "Harry Potter"

To retrieve the book:

GET BOOK

Output:
"Harry Potter"


Adding a List of Books

To add multiple books, you can use the LPUSH command, which adds items to the left (the front of the list):

LPUSH BOOKS "Harry Potter Part 1"
LPUSH BOOKS "Harry Potter Part 2"

To view the list of books:

LRANGE BOOKS 0 -1

Output:

1) "Harry Potter Part 2"
2) "Harry Potter Part 1"

Adding a Book to the End of the List

If you want to add books to the end of the list (from the right), you should use the RPUSH command. But first, if needed, you can remove items from the front of the list using the LPOP command.

Example:

  1. Remove the first book from the list:

     LPOP BOOKS
    
  2. Add a new book to the end of the list:

     RPUSH BOOKS "Harry Potter Part 2"
    
  3. View the updated list:

     LRANGE BOOKS 0 -1
    

    Output:

     1) "Harry Potter Part 1"
     2) "Harry Potter Part 2"
    

Implementing Redis in a Real-World Python Server

Here’s a simple Python example using FastAPI and Redis to demonstrate the basic concept of getting books from Redis:

Code with Explanations

from fastapi import FastAPI
import redis

# Initialize FastAPI app
app = FastAPI()

# Connect to Redis (Make sure Redis is running locally)
redis_client = redis.StrictRedis(
    host="localhost",       # Redis is running on your computer (localhost)
    port=6379,              # Default port for Redis
    decode_responses=True   # Ensures Redis returns data in a human-readable format (like strings)
)

# Pre-load some books into Redis for demonstration
redis_client.set("book:1", "Harry Potter and the Sorcerer's Stone")
redis_client.set("book:2", "The Hobbit")
redis_client.set("book:3", "1984")

@app.get("/books/{book_id}")
async def get_book(book_id: int):
    """
    Fetch a book by its ID from Redis.
    """
    book = redis_client.get(f"book:{book_id}")
    if book:
        return {"book_id": book_id, "title": book}
    return {"error": "Book not found"}

Why is the port 6379?

Imagine Redis is like a house. For your computer to knock on the right door and talk to Redis, it needs a specific address.

Redis's address is localhost (your computer), and its default door (or port) is 6379.

But why 6379?
It’s a fun choice by the Redis creators. If you type MERZ (a word that refers to the creator's online alias) on a phone keypad, it translates to 6379! Cool, right?

So, whenever you use Redis, unless you change the door number (port), it will always listen at 6379.


Why decode_responses=True?

Redis stores data in its own format, which can sometimes look like numbers or random characters.

For example:
If Redis sends you "b'Harry Potter'", it means the data is in byte format, which is how computers talk internally.

When we set decode_responses=True, Redis automatically converts this to something humans can read, like "Harry Potter". It’s like asking someone to speak to you in plain English instead of a secret code!


How It Works

  1. Redis Setup: Redis is connected locally on localhost at port 6379. Make sure Redis is installed and running.

  2. Preloaded Data: Three books (book:1, book:2, and book:3) are stored in Redis using the set command.

  3. Endpoint:

    • GET /books/{book_id}: Fetches the title of a book by its book_id.

    • If the book exists in Redis, it returns the title.

    • If not, it returns an error message.


Example Usage

Run the code and test the endpoint:

  1. Start the FastAPI server:

     uvicorn filename:app --reload
    
  2. Test the endpoint in your browser or with a tool like curl/Postman:

    • Request:

        GET http://127.0.0.1:8000/books/1
      
    • Response:

        {
            "book_id": 1,
            "title": "Harry Potter and the Sorcerer's Stone"
        }
      
    • Request (non-existent book):

        GET http://127.0.0.1:8000/books/99
      
    • Response:

        {
            "error": "Book not found"
        }
      
Â