Module 4 · Caching and performanceLesson 34 of 887 minIntermediate
How Redis works
Redis is an in-memory data store that runs commands one at a time, very fast, with optional saving to disk and replicas.
Watch three commands get handled one at a time. Then see how the log on disk brings data back after a restart, and how a replica takes over.
Redis is the most popular cache and in-memory data store. It's worth knowing how it works inside, because its design explains both its speed and its limits.
Memory first
All data lives in RAM. That's why reads and writes take microseconds. It also means your data size is limited by memory, and memory is more expensive than disk.
One command at a time
Redis handles all clients' commands on a single main thread with an event loop. It never runs two commands at once.
- Every command is atomic:
INCR,SETNX(set if not exists) andLPUSHcan't be interrupted. - No locking overhead, so it's very fast: often over 100,000 operations per second on one node.
- But one slow command (like
KEYS *on millions of keys) blocks everyone. Avoid those in production.
More than key-value
Redis has rich data types:
- Strings and counters
- Hashes (objects with fields)
- Lists (queues), sets, sorted sets (leaderboards, rate limit windows)
- Streams (a lightweight log for events)
- TTLs on any key
Keeping data safe
- RDB snapshots: save everything to disk every few minutes.
- AOF (append-only file): log every write, flushed to disk every second by default. On restart, replay the log.
- Replicas: async copies on other machines. Sentinel watches the primary and promotes a replica if it fails.
- Redis Cluster: splits keys across nodes using 16,384 hash slots, so you can scale beyond one machine.
Common uses
Caching, sessions, rate limiters, leaderboards, distributed locks, job queues and pub/sub. Treat it as fast and convenient, but if losing a second of writes would hurt, keep the real record in your main database.