Redis

On this page 7

Redis is an open-source in-memory key-value data store that keeps its entire dataset in RAM and serves reads and writes with sub-millisecond latency in typical deployments. Among database systems, Redis belongs to the NoSQL family, but unlike a simple cache it offers rich data structures such as lists, hashes, sets, sorted sets and streams, each with atomic server-side operations.

Redis is most often used alongside a primary database such as PostgreSQL, MySQL or MongoDB rather than instead of one. It serves as a cache, a session store, a message broker, a rate limiter and a source of real-time leaderboards. Optional persistence and replication let it hold data that must survive restarts, although its durability model differs from that of a disk-based relational database.

How Redis processes commands

Redis executes commands on a single main thread using an event loop. Because only one command runs at a time, every individual command is atomic without locks, and operations such as incrementing a counter or pushing to a list cannot interleave with other clients.

This design is fast because data lives in memory and most commands have constant or logarithmic complexity. Since version 6, Redis can use I/O threads for network reading and writing, while command execution stays single-threaded. The flip side is that one slow command, such as KEYS * on millions of keys, blocks every other client until it finishes.

Clients communicate through the text-based RESP protocol, usually on TCP port 6379. Multiple commands can be sent in a pipeline to save network round trips, grouped in a MULTI/EXEC transaction, or bundled in a Lua script or function that runs atomically on the server.

Data structures and their typical uses

The defining feature of Redis is that values are typed data structures, not opaque blobs. Choosing the right structure usually matters more for performance and memory than any configuration setting.

Data typeWhat it storesTypical useKey commands
StringBytes up to 512 MBCache entries, counters, flagsGET, SET, INCR
HashField-value mapUser profiles, object attributesHSET, HGETALL
ListOrdered sequenceSimple queues, recent itemsLPUSH, BRPOP
SetUnique unordered membersTags, unique visitors per daySADD, SINTER
Sorted setMembers ordered by scoreLeaderboards, rate limits, schedulingZADD, ZRANGE
StreamAppend-only log with IDsEvent processing with consumer groupsXADD, XREADGROUP
Core Redis data types

Specialized types extend this set: bitmaps for compact flags, HyperLogLog for approximate unique counts in about 12 KB per key with roughly 0.81 percent standard error, and geospatial indexes for radius queries. Any key can also carry a time to live (TTL), after which Redis deletes it automatically.

Persistence, replication and scaling

Redis offers two persistence mechanisms that can be combined. The choice determines how much data can be lost after a crash and how quickly the server restarts.

OptionHow it worksPossible data lossTrade-off
RDB snapshotsPeriodic point-in-time dump to diskMinutes since the last snapshotCompact files, fast restarts
AOF with fsync every secondLogs each write commandAbout one secondCommon balance of safety and speed
AOF with fsync alwaysSyncs every write to diskMinimalMuch lower write throughput
No persistenceMemory onlyEverything on restartPure cache use
Redis persistence options

For availability, Redis uses asynchronous primary-replica replication. Redis Sentinel monitors primaries and promotes a replica on failure. Redis Cluster shards data across nodes using 16,384 hash slots, so a dataset can exceed the memory of one machine. Because replication is asynchronous, a failover can lose writes that were acknowledged but not yet replicated.

Redis compared with other database systems

Redis complements rather than replaces general-purpose databases. The comparison below places it next to neighboring systems in the topic.

SystemData modelPrimary storageBest fit
RedisKey-value with data structuresMemory, optional diskCaching and real-time state
PostgreSQLRelational with SQLDiskTransactional system of record
MySQL and MariaDBRelational with SQLDiskWeb applications and OLTP
MongoDBDocumentDisk with memory cacheFlexible JSON-like records
SQLiteRelational, embeddedSingle local fileLocal and embedded storage
Redis and related database systems

Redis has no query language for ad hoc searches over values in its core model; data must be accessed by key, so key design replaces query design. Licensing has also changed: in 2024 Redis moved away from the BSD license, which led to the Valkey fork under the Linux Foundation, and later versions added an AGPL option. Teams should verify the license terms of the version they deploy.

Operating Redis well

Most Redis incidents come from memory limits, blocking commands and unsafe exposure. The table lists common symptoms, their causes and the usual fixes.

SymptomLikely causeFix
Writes rejected with OOM errorsmaxmemory reached with noevictionSet an eviction policy such as allkeys-lru
Latency spikes for all clientsSlow commands like KEYS or huge HGETALLUse SCAN and smaller structures
Latency spikes during snapshotsFork and copy-on-write on a large datasetLeave memory headroom; tune persistence
Data loss after failoverAsynchronous replication lagAccept the risk or use WAIT for critical writes
Unauthorized accessServer exposed without authenticationBind privately, enable ACLs and TLS
Common Redis problems and fixes

A sound baseline is to set maxmemory explicitly, keep roughly a quarter to a half of RAM free when persistence uses forking, avoid very large keys above a few megabytes, and monitor the slow log. Redis should never be the only copy of data that the business cannot rebuild.

In simple terms

Redis is like a very fast notepad kept in a computer’s memory. A main database is like a large filing cabinet: complete and safe, but slower to search. Redis keeps the most needed information within arm’s reach.

Applications use it to remember things for a short time. Examples are who is logged in, how many times someone tried a password, or the current top scores in a game. Its strength is speed, measured in fractions of a millisecond. Its limit is that memory is smaller and more expensive than disk.

A practical example

An online ticket shop expects heavy traffic when a popular concert goes on sale. Its product pages normally query PostgreSQL, which can handle a few thousand requests per second before slowing down. The team places Redis as a cache in front of the database: each event page is stored with a TTL of 30 seconds, so the database rebuilds it at most twice a minute.

The team also uses a sorted set as a sliding-window rate limiter that allows each client ten checkout attempts per minute, and an atomic DECR on a counter to track remaining seats. During the sale, most page requests are answered from memory, database load stays stable, and bots that flood the checkout are slowed automatically without affecting regular buyers.