# 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.

URL: https://levelrail.com/learn/databases/redis-basics-persistence-and-security/
Updated: 2026-11-27

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](https://levelrail.com/learn/troubleshooting/fix-out-of-memory-kills-oom/))).

## 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](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/docker/publish-container-ports-safely/)) explains why this matters.

## Step 2: Try the core commands

```
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:

```
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](https://levelrail.com/learn/deploy-operate/test-a-backup-by-restoring-it/)).

## Step 4: Lock it down

In `redis.conf`:

```
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](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)). Redis 6 and later also has ACL users, which let you give each app its own account with limited commands:

```
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](https://levelrail.com/learn/databases/database-connection-strings-explained/)). Block 6379 in your [firewall](https://levelrail.com/learn/glossary/#firewall)) from the internet, and do not rely on the password alone.

## Step 5: Limit memory

```
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:

| Policy | Behavior when full |
| --- | --- |
| `noeviction` | Writes fail with an error, reads continue. Right for queues and data you cannot lose. |
| `allkeys-lru` | Evicts least recently used keys. Right for a cache. |
| `volatile-lru` | Evicts 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

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `Could not connect to Redis at 127.0.0.1:6379: Connection refused` | Server not running | `sudo systemctl start redis-server` and check logs |
| `(error) NOAUTH Authentication required.` | `requirepass` set, no AUTH sent | `AUTH change-me` or use `REDISCLI_AUTH` |
| `(error) WRONGPASS invalid username-password pair or user is disabled.` | Wrong password or ACL user | Check 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 password | Set `requirepass` or connect locally |
| `(error) OOM command not allowed when used memory > 'maxmemory'.` | `noeviction` and memory full | Raise `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 `dir` | Free space, fix permissions |
| `Can't handle RDB format version` in the log | Dump from a newer Redis | Start a version at least as new |
| `(error) ERR unknown command` for an ACL user | The user lacks that command | Add it with `ACL SETUSER` |

## Quick reference

```
# 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
```

## Related lessons

- [Database connection strings explained](https://levelrail.com/learn/databases/database-connection-strings-explained/)): the redis:// and rediss:// URL forms.
- [Publish container ports safely](https://levelrail.com/learn/docker/publish-container-ports-safely/)): keep Docker from exposing 6379.
- [Set up a firewall with ufw](https://levelrail.com/learn/server-basics/set-up-a-firewall-with-ufw/)): block the port from outside.
- [Fix out-of-memory kills](https://levelrail.com/learn/troubleshooting/fix-out-of-memory-kills-oom/)): what happens without maxmemory.
- [Manage secrets for self-hosted Docker apps](https://levelrail.com/blog/manage-secrets-self-hosted-docker/)): store the Redis password properly.

## Next

Continue with [database connection pooling and limits](https://levelrail.com/learn/databases/database-connection-pooling-and-limits/)) to stop apps from running a database out of connections.

## 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

- [Redis persistence](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/)
