Redis 📂 Redis Introduction · 1 of 1 25 min read

Getting Started with Redis — In-Memory Speed, Keys, and TTL

A beginner-friendly Redis tutorial. Learn what Redis is and why the in-memory, single-threaded model is so fast, when to use Redis versus a normal database, how to install and run it with Docker or a package manager, the core commands SET, GET, DEL and EXISTS, and how key expiry works with EXPIRE, SETEX, TTL and PERSIST.

Section 01

What Is Redis?

The Whiteboard Next to the Filing Cabinet
A filing cabinet keeps every document safe for years. But if you need a number ten times a minute, you do not open a drawer each time. You write it on a whiteboard beside your desk. Reading the whiteboard is instant.

Redis is that whiteboard. Your main database (the filing cabinet) keeps everything safe on disk. Redis keeps the hot, frequently used data in memory, so your app reads it in a blink. Redis stands for REmote DImctionary Server — at heart it is one giant, very fast key→value dictionary.

Redis is an in-memory key–value store. You give it a key, it gives you back a value. Everything lives in RAM, which is why it answers in microseconds. It can also save to disk so data survives a restart, but its main job is speed.

📝 Redis Is One Big Dictionary in Memory
SET user:1 "Asha" GET user:1 → "Asha" Your app redis-cli or a client library Redis — in-memory key → value store KEY VALUE user:1"Asha" cart:57["book","pen"] views:home98213 (a counter) online:57"1" (expires in 30s) every value is found by its key, in one step

Section 02

Why Redis Is So Fast

Three simple choices make Redis fast. It keeps data in memory, it runs commands on a single thread, and it uses lean data structures. Let us look at each.

⚡
In memory (RAM)
no disk seek
Reading from RAM is thousands of times faster than reading from a disk. Redis keeps the working data in memory, so there is no drive to wait for.
🧭
Single thread
no locks
One command runs at a time, in order. No locks, no race conditions, no thread switching. Simple and predictable, and still very fast.
🧩
Lean structures
O(1) lookups
Most operations touch a key directly, so they take the same tiny time no matter how much data you store. Add a value, read a value, done.

Memory vs Disk — the speed gap

Bars show how long a read takes. Shorter is faster. The right side puts it in human terms: if a memory read felt like 1 second, a hard-disk read would feel like more than a day.

📊 How Long a Single Read Takes
RAM ~100 ns · feels like 1 second SSD ~100 µs · feels like 17 minutes HDD ~10 ms · feels like more than a day

The single-threaded model

Every command waits in one line and is served by one worker, in order. Each command is so quick that the line never gets stuck.

🧭 One Line, One Worker, In Order
Many clients app server A app server B app server C Command queue (in order) GET SET INCR GET Single thread running 1 reply Commands are served one by one. Because each is tiny, the line stays short.
🧠
Single Thread Is a Feature, Not a Limit

Because only one command runs at a time, you never get two commands clashing on the same key. Many operations are atomic for free. Modern Redis still uses extra threads for slow background jobs like saving to disk, but your commands run on one fast thread.


Section 03

Redis vs a Normal Database (RDBMS)

Redis does not replace MySQL or PostgreSQL. They do different jobs. An RDBMS is the safe home for your data. Redis is the fast layer in front of it.

PointRedisRDBMS (MySQL / PostgreSQL)
Stores data inMemory (RAM)Disk
SpeedMicrosecondsMilliseconds
Data modelKey → value structuresTables, rows, relations
QueriesLook up by keyRich SQL, joins, filters
TransactionsSimple (MULTI/EXEC)Full ACID across tables
Best forCache, counters, real-timeSource of truth, reporting
If it restartsCan reload from disk (optional)Data is always safe
⚡
Reach for Redis
Caching database results, login sessions, page-view counters, rate limiting, leaderboards, live presence, queues, and anything read very often.
fast & hot data
📚
Reach for an RDBMS
The permanent record: users, orders, payments, and anything you must never lose. Also complex reports that need joins, filters, and grouping.
safe & relational
🤝
Use both together
The common real-world setup. The RDBMS is the source of truth. Redis sits in front and serves the hot data fast. Best of both worlds.
truth + speed
✅ Good fit for Redis
Data read far more than written
Short-lived or throwaway data
Simple lookups by a key
Needs an answer in a blink
❌ Poor fit for Redis alone
Data you cannot ever lose
Reports with joins across tables
Datasets larger than your RAM
Complex multi-table transactions

Section 04

Install and Run Redis

Pick the way that suits you. Docker is the quickest for trying it out. On a server, the package manager is fine. Either way you talk to Redis through redis-cli.

🔧 Three Ways to Start Redis
Docker
Fastest to try. One command starts a container and exposes port 6379.
Linux
Install the redis-server package on Ubuntu or Debian.
macOS
Use Homebrew: brew install redis.

Option A — Docker (quickest)

# start Redis in the background, mapped to port 6379
docker run --name my-redis -p 6379:6379 -d redis

# open the Redis command line inside the container
docker exec -it my-redis redis-cli

Option B — Linux (Ubuntu / Debian)

sudo apt update
sudo apt install redis-server -y

# start the server (or it may already run as a service)
redis-server

# in another terminal, connect
redis-cli

Option C — macOS (Homebrew)

brew install redis
brew services start redis     # run it in the background
redis-cli

Check it works

PING
OUTPUT
PONG
✅
PONG Means You Are Connected

redis-cli shows a prompt like 127.0.0.1:6379>. Type PING and Redis replies PONG. That is your "hello world". You are now ready to store and read data.


Section 05

Keys, Values, and Basic Commands

A key is a name. A value is what you store under it. These four commands do most of the daily work: SET, GET, EXISTS, and DEL.

# store a value under a key
SET user:1 "Asha"

# read it back
GET user:1

# does the key exist? 1 = yes, 0 = no
EXISTS user:1

# delete the key (returns how many keys were removed)
DEL user:1

# now it is gone
GET user:1
OUTPUT (step by step)
SET user:1 "Asha" -> OK GET user:1 -> "Asha" EXISTS user:1 -> (integer) 1 DEL user:1 -> (integer) 1 GET user:1 -> (nil)
CommandWhat it doesReply
SET key valueStore a value under a keyOK
GET keyRead the valuethe value, or nil
EXISTS keyCheck if a key is there1 or 0
DEL keyRemove a keycount removed
🔑
Name Keys with Colons

Use a clear pattern like user:1, cart:57, or chat:42:messages. The colon has no special power, but it keeps keys tidy and easy to group. Good key names make a Redis database easy to read.

⚠️
Never Run KEYS * in Production

KEYS * scans every key at once and can freeze a busy server, because Redis is single-threaded. To look through keys safely, use SCAN, which walks them in small batches.


Section 06

Key Expiry and TTL

A big reason Redis fits caching is that keys can expire on their own. TTL means "time to live" — how many seconds a key has left before Redis deletes it automatically. You never have to clean up old cache by hand.

A key with a TTL counts down. When it hits zero, Redis removes it. No cron job, no cleanup code.

⏳ The Life of a Key with a TTL
1. Set with a TTL SETEX session:57 3 "abc" lives for 3 seconds 2. Counting down key session:57 is alive TTL: 3 → 2 → 1 → 0 3. Key removed gone automatically TTL now returns -2
# store a key and set it to expire in 60 seconds
SET otp:57 "839201"
EXPIRE otp:57 60

# how many seconds are left?
TTL otp:57

# do both in one step: set value AND expiry together
SETEX session:57 3600 "token-abc"

# the same idea using SET with the EX option
SET session:57 "token-abc" EX 3600

# changed your mind? make the key permanent again
PERSIST session:57

# check again: -1 means "no expiry set"
TTL session:57
OUTPUT
SET otp:57 "839201" -> OK EXPIRE otp:57 60 -> (integer) 1 TTL otp:57 -> (integer) 60 SETEX session:57 3600 "..." -> OK PERSIST session:57 -> (integer) 1 TTL session:57 -> (integer) -1
🔢
The Two Special TTL Numbers

TTL returns -1 when the key exists but has no expiry. It returns -2 when the key does not exist at all (already expired or never created). Any other number is the seconds left.

How Redis actually deletes expired keys

🧰 Lazy + Active Expiry
Lazy
When you touch a key, Redis checks its TTL. If it has expired, Redis deletes it right then and returns nothing.
Active
In the background, Redis keeps sampling random keys and removes the expired ones, so dead keys do not pile up unseen.
Result
An expired key is treated as gone the moment its time is up, even if the memory is freed a little later.
💡
TTL Is the Heart of Caching

Give cached data a TTL that matches how fresh it must be. Cache a home-page list for 60 seconds, a user profile for 10 minutes, an OTP for 5 minutes. When the time is up, the key clears itself and the next read rebuilds it. No cleanup code needed.


Section 07

Golden Rules

⚡ Redis Basics — Non-Negotiable Rules
1
Redis is a fast layer, not your only store. Keep the permanent copy in an RDBMS. Use Redis for hot, frequently read data.
2
Everything is a key. Name keys clearly with colons, like user:1 or cart:57. Good names keep the database readable.
3
Remember it is single-threaded. One command runs at a time. Avoid slow commands like KEYS * on a busy server; use SCAN instead.
4
Give cache keys a TTL. Use EXPIRE or SETEX so old data clears itself. Cache without a TTL slowly fills your memory.
5
Know your TTL replies. -1 means no expiry set, -2 means the key is gone. Any other value is the seconds remaining.
6
Plan for a restart. Redis can save to disk, but treat it as a cache you can rebuild. Never store data only in Redis that you cannot afford to lose.
You have completed Redis Introduction. View all sections →