Databases & SQL/
Lesson

Every web app eventually hits a wall: the database is slow, the same queries run thousands of times a day, and users start noticing. Redis exists to fix that. It's an in-memory data store that sits between your application and your main database, serving frequently requested data at memory speed instead of disk speed.

Think of it like a whiteboard next to your desk. Your filing cabinet (PostgreSQL) holds everything permanently, but writing on a whiteboard is instant. Redis is that whiteboard, fast, temporary, and perfect for information you need right now.

Why use Redis?

The speed problem with disk-based databases

When you query PostgreSQL or MySQL, the database reads data from disk, applies indexes, joins tables, and returns results. This can take anywhere from a few milliseconds to several seconds for complex queries. For a page that runs ten queries every time someone visits, that adds up quickly.

Redis stores everything in RAM. Memory access is measured in nanoseconds, not milliseconds. For the right workloads, this makes Redis orders of magnitude faster than your primary database.

Storage typeTypical read latencyPersistent?
SSD (PostgreSQL, MySQL)1–10 msYes
Redis (in-memory)< 1 msOptional
Application memory (variables)< 0.01 msNo (process only)

Where Redis fits in a real app

Redis is not a replacement for your main database, it works alongside it. Here are the most common patterns you'll encounter:

  • Caching: store the result of an expensive query so the next request skips the database entirely
  • SessionWhat is session?A server-side record that tracks a logged-in user. The browser holds only a session ID in a cookie, and the server looks up the full data on each request. storage: keep user login sessions without hitting a database on every request
  • Rate limitingWhat is rate limiting?Restricting how many requests a client can make within a time window. Prevents brute-force attacks and protects your API from being overwhelmed.: count how many APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. calls a user has made in the last 60 seconds
  • Pub/SubWhat is pub/sub?A messaging pattern where senders publish events to a channel and any number of listeners receive them in real time. messaging: broadcast events between services in real time
Redis is often called a "data structure server" because it supports more than just strings. Lists, sets, sorted sets, hashes, and streams are all built-in. For this lesson, you'll focus on the core string type.
02

Key-value structure

How Redis organizes data

Forget tables and rows. Redis stores every piece of data under a key, a unique string you choose, and retrieves it by that same key. There are no joins, no schemas, and no migrations.

SET user:1:name "Alice"
GET user:1:name  # Returns "Alice"

The key user:1:name is just a string. The colon-separated format is a naming convention, not syntax, Redis doesn't treat it specially. But it's widely used because it makes keys readable and namespaced.

Naming keys well

A good key naming convention prevents collisions as your app grows. The most common pattern is resource:id:field.

SET session:abc123 '{"userId": 42, "role": "admin"}'
SET ratelimit:user:42:minute:2024010110 "17"
SET cache:posts:page:3 '[{"id":1,...}]'
Keep key names short but descriptive. Redis stores all keys in memory, so unnecessarily long keys waste RAM at scale.
03

Basic commands

The core set

You can interact with Redis through its CLIWhat is cli?Short for Command Line Interface. A tool you use by typing commands in the terminal instead of clicking buttons. (redis-cli) or through a client library in your language. Either way, the commands are the same.

SET city "Paris"       # Store a string
GET city               # Retrieve it -> "Paris"
DEL city               # Delete it
EXISTS city            # Returns 0 (deleted) or 1
KEYS user:*            # List all keys matching a pattern

Time-to-liveWhat is ttl?Time-to-Live - a countdown attached to cached data that automatically expires it after a set number of seconds. (TTL)

One of Redis's most useful features is automatic expiration. You set a TTL on a key, and Redis deletes it once the time is up, no cron job needed.

SET verification_code "9472"
EXPIRE verification_code 300   # Expires in 5 minutes

# Or set both value and expiry in one command
SETEX temp_token 3600 "abc-secret"   # Expires in 1 hour

TTL temp_token   # Returns seconds remaining
When a key expires, Redis removes it lazily (on next access) and actively (periodic sweep). You won't get an error trying to GET an expired key, you'll just get nil.
04

Quick reference

CommandWhat it doesExample
SET key valueStore a stringSET name "Alice"
GET keyRetrieve a stringGET name
DEL keyDelete a keyDEL name
EXISTS keyCheck if key exists (1 or 0)EXISTS name
EXPIRE key secondsSet time-to-liveEXPIRE name 60
SETEX key seconds valueSet value + TTL togetherSETEX name 60 "Alice"
TTL keyCheck remaining TTLTTL name
INCR keyIncrement a number by 1INCR page_views
KEYS patternList matching keysKEYS user:*
javascript
// Redis CLI Examples
SET session:id:abc12345 '{"user_id": 1, "role": "admin"}'
GET session:id:abc12345

// Setting with expiration (Seconds)
SETEX temp_token 3600 "secret_value"

// Increments (Perfect for counters/rate limiting)
SET page_views 10
INCR page_views # Now 11