Repository navigation
Delivery
The broker delivers each event with a POST to the subscriber's endpoint (spec.subscriber.endpoint, or that of the sink spec.subscriber.sink names), or over the transport its scheme selects (see Transports). Any 2xx response acknowledges the event. For a subscription that tracks a stream offset, the broker then commits status.stream.ackedOffset (the offset of the next event to deliver) and moves on. Offsets are only committed after a successful delivery, so delivery is at-least-once: subscribers should be idempotent.
A delivery fails when the subscriber cannot be reached, responds with a non-success status code, or does not respond within the dispatch timeout. A subscription's mutation is applied by every delivery attempt: a mutation webhook shares the attempt's timeout, and its failures are retried like the subscriber's. Failed deliveries are retried according to spec.subscriber.retryPolicy. If the subscription has none, the broker's spec.dispatch.retryPolicy applies:
spec:
subscriber:
endpoint: https://subscriber.example.com/events # or an endpoint with authentication, or a sink: see Transports
timeout: PT30S # per attempt; defaults to the broker's spec.dispatch.timeout, or PT100S
rateLimit: 10 # optional maximum number of deliveries per second; must be strictly positive
retryPolicy:
statusCodes: [ 429, 503 ] # status codes to retry; all of them if empty. Connection failures and timeouts are always retried
backoffDuration:
type: exponential # constant | incremental | exponential
period: PT1S
exponent: 2
maxDelay: PT5M # caps the delay between two attempts; defaults to PT1H
maxAttempts: 10 # defaults to 5; set to -1 to retry forever
circuitBreaker:
breakAfter: 3 # consecutive failures after which delivery pauses...
breakDuration: PT30S # ...for this longWhile a delivery is being retried, the subscriber is reported unreachable in status.subscriber, and every failed attempt increments the cloud_streams_broker_delivery_failures_count metric. The event is never skipped. If the retry policy is exhausted, or the subscriber responds with a status code the policy does not retry, the subscription is faulted (status.stream.fault) with a message explaining how to resume, and the offset of the failed event is recorded in status.stream.faultedOffset. Resuming the subscription retries the event. POST /api/resources/v1/namespaces/{namespace}/subscriptions/{name}/skip?offset={faultedOffset} skips it: it requires the operator role, and returns 409 if the subscription isn't faulted by that event. Setting spec.stream.offset to the failed event's offset, or to the next one, does the same. Subscriptions that do not track a stream offset drop the event instead, and carry on, unless they have a dead-letter policy.
A subscription with a dead-letter policy sets aside the events it fails to deliver, rather than being faulted or dropping them. That's once the retry policy is exhausted, or when the subscriber responds with a status code the policy doesn't retry. Delivery then carries on with the next event.
spec:
deadLetter: {} # dead letters are stored in the subscription's dead-letter stream
# deadLetter:
# endpoint: https://dead-letters.example.com # or sent there, as structured cloud events, or to a sink-
Dead-letter stream: each dead letter records:
- the event, as it was sent to the subscriber, so mutated if the subscription mutates events;
- its offset;
- the reason it couldn't be delivered;
- when it was dead-lettered.
-
Dead-letter service: the event is sent with the
cloudstreams-subscriptionandcloudstreams-offsetheaders, and the reason, percent-encoded, incloudstreams-dead-letter-reason. The service may itself be another Cloud Streams gateway's ingestion endpoint. - If dead-lettering fails: the subscription is faulted, as it would be without a policy, and the event isn't skipped.
-
Metric: dead-lettered events are counted by
cloud_streams_broker_dead_letters_count.
Dead letters are browsed and redelivered with:
GET /api/resources/v1/namespaces/{namespace}/subscriptions/{name}/dead-letters?offset=&length=&direction= # most recent first by default
POST /api/resources/v1/namespaces/{namespace}/subscriptions/{name}/dead-letters/{offset}/redeliver # requires the operator role
A redelivery delivers the dead letter to the subscriber once, without an acknowledgement token, over its transport and authenticated as its endpoint or sink configures. It answers 502 Bad Gateway with the subscriber's response if the subscriber refuses it again. The dead-letter stream is a log: redelivering a dead letter doesn't remove it.
An HTTP endpoint can have its deliveries signed, following the Standard Webhooks specification, so that the subscriber can tell they come from Cloud Streams and haven't been tampered with. The same applies to the endpoints of dead-letter policies and of sinks:
spec:
subscriber:
endpoint:
uri: https://orders.example.com/events
signing:
use: orders-webhook # the secret that holds the 'secret' key, and the 'previous' one while rotating itEvery delivery then carries three headers, computed over the exact bytes sent:
| Header | Value |
|---|---|
webhook-id |
{namespace}/{subscription}/{offset}, or …/{first}-{last} for a batch |
webhook-timestamp |
When the attempt was made, in seconds since the Unix epoch |
webhook-signature |
v1, followed by the base64 HMAC-SHA256 of {id}.{timestamp}.{body}
|
-
Secrets: a secret is the base64 encoding of 24 to 64 random bytes, optionally prefixed with
whsec_, e.g.whsec_$(openssl rand -base64 32). It is read from the subscription's namespace, like the secrets of authentication policies.secretcan also be written in the policy itself, which is not recommended, since anyone allowed to read the resource can see it. -
Rotation: while
previousis set, deliveries carry two signatures, separated by a space. Set the new secret insecretand the old one inprevious, update the subscriber, then removeprevious. -
Verifying: the Standard Webhooks libraries, available for most languages, verify deliveries as they are. They also refuse deliveries whose timestamp is more than 5 minutes off, which bounds how long a captured delivery can be replayed, e.g. in JavaScript:
import { Webhook } from "standardwebhooks"; const webhook = new Webhook(process.env.SIGNING_SECRET); // the secret, prefixed with whsec_ or not const event = webhook.verify(rawBody, request.headers); // throws if the signature does not match
-
Duplicates:
webhook-idis sent with every delivery, signed or not. Retries share it, and so does the redelivery of a dead letter, since the subscriber never accepted it: a subscriber that records the ids it has handled can drop duplicates. The deliveries of a replayed subscription share their original ids too. An event redelivered on purpose, withPOST …/subscriptions/{name}/redeliver, has an id of its own, and a dead-letter service receives{id}/dead-letter. -
Failures: a secret that can't be read, or isn't valid, fails the delivery, which is retried like any other. Nothing is ever sent unsigned to an endpoint that signs.
-
Other transports: only HTTP deliveries can be signed. Kafka, NATS and AMQP authenticate their clients themselves.
Gateways can verify the signatures of their own publishers the same way (see Namespaces).
By default, a subscription delivers one event at a time, in the order of its stream, which caps its throughput at one round trip per event. Two opt-in modes raise it. They can't be combined.
spec:
subscriber:
endpoint: https://subscriber.example.com
batch: # delivers events in batches, as application/cloudevents-batch+json
maxSize: 100
linger: PT0.5S # how long a partial batch waits to fill once the subscription has caught up. Defaults to none
# ordering: # or delivers events in parallel, in order per key
# key: subject # the context attribute events are ordered by. Events that don't define it share a key
# maxConcurrency: 8 # how many keys are delivered concurrently
# maxInFlight: 1000 # how many events may be read and not handled yetHow delivery works in these modes:
- Reading: the broker reads what it delivers from the store, rather than delivering live events as they come.
-
Batches: a page of the store is one batch. The batch carries the offset of its first event in the
cloudstreams-offsetheader, and the subscription's rate limit applies per request. -
Ordering by key: each key has its own lane, which delivers its events one at a time, in order, while up to
maxConcurrencykeys are delivered concurrently. The broker reads ahead, and schedules each event on the lane of its key, up tomaxInFlightevents that haven't been handled yet. A key that is slow, or whose delivery is being retried, therefore only holds back its own events: the others keep being delivered, until the oldest unhandled event ismaxInFlightevents behind.
Offsets and failures:
- Committing: a batch's offset is only committed once every event of the batch has been delivered, dead-lettered or filtered out. In parallel, the committed offset is that of the oldest event that hasn't been handled yet, written once a page of events has been, once nothing is in flight anymore, or at least every second. Either way, the committed offset never moves past an event that hasn't been delivered.
- After a crash or a fault: delivery resumes from the committed offset. Delivery remains at-least-once, but events delivered after it, of other keys, are delivered again.
- Failed batches: a batch that fails for good is delivered again one event at a time, each with the retry and dead-letter policies. The event at fault is then dead-lettered, or faults the subscription, on its own.
-
Monitoring parallel delivery: the
cloud_streams_broker_ordering_active_keys,cloud_streams_broker_ordering_in_flightandcloud_streams_broker_ordering_oldest_agegauges report, per subscription, how many keys have events to deliver, how many events have been read and not handled yet, and for how long, in seconds, the oldest of them has been. An age that keeps growing means that a key is stuck, and holds back the committed offset.
Deferred acknowledgement isn't available in these modes: 202 Accepted is a success like any other.
Several replicas of a broker can run side by side, for availability and throughput. A replica only handles a subscription while it holds a lease on it in Redis, so that every subscription is handled by a single replica, and every event is delivered once. Leases are renewed periodically. When the replica that handles a subscription dies, its lease expires and another replica takes the subscription over. A replica that fails to renew a lease in time stops handling the subscription before the lease can be acquired by another one. When a replica stops gracefully, it releases its leases so that others take over immediately.
The replicas share the broker's subscriptions evenly:
- Fair share: each replica registers itself in Redis, as long as a lease lasts, and handles at most the amount of subscriptions the broker selects divided by the amount of its replicas that are alive, rounded up. A replica that is added, by hand or by an autoscaler, therefore takes over its share within a renewal interval or two.
- Handover: a replica past its share hands the subscriptions it acquired last over, as when it stops: it stops delivering, commits its offsets, and releases the lease, which another replica then acquires. Delivery remains at-least-once, and a deferred acknowledgement pending, kept in the subscription's status, survives the handover.
-
Monitoring: the
cloud_streams_broker_subscriptions_handledgauge reports how many subscriptions each replica handles.
Leases: # e.g. CLOUDSTREAMS_BROKER_LEASES__DURATION=00:00:15
Enabled: true # disabling leases is only safe with a single replica per subscription
Duration: '00:00:15' # how long a subscription stays unhandled when the replica that handles it dies
RenewalInterval: '00:00:05' # defaults to a third of the duration
Rebalance: true # false lets the first replicas to start keep every subscription they acquireScaling is the concern of an autoscaler, e.g. a HorizontalPodAutoscaler or KEDA: Cloud Streams gives it what it needs.
-
Ownership of the replicas: an autoscaled workload must not have its replicas set by whoever deploys it, who would otherwise undo the autoscaler's work at every upgrade or reconciliation. Set
spec.workload.autoscaled: trueon a gateway or a broker in Kubernetes mode, orautoscaled: trueon the chart'sgateway,broker, or an item ofgatewaysandbrokers. The operator or the chart then never sets the replicas of the deployment, and ignoresreplicasandreplicaCount. A deployment whose replicas were set before is scaled to one replica until the autoscaler scales it. -
Signal: a broker is best scaled on the lag of its subscriptions, the
cloud_streams_broker_subscription_laggauge, which its replicas report for the subscriptions they handle. A gateway is best scaled on its CPU, or on the rate of the events it ingests,cloud_streams_gateway_events_ingested_count. - Limits: a subscription is handled by one replica at a time, so a broker gains nothing from more replicas than it has subscriptions. Replicas report lag only for the subscriptions they handle, so a broker scaled to zero reports none: keep at least one replica.
For example, with KEDA and a Prometheus that receives the metrics of Cloud Streams (see deployments/grafana), where job is the broker's name:
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: orders-broker
namespace: tenant-a
spec:
scaleTargetRef:
name: orders-broker # the broker's deployment: '<name>-broker' in Kubernetes mode
minReplicaCount: 1
maxReplicaCount: 8 # at most one per subscription
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus.monitoring:9090
query: sum(cloud_streams_broker_subscription_lag{job="orders"})
threshold: "1000" # records yet to deliver per replicaA subscription behind the end of its stream, because it starts from an earlier offset, resumes after a fault or after its subscriber was unreachable, catches up by reading the records it missed a page at a time. The next page is read while the current one is delivered. Once caught up, it switches back to live delivery.
After each delivery, the broker commits the offset that follows it to the subscription's status, which is what a broker resumes from after a restart. By default, every delivery is committed at once. Under heavy load, commits can be batched instead, which saves one status write per event. A broker that dies then redelivers the events delivered since its last commit: delivery remains at-least-once. Uncommitted offsets are always written before a delivery is suspended for a deferred acknowledgement, before a subscription is faulted, and when the broker stops handling a subscription. With batching, the ackedOffset of the subscription's status, and the lag reported by the health endpoint, can trail actual delivery by up to the configured interval. The cloud_streams_broker_subscription_lag metric does not.
CatchUp: # e.g. CLOUDSTREAMS_BROKER_CATCHUP__PAGESIZE=500
PageSize: 100 # records read at once during catch-up
OffsetCommits: # e.g. CLOUDSTREAMS_BROKER_OFFSETCOMMITS__BATCHSIZE=100
BatchSize: 1 # deliveries committed at once: 1 commits every delivery
Interval: '00:00:01' # how long a delivered offset may remain uncommitted, when batchingA subscriber whose processing takes a while doesn't have to hold the connection open, or acknowledge an event it hasn't processed yet. It can defer the acknowledgement by responding 202 Accepted, and call back once it is done. Deferring is opt-in: by default, 202 Accepted is a success like any other, since many subscribers, such as ingestion endpoints and queues, answer it to mean that they took the event over.
spec:
subscriber:
ack:
mode: deferred # immediate (the default), or deferred
timeout: PT5M # deferred only: how long the subscriber may take to call back-
Broker default:
spec.dispatch.ack.modesets the mode of the broker's subscriptions that don't set one,immediateby default. -
Where it applies: a subscription that tracks a stream offset, delivers events one by one, i.e. without
batchnorordering, and delivers over HTTP. A subscription that setsdeferredotherwise is refused.
Every delivery of a subscription that defers acknowledgements carries the headers needed to do so:
| Header | Description |
|---|---|
cloudstreams-subscription |
The name of the subscription |
cloudstreams-offset |
The offset of the event in the subscription's stream |
cloudstreams-ack-token |
An opaque, single-use token identifying this delivery |
cloudstreams-ack-uri |
The uri to acknowledge the event at. Only sent when the broker's spec.dispatch.ack.callbackUri is set to the gateway's public base uri |
| Subscriber response | Broker behaviour |
|---|---|
2xx other than 202
|
The event is acknowledged: the offset is committed and the next event is delivered |
202 Accepted |
In the deferred mode, delivery is suspended until the subscriber calls back, or the acknowledgement expires. Otherwise, the event is acknowledged |
non-2xx
|
The delivery failed, and is retried according to the retry policy |
To resolve a deferred acknowledgement, the subscriber calls the gateway:
POST /api/resources/v1/namespaces/{namespace}/subscriptions/{name}/ack { "token": "..." } # the event is processed: delivery resumes after it
POST /api/resources/v1/namespaces/{namespace}/subscriptions/{name}/nack { "token": "...", "reason": "..." } # the event is redelivered
Both return 204 on success, and 409 if the token doesn't match a pending acknowledgement (unknown subscription or token, already used, or expired), so as not to reveal which subscriptions exist. A subscriber may call back as soon as it has responded: a token that the broker has yet to record as pending is given a few seconds to become so before being refused. Only a hash of the token is stored in the subscription's status. The token is the only authorization required, so these endpoints are anonymous even when the dashboard requires users to sign in.
An event that isn't resolved within spec.subscriber.ack.timeout (broker default spec.dispatch.ack.timeout, otherwise PT5M) is redelivered. The exception is a subscriber that has never called back: it most likely uses 202 to mean "done", so the subscription is faulted with a message saying to set spec.subscriber.ack.mode to immediate, or to return 200 OK. A pending acknowledgement is stored in status.subscriber.pendingAck, so it survives a broker restart. One restored by a subscription that no longer defers is forgotten, and its event redelivered. Only one event is ever in flight, so ordering is preserved.
The gateway's own ingestion endpoint (POST /api/events/pub) now responds 204 No Content, since events are persisted by the time it responds. This keeps a subscription that bridges two Cloud Streams instances from suspending on every event. The cloudstreams-outcome response header tells whether the event has been stored, or ignored because the gateway's split-horizon policy detected a loop (loopAction: ignore). Ignored events are counted by the cloud_streams_gateway_events_ignored_count metric, rather than as rejected.
Published events are validated against the CloudEvents specification: in particular, the names of extension attributes must only contain lower-case letters and digits. Invalid events are rejected with 400 Bad Request.