Traffic Analytics is a web analytics proxy for Ghost. It receives page-hit events from the ghost-stats.js browser script, enriches them (user-agent parsing, referrer parsing, and a privacy-preserving user signature), filters bot traffic, and forwards the result to Tinybird's /v0/events endpoint for storage in ClickHouse.
The same Docker image runs in three roles, selected by the WORKER_MODE environment variable in server.ts:
- Ingest app (
WORKER_MODEunset —src/app.ts) — the Fastify HTTP server that receivesPOST /api/v1/page_hit. - Worker app (
WORKER_MODE=true—src/worker-app.ts) — a Pub/Sub consumer that enriches events and forwards them to Tinybird. It exposes only health endpoints (/and/health) for Cloud Run. - Tinybird sync worker (
WORKER_MODE=tinybird-sync—src/tinybird-sync-worker-app.ts) — consumes Tinybird sync events from Pub/Sub, buffers each event type separately, and sends batches to their mapped Tinybird datasources.
The ingest app has two request-handling strategies (see src/handlers/page-hit-handlers.ts), chosen by whether PUBSUB_TOPIC_PAGE_HITS_RAW is set:
- Batch mode (default in dev and production) — publish events to Pub/Sub and return
202immediately. Page-hit enrichment and forwarding happen inworker; Tinybird sync batching and forwarding happen intinybird-sync. This is thedev:batchCompose profile:analytics-service+worker+tinybird-sync. - Proxy mode (synchronous) — no topic set. The request is enriched inline and proxied straight to
PROXY_TARGET(/v0/events) within the same request/response cycle. This is thedev:proxyCompose profile:analytics-service-proxy.
flowchart LR
Browser["Browser<br/>ghost-stats.js"]
subgraph Ingest["Ingest app (src/app.ts)"]
HMAC["HMAC validation<br/>(preValidation)"]
Validate["Schema validation"]
Bots["Filter bot traffic<br/>(preHandler)"]
Pre["Populate request defaults<br/>(route preHandler)"]
Pub["Publish raw event"]
end
Topic(["Pub/Sub topic<br/>PUBSUB_TOPIC_PAGE_HITS_RAW"])
Sub(["Pub/Sub subscription<br/>PUBSUB_SUBSCRIPTION_PAGE_HITS_RAW"])
subgraph Worker["Worker app (src/worker-app.ts)"]
Enrich["Enrich:<br/>user agent + referrer<br/>+ user signature"]
BotGuard["Defensive bot check"]
Batch["Batch<br/>(BATCH_SIZE / flush interval)"]
end
TB["Tinybird<br/>POST /v0/events"]
Browser -->|"POST /api/v1/page_hit"| HMAC
HMAC --> Validate --> Bots
Bots -->|"bot: 202 Accepted"| Browser
Bots -->|"not bot"| Pre --> Pub
Pub -->|"202 Accepted"| Browser
Pub --> Topic --> Sub --> Enrich
Enrich --> BotGuard --> Batch --> TB
Notes:
- HMAC validation (
src/plugins/hmac-validation.ts) is a globalpreValidationhook. It validates the signature and timestamp carried in the URL query parameters and strips them before downstream processing. It is skipped entirely ifHMAC_SECRETis unset, and it can be run in log-only mode withHMAC_VALIDATION_LOG_ONLY=true. - Enrichment (
transformPageHitRawToProcessed) parses the user agent withua-parser-js, parses the referrer with@tryghost/referrer-parser, and computes thesession_iduser signature. - Bot filtering runs in the ingest app's
bot-detectionpreHandlerhook before the request strategy is selected, so bot events return the standard202accepted response without being published to Pub/Sub or proxied to Tinybird. SetENABLE_BOT_DETECTION_HEADER=trueto includex-ghost-bot-detected: trueon these responses; the header is omitted by default. The worker retains a defensive check for legacy or directly published messages that bypassed the API. - Batching (
src/services/batch-worker/BatchWorker.ts) accumulates processed events and flushes them to Tinybird as newline-delimited JSON when the batch reachesBATCH_SIZE(default 50) or the flush timer fires (BATCH_FLUSH_INTERVAL_MS, default 1000ms). Messages areacked on a successful flush andnacked on failure. - Tinybird sync batching keeps separate buffers for automation runs and run steps. It flushes when a buffer reaches
TINYBIRD_SYNC_BATCH_SIZE(default 50) or afterTINYBIRD_SYNC_BATCH_FLUSH_INTERVAL_MS(default 1000ms).
When PUBSUB_TOPIC_PAGE_HITS_RAW is not set, the ingest app enriches the request inline and proxies it directly to PROXY_TARGET using @fastify/reply-from, returning Tinybird's response to the caller. There is no Pub/Sub topic and no separate worker in this mode.
- The publisher (
src/services/events/publisher.ts) and subscriber (src/services/events/subscriber.ts) both use@google-cloud/pubsuband readGOOGLE_CLOUD_PROJECTfor the project ID. - In local development and tests, a Pub/Sub emulator is used via
PUBSUB_EMULATOR_HOST. The Compose stack creates the topictraffic-analytics-page-hits-rawand subscriptiontraffic-analytics-page-hits-raw-sub.
User signatures depend on a daily-rotating salt, stored via an adapter pattern behind ISaltStore and selected by SALT_STORE_TYPE (see SaltStoreFactory.ts):
memory— in-process, lost on restart. This is the code default.file— JSON file atSALT_STORE_FILE_PATH(default./data/salts.json).firestore— Google Cloud Firestore; requiresGOOGLE_CLOUD_PROJECTandFIRESTORE_DATABASE_ID. This is what Docker Compose dev/test use (via the Firestore emulator atFIRESTORE_EMULATOR_HOST) and what production uses.
The user signature (UserSignatureService) is a SHA-256 hash of salt : site_uuid : ip : user-agent, where the salt is keyed by date and site UUID so it rotates daily per site. A cleanup scheduler periodically deletes expired salts (ENABLE_SALT_CLEANUP_SCHEDULER, FIRESTORE_CLEANUP_BATCH_SIZE).
OpenTelemetry is initialised in src/utils/instrumentation.ts before the app loads:
- The trace exporter is Jaeger (OTLP HTTP) by default, or Google Cloud Trace when
OTEL_TRACE_EXPORTER=gcporK_SERVICEis set (Cloud Run setsK_SERVICEautomatically). - Google Cloud Trace uses OTLP HTTP/protobuf at
https://telemetry.googleapis.com/v1/traces. Application Default Credentials supply refreshed authentication headers and thegcp.project_idresource attribute. Before deploying, enabletelemetry.googleapis.comand grant the runtime service accountroles/telemetry.tracesWriteron the destination project. If ADC specifies a quota project, grantroles/serviceusage.serviceUsageConsumerthere too. Send a staging request and confirm its trace arrives in Cloud Trace before promoting. See Google's migration guide. - OTLP endpoints default to the
jaegerservice (OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,OTEL_EXPORTER_OTLP_METRICS_ENDPOINT). - The reported service name is
analytics-workerin batch worker mode,analytics-tinybird-sync-workerin Tinybird sync mode, andanalytics-serviceotherwise.
- Deployment — CI and the deploy pipeline.
- AGENTS.md — module map, commands, and environment variables for contributors and coding agents.