Skip to content
application · database · cache

Memory-speed data,Redis.

An open-source, in-memory data structure store that works as a database, cache, and message broker — microsecond reads with optional disk persistence. This guide runs Redis three ways: Docker Compose for local development, a Kubernetes StatefulSet for production, and the redis-cli for testing and debugging.

More than a key-value cache

Every Redis value is a native data structure with commands tuned to a specific access pattern — picking the right one is the single biggest Redis performance decision you will make.

  • Structures — strings, hashes, sets, sorted sets, streams.
  • Durability — RDB snapshots, AOF logs, or both together.
  • Safety — SCAN in production, never KEYS *.
6379Port
MicrosecondsLatency
RDB + AOFPersistence
8+ nativeStructures

Start here

Overview

Redis is an in-memory data structure store used as a cache, database, and message broker. It keeps data in RAM for microsecond reads and writes, with optional disk persistence (RDB snapshots and AOF logs) so data survives restarts. This guide runs Redis three ways — with Docker Compose for local development, on Kubernetes as a StatefulSet for production, and directly through the redis-cli for testing and debugging.

The meta-engine

Information

Redis, traditionally recognized as a high-performance in-memory data structure store, has evolved to serve as a versatile meta-engine for data object storage. Leveraging its lightning-fast data retrieval capabilities, Redis can manage metadata about larger data objects stored elsewhere, acting as a dynamic indexing layer. This allows applications to swiftly locate and access objects based on attributes or tags stored in Redis, bridging the gap between high-speed data access and bulk storage. When used in this capacity, Redis enhances storage architectures by providing rapid, real-time insights into vast data landscapes without compromising on efficiency or performance.

Pick the right shape

Core Data Structures

Redis is more than a key-value cache — each value can be one of several native data structures, each with commands optimized for a specific access pattern.

StructureDescriptionCommon Use
StringBinary-safe value up to 512 MBCache, counters (INCR), flags
HashField-value map under one keyStore an object (user profile) compactly
ListOrdered, linked listQueues, activity feeds (LPUSH/BRPOP)
SetUnordered unique membersTags, unique visitors, membership tests
Sorted SetMembers ranked by scoreLeaderboards, rate limiting, priority queues
StreamAppend-only log with consumer groupsEvent sourcing, message queues
Bitmap / HyperLogLogSpace-efficient countingDaily active users, cardinality estimates

Choosing the right structure is the single biggest Redis performance decision — a sorted set leaderboard answers “top 10” in O(log N) where a naive list would be O(N log N).

Surviving restarts

Persistence: RDB vs AOF

By default Redis holds data in RAM, but it offers two persistence modes so data survives restarts. They can run together.

  • RDB (snapshots) — Periodically forks and writes a compact point-in-time dump (dump.rdb). Fast restarts and small files, but you can lose everything since the last snapshot on a crash.
  • AOF (append-only file) — Logs every write command and replays it on restart. Far more durable (appendfsync everysec loses at most one second), at the cost of larger files and slightly slower writes.

Local development

Redis Docker Integration

Integrating Redis with Docker Compose empowers developers to create consistent, reproducible, and scalable Redis environments. Known for its exceptional speed and flexibility, Redis becomes even more effective when combined with Docker Compose. This pairing significantly boosts the operational resilience of applications and integrates smoothly into the broader application ecosystem.

The real transformation comes in how this integration redefines development workflows. With Docker Compose, developers can simulate production-like conditions on their local machines, eliminating the common discrepancies between development and production environments. This approach not only improves efficiency and precision during the development phase but also significantly boosts developers’ confidence. By testing and iterating in an environment that closely mirrors the final production setting, developers can ensure higher quality and reliability in their deployments.

A minimal docker-compose.yml runs a password-protected Redis with a persistent volume:

services:
redis:
image: redis:7-alpine
container_name: kilobase-redis
command: ["redis-server", "--requirepass", "redispassword", "--appendonly", "yes"]
ports:
- "6379:6379"
volumes:
- redis-data:/data
restart: unless-stopped
volumes:
redis-data:

Bring it up with docker compose up -d. The --appendonly yes flag enables AOF persistence so data survives container restarts, and the named redis-data volume keeps it across docker compose down.

Production deploys

Redis on Kubernetes

Deploying Redis on Kubernetes offers scalable and resilient solutions for managing in-memory data. Kubernetes, a powerful orchestration platform for containerized applications, enhances Redis’s capabilities, making it well-suited for high-demand environments that require rapid scalability and high availability.

  • Scalability: Kubernetes can automatically scale Redis instances based on traffic demands, ensuring that your application maintains high performance under varying load conditions.
  • High Availability: By running Redis on Kubernetes, you can take advantage of Kubernetes’ self-healing features such as automatic restarts of failed Redis pods to minimize downtime.
  • Simplified Management: Kubernetes simplifies the deployment and management of Redis clusters. Using Kubernetes’ services and deployments, you can easily manage complex Redis configurations and persistent storage.
  1. StatefulSet: Redis is typically deployed as a StatefulSet in Kubernetes. This ensures that each Redis instance retains a stable pod identity and storage across pod rescheduling and restarts.
  2. Persistent Volumes: To ensure data persistence, Redis pods are configured with persistent volumes that are managed by Kubernetes. This setup protects data even if Redis pods are restarted.
  3. ConfigMaps and Secrets: Redis configuration files and sensitive information such as passwords are managed using Kubernetes ConfigMaps and Secrets, ensuring secure and flexible configuration.
  4. Load Balancing: Kubernetes Services are used to load balance requests across Redis pods, improving the distribution of client traffic and enhancing overall performance.

Deploying Redis with Kubernetes not only improves operational efficiency but also leverages cutting-edge technology to support dynamic, large-scale applications.

A minimal StatefulSet with a headless Service and a per-pod persistent volume:

apiVersion: v1
kind: Service
metadata:
name: redis
spec:
clusterIP: None
selector:
app: redis
ports:
- port: 6379
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: redis
spec:
serviceName: redis
replicas: 1
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: redis:7-alpine
args: ["--appendonly", "yes"]
ports:
- containerPort: 6379
volumeMounts:
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi

The clusterIP: None headless Service gives each pod a stable DNS name (redis-0.redis), and volumeClaimTemplates provisions a dedicated PVC per replica so data survives rescheduling.


You can interact directly with your Redis instance using the redis-cli command-line tool — perfect for quick testing, debugging, or peeking under the hood.

Thus, to connect to a redis instance via the cli:

Terminal window
redis-cli -h <host> -p <port> -a <password>

Example would be like this:

Terminal window
redis-cli -h redis -p 6379 -a redispassword

Once connected, these cover most day-to-day operations:

Terminal window
SET user:1 "alice" # store a string
GET user:1 # read it back
EXPIRE user:1 3600 # auto-delete after 1 hour
TTL user:1 # seconds remaining
HSET user:2 name bob age 30 # store a hash
HGETALL user:2 # read the whole hash
INCR page:views # atomic counter
ZADD board 100 alice # sorted set for leaderboards
ZREVRANGE board 0 9 WITHSCORES # top 10
KEYS * # list keys (avoid in production)
SCAN 0 MATCH user:* # cursor-based, production-safe
INFO memory # memory + stats

Questions

Frequently asked

Is Redis a database or a cache?

Both. Redis is an in-memory data structure store that can act as a primary database, a cache in front of a slower store, or a message broker. Persistence options (RDB snapshots and AOF logs) let it survive restarts when used as a database.

How do I run Redis with Docker Compose?

Define a redis service using the official redis image, expose port 6379, pass a password with --requirepass, and mount a named volume at /data for persistence. Then run docker compose up -d.

Why deploy Redis as a StatefulSet on Kubernetes?

A StatefulSet gives each Redis pod a stable network identity and persistent volume that survive rescheduling. This is required for data durability and for replication, where replicas must reliably find the primary.

How do I connect to a Redis instance from the command line?

Use redis-cli -h <host> -p <port> -a <password>. Inside Docker, exec into the container first, for example docker exec -it kilobase-redis redis-cli -a redispassword.

What is the difference between RDB and AOF persistence in Redis?

RDB writes periodic point-in-time snapshots — compact and fast to restore, but you can lose data since the last snapshot. AOF logs every write command and replays it on restart, giving far better durability at the cost of larger files. They can be enabled together.

Which Redis data structure should I use for a leaderboard?

A sorted set (ZSET). Members are ranked by a score, so ZADD updates a player's score and ZREVRANGE returns the top N in O(log N) time — far more efficient than sorting a list on every read.

Why should I avoid KEYS in production Redis?

KEYS scans the entire keyspace and blocks the single-threaded server until it finishes, stalling all other clients. Use SCAN instead, which returns keys in small cursor-based batches without blocking.

Does Redis lose data when it restarts?

Only if persistence is disabled. With RDB snapshots or AOF enabled (and a mounted volume in Docker or Kubernetes), Redis reloads its dataset on startup. A pure in-memory cache with no persistence starts empty after a restart.