π΄ Redis: From Basics to Real-World Usage¶
Redis (Remote Dictionary Server) is a lightning-fast in-memory data store used as a cache, message broker, and lightweight database.
It stores data as key-value pairs, keeps it in RAM for near-instant access, and can optionally persist it to disk.
Itβs often used alongside PostgreSQL: Postgres for durability, Redis for speed.
βοΈ 1. What Redis Actually Does¶
Redis keeps everything in memory but optionally syncs to disk (snapshots or append logs).
It supports complex data types, pub/sub messaging, and atomic operations β all with sub-millisecond latency.
| Use Case | Example |
|---|---|
| Cache | Store frequently accessed DB results. |
| Session Store | Track logged-in users. |
| Queue / Stream | Background jobs, real-time feeds. |
| Rate Limiter | Count requests per user/IP. |
| Pub/Sub | Event notification between services. |
π In short: Redis trades persistence for speed, but can be configured for both.
π§± 2. Core Concepts¶
| Concept | Description |
|---|---|
| Key | Identifier for a piece of data (string). |
| Value | Data stored under a key β can be string, hash, list, set, etc. |
| TTL | Time-to-live (expiration). |
| Persistence | Data saved to disk (RDB snapshots or AOF logs). |
| Pub/Sub | Publisher sends messages to channels; subscribers receive them. |
| Database index | Redis has logical DBs numbered 0β15 by default. |
β‘ 3. Basic Commands (Quick Reference)¶
redis-cli # Start CLI
ping # β PONG
set key "value" # store
get key # retrieve
del key # delete
exists key # check if exists
expire key 60 # expire after 60s
keys * # list all keys (use with caution)
flushall # delete everything
````
---
## π§© 4. Data Structures and Examples
### Strings
```bash
set greeting "Hello"
get greeting
incr counter
decr counter
Hashes (key β fields)¶
Lists (ordered queue)¶
Sets (unique values)¶
Sorted Sets (ranking)¶
Pub/Sub¶
π§ 5. Persistence Modes¶
Redis can persist data in two main ways:
| Mode | Description |
|---|---|
| RDB (Snapshot) | Saves full dataset at intervals (default). Fast, minimal overhead. |
| AOF (Append Only File) | Logs every operation β safer but slower. |
| Hybrid | Combines both for speed + durability. |
Example in redis.conf:
π§° 6. Running Redis with Docker¶
Check connection:
With password:
docker run -d \
-p 6379:6379 \
-e REDIS_PASSWORD=secret \
redis:7 \
redis-server --requirepass secret
π§© 7. Docker Compose Example¶
version: "3.9"
services:
redis:
image: redis:7
ports:
- "6379:6379"
volumes:
- redis_data:/data
command: redis-server --appendonly yes
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
retries: 5
backend:
build: ./backend
environment:
REDIS_HOST: redis
REDIS_PORT: 6379
volumes:
redis_data:
πΎ 8. Redis + Application Integration (Spring Boot Example)¶
application.properties:
Simple cache usage with Spring:
@Cacheable("users")
public User getUserById(Long id) {
return userRepository.findById(id).orElseThrow();
}
Make sure caching is enabled:
π‘ 9. Monitoring and Admin Commands¶
info # show metrics
dbsize # number of keys
monitor # live command log
config get * # view config
config rewrite # persist config changes
slowlog get # show slow commands
For real-time dashboards:
- RedisInsight
redis-exporterfor Prometheus / Grafana metrics.
π 10. Security & Performance Best Practices¶
- Set a password (
requirepass secret) β Redis is open by default. - Bind to localhost or internal networks (
bind 127.0.0.1). - Disable
FLUSHALLandCONFIGcommands in production. - Use connection pooling for app clients.
- For persistence: prefer AOF + fsync every second.
- Enable
maxmemoryandmaxmemory-policy allkeys-lrufor safe eviction.
Example snippet:
π» 11. IDE & Tool Integration¶
JetBrains IDEs¶
- Use built-in Database Tool Window β Add Data Source β Redis.
- Visualize keys, TTLs, and values directly.
- Supports
EVALand Lua scripting.
VS Code¶
Recommended extensions:
- Redis Explorer β browse keys, TTLs, and memory usage.
- REST Client β test APIs that interact with Redis.
- .env files β store connection secrets.
Example .env:
π 12. CI/CD Integration Example¶
GitHub Actions β Redis as test dependency:
services:
redis:
image: redis:7
ports: ['6379:6379']
options: >-
--health-cmd="redis-cli ping"
--health-interval=5s --health-retries=5
steps:
- uses: actions/checkout@v4
- name: Run integration tests
env:
REDIS_HOST: localhost
REDIS_PORT: 6379
run: ./gradlew test
π§© 13. Real-World Patterns¶
| Pattern | Description | Example |
|---|---|---|
| Cache-Aside | App reads from Redis; on miss, fetches DB + stores in Redis. | Common with Spring or Django. |
| Write-Through | Writes go to Redis and DB simultaneously. | Ensures consistency. |
| Pub/Sub | Services communicate via Redis channels. | Real-time notifications. |
| Streams | Event queue with consumer groups. | Great for jobs, analytics. |
Example stream usage:
π§ 14. Troubleshooting¶
| Issue | Fix |
|---|---|
| Redis not reachable | Check port 6379 and container health. |
| Keys disappear | TTL expired or memory eviction triggered. |
| βNOAUTHβ error | Set password in config and client. |
| High latency | Tune maxmemory + eviction policy. |
| Data not persistent | Enable appendonly yes. |
β 15. Summary¶
- Redis = speed and simplicity β an in-memory data store with persistence options.
- Ideal for caching, pub/sub, queues, and rate limiting.
- Use Docker for easy setup and Compose for multi-service integration.
- Always secure, monitor, and limit memory.
- Combine with PostgreSQL for the best of both worlds: durability + velocity.
π File path suggestion: