Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 42 ยท Getting Started

What Is Redis?

Learn what Redis is, why it is so fast, how its single-threaded command loop works, what it is used for, and how it differs from databases and Memcached.

Redis is a server that keeps your data in memory and lets many programs read and write it over the network. The name comes from REmote DIctionary Server, and that is a good first picture: a giant dictionary of keys and values that lives in its own process, so your web servers, workers and scripts can all share it.

What makes Redis different from a plain key-value store is that the values are data structures: strings, lists, hashes, sets, sorted sets, streams and more. Instead of fetching a whole blob, changing it and writing it back, you ask Redis to push onto a list, bump a score or add a member to a set, and the server does it for you in one step. Because everything sits in RAM, those steps usually take well under a millisecond.

This track teaches Redis from the first command to production operation. One thing to know up front: a Redis server cannot run inside this website. So real redis-cli sessions appear as read-only blocks, and every runnable example uses a small emulator written in JavaScript that implements the same command semantics. We will say clearly which is which.

The key-value model

Everything in Redis is addressed by a key, a binary-safe string such as user:42:name or cart:9f3a. Each key holds exactly one value, and the value has a type. You pick commands that match the type: SET and GET for strings, LPUSH for lists, ZADD for sorted sets, and so on.

Here is what a short session looks like in redis-cli, the command-line client (real Redis, read-only):

TEXT
127.0.0.1:6379> SET greeting "hello world"
OK
127.0.0.1:6379> GET greeting
"hello world"
127.0.0.1:6379> INCR visits
(integer) 1
127.0.0.1:6379> INCR visits
(integer) 2
127.0.0.1:6379> TYPE visits
string
127.0.0.1:6379> GET nothing
(nil)

Commands are plain words followed by arguments. OK is a status reply, (integer) a number, quoted text a bulk string, and (nil) means "there is no such key". The default port is 6379, which is what the prompt shows. The next lesson installs Redis and covers redis-cli in depth.

What lives in Redis

Keys Binary-safe names like user:42.
Values Strings, lists, hashes, sets and more.
Memory Data sits in RAM, so replies are fast.

One key, one value, one type.

1 / 2

Try a first emulator

The emulator below is a tiny model of a Redis server: a map from keys to values, and a run method that parses one command line and returns a reply. It implements only a handful of string commands, and it prints replies in the same style as redis-cli. Later lessons extend this exact design with more types, expiry and transactions.

JS MiniRedis: a first emulator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice three things. A missing key returns (nil), not an error. INCR creates a missing key as if it held 0. And INCR on text that is not a number returns an error reply, which a client library turns into an exception. All three behave exactly like real Redis. What the emulator lacks is everything outside the command logic: the network, persistence and real performance.

Why Redis is so fast

Three design choices explain the speed.

  • Memory first. Reading RAM takes nanoseconds, disks take microseconds to milliseconds. Redis keeps the whole dataset in RAM and uses disk only to survive restarts (see persistence).
  • Simple, efficient structures. Each type is implemented with compact encodings, and most commands are O(1) or O(log N). You pay for large collections only when you ask for the whole collection.
  • A single-threaded command loop. One thread executes commands one after another, so Redis needs no locks around your data. There is no thread switching and no contention. Newer versions can use extra threads for reading and writing sockets, but commands still execute one at a time on the main thread.

One command at a time, always atomic

Because only one command runs at any moment, every individual command is atomic: no other client can see it half done. That is why INCR is safe for counters. Two clients that both send INCR visits can never lose an update.

Contrast this with doing the work yourself in application code: read the value, add one, write it back. If two clients do that at the same moment, one increment vanishes. The next example replays exactly that interleaving, step by step, and compares it with INCR.

JS Lost update vs atomic INCR

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real Redis gives you the second behavior for free. The emulator reproduces the idea: each command is a whole step, so interleavings between the read and the write cannot happen. Multi-step logic across several commands is not atomic by itself, and transactions and Lua scripting exist to fix that.

Redis compared with other stores

Redis is usually not a replacement for your main database. It is the fast layer next to it.

Redis Relational database Memcached
Data lives In memory, optionally saved to disk On disk, with a memory cache Only in memory
Data model Keys with rich types Tables, rows, SQL Keys with plain strings
Queries By key and by structure Arbitrary queries and joins By key only
Durability Optional snapshots and logs Strong by default None
Typical role Cache, queue, counters, ranking System of record Simple cache

Compared with Memcached, Redis adds data structures, expiry control, persistence, replication and scripting, at the cost of more to learn. Compared with a database such as PostgreSQL, Redis gives up ad hoc queries and cheap storage per gigabyte in exchange for speed. RAM is more expensive than disk, so Redis suits data that is hot, small enough to fit in memory, or fast-changing.

Redis next to Memcached, Kafka, MongoDB and SQL databases

The table above compares three stores. Real systems usually weigh Redis against a few more, so here is the short version of how each differs and when each wins.

Memcached is a pure cache for strings. It is multi-threaded, has no persistence and no data structures. Choose it only if all you need is a simple, very large, shared cache. Redis does the same job and adds expiry control, atomic counters, hashes, lists, sets, sorted sets, replication and disk persistence, so most teams pick Redis even for plain caching.

Kafka is a distributed, partitioned event log built for very high throughput, long retention (days or forever) and many independent consumer groups replaying history. Redis streams give you a log with consumer groups too, but they live in memory, so they suit smaller volumes and shorter retention. If events are the system of record, or you need replay across weeks, use Kafka. If you need a fast job queue or an activity feed, Redis is simpler.

MongoDB (and other document databases) is a disk-first database with rich queries, secondary indexes, aggregation and a flexible schema. Redis is a memory-first structure server. You query Redis by key and by structure (a sorted set range, a set intersection), not by arbitrary fields, unless you add the search module. Use MongoDB when you must store and query lots of documents that exceed memory; use Redis for the hot slice that needs microsecond latency. See the MongoDB tutorial for the other side.

SQL databases (PostgreSQL, MySQL) give you transactions across many rows, joins, constraints and strong durability by default. Redis gives up joins and cheap storage per gigabyte in exchange for speed. Typical pairing: PostgreSQL as the system of record, Redis for caching its results, sessions, rate limits and leaderboards.

Redis Memcached Kafka MongoDB PostgreSQL / MySQL
Primary storage RAM (optional disk) RAM Disk log Disk Disk
Typical latency Sub-millisecond Sub-millisecond Milliseconds Milliseconds Milliseconds
Data model Typed structures Strings Append-only topics JSON-like documents Tables and rows
Query power By key and structure By key Read from an offset Rich queries and aggregation Full SQL with joins
Durability Configurable None Strong, replicated Strong, replicated Strong
Best for Cache, counters, queues, rankings Plain cache Event streaming, replay Flexible documents Relational system of record

Redis as a cache versus as a primary database

Redis can be used both ways, and the settings differ:

  • As a cache the data can be rebuilt. Turn persistence down or off, set maxmemory with an eviction policy such as allkeys-lru, give keys a TTL, and treat a missing key as normal.
  • As a primary database (for sessions you cannot lose, leaderboards, feature state) enable AOF, use replicas and Sentinel or Cluster, set maxmemory-policy noeviction so Redis refuses writes instead of deleting data, and take backups.

The rule from before still holds: if you cannot rebuild the data and cannot afford to lose seconds of it, a durable database should hold it first. The model below turns these questions into a rough recommendation. It is a teaching aid with simple rules, not a real selection tool.

JS Which store fits this workload?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The recommendations show the pattern: Redis wins on speed and on structures that map to a task (ranking, counting), the others win on size, retention, relations and queries. Most real systems use two of these together.

Typical uses

  • Caching: store the result of a slow query or API call with an expiry (caching patterns).
  • Sessions: a login session is a small record that must be fast to look up and disappear on its own.
  • Counters and rate limits: atomic INCR with expiry counts requests per user per minute.
  • Leaderboards: sorted sets keep scores ranked as they change.
  • Queues and events: lists and streams pass work between services.
  • Real-time messaging: pub/sub broadcasts messages to connected clients.

You do not have to use it for everything. A clear mental rule: if losing the data would be a disaster and you cannot rebuild it, keep it in a durable database first and treat Redis as a copy or an accelerator.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which description of a Redis value is most accurate?

    Each key holds one value with a type, and Redis commands operate on that structure directly.
  2. 2. Why can two clients safely run INCR on the same key at the same time?

    Commands run sequentially on one thread. A single command can never be interrupted by another client's command.
  3. 3. What does a missing key return from GET?

    GET on a key that does not exist returns nil, which is different from an empty string and is not an error.
  4. 4. Which statement about running Redis alongside a relational database is the best default?

    Redis keeps data in RAM and offers optional durability, so it is usually the fast layer beside a durable database.

Summary

  • Redis is an in-memory server that stores keys mapped to typed values such as strings, lists, hashes, sets and sorted sets.
  • Speed comes from RAM, efficient structures and a single-threaded command loop with no locking.
  • Every single command is atomic, which makes counters safe; multi-step logic needs transactions or scripts.
  • Redis complements a database (cache, sessions, counters, queues, rankings) rather than replacing it.
  • On this site, real Redis commands are read-only, and runnable examples use a JavaScript emulator of the same semantics.

Next, install Redis and learn the command-line client: Installing Redis and Using redis-cli.