</>
CodeLearn Pro
Start Learning Free β†’
πŸ—„οΈ Databases

Redis

✦ Beginner Friendly⚑ In-Memory Speed

The fastest data store in the world. Redis keeps everything in memory for sub-millisecond reads and writes. Used by Twitter, GitHub, Pinterest, and Snapchat for caching, sessions, queues, and real-time leaderboards.

6
Modules
18
Examples
100%
Free
0
Login Needed
Redis in-memory data store
⚑In-Memory Speed
redis-cliRedis 7
# Store a user session (expires in 1 hour)
SET session:abc123 '{"userId":1,"role":"admin"}' EX 3600

# Retrieve it
GET session:abc123

# Check how long until it expires
TTL session:abc123

# Store a user as a hash
HSET user:1 name "Alice" age 20 city "Cape Town"
HGETALL user:1

# Leaderboard with sorted set
ZADD leaderboard 95 "Alice"
ZADD leaderboard 82 "Bob"
ZREVRANGE leaderboard 0 -1 WITHSCORES
Output
OK
"{"userId":1,"role":"admin"}"
3598
1) "name" 2) "Alice" 3) "age" 4) "20"
1) "Alice" 2) "95" 3) "Bob" 4) "82"

About Redis

πŸ“…
Created
2009 by Salvatore Sanfilippo β€” open source, written in C
⚑
Speed
In-memory β€” sub-millisecond reads and writes
πŸ—οΈ
Type
Key-Value Store β€” NoSQL in-memory data structure server
πŸ“¦
Structures
Strings, Hashes, Lists, Sets, Sorted Sets, Streams
πŸ”§
Used for
Caching, sessions, queues, pub/sub, leaderboards, rate limiting
🌍
Runs on
Linux, macOS, Docker β€” Redis Cloud for managed hosting

Introduction

What is Redis?

Redis (Remote Dictionary Server) is an open-source, in-memory key-value data store created in 2009 by Salvatore Sanfilippo. Unlike traditional databases that read and write to disk, Redis keeps all data in RAM β€” making it extraordinarily fast with sub-millisecond response times and the ability to handle millions of operations per second.

Redis is not just a simple cache. It supports rich data structures β€” strings, hashes (like objects), lists (like arrays), sets (unique collections), and sorted sets (ranked leaderboards). Each data type has its own set of commands optimised for that structure's operations.

Most modern web applications use Redis alongside their primary database: PostgreSQL or MongoDB stores the persistent data, while Redis sits in front as a cache to serve hot data instantly without hitting the database on every request.

Redis Data Structures β€” What Each is Used For
StringCaching HTML/JSON, session tokens, counters, flags
HashUser profiles, settings objects, structured records
ListActivity feeds, message queues, recent items history
SetTags, followers, unique visitors, access control lists
Sorted SetLeaderboards, priority queues, time-series data

Why learn Redis in 2025?

  • βœ“Used by Twitter, GitHub, Pinterest, Snapchat, and thousands of startups
  • βœ“Caching knowledge alone can 10x your API performance
  • βœ“Essential for building scalable back-end systems
  • βœ“Session storage β€” the default choice for Node.js and Rails apps
  • βœ“Real-time features: chat, notifications, live leaderboards

Cheat Sheet

Redis Quick Reference

CommandWhat it does
SET key valueStore a string value
GET keyRetrieve a string value
SET key value EX 3600Store with expiry of 3600 seconds (1 hour)
TTL keySeconds remaining until key expires (-1 = never)
DEL keyDelete a key
EXISTS keyCheck if key exists (1 = yes, 0 = no)
INCR keyIncrement integer value by 1 (atomic)
HSET user:1 name AliceSet a field in a hash
HGET user:1 nameGet one field from a hash
HGETALL user:1Get all fields and values from a hash
LPUSH list valuePush value to the LEFT of a list
RPUSH list valuePush value to the RIGHT of a list
LRANGE list 0 -1Get all list elements (0 to end)
SADD myset valueAdd a member to a set (no duplicates)
SMEMBERS mysetGet all members of a set
ZADD board 95 "Alice"Add member with score to a sorted set
ZRANGE board 0 -1 WITHSCORESGet all sorted set members with scores

Need the full tutorial? Start the beginner course β†’

Preview

What Redis commands look like

caching.redisredis-cli
# ── Caching API responses ────────────────────────

# Cache a JSON response for 10 minutes
SET api:users:page1 '[{"id":1,"name":"Alice"},...]' EX 600

# Check if cache exists before hitting DB
EXISTS api:users:page1   # returns 1 if cached

# Retrieve cached data
GET api:users:page1

# See how long until cache expires
TTL api:users:page1

# Manually invalidate cache
DEL api:users:page1

# ── Rate limiting with INCR ───────────────────────

# Allow max 100 requests per minute per IP
INCR rate:192.168.1.1    # returns current count
EXPIRE rate:192.168.1.1 60  # resets after 60 seconds

# Atomic check-and-increment
INCR rate:192.168.1.1   # 1
INCR rate:192.168.1.1   # 2
# ... if count > 100, reject request
Output
OK
1 (exists)
'[{"id":1,"name":"Alice"},...]'
573 (seconds left)
1 (deleted)

1
OK
2
leaderboard.redisredis-cli
# ── Real-time leaderboard ────────────────────────

# Add players with their scores
ZADD game:scores 95 "Alice"
ZADD game:scores 82 "Bob"
ZADD game:scores 91 "Charlie"
ZADD game:scores 78 "Diana"
ZADD game:scores 88 "Edward"

# Get top 3 players (highest scores first)
ZREVRANGE game:scores 0 2 WITHSCORES

# Get Alice's rank (0 = best)
ZREVRANK game:scores "Alice"

# Get Alice's score
ZSCORE game:scores "Alice"

# Update score (add 5 bonus points)
ZINCRBY game:scores 5 "Bob"

# Count players with score >= 80
ZCOUNT game:scores 80 +inf
Output
1) "Alice"   2) "95"
3) "Charlie" 4) "91"
5) "Edward"  6) "88"

0   (rank 1st)
95  (score)
87  (82+5)
4   (Alice,Charlie,Edward,Bob)

FAQ

Frequently asked questions

What is Redis and what is it used for?

Redis (Remote Dictionary Server) is an open-source, in-memory key-value data store. Its primary uses are: caching (storing frequently accessed data in memory so databases are not hit repeatedly), session storage (keeping user session data for web apps), message queuing (pub/sub), real-time leaderboards (sorted sets), rate limiting (atomic counters), and job queues.

Why is Redis so fast?

Redis stores all data in RAM (memory) instead of on disk. Memory access is roughly 100,000x faster than disk access. Additionally, Redis uses a single-threaded event loop (like Node.js) which avoids locking overhead. It can handle over 1 million operations per second on a single machine with sub-millisecond latency.

Does Redis lose data when the server restarts?

By default Redis is volatile β€” data lives only in memory and is lost on restart. But Redis has two persistence options: RDB (snapshots β€” saves the dataset to disk periodically) and AOF (Append Only File β€” logs every write operation). You can enable either or both depending on your durability requirements. Redis Cluster also provides replication.

What is the difference between Redis and Memcached?

Both are in-memory caches, but Redis has many advantages: it supports rich data structures (hashes, lists, sets, sorted sets, streams), persistence to disk, pub/sub messaging, Lua scripting, and clustering. Memcached only supports strings and is purely a cache. Redis is almost always the better choice for new projects.

How do I install Redis?

On macOS: brew install redis && brew services start redis. On Ubuntu: sudo apt install redis-server. With Docker: docker run -d -p 6379:6379 redis. Then connect with the CLI: redis-cli. The default port is 6379. Redis Cloud and Upstash offer free managed Redis instances for development.

⚑

Ready to learn Redis?

6 modules, 18 examples with full output. Master every Redis data structure and build caching, sessions, queues, and real-time leaderboards.

βœ“No account neededβœ“Always freeβœ“Works on any device

The Story of Redis

Real history, real companies, and an honest look at where Redisshines and where it doesn't β€” not just a feature list.

πŸ•°οΈ

Where it came from

Salvatore Sanfilippo created Redis in 2009 while trying to improve the performance of a website analytics tool he was building β€” he needed something far faster than a traditional disk-based database for a very specific job: temporary, fast-changing data. Redis solved this by keeping all its data in RAM, which is roughly a thousand times faster to access than disk storage.

🏒

How it’s actually used today

Twitter uses Redis to power its timeline caching, GitHub uses it for background job queues, and Stack Overflow has used it for years to cache expensive database queries so pages load near-instantly. It's rarely a company's only database β€” it's almost always a fast companion sitting in front of a slower, permanent database like PostgreSQL.

βš–οΈ

Strengths & trade-offs

Keeping data in memory makes Redis extremely fast, but it also means data can be lost if the server restarts, unless you configure it to periodically save to disk β€” a trade-off that's completely fine for a cache, but wrong for data you can't afford to lose, like financial records.

🧭

What to learn next

Since Redis is almost always used alongside a primary database, learning SQL or MongoDB first (whichever fits your project) gives Redis proper context β€” it's best understood as a performance layer you add on top of an existing data setup, not a replacement for one.