
Email, SMS, push; retry, hàng đợi, template, hẹn giờEmail, SMS, push; retries, queues, templates, scheduling
OTP lúc chuyển khoảnAn OTP at transfer time.Một ví điện tử gửi 2 triệu tin mỗi ngày: OTP, biến động số dư, email khuyến mãi. Khách đang đứng ở quầy thanh toán chờ mã OTP trong vòng 5 giây.An e-wallet sends 2 million messages a day: OTPs, balance alerts, promotional email. A customer at the checkout counter waits for an OTP within 5 seconds.
Hãy theo một mã OTP cho user 42 khi khách đang đứng ở quầy thanh toán. API không gọi nhà mạng mà chỉ ghi notification và outbox trong một transaction rồi trả 202 sau 12 ms; relay đẩy sự kiện vào hàng critical và SMS worker mới là bên gửi. Chạy luồng thành công trước, rồi bật “Nhà cung cấp SMS lỗi” để xem retry, circuit breaker và DLQ, và “Gửi trùng yêu cầu” để xem idempotency chặn tin thứ hai.Follow an OTP for user 42 while the customer waits at the checkout counter. The API never calls the carrier; it writes the notification and outbox in one transaction and returns 202 in 12 ms, then a relay publishes to the critical queue and the SMS worker does the sending. Play the delivered flow first, then turn on “SMS provider fails” to see retries, the circuit breaker and the DLQ, and “Duplicate request” to see idempotency stop a second message.
1Auth service cần gửi OTP cho user 42 để xác nhận chuyển khoản. Nó gửi kèm idempotency key gắn với phiên giao dịch, để gọi lại cũng không sinh tin mới.The auth service needs to send user 42 an OTP to confirm a transfer. It includes an idempotency key tied to the transaction session, so calling again never creates a new message.
Consumer nhận lại cùng message sau khi crash. Dùng idempotency_key có unique index; worker khoá dòng và bỏ qua nếu đã SENT.A consumer gets the same message again after a crash. Keep an idempotency_key with a unique index; the worker locks the row and skips it when already SENT.
Exponential backoff + jitter (1 s, 2 s, 4 s…, tối đa 5 lần), circuit breaker theo nhà cung cấp; quá số lần thì vào DLQ.Exponential backoff with jitter (1s, 2s, 4s…, up to 5 attempts), a circuit breaker per provider, then the DLQ.
Ghi notification và outbox trong cùng transaction; relay đẩy sang Kafka/RabbitMQ sau khi commit.Write the notification and the outbox row in one transaction; a relay publishes to Kafka/RabbitMQ after commit.
Tách hàng theo độ ưu tiên critical / default / bulk, mỗi hàng có worker và giới hạn tốc độ riêng.Split queues by priority (critical / default / bulk), each with its own workers and rate limit.
Strategy chọn kênh, Template Method cho render → gửi → ghi kết quả, Adapter bọc SES, Twilio, FCM/APNs.Strategy picks the channel, Template Method runs render → send → record, Adapter wraps SES, Twilio, FCM/APNs.
Job quét bảng lịch dùng SELECT … FOR UPDATE SKIP LOCKED để hai instance không lấy cùng một tin.The scheduler polls with SELECT … FOR UPDATE SKIP LOCKED so two instances never pick the same message.
| BảngTable | Cột chínhKey columns | Ghi chúNotes |
|---|---|---|
notification | id, user_id, channel, template_code, payload, status, priority, idempotency_key, scheduled_at | unique(idempotency_key); PENDING → SENDING → SENT · FAILED · DEADunique(idempotency_key); PENDING → SENDING → SENT · FAILED · DEAD |
notification_attempt | notification_id, attempt, provider, error, latency_ms, created_at | Lịch sử từng lần gửi để tra lỗiEvery attempt, for troubleshooting |
template | code, channel, locale, subject, body, version | Biến name, otp, link được thay khi renderVariables such as name, otp, link are filled in at render time |
user_preference | user_id, category, channel, enabled | Tắt marketing nhưng vẫn nhận OTPMarketing off, OTPs still on |
outbox | id, topic, key, payload, published_at | Relay đẩy sang message brokerPublished to the broker by a relay |
EmailWorker là hộp Email Worker ở sơ đồ; SMS Worker và Push Worker có cùng khung, chỉ đổi provider (SMS Provider, FCM / APNs). NotificationRepository khoá dòng notification do Notification API ghi, còn DeadLetterPublisher là mũi tên sang hộp DLQ. Worker bỏ qua tin đã gửi, lỗi thì ném lại để framework thử lại, quá 5 lần thì đẩy vào DLQ.EmailWorker is the Email Worker box in the diagram; SMS Worker and Push Worker share the same shape and only swap the provider (SMS Provider, FCM / APNs). NotificationRepository locks the notification row the Notification API wrote, and DeadLetterPublisher is the arrow to the DLQ box. The worker skips messages already sent, rethrows on errors so the framework retries, and pushes to the DLQ after 5 attempts.
package com.example.notify;
import lombok.RequiredArgsConstructor;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@RequiredArgsConstructor
public class EmailWorker {
private final NotificationRepository repo;
private final EmailProvider provider;
private final DeadLetterPublisher dlq;
@KafkaListener(topics = "notify.email")
@Transactional(noRollbackFor = ProviderException.class)
public void handle(NotifyEvent e) {
Notification n = repo.lockById(e.id()); // SELECT … FOR UPDATE
if (n.isTerminal()) return; // SENT or DEAD: redelivery
try {
provider.send(render(n));
n.markSent();
} catch (ProviderException ex) {
n.recordFailure(ex); // attempt++
if (n.attempts() >= 5) dlq.send(e);
else throw ex; // retried with backoff
}
}
private EmailProvider.EmailMessage render(Notification n) {
return new EmailProvider.EmailMessage(n.getRecipient(), n.getTemplateCode(), n.getPayload());
}
}package main
import (
"context"
"fmt"
)
type EmailWorker struct {
tx TxRunner
provider EmailProvider
dlq Publisher
}
func (w *EmailWorker) Handle(ctx context.Context, e NotifyEvent) error {
var retry error // set when the provider failed but the attempt was saved
err := w.tx.Do(ctx, func(tx Tx) error {
n, err := tx.LockNotification(ctx, e.ID) // FOR UPDATE
if err != nil || n.Done() {
return err // nil when already SENT or DEAD
}
if err := w.provider.Send(ctx, render(n)); err != nil {
n.RecordFailure(err) // attempt++, DEAD on the 5th
if err := tx.SaveFailure(ctx, n); err != nil {
return err // infra error: roll back, nothing recorded
}
if n.Attempts >= maxAttempts {
return w.dlq.Publish(ctx, e)
}
retry = fmt.Errorf("%w: %v", ErrRetryLater, err)
return nil // commit the attempt count
}
return tx.MarkSent(ctx, n.ID)
})
if err != nil {
return err
}
return retry
}| KafkaKafka | RabbitMQRabbitMQ | |
|---|---|---|
| Hợp vớiGood for | Lưu lượng lớn, phát lại sự kiện, nhiều consumer groupHigh volume, replay, many consumer groups | Hàng đợi tác vụ, định tuyến linh hoạt, ưu tiênTask queues, flexible routing, priorities |
| Retry, DLQRetry, DLQ | Tự làm bằng topic retry + DLQBuild it with retry topics and a DLQ topic | Có sẵn dead-letter exchange, TTLDead-letter exchanges and TTL built in |
| Thứ tựOrdering | Theo partition (key = user_id)Per partition (key = user_id) | Theo queue, mất khi nhiều consumerPer queue, lost with many consumers |
| Chọn khiPick it when | Đã có Kafka, cần audit hoặc phát lạiKafka is already there, you need audit or replay | Team nhỏ, cần ưu tiên OTP đơn giảnA small team needs simple OTP priority |
Worker gọi nhà mạng thành công rồi chết trước khi ghi SENT, message được giao lại và khách nhận OTP thứ hai. Không thể xoá hoàn toàn khả năng này, nhưng có thể thu nhỏ nó: ghi SENDING với attempt id trước khi gọi, gửi kèm idempotency key nếu nhà cung cấp hỗ trợ, và khi thấy SENDING quá 30 giây thì tra trạng thái ở nhà cung cấp trước khi gửi lại.A worker calls the carrier successfully, then dies before recording SENT; the message is redelivered and the customer gets a second OTP. You cannot remove this window entirely, but you can shrink it: record SENDING with an attempt id before calling, pass an idempotency key when the provider supports one, and when a row has been SENDING for over 30 seconds, query the provider before resending.
Campaign 500.000 email đẩy vào cùng topic với OTP khiến OTP chờ hàng phút sau backlog. Tách topic hoặc queue theo mức ưu tiên, cấp worker riêng cho critical và theo dõi consumer lag của từng hàng. Đặt cảnh báo khi lag của critical vượt 2 giây.A 500,000-email campaign on the same topic as OTPs leaves OTPs waiting minutes behind the backlog. Split topics or queues by priority, give critical its own workers, and watch consumer lag per queue. Alert when critical lag exceeds 2 seconds.
Khi nhà mạng hồi phục, hàng nghìn worker retry cùng lúc ở đúng mốc 1, 2, 4 giây và làm nó sập lại. Dùng exponential backoff có jitter ngẫu nhiên, tối đa 5 lần, kết hợp circuit breaker theo nhà cung cấp. Retry trong worker không được block partition; hẹn lại qua hàng retry có độ trễ.When the carrier recovers, thousands of workers retry together at exactly 1, 2 and 4 seconds and knock it over again. Use exponential backoff with random jitter, at most 5 attempts, plus a circuit breaker per provider. Retries must not block the partition; reschedule through a delayed retry queue.
DLQ có 40.000 tin nằm im ba tuần vì không có cảnh báo và không có công cụ gửi lại. Đặt cảnh báo khi DLQ khác 0, lưu lý do lỗi cuối cùng trong message, và có lệnh redrive theo bộ lọc. Với OTP, đừng gửi lại tin quá hạn; đánh dấu EXPIRED thay vì redrive.A DLQ held 40,000 messages for three weeks because nothing alerted on it and there was no way to resend. Alert when the DLQ is non-empty, keep the last error reason in the message, and provide a filtered redrive command. For OTPs, never resend expired messages; mark them EXPIRED instead of redriving.
Mỗi pattern mở bài học tương ứng trong menu Pattern.Each one opens its lesson in the Patterns menu.
Message được giao lại và worker gửi lần hai. Chặn bằng trạng thái SENT có khoá dòng, hoặc idempotency key phía nhà cung cấp nếu có. “Exactly-once” trong thực tế là at-least-once cộng xử lý idempotent.The message is redelivered and the worker sends again. Prevent it with a SENT status under a row lock, or a provider-side idempotency key when available. In practice “exactly once” is at-least-once plus idempotent handling.
Tách hàng đợi theo độ ưu tiên, mỗi hàng có worker và giới hạn tốc độ riêng; campaign đi hàng bulk, OTP đi hàng critical.Separate queues by priority, each with its own workers and rate limit; campaigns use bulk, OTPs use critical.
Dồn tải lên nhà cung cấp đang lỗi (retry storm). Dùng exponential backoff có jitter và circuit breaker.It piles load on a provider that is already failing (a retry storm). Use exponential backoff with jitter and a circuit breaker.
DB và Kafka không có cam kết chung: transaction có thể rollback sau khi tin đã đi, hoặc commit xong rồi service chết trước khi gửi. Outbox gom cả hai vào một lần commit DB.The DB and Kafka share no commit: the transaction can roll back after the message left, or commit and then the service dies before sending. The outbox puts both into one DB commit.
Phím 1–4 để chọn đáp án, Enter để kiểm tra.Press 1–4 to choose an answer, Enter to check.
Ôn tập ngắt quãng (spaced repetition): thẻ được lặp lại sau 1 → 3 → 7 → 14 → 30 ngày để củng cố trí nhớ dài hạn.Spaced repetition: cards are repeated after 1 → 3 → 7 → 14 → 30 days to build long-term memory.