Chapter 9 · Lesson 7 of 8
Databases and data

Redis basics, persistence and security on a server

Redis is an in-memory key-value store that keeps data in RAM and saves it to disk with RDB snapshots, an append-only file or both, and it must be bound to localhost and password protected.

By the end you will

Run Redis safely with persistence, a password, a memory limit and an eviction policy that fits your use.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • An Ubuntu or Debian server with sudo, or Docker installed

Redis can save its memory to disk

Redis works in memory but can persist to disk with RDB snapshots, an AOF log of every write, or both, and it reloads them on restart.
  1. Writes land in memory first, and with RDB Redis saves a snapshot of the whole dataset to disk at set intervals.
  2. With AOF, every write command is appended to a log file.
  3. On restart, Redis replays the AOF to rebuild the data, and it prefers AOF when it is enabled.
  4. Without AOF, Redis loads the last RDB snapshot instead, and writes since then are lost.
Static diagram
  1. Redis memorysnapshotRDB snapshot
  2. Redis memoryappend writeAOF log
  3. AOF logreplay logRestart
  4. Restartdata backRedis memory

Redis keeps its data in memory and optionally saves it to disk, so you must choose how much loss you can accept and then secure it before anything else. Install it, check it with redis-cli ping, turn on persistence (RDB snapshots, an append-only file, or both), set a password, bind to localhost, and limit memory. Never expose port 6379 to the internet.

How it works#

Redis is a single-purpose server holding keys and values in RAM, which makes it very fast. Typical uses are caches, sessions, rate limit counters and job queues. Because the dataset lives in memory, two questions matter: what happens when the process stops, and what happens when memory runs out.

For the first question Redis has two persistence modes, and you can use both:

  • RDB writes a compact point-in-time snapshot (dump.rdb) when a rule such as save 3600 1 300 100 60 10000 fires, and on shutdown. Restarts load it quickly. A crash loses writes since the last snapshot.
  • AOF (append-only file) logs each write command. With appendfsync everysec the file is flushed to disk once a second, so a crash loses about one second. The file grows, and Redis rewrites it in the background to keep it small.

With both on, Redis loads the AOF at start because it is the more complete record. For a pure cache you can turn persistence off entirely.

For the second question there is maxmemory and a policy. Without maxmemory, Redis keeps growing until the kernel’s out-of-memory killer steps in (see fix out-of-memory kills).

Step 1: Install and test#

bash
sudo apt update
sudo apt install redis-server
sudo systemctl status redis-server
redis-cli ping

The reply PONG means the server answers. In Docker:

bash
docker run -d --name redis \
  -v redisdata:/data \
  -p 127.0.0.1:6379:6379 \
  redis:7 redis-server --appendonly yes --requirepass change-me

The image stores data in /data, so mount a named volume there. Replace change-me with a long random password. Binding the published port to 127.0.0.1 keeps it off the public interface, and the Docker publish lesson explains why this matters.

Step 2: Try the core commands#

output
SET greeting "hello"
GET greeting
EXPIRE greeting 60
TTL greeting
DEL greeting

EXPIRE sets a time to live in seconds, and TTL shows what is left, -1 for no expiry and -2 for a missing key. SET greeting hello EX 60 sets the value and expiry together. For listing keys use SCAN 0 MATCH user:* COUNT 100 rather than KEYS *, which blocks the server on big datasets.

Step 3: Configure persistence#

The config file on Debian and Ubuntu is /etc/redis/redis.conf. Edit it with sudo and set:

output
appendonly yes
appendfsync everysec
save 3600 1 300 100 60 10000

Then sudo systemctl restart redis-server. These three lines turn on both AOF and RDB. Check what the server uses with redis-cli CONFIG GET appendonly. Persistence files live in the directory set by dir, commonly /var/lib/redis. Back up that directory or copy dump.rdb while no rewrite is running, and test the restore as in test a backup by restoring it.

Step 4: Lock it down#

In redis.conf:

output
bind 127.0.0.1 -::1
protected-mode yes
requirepass change-me

bind restricts the interfaces, protected-mode yes refuses outside clients when there is no password, and requirepass makes every client send AUTH. Use a long random value and keep it in an environment variable or secret. Redis 6 and later also has ACL users, which let you give each app its own account with limited commands:

output
ACL SETUSER worker on >change-me-too ~jobs:* +get +set +lpush +rpop

That user can act only on keys starting with jobs: and use four commands. Connect with redis-cli --user worker --pass change-me-too and see the URL forms in database connection strings explained. Block 6379 in your firewall from the internet, and do not rely on the password alone.

Step 5: Limit memory#

output
maxmemory 256mb
maxmemory-policy allkeys-lru

Pick the size from the RAM you can spare after your other services. The policies you will use most:

PolicyBehavior when full
noevictionWrites fail with an error, reads continue. Right for queues and data you cannot lose.
allkeys-lruEvicts least recently used keys. Right for a cache.
volatile-lruEvicts only keys with an expiry. Keys with no TTL stay and can still fill memory.

Watch usage with redis-cli INFO memory and look at used_memory_human and maxmemory_human.

Check it worked#

  • redis-cli ping returns PONG (add -a or AUTH first once a password is set).
  • redis-cli CONFIG GET appendonly returns yes.
  • sudo ss -ltnp | grep 6379 shows 127.0.0.1:6379 only, not 0.0.0.0:6379.
  • From another machine, nc -vz 203.0.113.10 6379 fails.
  • After SET k v and a restart of the service, GET k still returns v.

Edge cases and gotchas#

  • FLUSHALL and FLUSHDB are destructive. FLUSHALL deletes every key in every database and FLUSHDB the current one. With persistence on, the empty state is written to disk, so restarting does not bring the data back. Never run them on a server you have not confirmed, and consider disabling them for apps with rename-command or ACL rules.
  • A password in the process list. redis-cli -a change-me can show up in ps and shell history. Set REDISCLI_AUTH or type AUTH inside the session.
  • Memory spikes during saves. A background save forks the process, and heavy writes during it can raise memory use. Leave headroom beyond maxmemory.
  • Disk-full persistence. If the disk fills, Redis may stop accepting writes with MISCONF.
  • Docker without a volume. The container’s filesystem disappears with the container, so unmounted /data means lost snapshots.
  • Eviction is silent. With allkeys-lru, important keys can be evicted. Use a separate instance for data you must keep.

Troubleshooting#

SymptomLikely causeFix
Could not connect to Redis at 127.0.0.1:6379: Connection refusedServer not runningsudo systemctl start redis-server and check logs
(error) NOAUTH Authentication required.requirepass set, no AUTH sentAUTH change-me or use REDISCLI_AUTH
(error) WRONGPASS invalid username-password pair or user is disabled.Wrong password or ACL userCheck the password and ACL LIST
(error) DENIED Redis is running in protected mode because protected mode is enabled and no password is set.Remote client, no passwordSet requirepass or connect locally
(error) OOM command not allowed when used memory > 'maxmemory'.noeviction and memory fullRaise maxmemory, or use an eviction policy for caches
(error) MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk.Disk full or no write access to dirFree space, fix permissions
Can't handle RDB format version in the logDump from a newer RedisStart a version at least as new
(error) ERR unknown command for an ACL userThe user lacks that commandAdd it with ACL SETUSER

Quick reference#

output
# redis.conf
bind 127.0.0.1 -::1
protected-mode yes
requirepass change-me
appendonly yes
appendfsync everysec
save 3600 1 300 100 60 10000
maxmemory 256mb
maxmemory-policy allkeys-lru
bash
redis-cli ping
redis-cli INFO memory
redis-cli CONFIG GET appendonly
redis-cli SET k v EX 60

Next#

Continue with database connection pooling and limits to stop apps from running a database out of connections.

Check what you learned4 questions
1You set appendonly yes and appendfsync everysec. What is the worst-case data loss after a crash?
2Redis is used as a cache and must never fail writes when full. Which policy fits?
3Which pair of settings keeps Redis from accepting remote connections by default?
4What does the command FLUSHALL do?

Frequently asked questions

What is the difference between RDB and AOF in Redis?

RDB saves point-in-time snapshots at intervals, which is compact and fast to load but can lose the writes since the last snapshot. AOF logs every write, so with appendfsync everysec you lose at most about a second.

Is Redis safe to expose to the internet?

No. Redis was designed for trusted networks, and an open instance is routinely taken over by scanners. Bind it to 127.0.0.1 or a private network, set a password, and block port 6379 in the firewall.

What does maxmemory-policy do?

When Redis reaches maxmemory, the policy decides what happens. noeviction rejects writes, allkeys-lru evicts the least recently used keys, and volatile-lru evicts only keys that have an expiry.

Does FLUSHALL delete data permanently?

Yes. It removes every key in every database, and with persistence on, the empty state is saved as well, so you cannot just restart to get the data back.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios