What Is Redis
Introduction
Redis (Remote Dictionary Server) is an open-source, in-memory data structure store that works as a database, cache, message broker, and streaming engine all at once. This chapter introduces what Redis is, what problems it solves, and how it differs from traditional disk-based databases. Understanding these basics will help you decide when Redis is the right tool—and when it is not.
Prerequisites
- None for this conceptual introduction
- Later installation chapters assume access to a terminal (Linux, macOS, or Windows with WSL)
- No prior database experience is required, but familiarity with key-value pairs helps
What Redis Does
At its core, Redis stores data in memory (RAM) instead of on disk. This single design choice makes it orders of magnitude faster than conventional databases for read and write operations. Instead of rows and tables, Redis gives you a rich collection of data structures:
| Data Structure | What It Stores | Common Use |
|---|---|---|
| String | Text, numbers, binary blobs | Caching, counters, session tokens |
| List | Ordered sequences | Message queues, activity feeds |
| Set | Unordered unique items | Tags, relationships, deduplication |
| Hash | Field-value mappings | User profiles, configuration objects |
| Sorted Set | Items ranked by a score | Leaderboards, time-series data |
| Stream | Append-only event logs | Event sourcing, message bus |
| Bitmap / HyperLogLog | Compact bit-level data | Real-time analytics, unique counts |
Redis is not a general-purpose relational database. You do not write SQL queries against it. You issue commands over a simple text protocol, and Redis responds with the data or confirmation you need.
Here is a minimal example using redis-cli. Imagine you want to cache how many times a blog post has been viewed:
# Connect to the local Redis server
redis-cli
# Set a view counter to 0 for post #42
SET post:42:views 0
# Increment the counter atomically each time someone loads the page
INCR post:42:views
# Read the current count
GET post:42:viewsThe INCR command is atomic. Even if a thousand clients increment the same key at the exact same millisecond, Redis guarantees the final count is correct. No locks, no transactions, no race conditions to worry about on your end.
The Single-Threaded Event Loop
Most developers hear "single-threaded" and assume slow. Redis turns that assumption upside down.
Redis uses a single event loop paired with I/O multiplexing. It means one thread processes all commands, but it never waits. While one client is thinking, Redis is already parsing the next request. Because everything happens in memory and there is no context switching between threads, a modest server can execute hundreds of thousands of operations per second.
Client A ──request──┐
Client B ──request──┼──→ Redis event loop ──→ memory operation ──→ response
Client C ──request──┘ (single thread)This design has a practical consequence: keep individual commands fast. If you run a command that scans a million keys, every other client waits. Later chapters cover how to avoid that pitfall with proper data modeling and the SCAN family of commands.
Where Redis Fits in Your Stack
Modern applications often use Redis alongside a primary database such as PostgreSQL or MySQL. Think of it as a specialized teammate, not a replacement.
Typical Architecture
┌─────────────┐ ┌─────────────┐ ┌─────────────────┐
│ Client │────→│ Web/API │────→│ Redis Cache │
│ (browser) │ │ server │ │ (hot data) │
└─────────────┘ └─────────────┘ └─────────────────┘
│
│ cache miss
↓
┌─────────────────┐
│ Primary Database│
│ (PostgreSQL, │
│ MySQL, etc.) │
└─────────────────┘The API server checks Redis first. If the data is there—a cache hit—it returns immediately. If not—a cache miss—it fetches from the primary database, stores the result in Redis, and then replies. Subsequent requests for the same data are served from memory in sub-millisecond time.
What Redis Excels At
Redis shines in scenarios where speed and simplicity matter more than complex querying:
- Caching: Store frequently accessed query results, HTML fragments, or API responses to protect your primary database and cut response times.
- Session storage: Share user login state across multiple web servers without sticky sessions.
- Rate limiting: Count API requests per user or IP within a sliding time window.
- Real-time leaderboards: Update and retrieve ranked data with
Sorted Setsin constant time. - Message brokering: Use
ListsorStreamsas lightweight queues between services. - Distributed locking: Coordinate exclusive access to a resource across multiple processes or machines.
- Real-time analytics: Count unique visitors with
HyperLogLogor track daily sign-ins withBitmapsusing only a few kilobytes.
Where Redis Is Not the Best Fit
Warning
Know the Limits
Because Redis is memory-first, storing multi-terabyte datasets can be expensive. It also does not support complex ad-hoc queries, joins, or ACID transactions across multiple keys the way relational databases do.
Avoid relying on Redis as your sole data store when:
- You need complex relational queries with joins and aggregations across many tables.
- Your dataset is larger than your available RAM and you cannot shard or expire old data.
- You require strict multi-document ACID transactions with rollback guarantees (Redis transactions are simpler and scoped to a single node).
- You must store data durably by default without configuring persistence. Redis can persist data, but its default mode is memory-only.
Core Features at a Glance
Before you dive into commands and configurations, here is a map of the major features you will explore in this track:
| Feature | What It Gives You |
|---|---|
| Persistence | RDB snapshots and AOF logs let you recover data after a restart. |
| Replication | A master node can stream changes to one or more replicas for read scaling and failover. |
| Sentinel | Automatic monitoring and failover when a master goes down. |
| Cluster | Data sharded across multiple nodes for horizontal scaling beyond a single machine's RAM. |
| Pub/Sub | Broadcast messages to any number of subscribers in real time. |
| Lua Scripting | Run atomic, server-side logic to reduce round trips. |
| Transactions | Queue multiple commands and execute them atomically with MULTI / EXEC. |
A Quick Taste in Python
You do not need a client library to understand Redis, but seeing one in action helps. Below is a short Python script using the official redis package. It connects to a local server, sets a key, and reads it back.
The setex command combines SET and EXPIRE. After 60 seconds, greeting automatically vanishes. This automatic expiration is one of the reasons Redis is so convenient for temporary data such as cached results and short-lived tokens.
Related Hello Code Tracks
| Track | Connection |
|---|---|
| MySQL / PostgreSQL | Primary database behind cache-aside |
| FastAPI | API cache integration |
| Vue | Browser SPA consuming cached REST APIs |
Tip
Full-stack pattern
Typical stack: Vue SPA → FastAPI/Django API → Redis cache → MySQL/PostgreSQL. See Vue chapter 17 and PostgreSQL deploy project.
FAQ
Is Redis a database or a cache?
It is both, depending on how you configure it. Many teams use it as a cache with expiration, but you can also enable persistence and treat it as a primary data store for specific use cases.
Does Redis lose all data when the server restarts?
Not necessarily. By default, Redis runs without persistence, so a restart clears memory. However, you can enable RDB snapshots, AOF append-only files, or both. These are covered in the persistence chapter.
Why is Redis single-threaded?
A single thread eliminates locking overhead and avoids cache-line thrashing between CPU cores. For in-memory workloads, this design is simpler and faster than traditional multi-threaded databases up to very high throughput.
Can I run queries like SELECT * FROM users WHERE age > 30?
No. Redis is not a relational database. You fetch data by exact key or by range within a specific data structure such as a Sorted Set. If you need ad-hoc filtering and joins, pair Redis with PostgreSQL or MySQL and use Redis for the speed-critical lookups.
How much RAM do I need?
Plan for your working dataset plus overhead. Redis adds some per-key and per-data-structure overhead, so a rough rule is to budget 1.5x to 2x the raw size of your data. The memory optimization chapter covers how to measure and reduce this.