Skip to content

Async Task Queue + Producer-Consumer

Mở đầu

User click "export report", rồi nhìn loading 30s — hợp lý? Khi op cần vài giây - vài phút, để user chờ không phải UX tốt. Async task queue = pattern core giải — quăng op tốn time vào background, user response ngay.

Bạn sẽ học:

  • Sync vs async: sao op nào phải async, UX improvement
  • Producer-Consumer: core idea + workflow
  • Worker pool: task distribute parallel
  • Reliability: retry, idempotency, dead letter queue
  • Selection: framework mainstream
ChươngNội dung
1Sao cần async
2Producer-Consumer
3Worker pool
4Reliability
5Framework

0. Toàn cảnh: sao không cho user "đợi suông"?

Vào nhà hàng. Tốt sẽ cho bạn mã order ngay, bạn tìm chỗ ngồi, chơi điện thoại, có món tới lấy. Không phải bắt bạn đứng cửa bếp nhìn đầu bếp nấu.

Web app có nhiều op "nấu" tương tự:

  • Gửi email/SMS: call 3rd party API, vài giây
  • Gen report/PDF: tính lượng lớn data, vài chục giây
  • Image/video processing: compress, transcode, watermark, vài phút
  • Data sync: cross-system, time không chắc

Core

Tách op tốn time khỏi "request-response" main flow, vào background queue. User submit xong nhận "received, processing" ngay, xong thì notify qua push/poll/WebSocket.


1. Sync vs Async: story của 1 order

User submit order, BE phải: trừ inventory, tạo order, gửi confirm email, update recommendation, log audit...

Sync: serial execute, user phải đợi hết. Async: chỉ core (trừ inventory, tạo order), còn lại queue background.

同步 vs 异步处理对比
点击按钮观察两种模式的差异
用户请求
等待提交
服务端处理
扣减库存50ms
创建订单100ms
发送确认邮件800ms
更新推荐系统600ms
记录审计日志300ms
DimSyncAsync
User waitTổng time mọi opChỉ core
ThroughputThấp (thread block)Cao (thread release nhanh)
Fail impactNon-core fail → toàn bộ failNon-core fail không ảnh hưởng main
ComplexityĐơn giảnCần queue infra
ConsistencyStrongEventual

Khi nào async?

3 tiêu chí: lâu (>1-2s), non-core (fail không ảnh hưởng main), delayable (không cần kết quả ngay). Thoả 2/3 → cân nhắc async.


2. Producer-Consumer

3 vai trò:

  • Producer: sinh task, thường web server xử user request
  • Queue: buffer task chờ xử, thường Redis, RabbitMQ
  • Consumer/Worker: lấy task từ queue + execute
Worker 工作池模型
观察任务如何被分发到不同 Worker 处理
Worker 数量: 3
任务队列 (0)
队列为空
Workers
Worker 1
💤 空闲
已完成: 0
Worker 2
💤 空闲
已完成: 0
Worker 3
💤 空闲
已完成: 0
已完成 (0)
暂无

3 giá trị queue

  1. Decouple: producer không cần biết ai xử, consumer không cần biết task từ đâu
  2. Smoothing burst: traffic peak → task pile trong queue, consumer xử theo nhịp
  3. Reliability: task persist, consumer crash cũng không mất
ComponentRoleImplementation
Message middlewareLưu + forward taskRedis, RabbitMQ, Kafka
SerializerSerialize paramJSON, MessagePack, Pickle
SchedulerManage cron + delayCron, APScheduler, node-cron
Result storeLưu kết quảRedis, DB, S3

3. Reliability: task không "mất" + không "duplicate"

Distributed env, network shake, service restart, resource thiếu xảy ra bất cứ lúc nào. Async task system phải có reliability đầy đủ.

2 vấn đề core: task loss (consumer xử nửa chừng crash) + duplicate execution (task được deliver 2 lần).

任务重试与退避策略
模拟任务失败后的重试过程
固定间隔
每次重试等待相同的时间,简单但可能造成"重试风暴"
延迟公式:delay = 2s

3 vũ khí reliability

  1. ACK: consumer xử xong mới gửi ACK, task chưa ACK sẽ re-deliver
  2. Retry strategy: task fail retry theo strategy, exponential backoff + jitter = best practice
  3. Idempotency: cùng task execute nhiều lần kết quả = 1 lần, qua unique ID dedup
MechanismGiảiImplementation
ACKTask lossXong xác nhận, timeout thì re-deliver
Dead Letter Queue (DLQ)"Poison message" fail liên tụcQuá retry limit chuyển DLQ, human can thiệp
IdempotencyDuplicate executionUnique ID dedup, DB unique constraint
Priority queueTask starvationHigh priority xử trước
TimeoutTask stuckSet max execution time, timeout → terminate + retry

4. Framework

主流异步任务框架对比
点击查看各框架详情
Celery
Python
Sidekiq
Ruby
Bull
Node.js
RQ
Python
Kafka Streams
Java/JVM
CeleryPython
Python 生态最流行的分布式任务队列,支持多种消息中间件(RabbitMQ、Redis),功能全面且社区活跃。
核心特性:
定时任务任务链结果存储自动重试优先级队列任务路由
典型场景:
数据处理管道、邮件发送、报表生成、机器学习训练任务

Recommendation

  • Python: medium-large = Celery, small = RQ, modern = ARQ/Dramatiq
  • Node.js: BullMQ (Bull next-gen)
  • Ruby: Sidekiq
  • Java: Spring Batch hoặc Kafka Streams
  • Go: Asynq (Redis-based) hoặc Machinery
  • Cross-language: Temporal (durable execution, hot 2024+)

Nếu project đã có Redis, plan Redis-based (Celery+Redis, BullMQ, Sidekiq) = đơn giản nhất.


Tổng kết

  1. Tiêu chí async: lâu, non-core, delayable — thoả 2 thì async
  2. Producer-Consumer: 3 vai trò decouple
  3. Worker pool: parallel consume tăng throughput
  4. Reliability: ACK + retry + idempotency, thiếu 1 cũng không
  5. Selection: theo stack + scale, Redis là middleware phổ biến nhất

2026 cho VN dev

  • Temporal: durable execution, code task như normal function nhưng auto retry/checkpoint
  • Inngest, Trigger.dev: serverless background job (Vercel/Cloudflare era)
  • BullMQ: chuẩn cho Node.js 2026
  • Celery + Redis: vẫn chuẩn cho Python (FastAPI, Django)
  • VN use case: send SMS OTP, gen invoice PDF, AI inference batch, sync ERP → cũ chuẩn dùng async
  • AI scenario: queue LLM call (rate limit OpenAI), batch embedding generation, image processing

Tài liệu