DEV Community

Abhishek
Abhishek Subscriber

Posted on

Redis is fast, not loyal: why it should never be your main DB

Title Image Thumbnail

So so so... you're going through Redis.

POV: You googled it or chatgpted it, AND wired Redis up. You run a read. It comes back before your finger even leaves the Enter key. You run a write. Done. Instant. No waiting, no spinner, nothing. (Must be the wind lol..)

import redis from 'ioredis'

const redis = new Redis(process.env.REDIS_URL || "redis://localhost:6379")

// redis.set redis.get redis.getTTL blah blah blah operations...
Enter fullscreen mode Exit fullscreen mode

And then your super intelligence reached to nirvana and think like -

"Wait. This thing is insanely fast. Why am I still dragging Postgres around like a heavy backpack? Why not just put everything in Redis and call it a day?"

Like bruh seriously?? I had that exact thought. A lot of people do. It feels like you found a cheat code.

So let me walk you through why that cheat code gets you killed in the next level, in plain language, no textbook voice.

Why Redis feels like it broke the laws of physics

Redis keeps your data in memory. Just RAM. It does not run to the hard disk and back for every little thing the way a normal database does. That round trip to disk is the slow part of most databases, and Redis simply skips it.

Will Smith Meme

Talking to it is almost too simple:

SET user:42 "Abhishek"
GET user:42
Enter fullscreen mode Exit fullscreen mode

You hand it a key, it hands you the value. No tables. No joins. No query planner sitting in the corner judging your life decisions. Just key in, value out.

That speed is real and that simplicity is lovely. But hold that exact simplicity in your mind, because it is also the trapdoor you are about to fall through.

Redis is the funny guy at 2AM: here is what actually goes wrong

People expect one boring reason. There are four, and each one bites in a different spot.

1. RAM is the rich, picky friend who needs a hotel suite

Your data lives in memory. Sounds great until you remember memory is the most expensive room in the whole house.

Anushka Sharma meme

A cheap disk holds a terabyte and nobody blinks. A terabyte of RAM is a fat server and a fatter invoice. So the day your data grows past what fits in memory, you hit a wall. Two choices. Pay a painful amount of money, or start throwing data out to make space.

A primary database is supposed to grow quietly for years without you thinking about it. Redis wants the whole dataset to fit in RAM today, comfortably, with legroom. Those two wishes do not get along, and your wallet is the one that suffers.

2. It can ghost you with your data (🚩)

This is the scary one. Read it twice.

Because Redis lives in memory, a crash or a restart wipes that memory clean. Redis does try to save copies to disk, but not on every single write. It either snapshots every few seconds, or appends writes to a file with a tiny delay.

Now play this out. A customer pays you. Redis says "got it, all good." One second later the server trips and dies. That payment can just vanish, because it was sitting in memory and had not been written to disk yet.

Think about that. The user has the money leaving their account, and your system has no memory of it ever happening. That is not a bug you debug at 2 in the morning. That is a refund email and a very awkward apology.

A real database refuses to play this game. When it tells you something is saved, it is saved, full stop. That promise is the entire reason databases exist. Redis trades a slice of that promise for speed, which is a brilliant deal for a cache and a terrifying one for your source of truth.

3. You can only find things if you already know where they are

Picture Redis as a giant wall of labeled drawers. Know the label, and the drawer flies open instantly. Do not know the label, and you are standing there sweating.

Here are questions your app asks every single day:

  • show me everyone who signed up last week
  • find every unpaid order above 500
  • how many users come from each city

In SQL, that last one is basically a single breath:

SELECT city, COUNT(*) FROM users GROUP BY city;
Enter fullscreen mode Exit fullscreen mode

In Redis there is no clean way to ask that. There is no "search by city" button unless you personally built that index by hand and kept it perfectly updated on every write, forever. Forget one update and your data quietly lies to you, and you will not notice until a customer does.

So you end up rebuilding half of what a database already gives you for free, just to ask the most basic questions about your own data. That is a lot of homework to volunteer for.

4. It has no idea your data is connected

Most apps are a web of relationships. A user has orders. An order has items. An item belongs to a product. Pull one thread and the others should follow.

A relational database understands these links and guards them. It will not let you create an order pointing to a user who does not exist. It keeps the story straight on its own.

Redis does not care even a little. To Redis it is all just keys and values sitting next to each other like strangers in an elevator. Keeping every connection correct becomes your job, in your code, forever, with no safety net. One bad deploy and you have got orders floating in space attached to nobody.

So where do you actually let Redis cook?

Enough theory. Here is where Redis earns its paycheck, with the code to match. Nothing fancy, just the patterns you will reach for again and again.

Let him cook meme

Caching (the famous one). Check Redis first. If it is there, great, you skip the slow database. If not, go ask the real database, then stash the answer for next time.

async function getUser(id) {
  const cached = await redis.get(`user:${id}`)
  if (cached) return JSON.parse(cached)        // fast path, straight from memory

  const user = await db.users.findById(id)     // slow path, hit the real DB
  await redis.set(`user:${id}`, JSON.stringify(user), "EX", 3600) // keep it for 1 hour
  return user
}
Enter fullscreen mode Exit fullscreen mode

That EX 3600 is the magic. It tells Redis to forget this on its own after an hour, so you never have to clean up.

Sessions and login tokens. Same idea, except expiry is the whole point. The token should die by itself when the session ends.

// when the user logs in
await redis.set(`session:${token}`, userId, "EX", 60 * 60 * 24) // gone in 24h, no cron job needed
Enter fullscreen mode Exit fullscreen mode

Rate limiting. Stop one angry user from hammering your API. Count their hits, and start a timer the first time you see them.

const hits = await redis.incr(`rate:${userIp}`)
if (hits === 1) await redis.expire(`rate:${userIp}`, 60) // open a 60 second window
if (hits > 100) throw new Error("Slow down buddy, too many requests")
Enter fullscreen mode Exit fullscreen mode

This is the kind of thing Redis does in microseconds without breaking a sweat, while doing it in a normal database on every request would set your server on fire.

Leaderboards and live counts. Redis has a special list that stays sorted by score for you. Perfect for "top players" or "trending now".

await redis.zadd("leaderboard", 1500, "player:42")             // add or update a score
const top10 = await redis.zrevrange("leaderboard", 0, 9)       // grab the top 10 instantly
Enter fullscreen mode Exit fullscreen mode

Notice the theme across all four. None of these is your source of truth. If Redis lost every bit of this tomorrow, your app would hiccup for a second and recover. That is exactly the kind of data Redis was born to hold.

The whole thing in one breath

Redis is fast because it skips the slow, boring, careful work.

A primary database exists to do exactly that slow, boring, careful work, because that is what keeps your data safe, findable, and honest.

So let Redis do speed. Let a real database do truth. Stand them side by side and you get both, instead of betting your business on one of them pretending to be the other.

Asking Redis to be your only database is like asking a race car to be your moving truck. Sure, it is fast. No, it is not getting your entire life across town without scattering half your furniture across the highway.

Use the race car to race. Use the truck to move. Stop expecting a cruiser bike to climb Himalayas.

Last but not the least if you enjoy my content, don't forget to leave a like & follow 𝕏 @0bhishek .✦ ݁˖
See you in next one (ΛΆΛƒ α΅• Λ‚ΛΆ)

Top comments (0)