
Mục Tiêu Series
- Biến Redis từ "cái cache nhanh" thành công cụ thiết kế hệ thống. Hoàn thành series, bạn tư duy được khi nào dùng Redis, chọn đúng data structure cho từng bài toán, triển khai caching/rate limiting/distributed lock/queue/realtime cho môi trường production, vận hành Redis ở quy mô lớn với Cluster, Sentinel, monitoring, hardening — và biết cả khi nào không nên dùng Redis.
Prerequisites
- ✅ Đã từng viết backend / API (bất kỳ ngôn ngữ nào)
- ✅ Hiểu HTTP request/response, client-server
- ✅ Đã dùng qua 1 database (SQL hoặc NoSQL)
- ✅ Khái niệm async / concurrency cơ bản
- ✅ Docker cơ bản (chạy được container)
- 📝 TypeScript/Node hoặc Python (code mẫu dùng cả hai)
- 📝 Khái niệm distributed systems (helpful)
- ❌ Không cần biết Redis trước đó
Ai Nên Học Series Này?
- Backend Engineer muốn dùng Redis vượt khỏi mức cache cơ bản
- Fullstack Dev cần scale API: caching, rate limit, session
- Người chuẩn bị phỏng vấn system design / backend
- DevOps / SRE vận hành Redis trong production
Ứng Dụng Sau Khi Học
- Thiết kế caching layer chống stampede, hot key, stale data
- Bảo vệ API bằng rate limiter phân tán (token bucket, sliding window)
- Distributed lock an toàn với fencing token, chống double-payment
- Background job system tin cậy với Redis Streams + consumer group
- Realtime: presence, chat, notification fanout, scale WebSocket
- Leaderboard, analytics, đếm unique với ZSet / HyperLogLog / Bloom
- Vận hành & hardening Redis ở quy mô lớn
Hai Lộ Trình Học
- Core Path (~60 bài): nền tảng phải nắm — caching, lock, streams, pub/sub, session, sorted set, scaling cơ bản.
- Advanced Path (~30 bài, gắn ⚡): đào sâu — Redlock debate, XAUTOCLAIM, RESP3 tracking, jemalloc fragmentation, Count-Min/Top-K, encoding internals.
- Beginner đi Core trước cho vững; Senior nhảy thẳng vào các bài ⚡.
- Các bài ⚡ trong danh sách dưới là Advanced Path.
Incident Stories
- Mỗi module kết bằng một sự cố production có thật (dòng 🔥 cuối mỗi module).
- Format: What happened → Why it happened → How Redis should be used.
- Ví dụ:
KEYS *làm Redis freeze, lock hết hạn gây double charge, ZSET không TTL gây OOM. - Học từ thất bại thật — nhớ lâu hơn nhiều so với lý thuyết.
Thời Gian Học
- Ước tính: 6-8 tuần
- Tổng số bài: 120+ bài học (12 module)
- Thời lượng mỗi bài: 10-20 phút (đọc + thực hành)
- Thực hành: 1.5-2.5 giờ/ngày
- Pace khuyến nghị: ~1.5 module/tuần
- Capstone cuối series: 4-6 ngày
Tools & Công Nghệ
- Redis 7.x / Redis Stack / Valkey
- Docker & Docker Compose
redis-cli+ RedisInsight- Client:
ioredis(Node/TS) &redis-py(Python) - RedisBloom, RedisTimeSeries (probabilistic & metrics)
redis-benchmark,memtier_benchmark
Tài Nguyên Tham Khảo
Cấu Trúc Mỗi Bài
- 🎯 Bài toán thực tế: vấn đề production cần giải
- 🧪 Cách làm ngây thơ & vì sao fail: tư duy phản biện
- 💡 Redis Pattern: giải pháp đúng + vì sao
- 💻 Code Example: snippet chạy được (Node + Python)
- ⚖️ Trade-off: đánh đổi về memory, latency, accuracy
- 🐛 Pitfalls & Anti-patterns: lỗi thường gặp
- ✅ Checklist + Quiz: tự đánh giá
Capstone Projects (Module 11)
- Cached + Rate-limited REST API hoàn chỉnh
- Reliable Background Job System với Redis Streams
- Realtime Leaderboard + Presence tracking
- Tổng kết & checklist tự đánh giá toàn series
Triết Lý Của Series
- Một lesson = Một vấn đề thực tế = Một pattern dùng được trong production.
- Không học command trước rồi mới tìm use case.
- Học từ bài toán thực tế → chọn Redis pattern → triển khai production.
- Anti-pattern được cảnh báo ngay trong từng module, không để đến cuối.
Danh Sách Bài Học
Module 0 — Redis Mental Model & Nền Tảng
- Redis sinh ra để giải quyết vấn đề gì? (latency-first, memory vs disk)
- Redis architecture: event loop, I/O threads (Redis 6+), RESP protocol
- Performance fundamentals: pipelining, batching, connection pooling
- TTL-First Thinking — tư duy dữ liệu có thời hạn, ephemeral state
- Tổng quan Data Structures (String, Hash, List, Set, ZSet, Bitmap, HLL, Streams, GEO)
- Persistence: RDB, AOF, Hybrid + fork/COW latency spike
- Redis ecosystem hôm nay: license, Valkey, Redis Stack, Redis 8
- Khi nào KHÔNG nên dùng Redis (vs Postgres / Memcached / Kafka)
- 🔥 Incident: Dùng Redis làm primary DB + tắt persistence → restart node mất sạch data
Module 1 — Caching Trong Production
- Cache-Aside Pattern: luồng get/set, fallback database
- Read-Through / Write-Through / Write-Behind — chọn pattern nào
- Thiết kế Cache Key: naming, namespace, versioning
- Chiến lược TTL: hard / soft / business + TTL jitter
- Negative Caching — cache kết quả null, chống spam DB
- Cache Stampede & Mutex Lock (single-flight)
- ⚡ Stale-While-Revalidate + Probabilistic Early Expiration (XFetch)
- Multi-layer Cache: L1 in-memory + L2 Redis + DB fallback
- Cache Invalidation & bài toán consistency
- Hot Keys — nhận diện (scaling chuyên sâu ở Module 9)
- Checklist + Anti-patterns Caching
- 🔥 Incident: Chạy
KEYS *trong production → Redis freeze → toàn bộ API timeout
Module 2 — Data Structures Thực Chiến
- String: cache, counter, token, bitfield
- Hash: user profile, metadata + Hash field TTL (Redis 7.4)
- List: queue cũ, timeline, capped list
- Set: tags, unique members, permission, set operations
- Sorted Set: leaderboard, ranking, delayed queue, rate limit
- Bitmap & Bitfield: daily active users, login streak
- HyperLogLog: đếm unique (deep-dive ở Module 8)
- GEO: tìm kiếm theo vị trí, "nearby" search
- ⚡ Encoding internals: listpack, intset, skiplist, embstr vs raw
- Chọn đúng Data Structure: problem → structure mapping
- Checklist + Anti-patterns Data Structure
- 🔥 Incident: Một Hash 5 triệu field →
HGETALLblock event loop → spike p99
Module 3 — Rate Limiting & Chống Abuse
- Vì sao cần Rate Limiting: abuse, cost, fair usage
- Atomicity — vì sao rate limiter cần Lua / lệnh atomic
- Fixed Window — đơn giản, nhược điểm burst traffic
- Sliding Window Log — chính xác, tốn memory
- Sliding Window Counter — cân bằng accuracy vs memory
- Token Bucket — pattern API phổ biến
- ⚡ Leaky Bucket & GCRA — traffic smoothing
- Distributed Rate Limiting — multi-instance đồng nhất
- Login Protection — chống brute force
- Quota theo user / API key (free vs paid, AI quota)
- Checklist + Anti-patterns Rate Limiting
- 🔥 Incident: Rate limiter kiểu GET-rồi-INCR (không atomic) → race condition → vượt giới hạn khi burst
Module 4 — Distributed Coordination
- Distributed Lock — tại sao cần lock phân tán
SET NX EX— lock cơ bản và bẫy đầu tiên- Lock Expiration Problem — deadlock & lock hết hạn giữa chừng
- Unlock an toàn — Lua script + ownership validation
- Fencing Token — vì sao chỉ lock thôi chưa đủ an toàn
- ⚡ Redlock + tranh luận Kleppmann vs antirez (efficiency vs correctness)
- Chống Double Payment — idempotency key
- Leader Election — chỉ 1 scheduler chạy
- Distributed Semaphore — giới hạn concurrency toàn hệ thống
- Singleton Worker & Cron Deduplication
- Checklist + Anti-patterns Coordination
- 🔥 Incident: Lock hết hạn giữa chừng vì job chạy lâu → 2 worker cùng xử lý → double charge
Module 5 — Reliable Queue & Async Processing
- Vì sao cần Queue: async processing, reliability
- Queue với List:
LMOVE/RPOPLPUSH+ giới hạn at-most-once - Redis Streams: log primitive (
XADD/XREAD) - Consumer Groups:
XREADGROUP,XACK, Pending Entries List - ⚡ Xử lý message fail:
XCLAIM/XAUTOCLAIM - Delayed Jobs — scheduler bằng Sorted Set
- Retry Strategy — exponential backoff, retry limit
- Dead Letter Queue (DLQ)
- Priority Queue + Idempotent Jobs
- Distributed Workers — scale horizontal
- Redis Queue vs Kafka / RabbitMQ / BullMQ — khi nào dùng gì
- Checklist + Anti-patterns Queue
- 🔥 Incident: Consumer crash sau khi xử lý nhưng trước
XACK→ message kẹt PEL mãi vì thiếuXAUTOCLAIM
Module 6 — Real-time Systems
- Pub/Sub cơ bản — và cảnh báo fire-and-forget (mất message)
- Keyspace Notifications — phản ứng theo sự kiện key
- Scale WebSocket multi-instance — Pub/Sub làm backplane
- ⚡ Sharded Pub/Sub (Redis 7) cho Cluster
- Presence Tracking — ai đang online
- Typing Indicator — chat realtime
- Notification Fanout — broadcast hiệu quả
- Kiến trúc Chat Room — room management
- Streams vs Pub/Sub — chọn cái nào
- Failure Recovery — reconnect, xử lý mất kết nối
- Checklist + Anti-patterns Realtime
- 🔥 Incident: Subscriber reconnect 2 giây → mất toàn bộ message Pub/Sub trong khoảng đó (không có replay)
Module 7 — Authentication & Session
- Session Store — quản lý session tập trung
- JWT Revocation — blacklist token
- Refresh Token Storage — secure refresh flow
- OTP Verification — email / SMS OTP
- Password Reset — temporary reset token
- Login Attempt Tracking — throttle đăng nhập
- Device / Multi-session Management
- Checklist + Anti-patterns Auth & Session
- 🔥 Incident: TTL blacklist ngắn hơn thời hạn còn lại của JWT → token đã revoke "sống lại" sau khi blacklist hết hạn
Module 8 — Analytics, Counting & Probabilistic
- Atomic Counter —
INCR/DECR - View / Like Counter — buffer rồi write-back DB
- Sliding Window Analytics — activity tracking
- Leaderboard System — Sorted Set
- Top-N / Trending — ranking thời gian thực
- HyperLogLog thực chiến — DAU/MAU, unique visitors
- Bitmap Analytics — retention & cohort
- RedisBloom: Bloom Filter & Cuckoo Filter
- ⚡ Count-Min Sketch & Top-K — heavy hitters
- ⚡ RedisTimeSeries — lưu & query metrics
- Approximate Counting Trade-offs — Set vs HLL vs Count-Min vs Top-K
- Checklist + Anti-patterns Analytics
- 🔥 Incident: ZSET leaderboard không TTL → memory tăng đều theo thời gian → Redis OOM
Module 9 — Production & Scaling
- Replication & High Availability
- Redis Sentinel — auto failover
- ⚡ Redis Cluster — hash slots, hash tags
{}, CROSSSLOT, resharding - Monitoring — latency, hit rate, slowlog,
LATENCY DOCTOR - ⚡ Benchmarking —
redis-benchmark,memtier, đo p99 - Tối ưu Memory — encoding, sizing, compression mindset
- Eviction Policies — LRU / LFU / volatile +
maxmemory - Big Keys Problem — detection & prevention
- Hot Keys Problem — chiến lược scaling
- ⚡ fork() & Copy-on-Write — latency spike khi BGSAVE
- ⚡ Memory Fragmentation — jemalloc,
activedefrag - ⚡ Client-side Caching (RESP3 tracking)
- Disaster Recovery — backup / restore + tổng hợp Anti-patterns
- 🔥 Incident:
maxmemory-policy=noeviction+ đầy RAM → mọi lệnh write trả OOM → app sập
Module 10 — Redis Hardening
- Vì sao Redis cần hardening — default config rất "mở"
- protected-mode & bind — không expose Redis ra public
- AUTH &
requirepass— lớp xác thực cơ bản - Redis ACL (Redis 6+) — user, permission, command category
- TLS — mã hóa kết nối in-transit
- rename-command — vô hiệu hóa lệnh nguy hiểm (FLUSHALL, CONFIG, KEYS)
- Network isolation — VPC, firewall, private subnet
- Secrets management & credential rotation
- ⚡ Audit log & phát hiện abuse
- Checklist + Anti-patterns Hardening
- 🔥 Incident: Redis mở port 6379 public không AUTH → bị scan → attacker chạy FLUSHALL / cài crypto-miner
Module 11 — Capstone Projects
- Project 1: Cached + Rate-limited REST API (ghép Module 1 + 3)
- Project 2: Reliable Background Job System với Streams (Module 5 + 4)
- Project 3: Realtime Leaderboard + Presence (Module 6 + 8)
- Tổng kết series — checklist tự đánh giá & lộ trình tiếp theo
Tips Học Hiệu Quả
- Mở
redis-clisong song: gõ tay từng lệnh, quan sát kết quả thay vì chỉ đọc. - Dùng RedisInsight từ đầu: nhìn data structure trực quan giúp xây mental model nhanh.
- Luôn hỏi "TTL bao lâu?": mỗi lần ghi key, tự hỏi nó nên sống bao lâu.
- Đọc bài toán trước code: hiểu "vì sao cách ngây thơ fail" trước khi xem pattern.
- Đo, đừng đoán: dùng
MEMORY USAGE,--bigkeys,SLOWLOGđể kiểm chứng. - Ưu tiên atomic: tập thói quen dùng Lua / lệnh atomic cho mọi thao tác đa bước.
- Đọc kỹ dòng 🔥 Incident: mỗi sự cố là một anti-pattern bạn sẽ không bao giờ lặp lại.
- Luôn nghĩ tới failure: "Nếu Redis chết lúc này thì sao?" — câu hỏi của mọi pattern production.
Lộ Trình Học Tập
Tuần 1: Mental Model & Nền Tảng (Module 0)
├── Setup Redis bằng Docker + RedisInsight (hands-on ngay)
├── Architecture: event loop, I/O threads, RESP
├── Performance: pipelining, batching, connection pool
└── TTL-first, persistence, ecosystem, khi nào KHÔNG dùng Redis
Tuần 2: Caching Production (Module 1)
├── Cache-Aside & các write pattern
├── TTL strategy, negative caching
├── Cache stampede, stale-while-revalidate
└── Invalidation & consistency
Tuần 3: Data Structures Thực Chiến (Module 2)
├── String, Hash, List, Set, Sorted Set
├── Bitmap, HyperLogLog, GEO
├── ⚡ Encoding internals (memory optimization)
└── Mapping: bài toán → data structure
Tuần 4: Rate Limiting & Coordination (Module 3 + 4)
├── Token bucket, sliding window (atomic với Lua)
├── Distributed lock + fencing token
├── ⚡ Redlock debate: efficiency vs correctness
└── Idempotency & leader election
Tuần 5: Reliable Queue & Realtime (Module 5 + 6)
├── Redis Streams + Consumer Groups
├── ⚡ XCLAIM / XAUTOCLAIM, retry, DLQ
├── Pub/Sub, presence, chat, notification fanout
└── Streams vs Pub/Sub — chọn đúng công cụ
Tuần 6: Auth/Session & Analytics (Module 7 + 8)
├── Session, JWT revocation, OTP, refresh token
├── Leaderboard, counters, HyperLogLog
├── RedisBloom, ⚡ Count-Min Sketch / Top-K
└── Approximate counting trade-offs
Tuần 7: Production, Scaling & Hardening (Module 9 + 10)
├── Replication → Sentinel → Cluster
├── Monitoring → ⚡ benchmarking → memory/eviction
├── ⚡ fork/COW, fragmentation, client-side caching
└── ACL, TLS, protected-mode, network isolation
Tuần 8: Capstone Projects (Module 11)
├── Cached + Rate-limited REST API
├── Reliable Background Job System với Streams
├── Realtime Leaderboard + Presence
└── Tổng kết & self-assessment toàn series
