Voting Service: overview
- 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 trongcmd/, SQL viết tay vớipgx/v5tronginternal/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àm | Không làm |
|---|---|
| Accept/reject vote, ghi vote + ledger + quota + idempotency + outbox | Quản lý campaign (chỉ giữ read model snapshot) |
| Điều phối paid vote saga, trả lời resolution | Giữ số dư credit |
| Publish event qua outbox relay | Gọ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 cao | Tự huỷ vote mà không có người xác nhận |
| Live ranking projection, final tally, correction | Cấ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
| Process | Lệnh | Port / pool |
|---|---|---|
| voting-api | bin/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-relay | voting-worker outbox-relay | pool riêng 4 conn, transaction_timeout=30s |
| ranking-projector | voting-worker ranking-projector | group votee-ranking-projector |
| campaign-sync | voting-worker campaign-sync | group votee-voting-campaign-sync |
| finalizer | voting-worker finalizer | group votee-voting-finalizer |
| attempt-sweeper | voting-worker attempt-sweeper | mỗi 30 s, batch 100 |
| idempotency-cleanup | voting-worker idempotency-cleanup | mỗi 10 phút, batch 1000 |
| Lệnh vận hành | kafka-topics, ranking-rebuild, ranking-reconcile, ranking-cache-warm | chạy tay |
4. Config chính
| Env | Mặc định | Ý nghĩa |
|---|---|---|
VOTEE_DATABASE_URL | postgres://voting_service:…@localhost:15432/votee | |
VOTEE_KAFKA_BROKERS | localhost:19092 | |
VOTEE_REDIS_ADDR | localhost:16379 | |
VOTEE_CREDIT_URL | http://localhost:8082 | rỗng ⇒ tắt paid vote |
VOTEE_RATE_LIMIT_PER_SEC | 20 | per actor; 0 tắt |
VOTEE_ATTEMPT_ABANDON_AFTER | 2m | tối thiểu 30s |
VOTEE_FINALIZATION_GRACE | 10s | phải > 5s |
VOTEE_INTERNAL_API_ENABLED | false | bật endpoint seed snapshot (dev) |
VOTEE_DB_MAX_CONNS | 20 |
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.
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
| Module | Câu hỏi nó trả lời | Case |
|---|---|---|
| Vote acceptance | Một vote được accept trong một transaction như thế nào? | C5, C6 |
| Idempotency | Retry cùng key thì sao? Request song song cùng key thì sao? | C1, C2 |
| Quota | Làm sao không vượt quota mà không SELECT COUNT? | C3, C4 |
| Campaign snapshot & time | Voting Core biết campaign đang mở thế nào, biên thời gian chính xác ra sao? | C6, C7 |
| Paid vote saga | Trừ credit và ghi vote ở hai service mà không có distributed transaction? | C10, C12 |
| Outbox & relay | Publish event chắc chắn khi và chỉ khi DB commit? | |
| Ranking projection | Live ranking nhanh, chịu duplicate, rebuild được? | C16 |
| Finalization & corrections | Final ranking không bỏ sót vote, sửa được mà vẫn audit được? | C17, C18 |
| HTTP API & rate limit | Mapping lỗi ra HTTP, an toàn khi retry? | C19 |
| Platform | Consumer 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 |
|---|---|---|
authority | Nơi duy nhất quyết định một loại dữ liệu đúng hay sai | Bounded contexts |
domain/store split | Luật nghiệp vụ thuần tách khỏi code chạm cơ sở dữ liệu | Vote acceptance |
hand-written SQL | SQL viết tay thay vì ORM để kiểm soát từng câu lệnh | Quota |
worker | Tiến trình nền, mỗi tác vụ một lệnh | Deployment |
Đọc tiếp: Vote acceptance, luồng nền tảng của Voting Core.