Votee — Architecture
Status: Implemented (campaign, voting, ranking, credit per (account, campaign) with refunds, identity with
token verification and the access policy, vote packages and payment with a fake provider). Real settlement with a
payment provider is not built. Operations are in operations.md; measured performance in
performance.md; the reasoning behind the design is on the study site (website/docs).
Legend: [R] confirmed requirement · [D] decision · [A] assumption.
1. Scope
The system covers the voting domain, identity and access, and package purchase: campaigns and candidates, voting rules and access policy, vote acceptance, quota, idempotency, accounts and guests, vote package purchase, paid voting through per-campaign credits, live and final ranking, domain events, and audit records. CMS features, an admin UI, eKYC and real money settlement with a payment provider are out of scope.
Confirmed product decisions
- [R] Award-show style multi-vote: each actor has a free vote quota per period and may
cast additional paid votes using credits. Single-choice voting is the special case
quota = 1. - [R] Credit is handled by a Spring Boot service using a reservation workflow.
- [R] Campaign & Rules are owned by a Spring Boot service and replicated to Voting Core.
- [R] Four Spring Boot services:
campaign-service,credit-service,identity-service,payment-service. - [D] Credit is scoped per
(account, campaign); purchased votes are not a shared wallet across campaigns. - [D] Paid votes are tied to an account. If
paid_vote_price > 0, guests are blocked. - [D] Vote packages are campaign configuration; payment keeps no second price catalogue.
Assumptions
- [D]
identity-serviceissues short-lived JWTs; voting-api verifies them locally against JWKS, with no synchronous call to identity per vote.X-Actor-Idis replaced by the verified token subject andX-Admin-Idby verified admin claims. - [A] Payment provider integration is a fake provider (HMAC-signed webhooks); a sandbox adapter may follow. Paid votes on prize campaigns must stay disabled until a legal review (jurisdiction not decided). This is an operating policy: the system does not enforce it.
- [A] Learning-scale load target: ~1–5k votes/s on a single machine; single region.
- [A] Default campaign timezone for period-based quotas is
Asia/Ho_Chi_Minh.
2. Components and deployables
| Deployable | Language | Responsibility |
|---|---|---|
voting-api | Go | Public API (:8080): votes (free and paid), vote history, live/final ranking. Internal API (127.0.0.1:8090): attempt resolution, vote invalidation, /metrics, optional dev snapshot seeding |
voting-worker | Go | One subcommand per worker: outbox-relay, ranking-projector, campaign-sync, finalizer, attempt-sweeper, idempotency-cleanup, outbox-cleanup, plus operations commands (kafka-topics, ranking-rebuild, ranking-reconcile, ranking-cache-warm) |
campaign-service | Java / Spring Boot | Campaign lifecycle, candidates, versioned rule sets, scheduler, finalization orchestration, the access policy (min_identity), vote packages |
credit-service | Java / Spring Boot | Credit accounts, reservations, credit ledger, capture/release, reservation expiry, balances per (account, campaign), refunds of unspent credit; grants only by consuming PaymentConfirmed |
identity-service (:8083) | Java / Spring Boot | Accounts, credentials, PII, email and phone verification, verification level, login lockout, JWT and refresh tokens, JWKS, guest identities, admin identities |
payment-service (:8084) | Java / Spring Boot | Orders (price snapshot), provider integration, webhooks, reconciliation, chargeback debt; outbox for PaymentConfirmed |
gateway (:8000) | Envoy | The one public origin: allowlisted routes to the five services above, CORS, limits and timeouts; /internal/** is never forwarded. It does not authenticate; services verify tokens themselves |
| PostgreSQL | — | Source of truth (one instance, one schema per context) |
| Kafka | — | Domain event distribution |
| Redis | — | Live ranking cache and rate limiting |
| Mailpit | — | Development only: catches identity-service's mail (verification codes); UI on :18025 |
voting-api and voting-worker are built from one Go module (voting-service) with
separate cmd/ entry points so that workers can be scaled and restarted independently.
The Spring services share only infrastructure code (platform-common: outbox relay,
event envelope), never domain code. The new services use the same domain / application /
infrastructure layering and an ArchitectureTest.
Ports :8083 and :8084 were proposed in the scope change and are in use; confirm them against your local setup.
3. Bounded contexts and ownership
| Context | Owner | Owns | Schema |
|---|---|---|---|
| Voting | Go | vote, vote_attempt, vote_ledger_entry, vote_quota_usage, idempotency_record, campaign_snapshot (read model), final_tally, frozen_ranking, outbox_event | voting |
| Integrity review | Go worker (voting-service) | vote_signal (pseudonymous, purged after 90 days), review_case, review_case_member | integrity |
| Ranking projection | Go worker | candidate_tally, applied_ledger_entry, Redis sorted sets | ranking |
| Campaign & Rules | campaign-service | campaign (with embedded current rules), candidate, rule_set_history, campaign_transition, outbox_event; the access policy is part of the rule set, vote_package | campaign |
| Credit | credit-service | credit_account, credit_reservation, credit_ledger_entry (append-only, unique per operation); all keyed by (account_id, campaign_id) (migration V2) | credit |
| Identity | identity-service | accounts (canonical email, verified phone), credentials, PII, verification level, verification challenges and send counters, phone releases, refresh tokens, guest identities, admin identities, signing keys | identity |
| Payment | payment-service | payment_order, payment_debt, webhook_event (dedupe), outbox_event | payment |
Rules:
- [D] A service writes only to its own schema. Cross-context communication is through HTTP APIs or Kafka events. Separate schemas on one instance keep local development simple; splitting into separate databases later requires no code change.
- [D] PII (email, phone, national ID if ever collected) lives only in
identity. Voting and campaign never store PII. - [D] Voting Core is the sole authority for vote validity. Kafka and Redis are never consulted to decide whether a vote is accepted.
4. Consistency and transaction boundaries
Strongly consistent (single PostgreSQL transaction)
| Context | Transaction contents |
|---|---|
| Voting (free vote) | idempotency record + vote + vote ledger entry + quota counters + outbox event |
| Voting (paid vote, step B) | vote attempt transition + vote + ledger entry + quota counters + idempotency record + outbox event |
| Credit | account balances + reservation + credit ledger entry (per (account, campaign)) |
| Campaign | campaign state + transition audit row + outbox event |
| Payment | order transition + webhook event record (dedupe by provider event id) + debt + outbox event |
| Identity | account / refresh token / key change; no event is required for authentication |
Eventually consistent
| Data | Source | Lag impact |
|---|---|---|
campaign_snapshot in Voting | campaign-service events | Only manual PAUSE / early END; time windows are exact (see §5.4). (Planned) the access policy travels in the same snapshot |
| Credit grant | payment.PaymentConfirmed.v1 | A paid order is spendable after the consumer commits the GRANT (idempotent by payment:<order_id>) |
| Live ranking (PostgreSQL projection, Redis) | vote events | Seconds; never affects acceptance |
| Credit capture | VoteAccepted event | Reserved credit is guaranteed to be captured or released after the outcome is known |
Campaign FINALIZED | FinalTallyComputed event | Final ranking is visible once computed |
There are no distributed transactions. Cross-context workflows use sagas built on the transactional outbox, idempotent consumers, and reconciliation.
5. Core designs
5.1 Vote acceptance
- One PostgreSQL transaction at
READ COMMITTED; correctness comes from atomic conditional statements and unique constraints, not from isolation level. - No network call to Kafka, Redis, or other services inside the transaction.
- A success response (
201) is returned only afterCOMMITsucceeds. transaction_timeout = 5sis set on every voting-api connection (closing barrier, §5.4); requires PostgreSQL 17+. Workers that hold locks across network calls (outbox relay) use their own pool with a longer timeout.
5.2 Idempotency
idempotency_recordprimary key:(actor_id, campaign_id, operation, idempotency_key).request_fingerprint= SHA-256 of the canonical request payload.- Flow inside the vote transaction: the record is inserted first as
IN_PROGRESS(INSERT ... ON CONFLICT DO NOTHING) and updated toCOMPLETEDbefore commit, soIN_PROGRESSis never visible to other transactions. A concurrent request with the same key blocks on the unique index until the first transaction commits or aborts. If the insert does not happen, the stored record is read: different fingerprint →422; otherwise the original outcome is replayed with headerIdempotent-Replayed: true. - The record stores the outcome (
ACCEPTED+vote_id, orREJECTED+rejection_code), not a serialized HTTP response. Replays rebuild the response from the immutable vote row, keeping HTTP concerns out of the database. - A key identifies one attempt, and every business rejection is final for that key —
including time-dependent ones such as
QUOTA_EXCEEDEDor a paused campaign. Retrying later requires a new key. Not stored (so the same key may be retried): validation errors (400), unknown campaign/candidate (404, the snapshot may not have arrived yet), and infrastructure errors (503). - Business rejections roll back partial quota claims with a
SAVEPOINTwhile keeping the idempotency record in the same transaction. - Records expire after 7 days and are deleted in small batches by
voting-worker idempotency-cleanup; after deletion the key is a fresh attempt again.vote.idempotency_keykeeps the audit trail.
5.3 Quota
-
Never
SELECT COUNT(*)followed byINSERT. -
Counter rows in
vote_quota_usage, keyed by scope. Free and paid votes use separate budgets so buying votes never consumes the free allowance:Scope Applies to Purpose FREE_ACTOR_CAMPAIGN_PERIODfree votes (mandatory) e.g. 10 free votes per actor per day FREE_ACTOR_CANDIDATE_PERIODfree votes (optional) limit concentration on one candidate PAID_ACTOR_CAMPAIGN_PERIODpaid votes (optional) anti-whale cap on purchased votes -
Atomic conditional upsert:
INSERT INTO voting.vote_quota_usage (scope_key, period_start, used)VALUES ($1, $2, $3)ON CONFLICT (scope_key, period_start) DO UPDATESET used = vote_quota_usage.used + EXCLUDED.usedWHERE vote_quota_usage.used + EXCLUDED.used <= $4RETURNING used;No row returned → quota exceeded → transaction outcome is a stored rejection.
-
Multiple scopes are updated in a fixed order to avoid deadlocks.
-
Periods are computed from the PostgreSQL clock in the campaign timezone.
-
Contention: counter rows are hot only per actor. Per-candidate totals and campaign-wide totals are not maintained synchronously; they are projections.
5.4 Campaign lifecycle and time semantics
DRAFT → SCHEDULED → ACTIVE ⇄ PAUSED → ENDED → FINALIZING → FINALIZED [→ CERTIFIED]
DRAFT | SCHEDULED → CANCELLED
- A vote is accepted iff the snapshot status is
SCHEDULEDorACTIVEandstarts_at <= now() < ends_at, wherenow()is the PostgreSQL transaction timestamp.accepted_at = now()is persisted on the vote. SCHEDULEDis accepted so a delayed scheduler transition never blocks a valid vote.PAUSED,ENDED,CANCELLED, and later states always reject.- Campaign and candidate snapshots are read in one statement: under
READ COMMITTEDeach statement has its own snapshot, so two reads could mix versions if a snapshot update commits in between. - Time windows are deterministic, so replication lag does not affect them. Manual PAUSE
and early END are eventually consistent (seconds) and documented as such. Every vote
records
campaign_snapshot_versionandrule_set_version. - While ACTIVE,
ends_atmay only be extended; shortening is an explicit, audited END command. - Closing barrier: finalization starts only after
ends_at + grace, withgrace > transaction_timeout, guaranteeing that no vote transaction can still commit. ENDED(no more votes) is distinct fromFINALIZED(final tally computed and published).- campaign-service implements the state machine in the
Campaignaggregate (plain methods taking the database clock, unit-tested without Spring). Admin commands use JPA optimistic locking (@Version); the scheduler (@Scheduled, every second) locks due campaigns withFOR UPDATE SKIP LOCKED, so several instances can run it. Every committed change appends a fullcampaign.CampaignSnapshotPublishedevent (event-carried state transfer) to the outbox;voting-worker campaign-syncapplies only newersnapshot_versions. Transitions are audited incampaign_transition, rule set versions inrule_set_history.
Finalization
- campaign-service moves ENDED → FINALIZING once
now ≥ ends_at + grace(grace 10 s > 5 s transaction timeout) and publishescampaign.FinalizationRequested{snapshot_version}. voting-worker finalizercomputes the tally only if Voting Core's own snapshot is at least that version and closed. Otherwise it retries: a manual END reaches Voting Core through campaign-sync, and until it does Voting Core may still accept votes, so finalizing earlier could miss them. The smoke test hits this race in practice (one retry, ~100 ms).- The tally is computed from the ledger in one statement into
final_tally_run+final_tally(append-only), with a ledger watermark and an MD5 checksum, and published asvoting.FinalTallyComputed. Duplicate requests return the existing version. - campaign-service consumes it: FINALIZING → FINALIZED; a newer version on a FINALIZED campaign is recorded as a correction.
5.5 Voting rules
- Rule sets are versioned data attached to a campaign: free quota per period, optional
per-candidate limit, max votes per request, free vote points, paid vote price and points,
optional paid cap per period. campaign-service validates them with the same rules as
Voting Core, so no snapshot is ever rejected downstream. Both sides run the shared vectors in
contracts/rules/rules-validation.jsonand must flag the same fields, so the two validations cannot drift apart. - The rule set has an access policy:
min_identity(GUEST | ACCOUNT | VERIFIED_ACCOUNT), versioned like the other rules. Ifpaid_vote_price > 0, guests are blocked entirely. campaign-service rejects such a rule set on write and voting-api re-checks it from the snapshot; both implementations must change together. The policy is enforced before quota and credit checks. - Two more rules:
min_account_age_seconds: the account must be that old. voting-api compares it with the token claimacct_created_at, so there is still no call to identity per vote. A missing claim fails closed.ranking_freeze_seconds: the public live ranking freezes that long beforeends_at. The frozen ranking is the ledger before the freeze instant. It is computed once, after the same closing barrier finalization uses (instant- 10 s > 5 s transaction timeout), and stored append-only in
voting.frozen_ranking[_run]. Votes keep being accepted, and auditors and administrators still see the live ranking.
- 10 s > 5 s transaction timeout), and stored append-only in
- Auditors hold the
AUDITORrole:GETon campaign-service (votee.auth.read-roles) and/v1/audit/campaigns/{id}/{tallies,invalidations}on voting-api. Invalidations now store their reason on the ledger entry. - Evaluation in Go is split into stateless rules (pure functions) and quota rules (mapped to counter scopes). A rule engine/DSL is deliberately not used yet.
5.6 Paid vote: credit reservation saga
Voting Core orchestrates; credit-service owns balances.
- Txn A (voting): claim the idempotency key, evaluate the rules (a request that would be
rejected fails fast without touching credit), create
vote_attempt(PENDING_RESERVATION)and mark the idempotency recordPENDING.reservation_key = attempt_id. The price is fixed here (price × votes, stored on the attempt); credit-service never needs campaign rules. - Sync HTTP, outside any transaction:
POST /internal/v1/reservationson credit-service (2 tries × 3 s), idempotent byreservation_key. credit-service inserts the reservation row first (concurrent requests with the same key serialize on its unique index), then debits withUPDATE … SET available = available - :amt, reserved = reserved + :amt WHERE … AND available >= :amt; insufficient credit rolls back the whole transaction. - Txn B (voting): lock the attempt row (
FOR UPDATEserializes concurrent resumes, the sweeper and the resolution endpoint); if still pending, re-evaluate rules and quota with the current clock, then either accept (vote + ledger + quota + outboxVoteAccepted{reservation_id}) or reject (outboxCreditReleaseRequested). - Respond after Txn B commits. credit-service consumes
VoteAcceptedand captures idempotently (UPDATE ... WHERE state = 'RESERVED').
| Failure | Handling |
|---|---|
| Insufficient credit | Attempt REJECTED; rejection stored for idempotent replay |
| credit-service failing or saturated | A bulkhead (default 128 reservations in flight) and a circuit breaker (opens after 5 failed calls in a row, 10 s) make a paid vote fail at once with 503 CREDIT_UNAVAILABLE and Retry-After instead of waiting on timeouts; the attempt stays pending and the same key resumes it. Free votes never touch credit-service |
| Reserve timeout / unknown result | Retry with the same reservation_key; if still unknown return 503 (retryable); a client retry with the same idempotency key resumes the attempt |
Vote rejected after reservation (including an access policy that changed in between: ACCESS_DENIED) | CreditReleaseRequested written in the same transaction |
| Voting Core crashes between steps 2 and 3 | Sweeper moves stale attempts to ABANDONED (conditional update) and emits release |
| Reservation TTL (10 min) expires | credit-service never auto-releases; it calls GET /internal/v1/vote-attempts/{key}/resolution. Voting Core answers CAPTURE or RELEASE, or PENDING for an attempt younger than 2 min; an older pending attempt is atomically ABANDONED before answering RELEASE. PENDING, errors or an unreachable Voting Core keep the credit reserved and are asked again 30 s later |
| Duplicate capture / consumer failure | At-least-once delivery + idempotent capture; capture on a RELEASED reservation raises an alert |
Client retries after ABANDONED | The stored outcome is replayed (409 ATTEMPT_ABANDONED); the client must use a new idempotency key. An abandoned attempt is never revived, so a release can never race with a late acceptance |
| Release requested before the reservation exists | No-op; the late reservation expires and is resolved as RELEASE |
Credit ledger: every balance change appends credit_ledger_entry(entry_type, reference) with a
unique (entry_type, reference) — one GRANT per payment reference, one RESERVE/CAPTURE/RELEASE
per reservation — so retries and duplicate events can never apply twice. Invariants, checked
by the tests: available = Σ available_delta, reserved = Σ reserved_delta = Σ open reservations. Capture of a released reservation (or the reverse) is refused and logged.
Per-campaign credit, purchase and refunds
- Scope (implemented). The balance key is
(account_id, campaign_id). Ledger rows and reservations carrycampaign_id. The saga above is unchanged: only the key scope changed, and voting reserves credit by(actor_id, campaign_id). - Invariants (implemented).
available >= 0andreserved >= 0, enforced by conditionalUPDATEas the reserve path already does, never by application code alone. Spends in one campaign never affect another. - Purchase flow (implemented). campaign-service defines the vote packages. payment-service creates an order that
snapshots the package price. Order states:
PENDING → PAID | FAILED;PAID → REFUNDED (partial) | DISPUTED. A webhook is verified by provider signature, deduplicated by provider event id, tolerates out-of-order delivery, and every transition is idempotent byorder_id. OnPAIDit writes the outbox eventpayment.PaymentConfirmed.v1 {order_id, account_id, campaign_id, credits, amount, currency}. credit-service consumes it (consumer groupvotee-credit-service-payments) and performs aGRANTwith referencepayment:<order_id>(unique, idempotent); a redelivery is a no-op and an event that cannot be applied (zero credits, an order id already used for other credit) goes to the dead-letter topic. The public grants endpoint no longer exists: this event is the only source of credit. - Refunds (implemented in credit-service). Only unspent credit is refundable: refund = min(credits granted by that order, current
available balance for the account and campaign). Attribution of spends to grants is FIFO per
(account, campaign); the refund formula does not depend on it, so no code attributes spends. - Chargebacks (implemented). The card network imposes them, so a loss can occur while the balance must never go
negative. payment-service records a debt for
(account, campaign)and blocks further purchases there until a new order settles it: the buyer creates a settlement order for the debt amount (it grants no credit), and paying it settles the debt. The debt is never stored as a negative credit balance; votes already accepted stand, and credit already granted stays spendable (an operator can refund the unspent part withPOST /internal/v1/orders/{id}/refund).
5.7 Ranking
- Live ranking (Phase 2, PostgreSQL):
voting-worker ranking-projectorconsumes vote events and, in one transaction, insertsranking.applied_ledger_entryrows and updatesranking.candidate_tally.- Deduplication is keyed on
ledger_entry_id(the identity of the fact), not on the messageevent_id. A re-published, replayed, or re-generated event for an already counted entry is ignored, and a rebuild can mark exactly the entries it counted. - Deltas are aggregated per candidate per batch, so a tally row is updated at most once per
batch. Vote events are partitioned by
candidate_id, so in steady state only one consumer writes a given tally row. - Entry ids are inserted in ascending order and tally rows are updated in sorted order. The concurrency test found a real deadlock when two projectors (as during a rebalance) inserted overlapping entries in map order.
GET /v1/campaigns/{id}/rankingserveskind: LIVE(ties share a rank) and reports itssource.
- Deduplication is keyed on
- Redis cache: after each commit the projector writes the candidates' absolute scores to a
sorted set plus a hash holding the version (
entries_applied, which only grows). A Lua script writes a member only if its version is ≥ the cached one, so concurrent projectors, replays and rebuilds can write in any order without moving the cache backwards. Reads use Redis and fall back to PostgreSQL (re-warming the cache) when the key is missing or Redis is down; cache write failures never fail an apply. - Final ranking: computed directly from
voting.vote_ledger_entry, never from the projection (see Finalization in §5.4);?kind=finalserves the latest version. - Corrections: votes are never updated or deleted (enforced by
BEFORE UPDATE/DELETE/TRUNCATEtriggers onvoting.voteandvoting.vote_ledger_entry). An invalidation appends a negative ledger entry (POST /internal/v1/votes/{id}/invalidate, idempotent per vote) and emitsvoting.VoteInvalidated; if the campaign is already finalized, a new tally version with the reason is computed in the same transaction. Quota is not refunded and paid credit is not returned: refunds are a separate business process. - Recovery:
voting-worker ranking-rebuild -campaign ID|-allrecomputes a campaign from the ledger. Projectors take a shared advisory lock per campaign (they never block each other); a rebuild takes it exclusively. Marking entries applied and computing tallies happen in one statement (writable CTEs), i.e. from one snapshot, so no entry can be counted without being marked or vice versa. Replaying Kafka after a rebuild changes nothing. - Reconciliation:
voting-worker ranking-reconcilereports lag (ledger entries not yet applied) separately from drift (tally ≠ sum of the entries it claims to have applied); only drift is an error, fixed by a rebuild.
5.8 Events and reliability
- Transactional outbox per service.
voting-worker outbox-relaylocks a batch withFOR UPDATE SKIP LOCKED(several relays may run), produces with the idempotent producer andacks=all, waits for every acknowledgement, then marks the rows published in the same transaction. A crash after the acknowledgement re-publishes the batch, so consumers must be idempotent. The relay pool usestransaction_timeout = 30sbecause it holds row locks while producing; vote transactions keep 5 s. - Ordering: rows are published in id order, but ids are assigned before commit, and several relays may interleave batches. Consumers must not rely on cross-batch order. The tally is commutative, so it does not.
- Consumers commit offsets only after their side effects commit, with rebalances blocked during
a polled batch.
- Poison records (malformed, unsupported schema version) go to
<topic>.dlqwith error and origin headers, and the partition moves on. - Transient failures (database or DLQ unavailable) are retried with backoff and never skipped: the partition lags until the dependency recovers. Skipping would lose data.
- Poison records (malformed, unsupported schema version) go to
- Topics are created explicitly (
voting-worker kafka-topics); broker auto-creation is off. Vote events:votee.voting.vote-events.v1(6 partitions) and its.dlq. - Retention: published outbox rows are deleted after 7 days (
voting-worker outbox-cleanup; a scheduled job in campaign-service and payment-service). Not implemented: deleting oldapplied_ledger_entryrows, because a replay of old Kafka records could count their entries twice. - Topics:
votee.voting.vote-events.v1(VoteAccepted, VoteInvalidated, CreditReleaseRequested; keycandidate_id, orattempt_idfor releases),votee.campaign.campaign-events.v1(snapshots, finalization requests; keycampaign_id),votee.voting.tally-events.v1(FinalTallyComputed; keycampaign_id),votee.payment.payment-events.v1(PaymentConfirmed; keycampaign_id; contractcontracts/events/payment.PaymentConfirmed.v1.schema.json). Go and Java use the same murmur2 key partitioner. votee.voting.vote-signals.v1(VoteSignalsRecorded; keycampaign_id) carries the pseudonymous request signals of accepted votes, written in the vote's transaction, tovoting-worker integrity-ingest.- Consumer groups:
votee-ranking-projector,votee-voting-campaign-sync,votee-voting-finalizer,votee-voting-integrity-ingest,votee-credit-service,votee-credit-service-payments,votee-campaign-service. The Java services use Spring Kafka'sDefaultErrorHandlerwith the same policy: poison → DLQ immediately, anything else retried with unbounded exponential backoff. - Consumer session timeout is 15 s: the chaos drill showed that a
kill -9'd member holds its partitions until its session expires (45 s by default); a graceful stop leaves at once. - Envelope:
event_id(UUIDv7),event_type,schema_version,aggregate_id,occurred_at,trace_id,payload. JSON validated by JSON Schema incontracts/.
5.9 Code structure and layering
Each service has three layers; dependencies point inward and are checked by tests (ArchUnit in
the Spring services, voting-service/internal/archtest in Go).
| Layer | Contains | campaign-service / credit-service | voting-service |
|---|---|---|---|
| Domain | Aggregates, value objects, domain events, domain exceptions, repository ports | domain/{model,event,exception,repository} (plain Java) | internal/voting |
| Application | One method per use case; outbound ports | application, application/port | internal/voting/app (Service, ports TxRunner, Tx) |
| Infrastructure | Inbound and outbound adapters | infrastructure/{persistence,messaging,web,client,scheduling,config} | pgstore, httpapi, creditclient, campaignsync, finalizer, outbox, ranking |
- Invariants that need the database stay atomic statements behind repository ports
(conditional balance and reservation updates, quota upserts, row locks,
@Version). The domain decides what is legal; the adapter makes it atomic. - The Campaign aggregate records domain events;
CampaignCommandServiceturns them into the audit trail, rule-set history and outbox events. No events means the command was a no-op. - campaign-service maps the plain aggregate to a separate JPA model (
CampaignJpaEntity). - Set-based reads and maintenance (history, final tally, snapshot replication, cleanup) remain adapter methods; they have no use-case logic.
6. Technology justification
| Technology | Usage | Why |
|---|---|---|
| Go | Voting Core API and workers | Hot path with high concurrency; explicit transaction control with pgx; goroutine-based workers |
| Spring Boot | campaign-service, credit-service, identity-service, payment-service | Lifecycle state machine, scheduling, admin workflows, ledger/reservation logic with declarative transactions; token issuance and webhook/order handling |
| Kafka | Event distribution, replay | Partition ordering, consumer groups, replay for projection rebuilds |
| PostgreSQL | Source of truth | ACID, conditional upserts, unique constraints, SKIP LOCKED, transaction_timeout |
| Redis | Live ranking, rate limiting | Sorted sets for top-N and rank queries; atomic Lua scripts; rate limiting fails open because correctness lives in PostgreSQL |
| React | Optional demo (Phase 5) | Only if it provides real demonstration value |
Libraries: Go — pgx/v5 with hand-written SQL, goose (embedded migrations), google/uuid
(UUIDv7), franz-go (Kafka), go-redis/v9, prometheus/client_golang. Java — Java 25, Spring
Boot 4.2 (Jackson 3), Spring Data JPA (campaign persistence model, optimistic locking), JdbcClient
(credit conditional updates, outbox, scheduler queries), Flyway, Spring Kafka, Micrometer
Prometheus, Maven multi-module with wrapper.
Deviations from the initial plan:
- No
sqlc. The vote transaction is a handful of carefully ordered statements; keeping them as explicit SQL inpgstore(one method per statement behind theapp.Txport) makes locking and ordering easy to read and review. Revisit if query count grows. - No
testcontainers-go. Integration tests create a throwaway, migrated database per test package on the PostgreSQL fromdeploy/docker-compose.yml(internal/platform/testdb). This is faster and has fewer dependencies; CI uses service containers. The Java tests use the same approach (DatabaseFixture, unique Kafka topics) instead of Testcontainers. - credit-service has no outbox. It publishes no events yet; the shared relay is disabled
(
votee.outbox.relay-enabled: false) and its schema has no outbox table. (Planned) payment-service does need one: it reusesOutboxWriter/OutboxRelayfromplatform-commonto publishpayment.PaymentConfirmed.v1, and credit-service gains a consumer for it (not a producer). - Java internal endpoints share the public port.
/internal/**of the Spring services is served on the same port as their public API. It is closed twice: the gateway never forwards it, and every/internal/**request needs the sharedX-Votee-Internal-Token(the services do not start withoutvotee.internal.token; voting-api's internal listener checks the same header). In thestackdeployment (make stack-up) only the gateway publishes a port among the Votee services; PostgreSQL, Kafka and Redis keep the host ports thatdeploy/docker-compose.ymlpublishes (15432,19092,16379). A caller that holds the token and reaches a service port can still call/internal/**: the token is a shared secret, not a per-caller identity. - No Toxiproxy. Credit-service failures are injected in Go tests with an in-process fake (timeouts, insufficient credit, state changes mid-reservation) and an HTTP test server.
- No OpenTelemetry tracing. Metrics and structured logs only; tracing is the next step.
- No React demo. The cross-service smoke test and the load generator cover what a demo would show.
7. Reconciliation jobs
| Job | Detects |
|---|---|
| Idempotency cleanup | Expired idempotency records (implemented: voting-worker idempotency-cleanup) |
| Outbox cleanup | Outbox rows published more than 7 days ago (implemented: voting-worker outbox-cleanup; the Spring services run the same job inside the service) |
| Outbox lag | Oldest unpublished event age (votee_outbox_lag_seconds) |
| Attempt sweeper | Pending paid attempts older than 2 min → ABANDONED + release (voting-worker attempt-sweeper) |
| Reservation expiry | Reservations past TTL, resolved via Voting Core (credit-service job, every 5 s) |
| Tally reconciler | Lag and drift between candidate_tally and the ledger (implemented: voting-worker ranking-reconcile) |
| Credit invariants | Account balances = credit ledger sums (asserted in tests; no scheduled job yet) |
| Payment reconciliation | PENDING orders older than 15 min versus the provider's state; applied through the webhook path with a synthetic event id; unknown to the provider for 24 h → FAILED (payment-service job, every minute) |
| Paid-order grant check (planned) | PAID orders with no matching payment:<order_id> GRANT in credit; today POST /internal/v1/orders/{id}/refund answers GRANT_PENDING while the grant is missing |
| Chargeback debt (planned) | Open (account, campaign) debts that still block purchases (visible through GET /v1/accounts/me/debts; no job yet) |
| Credit per campaign | (account, campaign) balances = ledger sums; no negative balance (asserted in tests; no scheduled job yet) |
Each job is idempotent and runnable manually from the CLI.
8. Observability
- Prometheus metrics: voting-api on the internal listener (
/metrics), workers onVOTEE_METRICS_ADDR, Spring services on/actuator/prometheus. Metric list and alerts inoperations.md. - Structured JSON logs (Go
slog, Spring Boot defaults). - Load generator
cmd/voting-load, cross-service smoke testinternal/smoke(build tagsmoke).
9. Roadmap
| Phase | Status | Scope | Exit criteria |
|---|---|---|---|
| 0 | Done | Repository, docs, local infrastructure, Go skeleton, CI workflow | make infra-up healthy, make test passes |
| 1 | Done | Voting Core free votes: schema, vote API, idempotency (+ cleanup), quota, append-only ledger, outbox writes, vote history | Same key ×100 → 1 vote; 5 actors × 40 parallel with quota 10 → 10 each; ledger/quota/outbox invariants; HTTP end-to-end test |
| 2 | Done | Outbox relay, Kafka, idempotent ranking projector, rebuild/reconcile, DLQ | Duplicates, relay crash after produce, concurrent relays/projectors, rebuild during applies, replay |
| 3 | Done | campaign-service, credit-service, campaign-sync, paid vote saga, resolution, sweeper | State machine and scheduler tests; 50 concurrent reservations never overdraw; saga failure cases; expiry never releases without a definitive answer |
| 4 | Done | Redis live ranking, rate limiting, finalization, corrections with tally versions | Cache never moves backwards; Redis loss/outage falls back to PostgreSQL; finalization waits for snapshot catch-up and barrier; correction → tally v2 |
| 5 | Done | Metrics, load generator, load and chaos runs, operations runbook, cross-service smoke test | performance.md: measured throughput/latency, contention, recovery |
| 6 | Done | Credit per campaign: (account, campaign) keys, non-negative conditional debit, refund entry type idempotent by order id | Concurrent reservations never overdraw a balance; a refund never exceeds the available balance; spends in campaign A never affect campaign B |
| 7 | Done | identity-service: accounts, verification levels, JWT and JWKS, guest tokens, admin claims; voting-api verifies locally and enforces min_identity | Expired and tampered tokens rejected; guest blocked in a paid campaign; signing-key rotation |
| 8 | Done | payment-service: orders, fake provider first, webhook endpoint, outbox for PaymentConfirmed, reconciliation, chargeback debt | Duplicate webhook grants once; out-of-order webhook converges; chargeback blocks purchase but keeps accepted votes; price snapshot survives a later price change |
| 9 | Done | Identity hardening: email verification, canonical email, disposable domains, login lockout, phone verification to VERIFIED_ACCOUNT with SMS limits and quarantine; gateway buckets per IPv6 /64 and per identity route | Unverified accounts cannot log in; Gmail aliases are one account; parallel guesses never exceed the login or code limits; one phone binds to one account, even when two race for it; refused sends claim nothing |
| 10 | Done | Campaign integrity rules: minimum account age, ranking freeze, AUDITOR role and audit reads | A young account or a token without acct_created_at gets ACCOUNT_TOO_NEW; the frozen ranking holds only votes before the freeze, is computed once after the barrier, and ends at finalization; auditors read but change nothing |
| 11 | Done | Integrity review and certified results: pseudonymous request signals, four detectors, review cases with batch invalidation, review_period_seconds and CERTIFIED | Signals hold no address; detectors open cases and never invalidate; a confirmation invalidates the members' votes with one tally version per batch and cannot be decided twice; the public sees the final result only once certified |
| 12 | Done | ASN lookup and proof of work: offline ip2asn table, hosting flag in signals, HOSTING_NETWORK detector, self-hosted challenges for hosting and busy networks | A vote from a hosting or busy network needs a solved, unexpired, unused challenge; others never do; the ASN travels with the signals |
Phases 6–8 follow the scope change of 2026-11-20 (identity, payment and per-campaign credit). Not in scope: CMS, an admin UI, eKYC, real settlement with a provider, and any change to the ranking or finalization protocol.