Go client for the HTTP server API of Centrifugo: every API method, including those of Centrifugo PRO. For a real-time client over WebSocket, see centrifuge-go.
go get github.com/centrifugal/gocent/v4
No dependencies. gocent implements the Centrifugo server SDK spec 0.4, as its reference implementation.
| Version | |
|---|---|
| Go | 1.27 or newer |
| Centrifugo | v6, any release |
| Map and shared poll methods | Centrifugo v6.8.0 or newer |
Error.Temporary, ErrTooManyRequests, refused requests reported as such rather than as internal errors |
Centrifugo v6.10.0 or newer |
Ed25519 tokens verified without JWKS, by client.token.ed25519_public_key |
Centrifugo v6.10.2 or newer |
| Methods marked "Centrifugo PRO only" | Centrifugo PRO v6 |
With an older Centrifugo, Retryable still works: it treats the internal
error, code 100, as temporary when the server does not mark errors.
client, err := gocent.New(gocent.Config{
APIEndpoint: "http://localhost:8000/api",
APIKey: os.Getenv("CENTRIFUGO_API_KEY"),
})
if err != nil {
log.Fatal(err) // the config is wrong, and the error says how
}
res, err := client.Publish(ctx, gocent.PublishRequest{
Channel: "news",
Data: jsontext.Value(`{"text":"hello"}`),
})
if err != nil {
return err
}
log.Printf("published at offset %d", res.Offset)Every API method is a Client method taking a request struct and returning a
result struct, with fields mapping one to one onto the
API. Create the Client once
and share it: it is safe for concurrent use.
Write integers which may pass 2^53 - an int64 ID, say - as JSON strings,
with the json:",string" option: browsers and JavaScript backends decode JSON
numbers as doubles, and round larger integers silently.
Every call is bounded by Config.RequestTimeout, ten seconds by default. A
context deadline shortens a call, never extends it:
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
info, err := client.Info(ctx, gocent.InfoRequest{}) // at most 500msSo a call made with an HTTP handler's context, which may live for minutes,
still gives up on a stuck Centrifugo after RequestTimeout. To let calls
take longer, raise RequestTimeout: a context with a later deadline does
not. http.Client.Timeout, in Config.HTTPClient, bounds every request of
the client on top of that. However a call times out,
errors.Is(err, context.DeadlineExceeded) is true.
BroadcastWithRetry makes several requests in one call: its context bounds
them all, waits between them included, and
BroadcastRetryOptions.AttemptTimeout is each attempt's own timeout,
replacing RequestTimeout for it, longer or shorter - so that an attempt
which hangs leaves time to retry.
| Error | Meaning | Check |
|---|---|---|
*gocent.Error |
Centrifugo refused the request or failed to carry it out | errors.Is(err, gocent.ErrUnknownChannel), or errors.AsType for Code |
*gocent.BroadcastFailedChannelsError, *gocent.BatchFailedCommandsError |
some parts of a broadcast or batch failed - see below | errors.AsType |
*gocent.HTTPError |
the request did not reach the API method | errors.Is(err, gocent.ErrUnauthorized) for rejected credentials |
*gocent.DecodeError |
the reply was not Centrifugo's - usually APIEndpoint points elsewhere |
errors.AsType |
gocent.ErrInvalidRequest |
the client could tell the request is wrong and did not send it | errors.Is |
gocent.ErrInvalidConfig |
New refused the config, or APIEndpointFunc or BearerTokenFunc returned an endpoint or token the client cannot send |
errors.Is |
*gocent.FunctionError |
APIEndpointFunc or BearerTokenFunc failed: Function names it, Err is its error |
errors.AsType; gocent.Retryable judges it by Err |
| network, context | as usual | errors.Is(err, context.DeadlineExceeded) for any timeout |
Centrifugo adds error codes over time: an unknown code is still an
*gocent.Error, so match the codes you handle and treat the rest by class.
gocent.Retryable(err) reports whether retrying may succeed: the error came from
a temporary condition - a broker being unavailable, a rate limit, the network -
not from the request.
A temporary error does not mean nothing was done: after a timeout, or even an
internal error, the publication may have happened. So retry a publication only
with an IdempotencyKey, and back off between a bounded number of attempts:
req := gocent.PublishRequest{
Channel: "orders:42",
Data: data,
// The same key on every attempt: a publication which happened in an
// earlier attempt, even one reported as failed, is not published again.
IdempotencyKey: "order-42-paid",
}
backoff := gocent.ExponentialBackoff(200*time.Millisecond, 5*time.Second)
for attempt := 1; ; attempt++ {
_, err := client.Publish(ctx, req)
if err == nil || !gocent.Retryable(err) || attempt == 3 {
return err
}
// Ends early, with the context's error, when ctx is cancelled or out of time.
if err := gocent.Wait(ctx, backoff(attempt)); err != nil {
return err
}
}Choosing keys:
- One key per publication or broadcast, reused only to retry that same one. A broadcast needs one key, not one per channel.
- Centrifugo remembers a key per channel, for five minutes by default. A retry
within that time is answered with the first result and not published again -
and so is a different publication into the same channel under the same key.
A key built from an ID must name the event too:
order-42-paid, notorder-42. - The memory, Redis and PostgreSQL brokers keep keys. The NATS broker ignores them, so with it a retry publishes again.
Retry a broadcast with client.BroadcastWithRetry rather than a retry library:
see below. With a retry library for other calls, give it gocent.Retryable as
the condition to retry on, and set an IdempotencyKey.
Broadcast publishes the same data into many channels in one request; a Batch
sends many commands at once. Both return an error unless every part succeeded:
_, err := client.Broadcast(ctx, gocent.BroadcastRequest{
Channels: []string{"user:1", "user:2"},
Data: jsontext.Value(`{"text":"hello"}`),
IdempotencyKey: messageID,
})
if err != nil {
return err // retrying with the same IdempotencyKey is safe
}b := client.NewBatch(gocent.BatchOptions{})
pub := b.Publish(gocent.PublishRequest{Channel: "news", Data: data})
stats := b.PresenceStats(gocent.PresenceStatsRequest{Channel: "news"})
if _, err := b.Send(ctx); err != nil {
return err
}
res, err := pub.Result() // each command has its own result and error
st, err := stats.Result()Parts succeed or fail on their own, and the result tells which case it is:
res.Repliedis true: Centrifugo carried the request out and replied for every part.res.Failed()lists the parts which failed, up to all, and the error is a*gocent.BroadcastFailedChannelsErroror*gocent.BatchFailedCommandsErrorlisting them too - or nil when none did.res.Repliedis false: the request failed as a whole - the network, the credentials, an invalid request - and no part got a reply. After a timeout or a network error Centrifugo may still have carried it out.
errors.Is answers for the call as a whole: it does not look into the parts,
so one unknown channel among many does not make
errors.Is(err, gocent.ErrUnknownChannel) true. To go on despite some failed
parts, stop only when Centrifugo did not reply, and read the parts - every
part always has an outcome, whatever the error:
res, err := client.Broadcast(ctx, req)
if !res.Replied {
return err // no channel got a reply
}
for _, ch := range res.Failed() {
log.Printf("not published into %s: %v", ch.Channel, ch.Err)
}The same for a batch: res, err := b.Send(ctx), then res.Replied and
res.Failed(); each command's typed result is in its Pending. Results
render as JSON by their wire names, with encoding/json and
encoding/json/v2 alike - {"channels": [...], "idempotency_key": ...} - an
error in them as {"code": 102, "message": "unknown channel"}.
Retrying:
-
a broadcast:
client.BroadcastWithRetrydoes it. It sends again only the channels which may still succeed, all attempts with oneIdempotencyKey- made for the call when the request has none - and returns every channel's last outcome, asBroadcastdoes:res, err := client.BroadcastWithRetry(ctx, req, gocent.BroadcastRetryOptions{})
The zero
BroadcastRetryOptionsretries once, after about 100 milliseconds;MaxAttemptssets how many attempts in all.OnAttemptErris called after each failed attempt which will be retried, with the channels to retry and their errors, and decides what happens before the retry: it waits, logs, counts, or returns an error to stop. Any strategy fits in it:backoff := gocent.ExponentialBackoff(200*time.Millisecond, 5*time.Second) res, err := client.BroadcastWithRetry(ctx, req, gocent.BroadcastRetryOptions{ MaxAttempts: 5, OnAttemptErr: func(ctx context.Context, a gocent.BroadcastAttempt) error { log.Printf("attempt %d: %d channels to retry", a.Attempt, len(a.Retry)) return gocent.Wait(ctx, backoff(a.Attempt)) // or gocent.Wait(ctx, time.Second) }, })
ExponentialBackoffgives a longer wait after each failed attempt, with some randomness, so that clients which failed together do not retry together; the default waits it. A*gocent.HTTPErrorina.Errcarries the response'sHeader: wait at least itsRetry-Afterto honour one.AttemptTimeoutbounds each attempt - see Timeouts.res.IdempotencyKeyis the key the attempts used: to retry the broadcast later, after it gave up - from a job queue, say - send it with that key.res.Attempts, each channel'sAttemptsandres.Failed()tell what happened.A retry library which calls
Broadcastagain on any error would instead send it to every channel again, those which already got it included. -
a batch: build a new one, with the same keys, from the commands
res.Failed()lists with a retryable error - every command when the batch failed as a whole. A batch is sent once, so keep your own list of its requests:Failed()gives each command'sIndexin it. Commands without a key are repeated.
BatchOptions{} runs the commands one by one, in order; Parallel runs them
concurrently. Centrifugo PRO sends a batch's publications to its broker
together: each channel's publications still take effect in order, but
publications into different channels may not, unless the namespace sets
publication_grouping_disabled.
HistoryAll, DeviceListAll, DeviceTopicListAll, UserTopicListAll and
MapReadStateAll return every item of a paged method, reading a page when
the loop reaches it:
var last gocent.StreamPosition
for item, err := range client.HistoryAll(ctx, gocent.HistoryRequest{Channel: "news", Limit: 100}) {
if err != nil {
return err
}
handle(item.Data)
last = item.Position() // where to resume from
}HistoryAll yields each publication with its position, and
MapReadStateAll each entry with the position of the state it was read at,
item.State: what MapReadStream follows the state from. Position() on a
publish, history, map publish, map remove or map read result is the
StreamPosition to read on from: HistoryRequest{Since: res.Position()}
reads what came after a publication.
With AutoBatch set, calls made concurrently go out together once
MaxInFlight requests are in flight - with no delay otherwise, since nothing
waits for a timer.
It is for processes making many calls at once - a service handling many
requests concurrently, a worker fanning publications out - and does nothing
for one making a few at a time. Set MaxInFlight to about half the calls the
process makes at once: above that, it never batches; just below, it batches
calls one at a time, and only limits them:
client, err := gocent.New(gocent.Config{
APIEndpoint: "http://localhost:8000/api",
APIKey: key,
AutoBatch: gocent.AutoBatch{MaxInFlight: 8},
})Every call still gets its own result or error, and keeps its own deadline. Calls
sharing a batch share its request, though: if the request itself fails - the
network, a body too large - every call in it fails. See
AutoBatch for
the details.
APIKey is sent in the X-API-Key header. BearerTokenFunc instead sends a
token as Authorization: Bearer, for Centrifugo PRO's JWKS authentication - it
is called for every request, so return a cached token, as an
oauth2.TokenSource does. Leave both unset when mutual TLS, configured in
HTTPClient, or a proxy authenticates instead.
To sign the tokens yourself, token.APITokenSource issues them and reuses each for
half its lifetime:
apiTokens := &token.APITokenSource{
Key: apiKey, // its own key - never one of the client tokens
Claims: token.APIClaims{Audience: "centrifugo-api", Scope: []string{"centrifugo:api"}},
}
client, err := gocent.New(gocent.Config{
APIEndpoint: "https://centrifugo.example.com/api",
BearerTokenFunc: apiTokens.Token,
})Centrifugo PRO accepts a token signed with any key of http_api.jwks.endpoint,
and checks the audience, issuer and scope only when configured to. So keep API
tokens apart from the connection and subscription tokens your users hold - or
any user can call the server API with their connection token:
- publish the API keys with
h.JWKS(apiKeys...)at an endpoint of their own, not the one ofclient.token.jwks_public_endpoint; - set
http_api.jwks.audienceandhttp_api.jwks.scopeto values only API tokens carry -token.APIrefuses claims with neither.
The API keys rotate as client keys do: see Key rotation with JWKS.
Rejected credentials make every call fail with an *HTTPError matching
gocent.ErrUnauthorized.
Tracing and metrics come from the HTTP client's transport. With OpenTelemetry:
hc := gocent.DefaultHTTPClient()
hc.Transport = otelhttp.NewTransport(hc.Transport)
client, err := gocent.New(gocent.Config{APIEndpoint: endpoint, APIKey: key, HTTPClient: hc})Each call is a span in its caller's trace, and Centrifugo continues the trace
when its OpenTelemetry API tracing is on. An automatic batch belongs to no
single caller: Config.BatchContext makes its request's context from the
callers', with a link to each caller's span, say. Config.OnRequest is told
of every request - method, commands and how many failed, duration, status,
error - for metrics without a transport of your own. See the
package docs.
client.Close(ctx) refuses new calls with gocent.ErrClosed and waits for the
ones in progress - calls queued for an automatic batch included - so that what
was accepted is sent before the process exits. Call it on SIGTERM:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := client.Close(ctx); err != nil {
log.Printf("gocent: calls still in progress at exit: %v", err)
}The proxy package is the other direction: the backend side of Centrifugo's
HTTP proxy, which calls your application when a client connects, subscribes,
publishes or makes an RPC call. proxy.Handlers has a method per proxy type,
taking a function:
h := proxy.Handlers{OnError: logProxyError} // the zero value works too
mux.Handle("/centrifugo/subscribe", h.Subscribe(
func(r *http.Request, req proxy.SubscribeRequest) (proxy.SubscribeResult, error) {
if !canRead(r.Context(), req.User, req.Channel) {
return proxy.SubscribeResult{}, &proxy.Error{Code: 403, Message: "permission denied"}
}
return proxy.SubscribeResult{}, nil
}))Return a result to accept the request, a *proxy.Error to reject it with an
error the client receives, or a *proxy.Disconnect to close the client's
connection; any other error fails the request, and goes to OnError to be
logged. Keep proxy endpoints reachable by Centrifugo only: whoever can call
them can claim to be any user. Put them on a network only Centrifugo reaches,
or check a secret header Centrifugo adds with the proxy's static_headers
option before the handler, and use TLS where the traffic leaves a trusted
network. See the
package docs.
The token package issues the JWTs Centrifugo authenticates clients with -
connection and subscription tokens, with Centrifugo's claims, signed with
HMAC, RSA (2048 bits or more), ECDSA or Ed25519 - and serves the endpoints the getToken
callbacks of client SDKs call:
key := token.HMAC(secret) // client.token.hmac_secret_key
h := token.Handlers{OnError: logError}
mux.Handle("/centrifugo/connection_token", h.Connection(
func(r *http.Request) (string, error) {
user, ok := sessionUser(r)
if !ok {
return "", token.ErrForbidden // 403: the client stops asking
}
return token.Connection(key, token.ConnectionClaims{User: user, ExpiresAt: time.Now().Add(time.Hour)})
}))h.Subscription serves subscription tokens the same way, with the channel the
client asks for. To rotate keys without restarting Centrifugo, see
Key rotation with JWKS.
By default Centrifugo verifies tokens with a single key from its
configuration: client.token.hmac_secret_key, or an RSA, ECDSA or Ed25519
public key. Changing that key means restarting Centrifugo, and from that
moment it refuses every token signed with the old key. To rotate keys without
that, your application can serve the keys itself, as a JSON Web Key Set (JWKS)
at Centrifugo's client.token.jwks_public_endpoint. Each key in the set has an
ID, and Centrifugo verifies a token with the key its kid header names:
// An ID for each key, never reused for another key: Centrifugo caches keys by ID.
key := token.Ed25519(privateKey).WithKeyID("2026-10")
mux.Handle("/centrifugo/jwks", h.JWKS(key)) // the URL of jwks_public_endpoint
tok, err := token.Connection(key, token.ConnectionClaims{User: "42", ExpiresAt: expiresAt}){"client": {"token": {"jwks_public_endpoint": "https://app.example.com/centrifugo/jwks"}}}Only RSA, ECDSA and Ed25519 keys can go in a set. An HMAC secret has no
public part to publish. Once jwks_public_endpoint is set, Centrifugo
verifies tokens with the set only, and refuses tokens signed with the key it
was configured with before. So moving to a JWKS is a one-time restart.
How Centrifugo reads the set:
- when a token names a key ID Centrifugo doesn't know, it fetches the set again, at most once every 5 seconds;
- it keeps the keys it fetched for 5 minutes (an hour before Centrifugo v6.10.2), so a key dropped from the set stops working within that time;
- when the endpoint can't be reached, it keeps using the keys it already has;
- a token whose key isn't in the set is refused as expired, and the client SDK asks for a new token.
Rotate a key in three steps. Each step is one deploy of your application, and every instance should finish a step before any instance moves to the next:
- Publish the new key alongside the current one, and keep signing with
the current one:
h.JWKS(current, next). - Sign with the new key. Centrifugo fetches the set the first time it sees the new ID.
- Drop the old key once every token it signed has expired: wait longer
than the longest
ExpiresAtyou give.
If a key leaks, do all three steps now, without waiting in step 3. Within 5 minutes Centrifugo refuses new connections with the leaked key's tokens. Clients that connected before stay connected until their tokens expire: disconnect them with the server API if needed.
Centrifugo PRO's API tokens rotate the same way, from a set of their own at
http_api.jwks.endpoint (see Authentication).
token.APITokenSource.CurrentKey returns the key to sign with, so it can switch
to the new key at step 2. Each API token is reused for half its TTL, so in
step 3 wait at least TTL after the switch.
Clients tracking keys of a shared poll
channel need a signature from the backend. The sharedpoll package makes one,
and serves the endpoint a subscription's getSignature callback calls:
h := sharedpoll.Handlers{OnError: logError}
mux.Handle("/centrifugo/shared_poll_signature", h.Signature(
func(r *http.Request, channel string, keys []string) ([]string, string, error) {
allowed := readable(r.Context(), user, channel, keys) // the rest are revoked
sig, err := sharedpoll.Sign(secret, user, channel, allowed, time.Now().Add(time.Hour))
return allowed, sig, err
}))An expiry is required: a signature which never expires is chosen explicitly,
with sharedpoll.SignNoExpiry.
Shared poll subscriptions are experimental in Centrifugo, and the package follows their changes.
Test code which uses gocent against an httptest server answering as
Centrifugo does - each method at /api/<method>, its reply
{"result": {...}} or {"error": {"code": ..., "message": ...}}:
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/publish":
fmt.Fprint(w, `{"result":{"offset":1,"epoch":"e"}}`)
case "/api/broadcast": // one response per channel, in order
fmt.Fprint(w, `{"result":{"responses":[{"result":{"offset":1}},{"error":{"code":102,"message":"unknown channel"}}]}}`)
case "/api/batch": // one reply per command, in order
fmt.Fprint(w, `{"replies":[{"publish":{"offset":1}},{"error":{"code":102,"message":"unknown channel"}}]}`)
}
}))
defer srv.Close()
client, err := gocent.New(gocent.Config{APIEndpoint: srv.URL + "/api"})Behind an interface of your own, a test double returns gocent's results and
errors as they are: a gocent.BroadcastResult with a
*gocent.BroadcastFailedChannelsError for a partial failure, and
gocent.NewBatchResult and gocent.NewPending for a batch.
- Package docs: everything above in more detail, plus writing commands for Centrifugo's async consumers.
- A 404 from a Centrifugo PRO method means the server is Centrifugo OSS; the error says so.
- Streaming AI output: Centrifugo for AI
apps, and
ExampleClient_Publish_streamin the package docs - what arrived every 50 ms, published in order into a channel with history. - Docs for agents and LLMs: centrifugal.dev/llms.txt, an index of the current (v6) documentation.
- Upgrading from v3: MIGRATING.md has complete programs before and after, and the changelog maps every call.
- Development: see AGENTS.md;
make checkruns everything CI does.
MIT license. Centrifugo PRO, which the methods marked "Centrifugo PRO only" call, is commercial software under its own license.