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

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-service issues short-lived JWTs; voting-api verifies them locally against JWKS, with no synchronous call to identity per vote. X-Actor-Id is replaced by the verified token subject and X-Admin-Id by 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​

DeployableLanguageResponsibility
voting-apiGoPublic 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-workerGoOne 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-serviceJava / Spring BootCampaign lifecycle, candidates, versioned rule sets, scheduler, finalization orchestration, the access policy (min_identity), vote packages
credit-serviceJava / Spring BootCredit 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 BootAccounts, credentials, PII, email and phone verification, verification level, login lockout, JWT and refresh tokens, JWKS, guest identities, admin identities
payment-service (:8084)Java / Spring BootOrders (price snapshot), provider integration, webhooks, reconciliation, chargeback debt; outbox for PaymentConfirmed
gateway (:8000)EnvoyThe 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​

ContextOwnerOwnsSchema
VotingGovote, vote_attempt, vote_ledger_entry, vote_quota_usage, idempotency_record, campaign_snapshot (read model), final_tally, frozen_ranking, outbox_eventvoting
Integrity reviewGo worker (voting-service)vote_signal (pseudonymous, purged after 90 days), review_case, review_case_memberintegrity
Ranking projectionGo workercandidate_tally, applied_ledger_entry, Redis sorted setsranking
Campaign & Rulescampaign-servicecampaign (with embedded current rules), candidate, rule_set_history, campaign_transition, outbox_event; the access policy is part of the rule set, vote_packagecampaign
Creditcredit-servicecredit_account, credit_reservation, credit_ledger_entry (append-only, unique per operation); all keyed by (account_id, campaign_id) (migration V2)credit
Identityidentity-serviceaccounts (canonical email, verified phone), credentials, PII, verification level, verification challenges and send counters, phone releases, refresh tokens, guest identities, admin identities, signing keysidentity
Paymentpayment-servicepayment_order, payment_debt, webhook_event (dedupe), outbox_eventpayment

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)​

ContextTransaction 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
Creditaccount balances + reservation + credit ledger entry (per (account, campaign))
Campaigncampaign state + transition audit row + outbox event
Paymentorder transition + webhook event record (dedupe by provider event id) + debt + outbox event
Identityaccount / refresh token / key change; no event is required for authentication

Eventually consistent​

DataSourceLag impact
campaign_snapshot in Votingcampaign-service eventsOnly manual PAUSE / early END; time windows are exact (see §5.4). (Planned) the access policy travels in the same snapshot
Credit grantpayment.PaymentConfirmed.v1A paid order is spendable after the consumer commits the GRANT (idempotent by payment:<order_id>)
Live ranking (PostgreSQL projection, Redis)vote eventsSeconds; never affects acceptance
Credit captureVoteAccepted eventReserved credit is guaranteed to be captured or released after the outcome is known
Campaign FINALIZEDFinalTallyComputed eventFinal 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 after COMMIT succeeds.
  • transaction_timeout = 5s is 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_record primary 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 to COMPLETED before commit, so IN_PROGRESS is 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 header Idempotent-Replayed: true.
  • The record stores the outcome (ACCEPTED + vote_id, or REJECTED + 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_EXCEEDED or 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 SAVEPOINT while 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_key keeps the audit trail.

5.3 Quota​

  • Never SELECT COUNT(*) followed by INSERT.

  • Counter rows in vote_quota_usage, keyed by scope. Free and paid votes use separate budgets so buying votes never consumes the free allowance:

    ScopeApplies toPurpose
    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 UPDATE
    SET used = vote_quota_usage.used + EXCLUDED.used
    WHERE vote_quota_usage.used + EXCLUDED.used <= $4
    RETURNING 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 SCHEDULED or ACTIVE and starts_at <= now() < ends_at, where now() is the PostgreSQL transaction timestamp. accepted_at = now() is persisted on the vote.
  • SCHEDULED is 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 COMMITTED each 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_version and rule_set_version.
  • While ACTIVE, ends_at may only be extended; shortening is an explicit, audited END command.
  • Closing barrier: finalization starts only after ends_at + grace, with grace > transaction_timeout, guaranteeing that no vote transaction can still commit.
  • ENDED (no more votes) is distinct from FINALIZED (final tally computed and published).
  • campaign-service implements the state machine in the Campaign aggregate (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 with FOR UPDATE SKIP LOCKED, so several instances can run it. Every committed change appends a full campaign.CampaignSnapshotPublished event (event-carried state transfer) to the outbox; voting-worker campaign-sync applies only newer snapshot_versions. Transitions are audited in campaign_transition, rule set versions in rule_set_history.

Finalization​

  1. campaign-service moves ENDED → FINALIZING once now ≥ ends_at + grace (grace 10 s > 5 s transaction timeout) and publishes campaign.FinalizationRequested{snapshot_version}.
  2. voting-worker finalizer computes 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).
  3. 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 as voting.FinalTallyComputed. Duplicate requests return the existing version.
  4. 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.json and 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. If paid_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 claim acct_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 before ends_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.
  • Auditors hold the AUDITOR role: GET on 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.

  1. 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 record PENDING. reservation_key = attempt_id. The price is fixed here (price × votes, stored on the attempt); credit-service never needs campaign rules.
  2. Sync HTTP, outside any transaction: POST /internal/v1/reservations on credit-service (2 tries × 3 s), idempotent by reservation_key. credit-service inserts the reservation row first (concurrent requests with the same key serialize on its unique index), then debits with UPDATE … SET available = available - :amt, reserved = reserved + :amt WHERE … AND available >= :amt; insufficient credit rolls back the whole transaction.
  3. Txn B (voting): lock the attempt row (FOR UPDATE serializes 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 + outbox VoteAccepted{reservation_id}) or reject (outbox CreditReleaseRequested).
  4. Respond after Txn B commits. credit-service consumes VoteAccepted and captures idempotently (UPDATE ... WHERE state = 'RESERVED').
FailureHandling
Insufficient creditAttempt REJECTED; rejection stored for idempotent replay
credit-service failing or saturatedA 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 resultRetry 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 3Sweeper moves stale attempts to ABANDONED (conditional update) and emits release
Reservation TTL (10 min) expirescredit-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 failureAt-least-once delivery + idempotent capture; capture on a RELEASED reservation raises an alert
Client retries after ABANDONEDThe 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 existsNo-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 carry campaign_id. The saga above is unchanged: only the key scope changed, and voting reserves credit by (actor_id, campaign_id).
  • Invariants (implemented). available >= 0 and reserved >= 0, enforced by conditional UPDATE as 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 by order_id. On PAID it writes the outbox event payment.PaymentConfirmed.v1 {order_id, account_id, campaign_id, credits, amount, currency}. credit-service consumes it (consumer group votee-credit-service-payments) and performs a GRANT with reference payment:<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 with POST /internal/v1/orders/{id}/refund).

5.7 Ranking​

  • Live ranking (Phase 2, PostgreSQL): voting-worker ranking-projector consumes vote events and, in one transaction, inserts ranking.applied_ledger_entry rows and updates ranking.candidate_tally.
    • Deduplication is keyed on ledger_entry_id (the identity of the fact), not on the message event_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}/ranking serves kind: LIVE (ties share a rank) and reports its source.
  • 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=final serves the latest version.
  • Corrections: votes are never updated or deleted (enforced by BEFORE UPDATE/DELETE/TRUNCATE triggers on voting.vote and voting.vote_ledger_entry). An invalidation appends a negative ledger entry (POST /internal/v1/votes/{id}/invalidate, idempotent per vote) and emits voting.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|-all recomputes 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-reconcile reports 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-relay locks a batch with FOR UPDATE SKIP LOCKED (several relays may run), produces with the idempotent producer and acks=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 uses transaction_timeout = 30s because 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>.dlq with 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.
  • 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 old applied_ledger_entry rows, because a replay of old Kafka records could count their entries twice.
  • Topics: votee.voting.vote-events.v1 (VoteAccepted, VoteInvalidated, CreditReleaseRequested; key candidate_id, or attempt_id for releases), votee.campaign.campaign-events.v1 (snapshots, finalization requests; key campaign_id), votee.voting.tally-events.v1 (FinalTallyComputed; key campaign_id), votee.payment.payment-events.v1 (PaymentConfirmed; key campaign_id; contract contracts/events/payment.PaymentConfirmed.v1.schema.json). Go and Java use the same murmur2 key partitioner.
  • votee.voting.vote-signals.v1 (VoteSignalsRecorded; key campaign_id) carries the pseudonymous request signals of accepted votes, written in the vote's transaction, to voting-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's DefaultErrorHandler with 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 in contracts/.

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).

LayerContainscampaign-service / credit-servicevoting-service
DomainAggregates, value objects, domain events, domain exceptions, repository portsdomain/{model,event,exception,repository} (plain Java)internal/voting
ApplicationOne method per use case; outbound portsapplication, application/portinternal/voting/app (Service, ports TxRunner, Tx)
InfrastructureInbound and outbound adaptersinfrastructure/{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; CampaignCommandService turns 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​

TechnologyUsageWhy
GoVoting Core API and workersHot path with high concurrency; explicit transaction control with pgx; goroutine-based workers
Spring Bootcampaign-service, credit-service, identity-service, payment-serviceLifecycle state machine, scheduling, admin workflows, ledger/reservation logic with declarative transactions; token issuance and webhook/order handling
KafkaEvent distribution, replayPartition ordering, consumer groups, replay for projection rebuilds
PostgreSQLSource of truthACID, conditional upserts, unique constraints, SKIP LOCKED, transaction_timeout
RedisLive ranking, rate limitingSorted sets for top-N and rank queries; atomic Lua scripts; rate limiting fails open because correctness lives in PostgreSQL
ReactOptional 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 in pgstore (one method per statement behind the app.Tx port) 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 from deploy/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 reuses OutboxWriter / OutboxRelay from platform-common to publish payment.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 shared X-Votee-Internal-Token (the services do not start without votee.internal.token; voting-api's internal listener checks the same header). In the stack deployment (make stack-up) only the gateway publishes a port among the Votee services; PostgreSQL, Kafka and Redis keep the host ports that deploy/docker-compose.yml publishes (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​

JobDetects
Idempotency cleanupExpired idempotency records (implemented: voting-worker idempotency-cleanup)
Outbox cleanupOutbox rows published more than 7 days ago (implemented: voting-worker outbox-cleanup; the Spring services run the same job inside the service)
Outbox lagOldest unpublished event age (votee_outbox_lag_seconds)
Attempt sweeperPending paid attempts older than 2 min → ABANDONED + release (voting-worker attempt-sweeper)
Reservation expiryReservations past TTL, resolved via Voting Core (credit-service job, every 5 s)
Tally reconcilerLag and drift between candidate_tally and the ledger (implemented: voting-worker ranking-reconcile)
Credit invariantsAccount balances = credit ledger sums (asserted in tests; no scheduled job yet)
Payment reconciliationPENDING 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 on VOTEE_METRICS_ADDR, Spring services on /actuator/prometheus. Metric list and alerts in operations.md.
  • Structured JSON logs (Go slog, Spring Boot defaults).
  • Load generator cmd/voting-load, cross-service smoke test internal/smoke (build tag smoke).

9. Roadmap​

PhaseStatusScopeExit criteria
0DoneRepository, docs, local infrastructure, Go skeleton, CI workflowmake infra-up healthy, make test passes
1DoneVoting Core free votes: schema, vote API, idempotency (+ cleanup), quota, append-only ledger, outbox writes, vote historySame key ×100 → 1 vote; 5 actors × 40 parallel with quota 10 → 10 each; ledger/quota/outbox invariants; HTTP end-to-end test
2DoneOutbox relay, Kafka, idempotent ranking projector, rebuild/reconcile, DLQDuplicates, relay crash after produce, concurrent relays/projectors, rebuild during applies, replay
3Donecampaign-service, credit-service, campaign-sync, paid vote saga, resolution, sweeperState machine and scheduler tests; 50 concurrent reservations never overdraw; saga failure cases; expiry never releases without a definitive answer
4DoneRedis live ranking, rate limiting, finalization, corrections with tally versionsCache never moves backwards; Redis loss/outage falls back to PostgreSQL; finalization waits for snapshot catch-up and barrier; correction → tally v2
5DoneMetrics, load generator, load and chaos runs, operations runbook, cross-service smoke testperformance.md: measured throughput/latency, contention, recovery
6DoneCredit per campaign: (account, campaign) keys, non-negative conditional debit, refund entry type idempotent by order idConcurrent reservations never overdraw a balance; a refund never exceeds the available balance; spends in campaign A never affect campaign B
7Doneidentity-service: accounts, verification levels, JWT and JWKS, guest tokens, admin claims; voting-api verifies locally and enforces min_identityExpired and tampered tokens rejected; guest blocked in a paid campaign; signing-key rotation
8Donepayment-service: orders, fake provider first, webhook endpoint, outbox for PaymentConfirmed, reconciliation, chargeback debtDuplicate webhook grants once; out-of-order webhook converges; chargeback blocks purchase but keeps accepted votes; price snapshot survives a later price change
9DoneIdentity 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 routeUnverified 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
10DoneCampaign integrity rules: minimum account age, ranking freeze, AUDITOR role and audit readsA 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
11DoneIntegrity review and certified results: pseudonymous request signals, four detectors, review cases with batch invalidation, review_period_seconds and CERTIFIEDSignals 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
12DoneASN lookup and proof of work: offline ip2asn table, hosting flag in signals, HOSTING_NETWORK detector, self-hosted challenges for hosting and busy networksA 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.