Platform (config, Kafka consumer, metrics, test helpers)
- Làm gì:
internal/platformgom hạ tầng mà mọi worker dùng: config từ env, pool Postgres (transaction_timeout), Kafka client +BatchConsumer[T]generic, Prometheus metrics, và helper test (DB/topic/Redis tạm). - Invariant chính: consumer commit offset chỉ sau khi side effect đã commit; poison ⇒ DLQ; lỗi tạm thời ⇒ retry vô hạn (không bao giờ bỏ qua).
- Code:
voting-service/internal/platform/(config,postgres,kafka,metrics,testdb,testkafka,testredis,testfixture). - Cần biết trước: Outbox & relay, Kafka errors.
- Từ khoá:
at-least-once consumer,poison message,consumer group rebalance,DLQ
1. Bối cảnh & yêu cầu
Tình huống: Ba consumer cùng nhận sự kiện kiểu at-least-once, và một sự kiện hỏng không được chặn cả partition.
- Ba consumer (projector, campaign-sync, finalizer) cần cùng chính sách at-least-once; viết lặp ba lần là ba chỗ có thể sai.
- Rebalance giữa batch có thể khiến commit offset cho partition đã chuyển sang member khác.
- Integration test cần DB/Kafka/Redis thật nhưng phải cô lập để chạy song song.
2. Thiết kế
| Quyết định | Vì sao |
|---|---|
DisableAutoCommit + commit sau handle | At-least-once: crash trước commit ⇒ redeliver, handler idempotent |
BlockRebalanceOnPoll | Không commit offset cho partition vừa bị lấy mất giữa batch |
| Phân loại poison (decode lỗi) vs transient (handler lỗi) | Poison không bao giờ thành công khi retry ⇒ DLQ để partition chạy tiếp; transient bỏ qua là mất dữ liệu ⇒ retry tới khi dependency hồi |
SessionTimeout(15s) | Chaos drill: member kill -9 giữ partition 45 s (mặc định); 15 s rút ngắn lag |
Generic BatchConsumer[T] với Decoder[T] + Handler[T] | Một implementation cho mọi consumer, chỉ khác decode/handle |
Murmur2 key partitioner (StickyKeyPartitioner(nil)) | Cùng partition với Java client cho cùng key |
Mỗi test package một database votee_test_<random> đã migrate | Chạy song song, không dọn dẹp chéo |
Quyết định thiết kế chính
Quyết định: commit offset sau khi xử lý, phân loại poison và transient
Vấn đề. Ba consumer (projector, campaign-sync, finalizer) cần cùng chính sách at-least-once; viết lặp là ba chỗ có thể sai.
Phương án khác. Bỏ qua lỗi sau vài lần thử: mất dữ liệu. Thử mãi mọi lỗi: một message hỏng chặn partition vĩnh viễn.
Lựa chọn. BatchConsumer[T] tắt auto-commit và commit sau khi xử lý, chặn rebalance trong lúc xử lý một batch. Lỗi giải mã (poison, không bao giờ thành công) chuyển sang <topic>.dlq; lỗi của handler (tạm thời) thử lại với backoff 100 ms đến 10 giây, không giới hạn.
Đánh đổi. Dependency lỗi lâu thì consumer đứng chờ (đúng hơn là mất dữ liệu). Cần người vận hành xem DLQ.
3. Invariants
| Invariant | Ai đảm bảo |
|---|---|
| Offset commit ⇒ side effect đã commit | Thứ tự trong pollOnce |
| Poison không chặn partition | DLQ + commit |
| Lỗi transient không bao giờ bị bỏ qua | Retry vô hạn tới khi ctx huỷ |
Vote pool luôn có transaction_timeout=5s | postgres.NewPool (worker cần lâu hơn phải gọi NewPoolWithTimeout tường minh) |
VOTEE_FINALIZATION_GRACE > 5s, VOTEE_ATTEMPT_ABANDON_AFTER ≥ 30s | config.Load từ chối giá trị sai |
4. Data model / DB
postgres.Migrate tạo schema voting/ranking nếu chưa có, rồi chạy goose với bảng version voting.goose_db_version; migration được embed vào binary (voting-service/migrations/embed.go).
5. Code walkthrough
| File | Vai trò |
|---|---|
platform/config/config.go | Load(): env + default + validate |
platform/postgres/postgres.go | NewPool, NewPoolWithTimeout, Migrate |
platform/kafka/kafka.go | NewClient, EnsureTopics, Publisher |
platform/kafka/consumer.go | ConsumerGroupOpts, BatchConsumer, DeadLetter, Retry |
platform/metrics/metrics.go | Toàn bộ metric votee_*, Serve cho worker |
platform/testdb/testdb.go | Create/Drop database tạm |
platform/testkafka/testkafka.go | Topic tạm (và .dlq), xoá sau test |
platform/testredis/testredis.go | Client + prefix riêng cho mỗi test |
platform/testfixture/fixture.go | NewCampaign, Cast, CastMany cho test projection/relay/e2e |
// Transient failures are retried forever: skipping would lose data; the partition lags
// until the dependency recovers.
if len(poison) > 0 {
if err := Retry(ctx, c.log, "publish to DLQ", func() error { return c.dlq.Publish(ctx, poison...) }); err != nil {
return err
}
}
if len(msgs) > 0 {
if err := Retry(ctx, c.log, "handle batch", func() error { /* c.handle(ctx, msgs) */ }); err != nil {
return err
}
}
if err := c.client.CommitRecords(ctx, records...); err != nil {
// Not fatal: the batch is redelivered and handled idempotently.
c.log.Error("commit offsets failed", "error", err)
}
DLQ record giữ nguyên key/value/headers gốc và thêm dlq_error, dlq_original_topic, dlq_original_partition, dlq_original_offset.
6. Failure modes
| Tình huống | Hệ thống làm gì | Phục hồi |
|---|---|---|
| DB down khi handle | Retry vô hạn; partition lag | Tự hồi |
| DLQ topic không ghi được | Retry; không commit | Tự hồi khi Kafka OK |
| Commit offset lỗi | Log; batch redeliver | Handler idempotent |
| Member chết đột ngột | Partition bị giữ tới hết session (15 s) | Rebalance tự động |
7. Testing
Helper test là nền của mọi integration test Go. Chạy cần make infra-up; CI dùng service container với cùng port. Biến môi trường: VOTEE_TEST_ADMIN_DATABASE_URL, VOTEE_TEST_KAFKA_BROKERS, VOTEE_TEST_REDIS_ADDR.
TestPipelineSurvivesDuplicatesPoisonAndReplay (voting-service/internal/e2e/pipeline_test.go) kiểm BatchConsumer end-to-end với 8 voter song song:
- Relay "crash" một lần sau khi produce ⇒ batch đầu được publish hai lần.
- Một poison record (
not-json) nằm giữa topic ⇒ vào DLQ, partition chạy tiếp. - Replay toàn topic với consumer group mới ⇒ ranking không đổi.
- Xoá projection và rebuild từ ledger ⇒ cùng kết quả.
8. Observability
| Metric | Ý nghĩa |
|---|---|
votee_consumer_records_total{consumer,result} | handled / skipped / poison |
votee_consumer_retries_total{consumer} | Lỗi transient |
Worker expose /metrics trên VOTEE_METRICS_ADDR | voting-api expose trên internal listener |
9. Câu hỏi thường gặp
Vì sao lỗi handler được retry vô hạn thay vì đưa vào DLQ sau N lần?
Lỗi handler thường do dependency (DB down). Event vẫn hợp lệ; đưa vào DLQ sau N lần là bỏ qua một vote khỏi projection, tức mất dữ liệu. Để partition lag và alert là đúng; khi DB hồi, mọi thứ tự bắt kịp.
BlockRebalanceOnPoll bảo vệ điều gì?
Nếu rebalance xảy ra giữa batch, partition có thể chuyển sang member khác, member kia bắt đầu từ offset đã commit. Member cũ commit offset sau khi xử lý xong thì không gây mất mát, nhưng có thể ghi đè offset của chủ mới. Chặn rebalance tới khi batch xong làm ranh giới rõ ràng.
10. Rút ra & từ khoá
Điều đáng nhớ: một consumer chung với chính sách lỗi rõ ràng (poison thì DLQ, lỗi tạm thời thì thử mãi) thay cho ba bản viết lặp, mỗi bản có thể sai một kiểu.
| Từ khoá | Nghĩa (một câu) | Nơi khác trong Votee dùng lại |
|---|---|---|
at-least-once consumer | Commit offset chỉ sau khi side effect đã commit | Event catalog |
poison message | Message không bao giờ xử lý được, đi DLQ | Kafka errors |
consumer group rebalance | Chia lại partition khi consumer vào hoặc ra | Deployment |
DLQ | Topic chứa message lỗi không xử lý được | Kafka errors |
11. Tham chiếu & đọc tiếp
- Kafka error handling (Java): cùng chính sách
- Testing: fixtures & commands
Đọc tiếp: Payment Service, service tiếp theo trong luồng nghiệp vụ.