Kingsfordweg 151, 1043GR Amsterdam, The Netherlands ● 24/7 support — support@novogara.com
Knowledge base

Redis and caching

Redis is the fastest way to make an application faster and one of the easiest things to leave dangerously exposed.

Bind it, now

An open Redis with no password is a complete server compromise: an attacker can write files as the Redis user, which has been used to install SSH keys and crypto miners for years. Scanners find them within minutes.

bind 127.0.0.1 10.0.0.2
protected-mode yes
requirepass <a long random password>

Only on an address your application can reach — localhost, or a private network as connecting your own servers describes. Then firewall it as well. Rename or disable CONFIG, FLUSHALL and DEBUG if nothing of yours uses them.

Set a memory limit and an eviction policy

By default Redis grows until the machine runs out and the OOM killer arrives — see swap and the OOM killer. Decide instead:

maxmemory 4gb
maxmemory-policy allkeys-lru

allkeys-lru
Evict the least recently used key when full. The right policy for a pure cache.
volatile-lru
Only evict keys that have a TTL. Use when Redis also holds data that must not disappear.
noeviction
Return errors instead of evicting. Correct for a queue or a session store where losing data silently is worse than failing loudly.

Persistence: decide deliberately

RDB snapshots are cheap and lose everything since the last one. AOF logs every write and loses almost nothing but costs IO. For a cache, turn both off — it is a cache. For sessions or a queue, use AOF with appendfsync everysec.

Set vm.overcommit_memory=1, or background saving fails on a busy instance at exactly the wrong moment.

What to cache first

In order of return:

  1. Expensive query results that are read far more often than they change
  2. Rendered fragments — the sidebar that costs eleven queries
  3. Sessions, which also makes a second application server possible; see load balancing
  4. Rate limit counters, which Redis does better than a database

Before any of that, check whether the slow query just needs an index. Caching a bad query hides it until the cache is cold and everything arrives at once. See database basics.

Watch three numbers

redis-cli info stats and info memory:

  • Hit ratio — keyspace hits against misses. Below about 80% the cache is not earning its keep.
  • evicted_keys — rising steadily means you need more memory or shorter TTLs.
  • used_memory_rss against used_memory — a large gap is fragmentation.

And always set a TTL. Keys without one are a slow memory leak with a plan to become an incident.


Still stuck? Mail support@novogara.com — an engineer answers, at any hour. Back to the knowledge base