Backend · Performance

Redis Caching: Tăng Tốc Ứng Dụng 10x

Redis Caching - Tăng tốc ứng dụng 10x

Twitter phục vụ 500 triệu tweets/ngày — nếu mỗi request query database, hệ thống sẽ sập trong vài giây. Bí mật? Redis cache xử lý 80% reads mà không touch database. Redis đọc data ở tốc độ 100,000+ ops/sec từ memory — nhanh hơn PostgreSQL query 10-100 lần. Theo DB-Engines 2025, Redis là #1 key-value store toàn cầu, được dùng bởi GitHub, Instagram, StackOverflow, và Discord. Bài viết này giải thích caching strategies, cache invalidation, các pitfalls phổ biến, và cách BanhCuonFlow dùng Redis trong production.

Tại Sao Redis?

Redis là in-memory data store — toàn bộ data nằm trong RAM, không cần disk I/O cho reads. So với database (data trên disk, cần query parsing, execution plan, disk seek), Redis nhanh hơn hàng chục lần. Nhưng Redis không chỉ là key-value cache — nó hỗ trợ rich data structures mỗi cái tối ưu cho use case khác nhau.

⚡ Strings: Cơ Bản Nhất

Key-value đơn giản: cache JSON response, session data, counters (INCR). Max 512MB/value. Dùng cho: API response cache, page counters, rate limiting.

📊 Hashes: Object Storage

Hash map: HSET user:123 name "John" email "john@x.com". Update individual fields mà không rewrite toàn bộ object. Dùng cho: user profiles, session attributes.

📡 Pub/Sub: Messaging

Publish/Subscribe pattern built-in. BanhCuonFlow dùng Redis Pub/Sub cho SignalR backplane — scale chat realtime multi-server. Zero-config, lightweight.

🏆 Sorted Sets: Ranking

ZADD leaderboard 100 "user:1". Auto-sorted by score. ZRANGE lấy top N. Dùng cho: leaderboards, priority queues, activity feeds.

3 Caching Strategies

🔄 Cache-Aside (Lazy Loading)

Application check cache trước. Cache miss → query DB → write to cache → return. Cache hit → return từ cache trực tiếp. Ưu điểm: Chỉ cache data thực sự cần (on-demand), không waste memory cho data ít truy cập. Nhược: First request luôn chậm (cold start), cần 3 roundtrips cho cache miss. BanhCuonFlow dùng pattern này cho: dashboard data, user permissions, department lists, task counts. Cache hit rate production: 85-92%.

📝 Write-Through

Mọi write đồng thời vào DB và cache. Application không trực tiếp write DB — write qua cache layer, cache đảm bảo consistency. Ưu điểm: Cache luôn consistent, no stale data, reads luôn fast. Nhược: Write latency tăng (2x writes cho mỗi operation), cache data có thể không bao giờ được đọc (waste memory). Phù hợp: data đọc nhiều ít thay đổi — configurations, permissions, look-up tables.

📦 Write-Behind (Write-Back)

Write vào cache trước, async flush vào DB sau (batch, interval, or queue). Ưu điểm: Write ultra-fast (chỉ write memory — sub-millisecond), batch DB writes giảm load. Nhược: Risk data loss nếu cache crash trước khi flush (mitigate: Redis AOF persistence + replication). Phù hợp: high-write workloads — analytics events, activity logs, view counts.

Cache Invalidation: "The Hardest Problem"

Phil Karlton (Netscape): "There are only two hard things in CS: cache invalidation and naming things." Cache invalidation khó vì: khi data trong DB thay đổi, cache cũ phải được xóa hoặc update — nếu không, users thấy stale data. Hậu quả: user thấy permission cũ → security risk, user thấy balance cũ → trust issue.

TTL-based (Time-to-Live): Set expire time (SETEX key 300 value — 5 phút). Sau TTL, cache tự xóa, request tiếp theo lấy fresh data. Simple nhưng có window stale data tối đa = TTL. Event-based: Khi data thay đổi (update task) → explicitly delete cache key (DEL task:123). Consistent nhưng cần code invalidation ở mọi nơi data thay đổi — dễ miss nếu codebase lớn. BanhCuonFlow approach: Hybrid — TTL 5 phút cho general data + event-based invalidation cho critical data (permissions, workflow state). Dual protection: even nếu miss event, TTL sẽ cleanup.

Redis Trong BanhCuonFlow: 3 Vai Trò

① Application Cache: Dashboard data, user permissions, department lists — cache-aside pattern, TTL 5 phút. Kết quả: giảm 70% DB queries, API response time từ 200ms → 15ms cho cached endpoints.

② SignalR Backplane: Multi-server deployment cần message bus để broadcast SignalR events đến đúng server/client. Redis Pub/Sub là lightweight, zero-config solution — tất cả instances subscribe channel, khi server A publish → servers B, C nhận event → forward đến connected clients.

③ SSO Token Store: SSO code exchange dùng Redis với TTL 5 phút — code tạo xong, 5 phút sau tự xóa nếu không dùng. Atomic SET + GET + DELETE operations đảm bảo code chỉ dùng 1 lần (prevent replay attacks).

Performance trong BanhCuonFlow

Redis cache, PostgreSQL optimized, SignalR realtime — kiến trúc tối ưu cho enterprise workloads.