Analytics overview
Product boundary/status correction, 2026-10-29: built-in shared core operations metrics, external professional analytics. Existing screens/models/pipelines are not end-to-end metric acceptance. Retention computation, source consistency and aggregate semantics still have gaps. See scope, source evidence and delivery plan. Metric groups below are a catalog, not a statement that all are implemented.
The analytics stack supports game behavior, retention, revenue, and warehouse reporting. Queries converge in the Analytics console; ingestion and storage are intentionally separated from the control plane.
Pipelines
| Pipeline | Source | Path | Best suited for |
|---|---|---|---|
| ClickHouse pipeline | Game clients and servers | HMAC-authenticated ingest -> Redis Streams -> analytics-worker -> ClickHouse | High-volume events, warehouse detail, and pre-aggregated reports. |
| Server GORM | Server business models | Per-game relational tables | Business-entity joins and moderate-volume overview, retention, behavior, payment, and level reports. |
| OpenTelemetry bridge | Server telemetry | In-process bridge -> Redis Streams -> ClickHouse pipeline | Server-side automatic events without game-client changes. |
Open the full SVG architecture diagram · Chinese SVG
Arrows represent writes or query requests/responses, not a timeline. Dashed lines are optional; crossings without dots do not join. The bridge and Analytics API are Server modules. Browsers call Server APIs rather than connecting to databases. Warehouse and relational reports use separate sources.
Current wiring and source evidence
| Relationship | Implementation and limits |
|---|---|
| Producers → ingest → Redis | Routes /api/ingest/events and /api/ingest/payments and authentication in cmd/ingest/cmd/root.go; JSON stream publishing in internal/analytics/mq/redis_pub.go. HTTP 202 does not confirm ClickHouse durability. Keep HMAC secrets on trusted producers. |
| Server bridge → Redis | The in-process buffer and publisher in internal/telemetry/analytics_bridge.go write directly to analytics:events, without ingest HTTP. Control-plane telemetry is not game DAU. |
| Worker ↔ Redis; worker → ClickHouse | Consumer-group reads, pending reclaim, retry/dead letters and detail/aggregate batches in internal/analytics/worker/worker.go. ACK and warehouse persistence are not atomic; ARCH-011/012 remain open. |
| Browser → Server → databases | web/src/services/api/analytics.ts, internal/handler/routes.go, internal/api/analytics/warehouse.go and the relational report implementations in that directory. Warehouse endpoints read ClickHouse; relational reports do not automatically consume warehouse events. |
This diagram shows the default Redis path. internal/analytics/mq/factory.go also offers Kafka/noop publishers, but the existing worker consumes Redis; Kafka is not a connected substitute in this diagram. Professional integrations and accepted core metrics remain target deliverables.
Batch validation and retry semantics
- Ingest validates the whole batch before publishing anything (DATA-016): an invalid item returns
400withdetails.indexand enqueues nothing. - A publish failure mid-batch returns
500 queue_write_failedwithdetails.enqueued/details.failed_index/details.total(DATA-017): items before the failure are already in the stream and are disclosed, not hidden behind a bare batch-level error. - Retry contract: re-submit the same batch unchanged. Events without a producer
event_idget a deterministic UUIDv5 derived from the payload fingerprint in the worker (internal/analytics/worker/worker_insert.go,deriveEventID), so re-submission and worker redelivery collapse onto the same ClickHouse natural key instead of inserting random new ids. A producer-supplied valid UUIDevent_idis honored as-is. - Amount precision (DATA-018):
amount_centsmust be a positive integer within the uint64 range. Ingest decodes JSON numbers withUseNumberand parses digit-for-digit — fractional, negative and oversized values are rejected400with the item index; the worker parses the amount the same way and dead-letters a bad row with a reason instead of truncating through float64. - Retry retention (DATA-019): failed messages requeue into the source stream without any retention cap of their own — source-stream trimming (e.g.
ANALYTICS_REDIS_MAXLEN) belongs to the publisher's configuration. A retry copy can no longer evict unread backlog entries once the backlog exceeds the old 1000-entry cap; retry volume is bounded byretry_count(dead-lettered aftermaxPendingRetries). - Aggregate recovery (DATA-020): every touched minute/day carries a durable flush marker in Redis (
ANALYTICS_AGG_DIRTY_SET), so a crash after the raw event was ACKed but before the aggregate row landed still leaves a flush obligation after restart. When a best-effort HLL write fails, a separate rebuild marker (ANALYTICS_AGG_REBUILD_SET) makes the next flush re-derive that HLL from the persistedanalytics.eventsrows (HLL union is idempotent). A rebuild failure keeps the marker and does not persist a false zero; a healthy HLL write incurs no rebuild query. - Pipeline alert recovery (DATA-022):
event_stream_stalled/event_volume_dropalerts close only on positive evidence — a scope row actually read in the current round that satisfies the recovery rule. A scope missing from the discovery window (fully silent = the very stall being alerted), a failed query, or a partially read result set is treated as unknown and keeps the alert firing (events_query_failedmarks the unknown round separately). Recent and baseline rates are each divided by their own window length, so a non-default window pair does not skew the comparison. - Consumer group initialization (DATA-023): a freshly created group starts at
WORKER_GROUP_START— default0, so a worker started after the first inbound events consumes the retained backlog;$opts into latest-only. An existing group is never repositioned at startup: the Redis-native cursor keeps the consumption position across restarts and a stale application checkpoint cannot replay ACKed data. The persisted checkpoint is applied only when creating a group (resume after Redis lost the group) or through the explicitWORKER_GROUP_RESET=trueoperator reset. Group creation failures are logged, never silently discarded; aBUSYGROUPrace against another worker keeps that worker's cursor. - Window-wide behavior aggregation (DATA-024): summary, heatmap, adoption breakdown, funnel, paths and level/episode/map reports aggregate the entire query window by paging through every matching event, trusting the model's authoritative
countto know when a type is exhausted (requested page sizes are re-normalized byListEvents). Windows larger than the aggregation bound (maxWindowEvents, 50000) return a bounded sample and disclose it in the responsesampleobject (totalEvents/scannedEvents/sampled/coverage), so a partial read is never presented as complete; the paged events endpoint keeps its own page-size contract. - Realtime metric sources (DATA-025):
onlineUserscounts distinct users with aheartbeat,session_startor dottedsession.startevent inside the 15-minute realtime window, andactiveSessionscountssession_start/session.startevents in the same window. Business events (login,purchase, ...) feed throughput (eventsPerMinute, all behavior events / 15 minutes) but no longer inflate online or session counts. The/analytics/realtimeresponse includes asourceobject naming each signal and the window length, and the realtime online series uses the same liveness events. Boundary: there is no player-session/heartbeat table, so "online" is an activity liveness proxy derived from analytics events, not a count of live sockets; a user with no liveness event in the window is offline by this definition even if still connected. - Realtime series bucketing (DATA-026):
/analytics/realtime/seriesreads the whole requested window in one bounded query (maxRealtimeBucketRows, 100000) and buckets rows in Go; database round trips are decoupled from the bucket count (the old code issued two queries per bucket — up to 2880 at the longest supported window). Every bucket is materialised, including empty ones, and a row on a bucket boundary contributes to exactly one bucket. Events beyond the row cap are disclosed in the responsesampleobject (scannedEvents/sampled/coverage), never presented as a complete window. - Overview WAU and retention read chain (DATA-027):
/analytics/overviewreturns a real rollingwau(the same distinct-user measure as DAU/MAU over 7 days) andretentionD1/D7/D30computed from distinct (day, user) behavior-activity pairs — the retention cohort table has no production writer, so behavior events are the only source. A cohort day counts once day+N has fully elapsed inside the queried window (a date-only end covers its whole day; a "now" end yields only fully elapsed return days), and the value is pooled retained users / pooled cohort users across mature days. Each figure carriesstatus(ok|pending|no_source),cohorts(mature cohort days pooled),sampled(pair scan truncated atmaxRetentionPairRows) andvalue(null unlessok; 0 is a real zero). The web overview maps a number only forok— a real zero renders 0%,pendingrenders "Pending maturity" andno_sourcekeeps the-placeholder; Mobile reads the same status payloads through the analytics facade. Boundary: retention is an activity-pair approximation, not the cohort-table definition pending the DATA-001 metric decision. - Peak online from the observation window (DATA-028):
/analytics/overviewreturnspeakOnline— per-day peaks taken as the interval maximum of the same online series the realtime screen plots (distinct liveness users per bucket, half-open buckets so a boundary event lands in exactly one bucket). Days follow the declared UTC boundary the rest of the relational overview trends use (DATE(occurred_at)), and themetaobject disclosestimezone,granularitySeconds(1-minute buckets),sampled(row scan truncated atmaxPeakOnlineRows),totalDays/coveredDaysandcoveredFrom/coveredTo. A day counts as observed when any event row falls on it: a day with rows but no liveness events has a real zero peak, while a day without rows was never measured — it is excluded frompointsand visible ascoveredDays < totalDays, never drawn as a zero. The web overview charts only the real peak points (the old mapping presented daily active users under the peak-online label) and renders the timezone/granularity/coverage line under the spark. Boundary: no business-timezone config exists yet, so the day boundary is UTC by declaration; intraday partial coverage of boundary days is not tracked. - Facade query parameter semantics (DATA-029):
/analytics/facade/querydeclares, per domain, the parameters it actually consumes (facadeDomainSpecsininternal/api/analytics/facade.go); unsupported input gets a field-level diagnostic (422 withdetailskeyed by the offending field) instead of being silently ignored. The metric vocabulary is the domain response's top-level keys, andmetricsnarrows the payload to that subset (absent/empty returns the canonical shape); filter keys outside the domain's declared set (cohortis retention-only,daysis warehouse-only) are diagnosed;timeRangemaps tostartDate/endDatefor date-range domains, to an hour lookback for invocations (capped at 30 days instead of silently snapping to the 24h default), and is rejected for fixed-window domains (realtime resolves its own 15-minute liveness window; warehouse resolves its window fromfilter.days). Web and mobile client tests cover different windows producing different requests/results. Boundary: cross-domain metric-caliber unification (windows, dimensions, denominators, source freshness) remains DATA-006. - Per-domain summary time budgets (DATA-030):
/analytics/facade/summarybounds every domain's wait under a per-domain budget (facadeDomainBudget, 5s, derived from the caller's context): a domain blocking past its budget reports the recognizabletimeoutcard status with the budget error while the other domains still return in time; caller cancellation releases every pending domain wait immediately (abandoned domains report unavailable with a caller-context error, never dropped silently); and in-flight domain summaries are capped by a worker pool (facadeSummaryConcurrency, 4). The mobile dashboard renders the timeout chip and the error text explicitly. - Inbound-chain acceptance (DATA-031):
scripts/e2e/analytics.shpublishes fixed samples through the realcmd/ingestentry with test HMAC credentials — accepted batch, duplicate re-submit, invalid batch (DATA-016: 400 +details.index, nothing enqueued), header/game_idmismatch, fractionalamount_centsrejection (DATA-018) and nonce replay (429) — and verifies the downstream ClickHouse shapes: raw rows collapse onto the derived event-id natural keys, the payment amount survives the chain intact,minute_onlinecovers distinct fully-elapsed minutes, anddaily_revenueaggregates the exact cents. The direct-Redis XADD worker test is retained to isolate worker behavior from ingest. - Session-length distribution (DATA-037):
/analytics/warehouse/sessionsreturns the length distribution of ended sessions from the ClickHouse pipeline A only (the bridgesession_end/session.endevents; the relational BehaviorEvent table is a separate pipeline and does not feed this endpoint). Input contract: an end event counts only when it carries both a non-emptysession_idand a numericduration_msprop (JSONHaspre-filter; string/NaN/Inf/negative values land ininvalidDurations, never in the distribution). Policy: the latest end event per session wins (redelivered or repeated closes collapse onto one session), durations are never imputed — a started session with no valid end inside the window is disclosed asunresolvedinstead of assuming a length, and duplicate heartbeat-driven starts do not inflate anything. Sessions are attributed by their end time, so a session that started the previous day but ends inside the window counts exactly once. The response materialises 11 fixed half-open buckets (0-30s…12-24h,24h+), cause counts sorted by volume, and nearest-rankavg/p50/p95(milliseconds); the raw scan is bounded (maxWarehouseSessionRows, 50000) and hitting the cap marks the responsesampledinstead of presenting a truncated read as complete. The e2e script plants one underscore-spelling and one dotted-spelling (cross-day) end sample and proves the endpoint's predicate family (event IN (...)+JSONHas) runs on the real engine. Boundary: heartbeats never extend a session's duration; sessions still open at query time remain unresolved; source unification across pipelines stays with DATA-002. - Publisher factory fail-fast (DATA-043):
mq.NewFromEnvrefuses construction whenREDIS_URLis unparseable (mq.NewRedisreturns an initialization error instead of silently selecting the noop publisher), and the ingest entry exits non-zero before opening its listener — a misconfigured address can no longer acknowledge publishes while dropping every event. Empty-write mode is reachable only through explicitANALYTICS_MQ_TYPE=noop. - Result-stream iteration errors are honored (DATA-044): every warehouse reader that walks ClickHouse rows (DAU, online, revenue, session-length distribution) and the pipeline monitor's scope query check the driver
Err()after iteration — a stream that dies before the first row or mid-read surfaces as a warehouse query failure (HTTP 500 via the warehouse error mapping) instead of a truncated point list presented as a successful payload; full reads and empty reads keep their normal shapes. - Listener failures terminate the ingest process (DATA-045): an occupied port at startup or a mid-run listener death surfaces as the process exit error (non-zero exit via the CLI error path) instead of being logged while the process keeps running without serving; SIGTERM on a usable port keeps the graceful shutdown.
- Request body cap applied before auth reads (DATA-046): the ingest endpoints enforce the same actual byte limit (
ANALYTICS_INGEST_MAX_BODY_MB) at the auth layer before any byte is read — a request whose declared length exceeds the cap is rejected without reading the body, and a chunked upload withoutContent-Lengthstops at the cap viahttp.MaxBytesReader; oversized requests get a stable413 body_too_largebefore signature verification instead of being fully buffered for the digest. Auth verification and business decoding consume the same bounded bytes; the handler-level oversized detection matches the cap by error type (http.MaxBytesError) rather than message text. Boundaries: a body of exactly the limit passes; the metrics middleware declared-length pre-check stays as a secondary branch; a configured limit of 0 rejects every body at the gate. - Boundary: the payments table has no dedup column; identical payment re-submission still appends a second raw row and relies on
order_id-keyed read semantics for reconciliation (tracked by DATA-004/051/056).
Metric groups
- Foundation: DAU, WAU, MAU, stickiness, and D1/D7/D30 retention.
- Progression and economy: level completion, conversion, source sinks and sources, balance signals.
- Engagement and social: session length, feature use, team and guild activity, messaging.
- Combat and content: win-rate distribution, character balance, ranked distribution, PVP/PVE participation.
- Campaign and operations: participation, completion, incremental revenue, push delivery and conversion.
- Experience: page dwell time, interaction and error rates, discovery, latency, and network quality.
Operational shape
- Start Redis and ClickHouse.
- Run
ingestwith the configured HMAC secret. - Run
analytics-worker. - Run the Server and open the Analytics console.
Schema and pipeline changes should be additive where practical. Existing events must remain queryable while new dimensions or aggregates are introduced.
Reading path
- Start with the game metrics map for definitions.
- Use the collection architecture page for event ownership.
- Use the ClickHouse schema page before adding queries or aggregates.
- Use best practices and troubleshooting pages for rollout and failure handling.
