🦄 Redis For Dummies

Sponsored by

Hello friends!

Welcome to this week’s Sloth Bytes. I hope you had a fun week!

Typing is a thing of the past

Typeless turns your raw, unfiltered voice into beautifully polished writing - in real time.

It works like magic, feels like cheating, and allows your thoughts to flow more freely than ever before.

With Typeless, you become more creative. More inspired. And more in-tune with your own ideas.

Your voice is your strength. Typeless turns it into a superpower.

Redis For Dummies

Redis is cool. That is all.

What is Redis?

Redis (REmote DIctionary Server) is a shared in-memory, NoSQL key/value store that is used primarily as an application cache or quick-response database.

Why Redis is So BLAZINGLY Fast?

Redis stores data in memory (RAM), rather than on a disk or solid-state drive (SSD)

If it’s a key value structure why can’t I just do this?

my_dic = {}
my_dic["sloth"] = {"name": "hi", "email": "[email protected]"}

Great question!

  • No persistence: Restart your app, you lose all cached data

  • No expiration: Cache grows forever until you run out of memory

  • Not thread-safe: Multiple requests can corrupt your cache

  • No network access: Each process has its own isolated cache

Now you could get past these issues if you program them yourself, but guest what…

You just recreated Redis. 

Good job.

Common Use Cases

import redis
def get_user_profile(user_id):
    # Check cache first
    cached = redis.get(f"user_profile:{user_id}")
    if cached:
        return json.loads(cached)
    
    # Cache miss - query database and cache result
    profile = database.execute(complex_query, user_id)
    redis.setex(f"user_profile:{user_id}", 3600, json.dumps(profile))
    return profile

2. Session Storage

import express from 'express';
import session from 'express-session';
import RedisStore from 'connect-redis';
import { createClient } from 'redis';

const app = express();
const redisClient = createClient(); 
redisClient.connect();

app.use(session({
  store: new (RedisStore(session))({ client: redisClient }),
  secret: 'secret', resave: false, saveUninitialized: false
}));

app.get('/', (req, res) => res.send(`Views: ${++req.session.views || (req.session.views = 1)}`));
app.listen(3000);

3. Real-time Features (Pub/Sub)

# fun little example

import redis
import time
import threading

client = redis.Redis(host='localhost', port=6379, db=0)

def message_handler(message):
    print(f"Received message: {message['data']}")

pubsub = client.pubsub()
# Subscriber - receive instantly
pubsub.subscribe(**{'notifications': message_handler})

def run_pubsub():
    for message in pubsub.listen():
        if message['type'] == 'message':
            message_handler(message)

thread = threading.Thread(target=run_pubsub)
thread.start()

time.sleep(1)
# Publisher - send notifications
publish_result = client.publish('notifications', 'Hello, Redis!')
print(f"Message published, number of subscribers that received the message: {publish_result}")

pubsub.unsubscribe()
thread.join()

4. Rate Limiting

# simple example
def rate_limit(user_id, limit=100):
    key = f"rate_limit:{user_id}"
    current = redis.incr(key)
    if current == 1:
        redis.expire(key, 3600)  # Reset after 1 hour
    return current <= limit

When to Use Redis?

Perfect for:

  • Caching frequently accessed data

  • Session storage for web apps

  • Real-time features (chat, notifications)

  • Rate limiting and counters

  • Leaderboards and rankings

Skip for:

  • Primary data storage (use a real database)

  • Complex queries (SQL is better)

  • Data larger than available RAM

  • Strong consistency requirements

Redis makes slow things fast.

It won't replace your primary database, but it will make your applications dramatically faster.

In a world where users expect instant responses, Redis is often the difference between a snappy app and a slow one.

The performance gain can be addictive.

Once you see a 2-second page load become 200ms, you'll want to use Redis everywhere.

Thanks for the feedback 😁 

Thanks to everyone who submitted!

AspenTheRoyal, NeoScripter, gcavelier, seansjlee, Suji-droid, s4ngyeonpark (private repo sorry!), and RelyingEarth87!

What Gives a Bad Mood?

Let’s say the greatest impact on someone's mood are: weather, meals, and sleep.

Your task is, given an array of sub-arrays of different values for:

[Mood, Weather, Meals, Sleep].

All values except for meals are 1-10 (1 = bad, 10 = good)

Meals are from 1-3

Determine which other variable has had the greatest impact on the mood.

Examples

greatestImpact([
  [1, 1, 3, 10],
  [1, 1, 3, 10],
  [1, 1, 3, 10]
])
output = "Weather"
# Weather was always low but all others were high.

greatestImpact([
  [10, 10, 3, 10],
  [10, 10, 3, 10],
  [10, 10, 3, 10]
])
output = "Nothing"

# Great days! all values were high.

greatestImpact([
  [8, 9, 3, 10],
  [2, 10, 1, 9],
  [1, 9, 1, 8]
])
output = "Meals"

greatestImpact([
  [10, 9, 3, 9],
  [1, 8, 3, 4],
  [10, 9, 2, 8],
  [2, 9, 3, 2]
])
output = "Sleep"

Notes

  • All values except for meals are 1-10 (1 = bad, 10 = good)

  • Meals are from 1-3

How To Submit Answers

Reply with

  • A link to your solution (github, twitter, personal blog, portfolio, replit, etc)

  • or if you’re on the web version leave a comment!

  • If you want to be mentioned here, I’d prefer if you sent a GitHub link or Replit!

That’s all from me!

Have a great week, be safe, make good choices, and have fun coding.

If I made a mistake or you have any questions, feel free to comment below or reply to the email!

See you all next week.

What'd you think of today's email?

Login or Subscribe to participate in polls.

Want to advertise in Sloth Bytes?

If your company is interested in reaching an audience of developers and programming enthusiasts, you may want to advertise with us here.

Reply

or to participate.