redis-patterns
Skill này làm gì
Hướng dẫn này giúp bạn dùng Redis, một cơ sở dữ liệu nhanh, cho các tác vụ lập trình phổ biến. Nó chỉ cách lưu dữ liệu hiệu quả để tăng tốc ứng dụng, kiểm soát truy cập và gửi thông điệp.
Khi nào nên dùng
- ✓Khi bạn muốn ứng dụng nhanh hơn nhờ bộ nhớ đệm.
- ✓Để giới hạn tần suất người dùng có thể làm một việc trong một khoảng thời gian.
- ✓Để đảm bảo chỉ một đoạn code chạy tại một thời điểm.
Liên kết skill
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/redis-patterns/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm sao để dùng Redis lưu thông tin phiên đăng nhập của người dùng một cách an toàn?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Nó dùng các cấu trúc dữ liệu của Redis như chuỗi và hash để lưu thông tin. Với các tác vụ phức tạp hơn, nó có thể dùng script đặc biệt hoặc giao dịch để đảm bảo mọi thứ diễn ra đúng.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
Redis Patterns
Quick reference for Redis best practices across common backend use cases.
How It Works
Redis is an in-memory data structure store that supports strings, hashes, lists, sets, sorted sets, streams, and more. Individual Redis commands are atomic on a single instance; multi-step workflows require Lua scripts, MULTI/EXEC transactions, or explicit synchronization to stay atomic. Data is optionally persisted via RDB snapshots or AOF logs. Clients communicate over TCP using the RESP protocol; connection pools are essential to avoid per-request handshake overhead.
When to Activate
- Adding caching to an application
- Implementing rate limiting or throttling
- Building distributed locks or coordination
- Setting up session or token storage
- Using Pub/Sub or Redis Streams for messaging
- Configuring Redis in production (pooling, eviction, clustering)
Data Structure Cheat Sheet
| Use Case | Structure | Example Key |
|---|---|---|
| Simple cache | String | product:123 |
| User session | Hash | session:abc |
| Leaderboard | Sorted Set | scores:weekly |
| Unique visitors | Set | visitors:2024-01-01 |
| Activity feed | List | feed:user:456 |
| Event stream | Stream | events:orders |
| Counters / rate limits | String (INCR) | ratelimit:user:123 |
| Bloom filter / HLL | HyperLogLog | hll:pageviews |
Core Patterns
Cache-Aside (Lazy Loading)
import redis
import json
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
def get_product(product_id: int):
cache_key = f"product:{product_id}"
cached = r.get(cache_key)
if cached:
return json.loads(cached)
product = db.query("SELECT * FROM products WHERE id = %s", product_id)
r.setex(cache_key, 3600, json.dumps(product)) # TTL: 1 hour
return product
Write-Through Cache
def update_product(product_id: int, data: dict):
# Write to DB first
db.execute("UPDATE products SET ... WHERE id = %s", product_id)
# Immediately update cache
cache_key = f"product:{product_id}"
r.setex(cache_key, 3600, json.dumps(data))
Cache Invalidation
# Tag-based invalidation — group related keys under a set
def cache_product(product_id: int, category_id: int, data: dict):
key = f"product:{product_id}"
tag = f"tag:category:{category_id}"
pipe = r.pipeline(transaction=True)
pipe.setex(key, 3600, json.dumps(data))
pipe.sadd(tag, key)
pipe.expire(tag, 3600)
pipe.execute()
def invalidate_category(category_id: int):
tag = f"tag:category:{category_id}"
keys = r.smembers(tag)
if keys:
r.delete(*keys)
r.delete(tag)
Session Storage
import time
import uuid
def create_session(user_id: int, ttl: int = 86400) -> str:
session_id = str(uuid.uuid4())
key = f"session:{session_id}"
pipe = r.pipeline(transaction=True)
pipe.hset(key, mapping={
"user_id": user_id,
"created_at": int(time.time()),
})
pipe.expire(key, ttl)
pipe.execute()
return session_id
def get_session(session_id: str) -> dict | None:
data = r.hgetall(f"session:{session_id}")
return data if data else None
def delete_session(session_id: str):
r.delete(f"session:{session_id}")
Rate Limiting
Fixed Window (Simple)
def is_rate_limited(user_id: int, limit: int = 100, window: int = 60) -> bool:
key = f"ratelimit:{user_id}:{int(time.time()) // window}"
pipe = r.pipeline(transaction=True)
pipe.incr(key)
pipe.expire(key, window)
count, _ = pipe.execute()
return count > limit
Sliding Window (Lua — Atomic)
-- sliding_window.lua
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count < limit then
-- Use unique member (now + sequence) to avoid collisions within the same millisecond
local seq_key = key .. ':seq'
local seq = redis.call('INCR', seq_key)
redis.call('EXPIRE', seq_key, math.ceil(window / 1000))
redis.call('ZADD', key, now, now .. '-' .. seq)
redis.call('EXPIRE', key, math.ceil(window / 1000))
return 1
end
return 0
sliding_window = r.register_script(open('sliding_window.lua').read())
def allow_request(user_id: int) -> bool:
key = f"ratelimit:sliding:{user_id}"
…
Câu hỏi thường gặp
Redis là gì?
Redis là cơ sở dữ liệu lưu thông tin trong bộ nhớ máy tính để truy cập rất nhanh. Nó hỗ trợ nhiều kiểu dữ liệu như văn bản, danh sách và tập hợp.
Vì sao dùng connection pool?
Tạo kết nối mới đến Redis mỗi lần ứng dụng cần có thể chậm. Connection pool giữ sẵn các kết nối để dùng, tiết kiệm thời gian.
Khóa phân tán (distributed lock) là gì?
Đây là các tín hiệu đảm bảo chỉ một ứng dụng hoặc tiến trình được truy cập tài nguyên dùng chung tại một thời điểm, tránh xung đột.
Chi tiết
Mô tả gốc của tác giả
Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub/sub, and connection management for production applications. Use when adding caching, a distributed lock, rate limiting, or pub/sub with Redis, or when key design needs review.
repo: affaan-m/ECC
Độ phổ biến
- Sao GitHub
- 280k
- Vị trí xếp hạng
- #240
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
accessibility
280kGiúp agent của bạn tạo giao diện mà ai cũng dùng được, đảm bảo website và app hoạt động tốt với người khuyết tật như người mù hoặc khó vận động.
agent-architecture-audit
280kGiúp agent của bạn kiểm tra xem mọi thứ có hoạt động đúng không, đồng thời tìm và sửa các lỗi trong hệ thống AI để chúng chạy như mong đợi.
agent-eval
280kGiúp agent của bạn so sánh các công cụ lập trình AI khác nhau, đo xem công cụ nào nhanh hơn, rẻ hơn và đáng tin cậy hơn cho từng tác vụ.
agent-harness-construction
280kGiúp agent của bạn hiểu rõ hơn cách thực hiện tác vụ, tối ưu các công cụ và chỉ dẫn mà agent dùng để tăng khả năng thành công.
Skill tương tự
shopify
260kGiúp agent của bạn đọc và cập nhật dữ liệu cửa hàng Shopify như sản phẩm, tồn kho, đơn hàng và khách hàng qua Shopify GraphQL API.
rest-graphql-debug
260kGiúp agent của bạn tìm lý do một lệnh gọi API REST hoặc GraphQL thất bại, kiểm tra kết nối, đăng nhập, định dạng yêu cầu và phản hồi theo từng lớp.
har-derived-api-client
260kGiúp agent của bạn ghi lại lưu lượng mạng của một website một lần, rồi xây một client API trực tiếp, để không phải nhấp qua trang mỗi lần.