Fullstack Python
Trang chủ / Module 8
🧰 Module 8 / 19 · 4 ngày 📅 Tuần 6 ●●●○ Khó

Redis, cache & background jobs: Celery, arq, idempotency, rate limit, outbox

Làm hệ thống nhanh và bền: cache-aside và vô hiệu hoá cache, chống stampede, background job với Celery (retry, acks_late, idempotent, beat), lựa chọn nhẹ hơn cho async (arq, Dramatiq, Taskiq), rate limiting, khoá phân tán, idempotency key và outbox.

RedisCacheCeleryarq/DramatiqIdempotencyOutbox
📌 Vì sao module này quan trọng

Việc chậm trong request (gửi mail, gọi API ngoài, xử lý file, gọi LLM mất 20 giây) làm worker web cạn và người dùng chờ. Celery là hạ tầng job phổ biến nhất của Python — và cũng là nơi sinh nhiều sự cố production nhất: task chạy hai lần, task mất khi worker bị kill, task chạy trước khi transaction commit, prefetch làm một worker ôm hết việc. Hỏi về idempotency và cache invalidation là chuẩn của vòng phỏng vấn senior.

🎯 Mục tiêu học tập

  • Áp dụng cache-aside với Redis, TTL có jitter, vô hiệu hoá sau commit, chống stampede
  • Cấu hình Celery production: acks_late, retry/backoff, time limit, prefetch, queue riêng
  • Viết task idempotent; lên lịch bằng Celery beat không chạy trùng
  • Chọn giữa Celery, arq, Dramatiq, Taskiq cho ứng dụng async
  • Cài rate limiting, idempotency key và outbox pattern

Cache với Redis

import json, random
from redis.asyncio import Redis

redis = Redis.from_url(settings.redis_url, decode_responses=True)

async def get_project_cached(session, project_id: int, org_id: int) -> dict:
    key = f"project:v1:{org_id}:{project_id}"             # key chứa tenant
    if (hit := await redis.get(key)) is not None:
        return json.loads(hit)
    data = ProjectOut.model_validate(await repo.get(session, project_id, org_id)).model_dump(mode="json")
    await redis.set(key, json.dumps(data), ex=300 + random.randint(0, 60))   # TTL jitter
    return data

# Sau khi commit cập nhật project:
await redis.delete(f"project:v1:{org_id}:{project_id}")
  • Xoá cache sau khi DB commit; dùng version trong key để vô hiệu hoá hàng loạt.
  • Stampede: lock SET NX để chỉ một tiến trình tính lại, hoặc stale-while-revalidate.
  • functools.cache/lru_cache chỉ cache trong một process — mỗi worker một bản, không vô hiệu hoá chéo được.
  • Không dùng chung Redis có eviction cho cả cache và broker queue.

Celery cấu hình cho production

app = Celery("taskflow", broker=settings.redis_url, backend=None)   # backend chỉ khi thật cần lấy kết quả
app.conf.update(
    task_acks_late=True,                 # ack sau khi xong → worker chết giữa chừng thì task được giao lại
    task_reject_on_worker_lost=True,
    worker_prefetch_multiplier=1,        # không để một worker ôm nhiều task dài
    task_time_limit=300, task_soft_time_limit=270,
    task_routes={"billing.*": {"queue": "critical"}, "exports.*": {"queue": "heavy"}},
    broker_transport_options={"visibility_timeout": 3600},   # Redis: phải dài hơn thời gian task lâu nhất
)

@app.task(bind=True, autoretry_for=(httpx.HTTPError,), retry_backoff=True, retry_jitter=True, max_retries=5)
def send_invoice_email(self, invoice_id: int) -> None:          # truyền ID, không truyền object
    with SessionSync() as s:
        invoice = s.get(Invoice, invoice_id)
        if invoice is None or invoice.emailed_at:                 # idempotent
            return
        mailer.send(build_invoice_mail(invoice))
        invoice.emailed_at = utcnow()
        s.commit()
  • acks_late = at-least-once → task phải idempotent.
  • Celery worker chạy code đồng bộ; gọi code async trong task cần asyncio.run hoặc dùng hàng đợi native async.
  • Dispatch task sau commit (transaction.on_commit ở Django; với SQLAlchemy dùng outbox hoặc hook after_commit).
  • Giám sát bằng Flower, metric độ dài hàng đợi, task lỗi.

Lên lịch và các lựa chọn khác

app.conf.beat_schedule = {
    "deadline-reminders": {"task": "notifications.send_deadline_reminders", "schedule": crontab(minute=0)},
    "monthly-report": {"task": "reports.monthly", "schedule": crontab(0, 2, day_of_month=1)},
}
Công cụĐặc điểm
CeleryPhổ biến nhất, nhiều tính năng (chain, group, chord, beat), đồng bộ, cấu hình nhiều
arqNative asyncio trên Redis, nhẹ — hợp với FastAPI
DramatiqĐơn giản, mặc định an toàn hơn Celery (ack sau khi xong)
TaskiqAsync, nhiều broker, tích hợp FastAPI
TemporalWorkflow bền vững nhiều bước, chờ nhiều ngày, bù trừ

Beat chỉ chạy một instance (nhiều instance = chạy trùng); task định kỳ cũng nên idempotent.

Rate limit, idempotency key, outbox

# Idempotency key cho POST /payments
async def idempotent(request: Request, user: UserDep) -> str:
    key = request.headers.get("Idempotency-Key")
    if not key:
        raise AppError(400, "IDEMPOTENCY_KEY_REQUIRED", "Thiếu Idempotency-Key")
    rkey = f"idem:{user.id}:{key}"
    if not await redis.set(rkey, "processing", nx=True, ex=86400):   # nguyên tử
        prev = await redis.get(rkey)
        if prev == "processing":
            raise AppError(409, "IN_PROGRESS", "Đang xử lý")
        raise ReplayResponse(json.loads(prev))
    return rkey
  • Rate limit: slowapi / fastapi-limiter hoặc tự viết bằng Redis (INCR + EXPIRE, sliding window bằng sorted set); theo user/API key, trả 429 + Retry-After.
  • Outbox: ghi sự kiện vào bảng outbox trong cùng transaction với dữ liệu; worker đọc bằng FOR UPDATE SKIP LOCKED và phát đi — không mất sự kiện khi tiến trình chết.

🏋️ Bài tập thực hành

Làm hệ thống nhanh và bền

(1) Cache chi tiết project và dashboard, đo p95 trước/sau bằng k6, test chứng minh cập nhật xong không đọc dữ liệu cũ. (2) Email mời thành viên và xuất CSV 1 triệu dòng bằng Celery (hoặc arq) với queue riêng; giả lập nhà cung cấp email lỗi 50%, chứng minh không mất, không gửi trùng. (3) Kill worker giữa chừng, chứng minh task được chạy lại nhờ acks_late. (4) Beat nhắc deadline mỗi giờ. (5) Idempotency key cho thanh toán — 20 request song song cùng key chỉ tạo 1 bản ghi. (6) Outbox cho sự kiện task.completed.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Cache có key theo tenant, vô hiệu hoá sau commit
  • Celery: acks_late, prefetch=1, time limit, queue riêng, task idempotent
  • Beat chạy một instance, task định kỳ idempotent
  • API thanh toán có idempotency key; sự kiện quan trọng qua outbox