Chuyển tới nội dung chính

Voting Service: overview

TL;DR
  • Voting Core là authority duy nhất cho tính hợp lệ của vote: nhận vote, idempotency, quota, ledger, paid vote saga, projection, finalization.
  • Một Go module (github.com/votee/voting-service), nhiều entry point trong cmd/, SQL viết tay với pgx/v5 trong internal/voting/pgstore.
  • Domain logic thuần (không I/O) ở internal/voting; mọi thứ chạm DB ở pgstore. Unit test cho domain, integration test trên Postgres thật cho store.
  • Giải case: C1, C2, C3, C4, C5, C6, C7, C10, C16, C17, C18.
  • Cần biết trước: Architecture overview, Bounded contexts.
  • Từ khoá: authority, domain/store split, hand-written SQL, worker

1. Trách nhiệm & ranh giới​

Tình huống: An bấm Vote cho Mai. Voting Core là nơi duy nhất quyết định vote đó có hợp lệ hay không.

LàmKhông làm
Accept/reject vote, ghi vote + ledger + quota + idempotency + outboxQuản lý campaign (chỉ giữ read model snapshot)
Điều phối paid vote saga, trả lời resolutionGiữ số dư credit
Publish event qua outbox relayGọi Kafka/Redis trong vote transaction
Hậu kiểm gian lận (signal, detector, review case) và proof of work cho vote từ mạng rủi ro caoTự huỷ vote mà không có người xác nhận
Live ranking projection, final tally, correctionCấp token, quản lý tài khoản (identity-service); Voting Core chỉ verify token cục bộ và kiểm access policy

2. Cấu trúc package​

voting-service/
├── cmd/
│ ├── voting-api/ # HTTP public + internal listener
│ ├── voting-worker/ # subcommand cho từng worker và lệnh vận hành
│ ├── voting-migrate/ # chạy goose migrations
│ └── voting-load/ # load generator
├── migrations/ # 00001…00005, embedded (embed.go)
└── internal/
├── voting/ # domain thuần: command, rules, Decide(), attempt state, errors
│ └── pgstore/ # use case trên PostgreSQL: CastVote, saga, final tally, history
├── httpapi/ # router, handler, error mapping
├── outbox/ # relay outbox → Kafka
├── ranking/ # projector, rebuild/reconcile, Redis cache, reader
├── campaignsync/ # consumer snapshot campaign
├── finalizer/ # consumer FinalizationRequested
├── creditclient/ # HTTP client reserve credit
├── ratelimit/ # fixed-window limiter (Redis Lua)
├── integrity/ # signal, detector, review case (ingest/, integritystore/)
├── asn/ # tra ASN offline, phân loại mạng hosting
├── pow/ # challenge proof of work và bảo vệ dùng lại
├── events/ # wire contract của event
├── platform/ # config, postgres, kafka, metrics, test helpers
├── e2e/ # test HTTP + pipeline end-to-end
└── smoke/ # full flow với mọi service (build tag smoke)

voting không import package nào khác trong repo: domain rules test được không cần DB.

Quyết định thiết kế chính​

Quyết định: SQL viết tay với pgx, domain thuần tách khỏi store​

Vấn đề. Đúng đắn của Voting Core đến từ từng câu lệnh SQL (upsert có điều kiện, khoá, savepoint). Cần nhìn thấy và kiểm soát chính xác từng câu.

Phương án khác. Dùng ORM: ít code hơn nhưng che mất thứ tự câu lệnh, khoá và mức cô lập, đúng những thứ quyết định tính đúng.

Lựa chọn. Dùng pgx/v5 với SQL viết tay trong internal/voting/pgstore; luật nghiệp vụ nằm ở package voting không import gì khác trong repo. Use case điều phối qua cổng Tx mà mỗi method là một thao tác lưu trữ, không chứa quyết định nghiệp vụ.

Đánh đổi. Nhiều SQL phải tự viết và tự kiểm thử. Đổi lại luật test không cần DB, store test trên PostgreSQL thật, và mỗi đảm bảo đồng thời nằm trong một câu lệnh đọc được.

3. Process & port​

ProcessLệnhPort / pool
voting-apibin/voting-api:8080 public (client đi qua gateway), 127.0.0.1:8090 internal + /metrics (mọi route /internal/** cần X-Votee-Internal-Token, VOTEE_INTERNAL_TOKEN); pool transaction_timeout=5s
outbox-relayvoting-worker outbox-relaypool riêng 4 conn, transaction_timeout=30s
ranking-projectorvoting-worker ranking-projectorgroup votee-ranking-projector
campaign-syncvoting-worker campaign-syncgroup votee-voting-campaign-sync
finalizervoting-worker finalizergroup votee-voting-finalizer
attempt-sweepervoting-worker attempt-sweepermỗi 30 s, batch 100
idempotency-cleanupvoting-worker idempotency-cleanupmỗi 10 phút, batch 1000
Lệnh vận hànhkafka-topics, ranking-rebuild, ranking-reconcile, ranking-cache-warmchạy tay

4. Config chính​

EnvMặc địnhÝ nghĩa
VOTEE_DATABASE_URLpostgres://voting_service:…@localhost:15432/votee
VOTEE_KAFKA_BROKERSlocalhost:19092
VOTEE_REDIS_ADDRlocalhost:16379
VOTEE_CREDIT_URLhttp://localhost:8082rỗng ⇒ tắt paid vote
VOTEE_RATE_LIMIT_PER_SEC20per actor; 0 tắt
VOTEE_ATTEMPT_ABANDON_AFTER2mtối thiểu 30s
VOTEE_FINALIZATION_GRACE10sphải > 5s
VOTEE_INTERNAL_API_ENABLEDfalsebật endpoint seed snapshot (dev)
VOTEE_DB_MAX_CONNS20

Nguồn: voting-service/internal/platform/config/config.go.

5. Dependencies​

pgx/v5 (SQL viết tay), goose (migration embedded), google/uuid (UUIDv7), franz-go (Kafka), go-redis/v9, prometheus/client_golang, golang.org/x/sync/errgroup.

Vì sao không dùng sqlc / ORM?

Vote transaction chỉ là vài statement được sắp thứ tự cẩn thận (claim → snapshot → quota → vote → ledger → outbox). Giữ SQL tường minh trong pgstore giúp review locking và thứ tự dễ hơn. Xem lại khi số query tăng.

6. Danh sách module​

ModuleCâu hỏi nó trả lờiCase
Vote acceptanceMột vote được accept trong một transaction như thế nào?C5, C6
IdempotencyRetry cùng key thì sao? Request song song cùng key thì sao?C1, C2
QuotaLàm sao không vượt quota mà không SELECT COUNT?C3, C4
Campaign snapshot & timeVoting Core biết campaign đang mở thế nào, biên thời gian chính xác ra sao?C6, C7
Paid vote sagaTrừ credit và ghi vote ở hai service mà không có distributed transaction?C10, C12
Outbox & relayPublish event chắc chắn khi và chỉ khi DB commit?
Ranking projectionLive ranking nhanh, chịu duplicate, rebuild được?C16
Finalization & correctionsFinal ranking không bỏ sót vote, sửa được mà vẫn audit được?C17, C18
HTTP API & rate limitMapping lỗi ra HTTP, an toàn khi retry?C19
PlatformConsumer at-least-once, config, metrics, test fixture dùng chung?

7. Rút ra & từ khoá​

Điều đáng nhớ: luật vote nằm trong một package Go thuần không I/O, mọi thứ chạm cơ sở dữ liệu nằm ở pgstore, nên luật kiểm thử không cần DB còn đúng đắn về đồng thời được kiểm thử trên PostgreSQL thật.

Từ khoáNghĩa (một câu)Nơi khác trong Votee dùng lại
authorityNơi duy nhất quyết định một loại dữ liệu đúng hay saiBounded contexts
domain/store splitLuật nghiệp vụ thuần tách khỏi code chạm cơ sở dữ liệuVote acceptance
hand-written SQLSQL viết tay thay vì ORM để kiểm soát từng câu lệnhQuota
workerTiến trình nền, mỗi tác vụ một lệnhDeployment

Đọc tiếp: Vote acceptance, luồng nền tảng của Voting Core.