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

Votee — Operations

Processes​

ProcessCommandPortScales
gatewayEnvoy, docker compose service gateway:8000 public (VOTEE_GATEWAY_PORT), admin 127.0.0.1:9901 inside the container onlyhorizontally (stateless)
voting-apibin/voting-api:8080 public, 127.0.0.1:8090 internal + /metricshorizontally
outbox relayvoting-worker outbox-relayVOTEE_METRICS_ADDRseveral (SKIP LOCKED)
ranking projectorvoting-worker ranking-projectoridem≤ partitions (6)
campaign syncvoting-worker campaign-syncidem≤ partitions
finalizervoting-worker finalizeridem≤ partitions
attempt sweepervoting-worker attempt-sweeperidemseveral (SKIP LOCKED)
idempotency cleanupvoting-worker idempotency-cleanupidemone is enough
outbox cleanupvoting-worker outbox-cleanup (-retention 168h, -interval, -batch, -once)idemone is enough
integrity ingestvoting-worker integrity-ingestidem≤ partitions (6); idempotent by vote
integrity scanvoting-worker integrity-scan (-interval, -lookback, -retention, -campaign, -once)idemone is enough (a scan of a campaign is one transaction; concurrent scans are harmless)
campaign-servicejava -jar campaign-service.jar:8081 (/actuator/prometheus)several (scheduler uses SKIP LOCKED)
credit-servicejava -jar credit-service.jar:8082several
identity-servicejava -jar identity-service.jar:8083several (signing keys live in the database)
payment-servicejava -jar payment-service.jar:8084several (webhooks dedupe in the database; reconciliation is idempotent)

Start order (services on the host): make infra-up (includes the gateway, which starts without its upstreams), make migrate, make kafka-topics, the Spring services (Flyway migrates their schemas), then voting-api and workers. Every process tolerates its dependencies starting later. The Spring jars need Java 25.

Key configuration (Go, environment): VOTEE_DATABASE_URL, VOTEE_WORKER_DATABASE_URL (the workers' connection, a role with its own connection cap; empty: same as VOTEE_DATABASE_URL), VOTEE_KAFKA_BROKERS, VOTEE_REDIS_ADDR, VOTEE_CREDIT_URL (empty disables paid votes), VOTEE_RATE_LIMIT_PER_SEC (0 disables), VOTEE_ATTEMPT_ABANDON_AFTER (default 2m), VOTEE_FINALIZATION_GRACE (default 10s, must exceed 5s), VOTEE_INTERNAL_API_ENABLED (development snapshot seeding), VOTEE_CREDIT_MAX_IN_FLIGHT (reservations in flight to credit-service, default 128), VOTEE_CREDIT_BREAKER_FAILURES (failed calls in a row that open the breaker, default 5), VOTEE_CREDIT_BREAKER_OPEN (how long it stays open, default 10s), VOTEE_SIGNALS_KEY (secret that hashes client networks for fraud review; empty records no signals), VOTEE_CLIENT_IP_HEADER (header with the client address, last entry used; X-Forwarded-For behind the gateway, empty uses the TCP peer), VOTEE_ASN_DB (ip2asn TSV for hosting-network detection; make asn-download writes deploy/asn/ip2asn-combined.tsv, mounted at /asn in the stack), VOTEE_POW_SECRET (signs proof-of-work challenges; empty disables them), VOTEE_POW_DIFFICULTY (default 18 bits), VOTEE_POW_NETWORK_VOTES_PER_MIN (votes a network sends per minute before it must prove work; 0: only hosting networks must). Refresh the ASN file regularly: network ownership changes.

Payment provider: SePay sandbox (development)​

payment-service uses the fake provider unless VOTEE_PAYMENT_PROVIDER=sepay. The SePay adapter is configured for the sandbox only (pgapi-sandbox.sepay.vn, pay-sandbox.sepay.vn); production hosts are not configured.

One-time setup:

  1. Install the CLI with brew install sepayvn/sepay-cli/sepay, then sign in with sepay login (needs a my.sepay.vn account with Test mode on).
  2. On my.sepay.vn, start Payment Gateway in Sandbox and copy the merchant ID and secret key (the secret is shown once). Configure the IPN with auth type SECRET_KEY and note its secret.
  3. Set where SePay delivers IPNs: sepay pg ipn set <url> --auth-type SECRET_KEY --secret <IPN secret>. <url> must be reachable by SePay.

Run:

export VOTEE_PAYMENT_PROVIDER=sepay
export VOTEE_SEPAY_MERCHANT_ID=<merchant id>
export VOTEE_SEPAY_SECRET_KEY=<sandbox secret key>
export VOTEE_SEPAY_IPN_SECRET_KEY=<IPN secret>
make run-payment

In a second terminal, make sepay-listen mirrors each IPN to localhost:8084/v1/webhooks/sepay with the same headers. sepay pg order get <order id> shows what SePay holds for an order; the order id is the invoice number. The compose stack reads the same variables.

Deployment modes​

ModeCommandWhat is reachable
Stack (everything in containers)make stack-up, make stack-down, make stack-ps, make stack-logsthe gateway on :8000 and the documentation listener on 127.0.0.1:8001; the services publish nothing. PostgreSQL, Kafka and Redis keep their host ports for tooling
Services on the hostmake infra-up and make run-*the gateway on :8000 plus every service on its own port (:8080–:8084): convenient for debugging, not isolated

make smoke runs the full-flow smoke test from a container inside the stack network (the services have no host port to call). All services share one secret for /internal/**, VOTEE_INTERNAL_TOKEN (default for development dev-internal-token-change-me); see api.md. The Go image runs voting-api, voting-worker <subcommand> and voting-migrate; the migrate and kafka-topics one-shot services run before the others.

Gateway​

Envoy forwards the public API of the five services on one port and closes everything else. The routes, CORS origins, limits and timeouts are in deploy/gateway/envoy.yaml; after editing it run make gateway-validate, then docker compose -f deploy/docker-compose.yml restart gateway (a restart drops open connections).

TaskCommand
Access log (one JSON line per request: request_id, status, flags, upstream, duration_ms)make gateway-logs
Counters (cluster.<service>.upstream_rq_*, http.public.downstream_rq_*, edge_rate_limit.*)make gateway-stats
Trace a request across the gateway and a servicethe request_id of the gateway log is the X-Request-Id the client received

The gateway reaches each service by its name (voting-api, campaign-service, credit-service, identity-service, payment-service). With make stack-up Docker DNS resolves them to the containers; with the services on the host (make infra-up, make run-*) extra_hosts points the names at the host. A 503 with response flag UF or UH means that service is down or not listening on all interfaces; UT or a 504 means it did not answer within the route timeout. A new public endpoint answers 404 ROUTE_NOT_FOUND through the gateway until its route is added to envoy.yaml. The address rate limit is kept per gateway instance.

Metrics​

MetricMeaningAlert idea
votee_votes_total{vote_type,outcome,code,replayed}vote outcomesspike in outcome="ERROR"
votee_http_request_duration_secondslatency by routep99 > 250 ms
votee_outbox_lag_secondsage of oldest unpublished event> 30 s
votee_consumer_records_total{consumer,result}handled / skipped / poisonany poison
votee_consumer_retries_total{consumer}transient failuressustained increase
votee_ranking_entries_total{result}applied / duplicate—
votee_paid_attempts_abandoned_totalsweeper abandonments> 0 means credit-service or voting-api trouble
votee_rate_limited_total, votee_rate_limiter_errors_totalrate limitinglimiter errors > 0 (Redis down, failing open)

Kafka consumer lag per group is visible with kafka-consumer-groups.sh --describe --group <g>.

Runbooks​

Live ranking is stale. voting-worker ranking-reconcile -campaign <id>. Unapplied entries means lag: check votee_outbox_lag_seconds (relay) and consumer lag (projector). Drift means the projection is wrong: voting-worker ranking-rebuild -campaign <id> (safe while projectors run; replays afterwards change nothing).

Redis lost data or was down. Nothing to do for correctness: reads fall back to PostgreSQL and re-warm the cache. To warm everything at once: voting-worker ranking-cache-warm -all. While Redis is down the rate limiter fails open.

Messages in a .dlq topic. These are poison records (malformed or unsupported schema version); headers dlq_error, dlq_original_* (Go) or kafka_dlt-* (Spring) explain why. Fix the producer or add support, then re-publish the records to the original topic; consumers are idempotent. For the projection a rebuild is an alternative to re-publishing.

Outbox lag grows. Relay down or Kafka unavailable. Rows stay unpublished and nothing is lost; restart the relay. Several relays may run at once.

Paid votes return 503. credit-service unreachable. Attempts stay pending; clients retrying with the same key resume them. After 2 min the sweeper abandons them and requests release.

Reservations stay RESERVED. The expiry job asks Voting Core every 30 s and never releases without a definitive answer. Check that credit-service reaches voting-api's internal listener (votee.credit.voting-internal-url).

Campaign stuck in FINALIZING. The finalizer retries while Voting Core's snapshot is older than the request or the barrier has not passed. Check campaign-sync (consumer lag) and the finalizer logs.

Correcting a fraudulent vote. POST 127.0.0.1:8090/internal/v1/votes/{vote_id}/invalidate {"reason": "..."}. Idempotent. A finalized campaign gets a new tally version automatically; earlier versions remain for audit.

Reviewing fraud cases. The detectors open cases; nothing is invalidated until a person confirms one.

  1. GET 127.0.0.1:8090/internal/v1/integrity/campaigns/{id}/cases?status=OPEN lists the queue, highest score first. POST …/campaigns/{id}/scan runs the detectors now instead of waiting for integrity-scan.
  2. GET …/integrity/cases/{case_id} shows the evidence and the members. A network case on a mobile carrier or an office can be real fans: check the evidence and member_count before confirming.
  3. POST …/integrity/cases/{case_id}/decision {"decision": "CONFIRM" | "DISMISS", "reason": "…", "decided_by": "…"}. CONFIRM invalidates every vote of the members in that campaign, with one tally version per 500 votes; paid credit is not refunded. If it fails halfway the case stays OPEN: repeat the same call.
  4. Decide within the campaign's review_period_seconds: after that the result is CERTIFIED, and a confirmation becomes a public correction.

Existing development volume and the integrity schema. deploy/postgres/init creates it only for a new volume. Once, before make migrate or make stack-up: docker compose -f deploy/docker-compose.yml exec postgres psql -U postgres -d votee -c "CREATE SCHEMA IF NOT EXISTS integrity AUTHORIZATION voting_service; ALTER ROLE voting_service SET search_path = voting, ranking, integrity".

Existing development volume and the voting_worker role. Also created only for a new volume. Once, as superuser, then set VOTEE_WORKER_DATABASE_URL (the stack file already does): CREATE ROLE voting_worker LOGIN PASSWORD 'voting_worker' CONNECTION LIMIT 40, then the last statements of deploy/postgres/init/01-schemas.sql (search path, GRANT USAGE and the two ALTER DEFAULT PRIVILEGES), and GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA voting, ranking, integrity TO voting_worker for the tables that exist.

Recovery drill (verified)​

See performance.md: kill -9 of the projector and the relay and a Redis outage during load lost nothing, the vote API was unaffected, and the projection and cache converged to the ledger.