Learning objectives
After reading this article you will be able to:
- Understand what Redis is and why it is fast
- Learn its data structures and the most common use cases
- Know how Redis persists data and when not to use it as your main database
When a page is slow because every request hits the database, the database is rarely the problem. The same data is simply being read thousands of times. Redis was built for exactly that: keep what is read constantly in memory and hand it back with almost no wait.
Today it goes beyond caching. According to its official documentation, it is an in-memory data store used as a cache, document database, vector database, streaming engine and message broker.
What is Redis?#
Redis is a data structure server that keeps its dataset in RAM. You connect over the network, send commands such as SET and GET, and get a reply. The open source project has existed since 2009.
The basic model is key-value: each piece of data has a key (text) and a value. What sets it apart from a plain dictionary is that the value can be a whole structure (list, set, hash) and the server understands these structures, with atomic operations on them.
Why is Redis so fast?#
The main reason is memory. Reading from RAM is much faster than reading from disk, and Redis keeps the dataset there. Access is also direct, by key, with no query planning or joins, and the commands are simple and specific to each structure.
The price of that speed is capacity: RAM costs more per gigabyte than disk, so your Redis dataset has to fit in the memory you provision.
Which data structures does Redis have?#
Redis Open Source offers, among others, these types:
- Strings: a sequence of bytes. Good for text, serialized JSON and counters.
- Hashes: field-value pairs, like an object with properties.
- Lists: lists of strings in insertion order, good for simple queues.
- Sets: unique, unordered strings with O(1) membership tests.
- Sorted sets: unique strings ordered by a score, ideal for leaderboards.
- Streams: an append-only event log, to process events in the order they happened.
- Others: bitmaps, geospatial indexes, HyperLogLog, JSON, time series and vector sets.
Any key can have a time to live (TTL). When it runs out, Redis deletes the key by itself. That is how a cache cleans itself and how a session expires.
What is Redis used for in practice?#
The most common uses:
- Cache: store the result of a slow query or an API call for a few seconds or minutes.
- Sessions: keep the user session somewhere that several application processes can read.
- Counters and rate limiting:
INCRincrements a number atomically, which covers hit counting and rate limits. - Leaderboards: a sorted set keeps scores ordered without you re-sorting anything.
- Queues and pub/sub: lists, streams and publish channels pass work or messages between processes.
- Bots: store cooldowns, per-server settings or temporary command state.
Example: query cache in Node.js#
The code below uses node-redis (install with npm install redis) and the cache-aside pattern: try the cache, and on a miss fetch from the source and write the result with a 60-second TTL. The connection URL lives in an environment variable.
import { createClient } from "redis";
const redis = createClient({ url: process.env.REDIS_URL });
redis.on("error", (err) => console.error("Redis Client Error", err));
await redis.connect();
// Simulates a slow query to the main database
async function loadUserFromDatabase(id) {
await new Promise((resolve) => setTimeout(resolve, 300));
return { id, name: "Ada" };
}
async function getUser(id) {
const key = `user:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // cache hit
const user = await loadUserFromDatabase(id); // cache miss
await redis.set(key, JSON.stringify(user), {
expiration: { type: "EX", value: 60 },
});
return user;
}
console.log(await getUser(1)); // ~300 ms
console.log(await getUser(1)); // served by Redis
await redis.quit();Set REDIS_URL as redis://user:password@host:6379 (or rediss:// when the server requires TLS). Save the file as cache.mjs and run node cache.mjs: the first call takes about 300 ms, and the second comes straight from Redis. Note the type:id key convention (user:1): Redis has no namespaces, and the documentation recommends this pattern.
Does Redis data survive a restart?#
It can, if you enable persistence. Redis has two methods, which can be combined:
- RDB: takes snapshots of the dataset at intervals (for example,
save 60 1000writes every 60 seconds if at least 1000 keys changed). It is compact and restarts fast, but an unexpected shutdown can lose the last few minutes. - AOF (append-only file): logs every write and replays them on startup. With
appendonly yesand the defaultappendfsync everysecpolicy, you lose at most about one second of writes.
You can also turn persistence off, which is common when Redis is only a cache. The documentation suggests using RDB and AOF together if you want a level of data safety comparable to PostgreSQL.
What happens when memory fills up?#
You set a limit with maxmemory (for example, maxmemory 100mb). When it is reached, Redis follows the maxmemory-policy setting. With noeviction, it refuses new writes and returns an error. With allkeys-lru, it deletes the least recently used keys, which is a good default for a cache. There are also volatile-* variants that only remove keys that have a TTL.
This is where a cache and a database part ways: in a cache, dropping old keys is the behavior you want. For data that must not disappear, use noeviction and monitor usage.
When should you not use Redis?#
- Large, relational data: if the dataset does not fit in RAM or you need joins, ad hoc queries and constraints, a database like PostgreSQL is a better fit. See also how to choose a database.
- Documents with flexible queries: MongoDB is built for that.
- Critical data without persistence: in a cache setup with no persistence, a restart wipes everything.
- Scanning all keys: the
KEYScommand blocks the server on large datasets. UseSCAN, which iterates in small steps.
A common setup is Redis next to a main database: the database holds the truth and Redis speeds up reads. To decide where to run the database, read how to host a database.
Redis or Valkey?#
Valkey is a BSD project backed by the Linux Foundation that includes BSD-licensed Redis code. Redis Open Source, from version 8 on, is offered under RSALv2, SSPLv1 or AGPLv3, your choice. Read the license if you plan to redistribute or resell the software, and check compatibility with the version and modules you use.
How to do this on Square Cloud#
The cache example above runs, with only the connection changed, on Square Cloud's Redis hosting, available from the Standard plan (from R$44.99 per month); Hobby does not include databases. You create Redis in the dashboard, always on a recent version, and pick its memory from 512 MB, taken from the plan's RAM. Since the dataset has to fit in that memory, size it by what your data takes, plus headroom. The database is ready in seconds in the same datacenter as your applications, with an average latency of about 1 ms.
The connection requires TLS: the dashboard URL starts with rediss://, and your client must trust the CA of the certificate you download there (in node-redis, pass the file in socket.ca). Keep the URL in REDIS_URL, the same variable as in the example. There is a single logical database, so the type:id key convention is what keeps cache, sessions and queues apart. Idle clients are disconnected after 5 minutes: node-redis reconnects on its own, but check that behavior if you use another client.
Hosted Redis has persistence and supports PUBLISH/SUBSCRIBE, which covers sessions, counters and pub/sub on top of caching. You take manual snapshots whenever you want, and every plan that includes databases also takes an automatic daily snapshot, which restores into the same database, another Redis or a new database.
See the details and create the instance on Redis Hosting.
Database hosting
MongoDB, PostgreSQL, MySQL and Redis next to your app
FAQs
Is Redis a database or just a cache?
Both. Redis is an in-memory data store that works as a cache, but it also has on-disk persistence and replication, so many teams use it as a primary database for simple, fast-access data.
Does Redis lose data when it restarts?
It depends on the configuration. With RDB or AOF enabled, Redis writes data to disk and reloads it on startup. Without persistence, everything in memory is lost on restart.
Is Redis free?
The Redis Open Source code is public and you can install it yourself. Starting with Redis 8 it is offered under RSALv2, SSPLv1 or AGPLv3, your choice. Running the server still costs memory and infrastructure.
What is the difference between Redis and Valkey?
Valkey is a BSD-licensed open source project backed by the Linux Foundation that includes BSD-licensed Redis code. They target the same kind of use, but check compatibility for the version and modules you need.
More in Databases
See all 24 articles- How much does database hosting cost?Cloud database hosting costs from zero to hundreds of dollars a month. See what sets the price: instance, disk, traffic, snapshots, and how to estimate yours.
- How to host a database for your appTo host a database, pick an engine, create the instance, store the connection string in an environment variable and test the connection. Step-by-step guide.
- What is PostgreSQL?PostgreSQL is an open source relational database that uses SQL and guarantees ACID transactions. Learn how it works, what it is for and when to pick another one.
- How to choose a database for your projectFor most projects, PostgreSQL or MySQL is enough. See when to pick MongoDB, Redis or SQLite instead, with clear criteria and a recommendation per scenario.