Databases
The in-memory data store from first SET to persistence, replication, clustering and operations.
A path through Redis for backend developers: core data types and their commands, atomicity, pipelining, transactions and Lua, then persistence, security, replication, Sentinel, Cluster and day-to-day operations. Each subject links the official documentation.
The subjects follow the roadmap.sh Redis roadmap.
Redis is a single-threaded (for command execution), in-memory server that stores keys pointing at typed values — strings, hashes, lists, sets, sorted sets, streams and more — and answers in well under a millisecond. It is used as a cache, a primary store for hot data, a message bus and a coordination tool. Know its trade-offs: data must fit in RAM, and durability is configurable rather than guaranteed.
Values are real data structures held in RAM and manipulated server-side by dedicated commands (LPUSH, ZINCRBY, SINTER), so you change data in place instead of reading, modifying and writing back blobs.
Every piece of data lives under a binary-safe key in a flat keyspace. Lookups by key are O(1); there are no secondary indexes or joins unless you build them yourself or use the query engine.
The most common role: keep hot results in Redis with a TTL in front of a slower database or API, and configure an eviction policy so memory pressure drops cold keys instead of failing writes.
Pub/Sub for fire-and-forget fan-out, lists for simple work queues with blocking pops, and streams for durable, replayable logs with consumer groups and acknowledgements.
Relational databases give you ad-hoc queries, joins and disk-first durability; document stores give flexible queries over large datasets. Redis trades those for raw speed and rich in-memory structures, which is why it usually sits beside a primary database rather than replacing it.
Pick it when the working set fits in memory and you need microsecond-level latency: caching, sessions, rate limiting, counters, queues and leaderboards. Avoid it as the only home for data you cannot afford to lose or that outgrows RAM.
Most Redis deployments do one of a handful of jobs. Each maps onto a data type and a few commands, so learning the patterns is the fastest way to see why the data types exist.
Cache-aside is the usual pattern: read from Redis, on a miss load from the database and SET key value EX 300. Watch for stampedes on hot keys and stale data after writes; invalidate or use short TTLs.
Counters with INCR, unique visitors with HyperLogLog, activity flags with bitmaps and event logs with streams give live dashboards without hammering the main database.
Store each web session as a hash keyed by session ID with an expiry that is refreshed on activity. Every app server sees the same sessions, so you can scale out without sticky load balancing.
Broadcast events such as chat messages or cache-invalidation notices to every connected subscriber. Delivery is at-most-once: offline subscribers miss messages, so use streams when you need durability.
Sorted sets keep players ordered by score with ZINCRBY and return rank or top-N in logarithmic time; atomic INCR/INCRBY handles page views, quotas and rate limits.
Three properties explain why Redis is everywhere: data structures that go far beyond plain key-value, very high throughput from an in-memory event loop, and optional persistence plus replication for when the data must survive restarts.
Point-in-time RDB snapshots, an append-only log of writes (AOF), both together, or neither for a pure cache. The choice sets how much data a crash can lose and how fast restarts are.
Strings, hashes, lists, sets, sorted sets, bitmaps, HyperLogLog, geospatial indexes, streams, and in Redis 8 JSON, time series, vector sets and probabilistic types, each with commands tuned to it.
One instance can serve on the order of 100k+ simple operations per second; pipelining raises that further. Replicas scale reads and Redis Cluster shards the keyspace across nodes to scale writes and memory.
Get a server on your machine to experiment with. Packages and containers are quickest; building from source gives you the newest release and optional features like TLS.
brew install redis on macOS, or the official packages.redis.io APT/RPM repository on Linux, which is newer than most distro defaults. On Windows, use WSL or Docker.
Build from the source tarball with make (add BUILD_TLS=yes for TLS) and you get redis-server, redis-cli, redis-benchmark and the check tools ready to run without installing anything system-wide.
docker run -d -p 6379:6379 redis starts a server in seconds. Mount a volume on /data and pass a config or --appendonly yes if you want data to survive the container.
Start a server, connect with the CLI and issue your first commands. Redis speaks a simple text protocol (RESP), so the CLI is just a thin client over the same commands your application will send.
redis-server with no arguments uses defaults on port 6379; redis-server /path/redis.conf or flags like --port 6380 --save "" override them. Under systemd it runs as a service.
redis-cli -h host -p port -a password opens an interactive prompt with hints and history. Useful flags: --tls, -n db, --scan --pattern, --bigkeys and --latency.
Start with PING, SET greeting hello, GET greeting, EXISTS, TYPE and DEL. Every command returns a typed reply, and nil means the key does not exist.
Operations that work on any key regardless of type: creating, reading, checking and removing keys. Commands are type-checked — calling a list command on a string key returns a WRONGTYPE error.
Writing a key creates it, and most type-specific commands create the key on first use. EXISTS checks presence, TYPE tells you what is stored and RENAME moves a value to a new name.
DEL k1 k2 … removes keys and returns how many existed. Deleting a huge collection blocks the server while memory is freed; UNLINK does the reclaiming in a background thread.
A key holds exactly one type for its whole life. Choose by access pattern: strings for blobs and counters, hashes for objects, lists for queues, sets for membership, sorted sets for ranking.
The simplest type: a binary-safe byte sequence up to 512 MB, which may hold text, serialized JSON, an image or an integer. Beyond the basics there are MSET/MGET, GETDEL, GETEX, INCRBY, INCRBYFLOAT, GETRANGE and SETRANGE.
Stores a value, replacing whatever was there and clearing any TTL. Options make it atomic and versatile: EX/PX for expiry, NX to only create, XX to only update, KEEPTTL and GET to return the old value.
Returns the string at a key or nil if missing. It errors on non-string types, so check with TYPE if a key might hold something else.
Atomically adds one to an integer string, treating a missing key as 0, and returns the new value. Ideal for counters and ID generation without race conditions; it errors on non-integer values.
The atomic decrement, with DECRBY for larger steps. Values are signed 64-bit, so a counter can go negative unless you guard it with a script.
Adds bytes to the end of a string (creating it if needed) and returns the new length — handy for compact append-only logs or building time-series samples in one key.
Returns the length in bytes, not characters, of the stored string; 0 for a missing key. Multi-byte UTF-8 text will report more than its visible length.
Keeping a keyspace sane as it grows: predictable names, safe ways to find keys, and expiries so stale data cleans itself up.
Use colon-separated namespaces like user:1001:profile. Keep names readable but short, since every byte is stored per key, and put the entity ID where cluster hash tags can group related keys.
KEYS user:* walks the whole keyspace and blocks the server — never run it in production. Use cursor-based SCAN 0 MATCH user:* COUNT 100 and loop until the cursor returns to 0.
Keys with a TTL are removed lazily when accessed and by a periodic background sampler. Overwriting a key with SET clears its TTL, while modifying it in place (INCR, LPUSH) keeps it.
EXPIRE key seconds (or PEXPIRE, EXPIREAT) sets a time to live; NX, XX, GT and LT flags control when it applies. PERSIST removes the expiry again.
Returns remaining seconds to live (PTTL for milliseconds). -1 means the key exists without an expiry and -2 means it does not exist.
A hash maps field names to string values under one key — a natural fit for objects like a user profile. Small hashes use a compact encoding, making them memory-efficient; other commands include HINCRBY, HMGET, HLEN, HSCAN and, since 7.4, per-field expiry with HEXPIRE.
HSET user:1 name Ada age 36 sets one or many fields and returns how many were new. It replaces the older HMSET.
Reads a single field from a hash, returning nil if the field or key is missing; use HMGET to fetch several fields in one round trip.
Returns every field and value. Fine for small objects, but it is O(n) — iterate large hashes with HSCAN instead of blocking the server.
Removes one or more fields and returns the count removed. When the last field goes, the key itself disappears.
Returns 1 if a field exists in the hash, 0 otherwise — cheaper than fetching the value when you only need presence.
Linked sequences of strings with fast pushes and pops at both ends, used for queues, stacks and recent-activity feeds. Blocking variants (BLPOP, BLMOVE) let workers wait for jobs, and LTRIM caps a list to a fixed size.
Inserts one or more values at the head and returns the new length. Pushing several at once inserts them one after another, so they end up in reverse order.
Appends to the tail. RPUSH plus LPOP gives a FIFO queue; RPUSH plus RPOP gives a stack.
Removes and returns the head element, or several with a count argument. BLPOP waits with a timeout when the list is empty, which is how simple job workers block.
Removes and returns from the tail. Popping removes the job before it is processed, so for reliable queues move it to a processing list with LMOVE instead.
Returns elements between two inclusive indexes, where negative numbers count from the end: LRANGE feed 0 9 is the latest ten, 0 -1 is everything.
Fetches one element by index. It walks the list, so it is O(n) in the middle — lists are for ends, not random access.
Returns the length in constant time, 0 for a missing key — a quick way to monitor queue backlog.
Atomically pops from one list and pushes to another, choosing LEFT/RIGHT for each side. It is the basis of reliable queues and replaces the deprecated RPOPLPUSH.
Unordered collections of unique strings with O(1) membership checks and server-side set algebra. Use them for tags, unique visitors, permissions and relationships; SPOP, SRANDMEMBER and SSCAN round out the toolkit.
Adds members and returns how many were actually new; duplicates are silently ignored, which makes it a natural deduplication tool.
Returns every member in no particular order. On large sets it blocks the server — iterate with SSCAN instead.
Removes the given members and returns how many were present. An emptied set is deleted automatically.
Constant-time membership test returning 1 or 0; SMISMEMBER checks several members in a single call.
Returns members present in all given sets, for example users who follow both accounts. SINTERSTORE saves the result and SINTERCARD only counts it.
Returns the number of members in constant time. For approximate counts of huge sets, HyperLogLog uses a tiny fraction of the memory.
Returns every member found in any of the given sets; SUNIONSTORE writes the union into a destination key.
Returns members of the first set that appear in none of the others — for example items a user has not seen yet. SDIFFSTORE saves the result.
Unique members each paired with a floating-point score and kept ordered by it, built on a skip list plus a hash table. They power leaderboards, priority queues, time-ordered indexes and sliding-window rate limiters; see also ZREVRANK, ZPOPMIN, ZRANGESTORE and ZREMRANGEBYSCORE.
ZADD board 120 alice adds or updates members with scores. Flags: NX/XX for create-only or update-only, GT/LT to only raise or lower a score, and CH to count changed members.
Since Redis 6.2 one command covers rank, score and lexicographic ranges via BYSCORE, BYLEX, REV and LIMIT; add WITHSCORES to get scores back.
Returns members whose scores fall between min and max, with ( for exclusive bounds and -inf/+inf. It is deprecated in favour of ZRANGE … BYSCORE but still common in existing code.
Removes the named members and returns how many were present; ZREMRANGEBYSCORE drops a whole score range, such as entries older than a timestamp.
Atomically adds to a member's score, creating it at the increment if absent, and returns the new score — the one-liner behind live leaderboards.
Returns a member's zero-based position counting from the lowest score; ZREVRANK counts from the highest, which is what leaderboards usually display.
Counts members with scores in a range in logarithmic time without returning them, for example events in the last hour when scores are timestamps.
Commands run one at a time on the main thread, so every single command is atomic — no other client sees a half-applied INCR or LMOVE. For several steps that must be indivisible you use MULTI/EXEC, Lua scripts or functions; a plain sequence of commands from one client can interleave with others.
Send many commands without waiting for each reply, then read the replies together. It removes round-trip latency and system-call overhead and can multiply throughput, but it is not atomic — other clients' commands may run in between. Keep batches to a few thousand commands to bound memory.
Doing more per round trip: variadic commands like MSET, MGET, HSET with many fields and SADD with many members, plus pipelines, transactions and scripts. In a cluster, multi-key commands only work when all keys hash to the same slot.
Not a separate type but bit-level commands on strings: each offset is one bit, so a million users' daily-active flags take about 125 KB. Use them for feature flags, attendance and presence tracking where IDs are dense integers.
Sets the bit at an offset to 0 or 1 and returns its previous value. The string grows to fit, so a single very large offset allocates a lot of memory at once.
Returns the bit at an offset; offsets beyond the end of the string, or a missing key, read as 0.
Counts set bits, optionally within a byte or (since 7.0) bit range — for example how many users were active today.
Combines bitmaps with AND, OR, XOR or NOT into a destination key, such as users active on every day of a week. It is O(n) in the string length.
Finds the first bit set to 0 or 1, optionally within a range — handy for allocating the first free slot or finding the first active ID.
A probabilistic structure that estimates the number of distinct elements using at most about 12 KB per key, with a standard error under 1%. You cannot list members, only count them — perfect for unique visitors or search terms at scale.
Adds elements to the estimator and returns 1 if the internal registers changed, meaning the approximate cardinality probably grew.
Returns the estimated distinct count. Given several keys it estimates the size of their union on the fly without modifying them.
Merges several HyperLogLogs into a destination key, for example rolling daily unique-visitor counters up into a weekly one.
An append-only log of entries, each a small field-value map with a time-based ID. Unlike Pub/Sub, entries persist and can be re-read; consumer groups (XGROUP, XREADGROUP, XACK, XPENDING, XAUTOCLAIM) split work across consumers and track what was processed.
XADD events * type click page /home appends an entry with an auto-generated ID of millisecond time and sequence. Add MAXLEN ~ 10000 to trim old entries as you write.
Reads entries between two IDs, with - and + as the extremes and COUNT for paging; XREVRANGE reads newest-first.
Reads entries after a given ID from one or more streams; with BLOCK ms and the $ ID it waits for new entries, acting like a tail -f.
Returns the number of entries in a stream in constant time, useful for monitoring growth and checking trimming works.
Locations stored as geohash-encoded scores in a sorted set, queried by radius or bounding box. Good for "nearby drivers" or store locators; GEODIST, GEOPOS and GEOHASH cover distances and coordinates.
Adds members at a position — longitude first, then latitude, a common source of bugs. Supports NX, XX and CH like ZADD.
Finds members within a radius (BYRADIUS) or box (BYBOX) around a member or coordinate, optionally sorted by distance with ASC and limited by COUNT. It supersedes GEORADIUS.
Publishers send messages to named channels and every currently subscribed client receives them. Nothing is stored, so there is no replay or acknowledgement; PSUBSCRIBE matches channel patterns and, since 7.0, sharded Pub/Sub (SPUBLISH) scales better in a cluster.
Puts the connection into subscriber mode on one or more channels. Under RESP2 that connection can then only run subscription commands, so clients use a dedicated connection for it.
Leaves the named channels, or all of them when called without arguments; PUNSUBSCRIBE does the same for pattern subscriptions.
Sends a message to a channel and returns how many clients received it. A return of 0 means the message was simply dropped.
A transaction queues commands after MULTI and runs them all in sequence on EXEC with no other client interleaving. There is no rollback: if one command fails at runtime the others still apply, so validate inputs first. DISCARD abandons the queue.
Starts a transaction; subsequent commands reply QUEUED instead of running. Syntax errors at queue time make the whole EXEC fail.
Runs the queued commands atomically and returns an array of their replies, or a null reply if a watched key changed and the transaction was aborted.
Marks keys before MULTI; if any of them change before EXEC, the transaction is aborted. UNWATCH clears the watch list.
The check-and-set pattern: WATCH a key, read it, compute, then MULTI … EXEC; on a null reply, retry. It works well under low contention — for heavy contention a Lua script is simpler.
Run Lua inside the server with redis.call() so read-modify-write logic happens atomically in one round trip. Scripts block everything else while running, so keep them short, and pass every key through KEYS for cluster compatibility. Redis 7 functions (FUNCTION LOAD, FCALL) are the managed successor.
EVAL script numkeys key… arg… runs a script with keys in KEYS[] and arguments in ARGV[]. Never build script text from user input; pass values as arguments.
Runs a cached script by its SHA1 digest after SCRIPT LOAD, saving bandwidth. On a NOSCRIPT error (after a restart or failover) the client falls back to EVAL.
Redis lives in memory but can write to disk so data survives restarts. You choose between snapshots, a write log, both, or nothing, trading durability against write overhead, disk use and restart time.
With save "" and appendonly no Redis is a pure in-memory cache: fastest, but every restart starts empty. Beware replicas of a non-persistent master — a restarted empty master can wipe them.
RDB files are compact and load fast but lose everything since the last snapshot; AOF with everysec loses about a second at most but is larger and slower to replay. Many setups enable both.
With aof-use-rdb-preamble yes (the default) an AOF rewrite writes an RDB snapshot as its base followed by incremental commands, giving fast loads and fine-grained durability together.
RDB writes a compact binary dump of the whole dataset at a point in time. It is ideal for backups and fast restarts, at the cost of losing writes made after the most recent snapshot.
BGSAVE forks a child that writes the dataset to a temporary file and renames it to dump.rdb, while copy-on-write lets the parent keep serving. Write-heavy instances need spare RAM for copied pages.
save <seconds> <changes> rules trigger snapshots, e.g. save 300 100 snapshots after 5 minutes if at least 100 keys changed. Multiple rules combine; save "" disables automatic snapshots.
Use RDB for periodic backups and quick restarts when losing minutes of writes is acceptable. Copy snapshots off the host, watch fork time in INFO persistence, and leave headroom for copy-on-write.
AOF logs every write command so the dataset can be rebuilt by replaying it. It narrows the data-loss window to your fsync policy at the cost of bigger files and periodic rewrites.
With appendonly yes, writes are appended and flushed according to appendfsync: always (safest, slowest), everysec (the default balance) or no (leave it to the OS). Since 7.0 the AOF is a set of base and incremental files tracked by a manifest.
The log keeps growing, so Redis rewrites it in the background into the minimal set of commands for the current data. It triggers via auto-aof-rewrite-percentage and auto-aof-rewrite-min-size, or manually with BGREWRITEAOF.
A crash mid-write can leave a partial last command; with aof-load-truncated yes Redis discards it and starts. Real corruption in the middle needs redis-check-aof --fix — back the file up first.
Out of the box anyone who can reach the port can run any command. Set requirepass for a single shared password, or better, use ACLs (Redis 6+) to create named users limited to specific commands and key patterns, and disable or restrict the default user.
Redis is built to be reached only by trusted clients. Bind to private interfaces, keep protected-mode on, firewall port 6379, never expose it to the internet, and block dangerous commands like FLUSHALL, CONFIG and DEBUG through ACLs.
Since Redis 6, TLS can encrypt client, replication and cluster-bus traffic. Build with BUILD_TLS=yes, then configure tls-port, tls-cert-file, tls-key-file and tls-ca-cert-file; set port 0 to turn off plaintext. Expect some CPU overhead and connect with redis-cli --tls.
A replica runs REPLICAOF host port, receives a full snapshot, then streams the master's writes asynchronously. Replicas are read-only by default and reconnect with partial resync from the replication backlog; WAIT lets a client block until writes reach N replicas, though it still is not strong consistency.
Sentinel provides high availability for non-clustered Redis: a group of Sentinel processes monitors a master, agrees by quorum that it is down, promotes a replica and tells clients the new address. Run at least three Sentinels on independent hosts and use Sentinel-aware clients.
Redis Cluster shards keys over 16,384 hash slots spread across masters, each with replicas for automatic failover. Clients follow MOVED/ASK redirects; multi-key operations need all keys in one slot, which {hash tags} arrange. Only database 0 exists in cluster mode.
Most Redis performance problems come from memory pressure, big keys and slow O(n) commands rather than the server itself. Measure with INFO, SLOWLOG and redis-cli --bigkeys before tuning.
Check INFO memory and MEMORY USAGE key, watch fragmentation ratio, and prefer small hashes and sets that fit compact encodings. Set maxmemory so Redis never pushes the host into swap.
When maxmemory is reached, maxmemory-policy decides what happens: noeviction rejects writes, allkeys-lru/allkeys-lfu suit caches, and volatile-* policies only evict keys with a TTL.
The slow log records commands whose execution exceeded slowlog-log-slower-than microseconds. Read it with SLOWLOG GET to find KEYS, huge HGETALLs or heavy scripts; network time is not included.
Redis ships with everything needed for first-line diagnosis: introspection commands, a live command tap and a load generator.
Returns server stats by section — memory, clients, persistence, stats, replication, keyspace and more. Hit ratio, connected clients and replication lag all come from here.
Streams every command the server processes in real time. Great for debugging what a client actually sends, but it can sharply cut throughput — never leave it running in production.
Generates load with -c clients, -n requests, -P pipeline depth and -t to pick commands. Benchmark with realistic payload sizes and from a separate host to get meaningful numbers.
Graphical browsers and metric exporters make day-to-day work and long-term monitoring easier than the CLI alone.
Redis's free desktop and web GUI: browse keys by type, run commands with a workbench, analyse memory and the slow log, and profile live traffic.
A lightweight open-source web UI written in Node.js for viewing and editing keys, easy to run as a Docker container next to a development Redis.
Track latency, memory, evictions, hit ratio, connections and replication lag over time. The common stack is redis_exporter feeding Prometheus with Grafana dashboards and alerts.
Modules are shared libraries loaded with loadmodule or MODULE LOAD that add new types and commands. Since Redis 8 the main ones — JSON, the query engine, time series and probabilistic structures — ship built into Redis Open Source.
A native JSON type: JSON.SET doc $ '{…}' and JSON.GET doc $.path read and update nested fields with JSONPath, without rewriting the whole document.
The query engine indexes hashes and JSON with FT.CREATE and answers full-text, numeric, tag, geo and vector similarity queries plus aggregations through FT.SEARCH and FT.AGGREGATE.
A time-series type with TS.ADD and TS.RANGE, retention periods, labels for filtering and compaction rules that downsample raw data into aggregates automatically.
Probabilistic structures — Bloom and cuckoo filters, count-min sketch, top-k and t-digest — answering "seen before?" or "how frequent?" in a fraction of the memory of exact sets.
The configuration file holds every server setting: network, security, persistence, memory limits, replication and more. Most settings can be read and changed live with CONFIG GET / CONFIG SET, and CONFIG REWRITE writes those changes back into the file so they survive a restart.
Read the release notes for breaking changes, then upgrade with minimal downtime by starting the new version as a replica, letting it sync, and promoting it (or failing over with Sentinel or a cluster). Newer versions read older RDB files, but not the other way round, so test rollback plans.
The RDB file is a ready-made backup: it is written to a temp file and renamed atomically, so copying it while Redis runs is safe. Schedule copies off the host with timestamps and retention, and restore by placing the file in the data directory before starting Redis.
Plan for losing a whole host or region: encrypted backups stored in another location, replicas in a different zone, documented failover steps, and regular restore drills that measure your real recovery time and data loss.
Redis Ltd.'s commercial offering, now sold as Redis Software (self-managed) and Redis Cloud. It adds a cluster manager with automatic sharding and failover, multi-region replication, tiered storage and enterprise security on top of the open-source engine.
Several clusters in different regions all accept writes and converge using CRDT-based conflict resolution, giving local latency for global users and survival of a full region outage.
Now called Auto Tiering: keys and hot values stay in RAM while colder values move to NVMe SSDs, cutting cost for large datasets with skewed access patterns.
Role-based access control, LDAP integration, TLS everywhere, encryption at rest and audit logging, for organisations with regulatory requirements.
When you need multi-region writes, very large datasets on tiered storage, a vendor SLA and support, or simply do not want to run Sentinel or Cluster yourself.