https://github.com/centrifugal/centrifugo
https://centrifugal.dev/docs/getting-started/introduction
https://centrifugal.dev/docs/getting-started/quickstart
https://centrifugal.dev/docs/server/configuration
https://centrifugal.dev/docs/server/authentication
https://centrifugal.dev/docs/server/channels
https://centrifugal.dev/docs/server/server_api
https://centrifugal.dev/docs/transports/overview
https://centrifugal.dev/docs/transports/client_api
https://github.com/centrifugal/centrifuge-js

1. Important Points#

Centrifugo 是 self-hosted real-time messaging server。它负责维护大量客户端长连接,业务后端负责鉴权、生成 connection token、通过 server API publish 消息。

适合:
    WebSocket / SSE / HTTP-streaming real-time updates
    chat / notification / dashboard / collaboration presence
    backend wants to avoid managing connection fan-out itself
    multiple language backends publish to one real-time gateway
    browser / mobile / server clients need unified real-time protocol

不适合:
    durable message queue replacement
    long-term event store
    complex stream processing engine
    business authorization brain
    direct database change capture without backend design
核心原则:
    Centrifugo is connection and fan-out layer
    application backend owns identity and business authorization
    browser never gets token signing secret or API key
    client subscribes to channels; backend publishes to channels
    channel design should follow product access boundary
    production must configure allowed origins, TLS, auth, metrics, and engine

2. Architecture#

request flow#

browser app
    -> login to application backend
        -> backend verifies user/session
        -> backend signs short-lived Centrifugo connection JWT
    -> browser connects to Centrifugo with JWT
    -> browser subscribes to allowed channels

application backend
    -> business event happens
    -> backend calls Centrifugo server API publish
    -> Centrifugo fans out publication to subscribed clients

responsibility split#

Component Responsibility Do Not Put Here
Browser client connect, subscribe, receive publications token signing secret, API key
Application backend login, user authorization, JWT generation, publish calls long-lived WebSocket fan-out
Centrifugo connection management, channel subscription, fan-out, presence/history when enabled business permission model
Redis / NATS / broker engine cross-node publication and presence/history coordination application source of truth

3. Core Concepts#

Concept Meaning Notes
Transport client connection protocol WebSocket is the normal browser default
Client connected user/device/session authenticated by connection token when enabled
Channel named real-time topic examples: user:1001, order:123, chat:index
Namespace channel prefix with shared config use to group channel policy
Publication message sent to a channel usually produced by backend
Presence who is online in a channel useful for chat/collaboration, has cost
History short message retention per channel useful for reconnect/recover, not a database
Server API backend-to-Centrifugo HTTP/gRPC API publish, broadcast, presence, history, disconnect
Token JWT for connection/subscription signed by backend, short TTL

channel naming#

recommended examples:
    user:1001
    order:ord_123
    chat:index
    tenant:t1:notification

avoid:
    one global channel for all private data
    user-controlled channel names without validation
    high-cardinality channel explosion without capacity test
    putting secrets or PII into channel names

4. Service Configuration#

local dev config#

{
  "client": {
    "token": {
      "hmac_secret_key": "dev-token-secret-change-me"
    },
    "allowed_origins": ["http://localhost:5173"]
  },
  "http_api": {
    "key": "dev-api-key-change-me"
  },
  "prometheus": {
    "enabled": true
  },
  "channel": {
    "namespaces": [
      {
        "name": "chat",
        "allow_subscribe_for_client": true,
        "presence": true,
        "history_size": 20,
        "history_ttl": "300s"
      }
    ]
  }
}
notes:
    client.token.hmac_secret_key signs client JWT
    http_api.key protects server API
    client.allowed_origins should be exact browser origins
    allow_subscribe_for_client lets browser SDK subscribe directly in that namespace
    history is short-term recovery buffer, not durable storage

production baseline#

production config baseline:
    pin exact Centrifugo image version
    run behind HTTPS reverse proxy / ingress
    set client.allowed_origins explicitly
    keep client.token.hmac_secret_key and http_api.key in secret manager
    use short-lived connection tokens
    do not expose server API publicly
    enable Prometheus metrics
    use Redis / NATS / other supported engine when running multiple nodes
    set resource requests/limits and file descriptor limits
    test reconnect, deploy restart, and backend publish failure behavior

5. Client SDK Decision#

The hands-on in this section uses JavaScript browser client.

Platform Package / SDK Use Case
JavaScript browser centrifuge / centrifuge-js SPA, dashboard, admin console, web chat
Node.js backend HTTP/gRPC server API client or plain HTTP publish from backend service
Mobile native/mobile client SDKs mobile real-time app
Server-side consumers language-specific clients when needed service-to-service subscriptions
browser rule:
    browser gets only a short-lived connection token
    browser does not know client.token.hmac_secret_key
    browser does not know http_api.key
    token refresh should call application backend

6. Security Best Practices#

connection auth:
    sign JWT in application backend
    keep token TTL short
    include stable user id in sub
    validate channel access before issuing subscription capability or enabling client-side subscribe

origin and network:
    configure client.allowed_origins
    expose only client transport endpoint to browsers
    keep server API on private network or behind backend-only auth
    terminate TLS at ingress/proxy or Centrifugo

secrets:
    client.token.hmac_secret_key and http_api.key are production secrets
    rotate secrets with rollout plan
    never commit real secrets into config.json

7. Monitoring#

important signals:
    connected clients
    number of subscriptions
    publish rate and errors
    command / API errors
    disconnect reason spike
    node memory and CPU
    Redis / engine latency when clustered
    reconnect storm after deployment or network event
recommended alerts:
    API publish error rate > 1% for 5 minutes
    connected clients drop > 50% within 5 minutes
    process restarts unexpectedly
    p95 publish/API latency above product SLO
    Redis / broker unavailable
    file descriptor usage near limit

8. Files In This Section#

Setup.md:
    Docker / Compose / K8S setup and operations baseline

HandsOn.md:
    runnable local Centrifugo + JavaScript browser SDK demo