What is Redis?

Redis is an in-memory, key-value data store that prioritizes speed above all else. The name stands for REmote DIctionary Server, and it's been the de facto standard for ultra-fast data access since 2009.

Unlike traditional databases (like PostgreSQL) that store data on disk, Redis keeps everything in RAM. This means queries return results in microseconds — thousands of times faster than disk-based systems. The trade-off? Redis can't store terabytes of data, but it's perfect for data you need instantly: cache layers, session storage, leaderboards, and real-time analytics.

Key characteristic: Redis is single-threaded. This means all operations are atomic (they can't be interrupted), making Redis predictable and eliminating complex locking problems.

A Brief History

Redis was created in 2009 by Salvatore Sanfilippo, an Italian programmer who needed a fast data structure store for a web analytics project. He open-sourced it in 2010, and it quickly became the go-to choice for companies needing sub-millisecond response times.

Today, Redis powers systems at:

  • Twitter — Caching tweets and timelines
  • GitHub — Rate limiting and sessions
  • Stripe — Real-time counters and queue management
  • Netflix — Caching recommendations and user data
  • Instagram — Leaderboards and activity feeds

In the 2020s, Redis evolved to support clustering (sharding data across multiple servers), modules, and streams. Today it remains the fastest in-memory database in production use.

Real-World Use Cases

Redis excels in scenarios where speed and freshness matter more than durability. Here are the most common patterns:

Caching Layer

The Problem
Your web app queries PostgreSQL for product details, but DB queries take 100ms. You receive 1 million requests/day.
The Redis Solution
Store popular products in Redis (1ms response). On cache miss, query PostgreSQL and populate Redis. Total latency drops 99x. ShopStream could cache the top 100 products, refreshing them every hour.

Session Storage

The Problem
Users log in. Where do you store their session data? If on disk, they're slower. If in app memory, they lose sessions when servers restart.
The Redis Solution
Store sessions in Redis with a TTL (time-to-live). When a user logs in, create a session key: session:user123 = {name, email, login_time}. The session auto-expires after 1 hour.

Leaderboards & Counters

The Problem
An e-commerce app needs a real-time top-sellers leaderboard. Querying PostgreSQL every 100ms kills performance.
The Redis Solution
Use Redis Sorted Sets. Each product is a member with its sales count as the score. Redis updates in O(log N) time. The top 10 sellers? One command: ZREVRANGE shopstream:sales 0 9.

Rate Limiting

The Problem
Prevent users from spamming your API. Allow 100 requests/minute per IP.
The Redis Solution
Store a counter in Redis: rate:192.168.1.1. Increment on each request. Set TTL to 60 seconds. If counter exceeds 100, reject. This runs in microseconds.

Pub/Sub (Real-Time Messaging)

The Problem
Send notifications to thousands of connected users instantly. HTTP requests are too slow.
The Redis Solution
Publishers post to Redis channels. Subscribers listen and receive messages in real-time (milliseconds). Perfect for live updates, chat, and activity feeds.

Queues & Job Processing

The Problem
Process async tasks (email, image resizing). Need a reliable queue that workers consume from.
The Redis Solution
Use Redis Lists as a queue. Push jobs to the left, pop from the right. Workers process jobs durably, and if a worker crashes, the job stays in Redis.

Redis vs Traditional Databases

Redis and PostgreSQL serve different purposes. Use both:

Aspect Redis PostgreSQL
Storage In-memory (RAM) On-disk (SSD/HDD)
Speed Microseconds (1-100 μs) Milliseconds (1-50 ms)
Data Size Limited by RAM (GB) Unlimited (TB+)
Persistence Optional (RDB/AOF) Always durable
Transactions MULTI/EXEC (atomic) ACID guarantees
Joins N/A (key-value only) Complex joins native
Use Cases Cache, sessions, leaderboards, queue Transactional data, reports, analytics

Architecture pattern: Most production systems use both. PostgreSQL is the source of truth (durability). Redis sits in front as a cache layer and operational store (speed).

Persistence: How Redis Survives Restarts

Since Redis runs in RAM, all data is lost if the server crashes. To prevent this, Redis offers two persistence modes:

RDB (Redis Database Snapshots)

How it works: Redis saves a binary snapshot of all data to disk at intervals (e.g., every 1 minute or after 1000 writes).

Pros: Compact, fast recovery.

Cons: You lose data written between snapshots. Heavy snapshots can block the server.

AOF (Append-Only File)

How it works: Redis logs every write command to a file. On restart, it replays all commands to rebuild state.

Pros: Lose at most 1 second of data. Fine-grained durability.

Cons: AOF files grow large. Slower recovery on restart.

Hybrid: RDB + AOF

Modern Redis (7.0+) combines both: periodic RDB snapshots for efficiency, plus AOF for recent writes. Best of both worlds.

Your First Redis Commands

Let's try the most fundamental Redis operations. These assume a Redis server running on localhost:6379 and the redis-cli command-line tool installed.

Q1: SET a Key

shell
OK

What happened: The SET command stores a key-value pair. mykey is the key. "Hello, Redis!" is the value. The response OK means success.

Q2: GET a Key

shell
"Hello, Redis!"

What happened: GET retrieves the value for a key. Redis returns the string we stored.

Q3: Check if Key Exists

shell
(integer) 1

What happened: EXISTS returns 1 if the key exists, 0 if not. The key mykey exists, so the answer is 1.

Q4: Get the Data Type

shell
"string"

What happened: TYPE returns the data type of a key's value. We stored a string, so the type is string. Redis has other types too: list, set, zset (sorted set), hash, stream.

Q5: Delete a Key

shell
(integer) 1

What happened: DEL deletes a key. The response 1 means 1 key was deleted. If the key didn't exist, DEL would return 0.

Q6: Verify Deletion

shell
(integer) 0

What happened: The key no longer exists. EXISTS returns 0.

ShopStream Example: Caching Product Data

Here's how ShopStream marketplace could use Redis to cache popular products:

Store a Product

shell
OK

Retrieve It (Instant)

shell
{"name":"Wireless Headphones","price":89.99,"stock":150}

Set Expiration (Cache for 1 Hour)

shell
(integer) 1

What happened: EXPIRE sets a TTL (time-to-live) of 3600 seconds (1 hour). After that time, Redis auto-deletes the key. This is perfect for cache data that should refresh periodically.

Test Your Knowledge

Question 1 of 5
What year was Redis created and by whom?
Question 2 of 5
Name three use cases for Redis (select the best answer):
Question 3 of 5
Is Redis a replacement for PostgreSQL?
Question 4 of 5
What is the difference between RDB and AOF persistence?
Question 5 of 5
Why is Redis fast compared to traditional databases?
0
/5
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

You're learning to scale. Build systems that millions use.

Join the Best AI Program: The AI-Era Data Engineer — 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Data Engineer →