Telemetry Pipeline
The telemetry pipeline is a background service that batches messages from the adapter and publishes them to NATS JetStream. It implements both ITelemetryClient and IPropertiesClient — a single channel feeds two branches (telemetry vs reported properties). The canonical contract lives in the telemetry-pipeline spec.
Flow
Telemetry.SendAsync(deviceId, TelemetryMessage)
Telemetry.SendAndConfirmAsync(deviceId, TelemetryMessage)
Properties.ReportAsync(deviceId, JsonObject)
│
▼
┌─────────────────────┐
│ Bounded Channel │ capacity: 50,000 (default)
│ Wait when full │ single reader, multi-writer
└────────┬────────────┘
│
▼
┌─────────────────────┐
│ Batch Accumulator │ 256 messages OR 50 ms window
└────────┬────────────┘
│
┌────┴────────┐
│ │
▼ ▼
┌─────────┐ ┌──────────────────┐
│Telemetry│ │Reported Properties│
│ (batch) │ │ (semaphore-bound) │
└────┬───┘ └────────┬─────────┘
│ │
▼ ▼
Scatter- DB twin update
gather (replace + ver++)
JetStream +
publish JetStream publish
Both branches publish to the same JetStream stream (ingress by default); only the messageType header differs.
Hot-path bytes (no JSON round-trip)
TelemetryMessage.Payload is ReadOnlyMemory<byte>. The pipeline writes those bytes directly as the NATS message body — there is no parse/re-serialise on the telemetry branch. Per-message overhead is the channel write and one NATS publish.
If you need per-message routing decisions, do them in the adapter before Telemetry.SendAsync and surface the result as a header or as a separate publish — do not reach into the bytes from inside the pipeline.
Telemetry branch
Telemetry is published to JetStream using a scatter-gather pattern:
- Scatter — fire all publishes in the batch without awaiting acks.
- Gather — collect all ack responses (pipelined, ≈1 RTT total).
Subject: ingress.providerclient.{providerId}__{deviceId} ({SubjectPrefix}.providerclient.…; the prefix defaults to ingress). The NATS server maps it onto ingress.partition.{N} for the asset processor.
Headers added per message:
| Header | Value |
|---|---|
messageType | ProviderClientTelemetry |
providerId | the provider's id |
providerClientId | the device id |
enqueuedTime | ISO 8601 UTC timestamp |
A fresh NatsHeaders instance is allocated per publish call because the NATS .NET client mutates it during publish — do not cache or reuse a NatsHeaders across messages.
Reported-properties branch
Each reported message requires a database update before publishing:
- Update
device_twin_entityatomically — the report replaces the whole reported document (it is not merged), incrementsReportedVersion, setsLastActivity. - If the twin row doesn't exist yet, it is created in the same call.
- Publish to JetStream with
messageType: ProviderClientPropertiesChanged.
Concurrency is bounded by MaxReportedConcurrency (default 16) so a fleet-wide reported burst can't exhaust the PostgreSQL connection pool. The DB write and the NATS publish are paired — if the DB write fails, the message is not published to the main stream; it is routed to the dead-letter stream (see Publish retry and dead letter).
The twin endpoints never accept reported writes; reported state flows exclusively through this branch.
Backpressure
The channel uses BoundedChannelFullMode.Wait. When the channel is full, SendAsync (and ReportAsync) does not complete until the pipeline has drained room for the message. Nothing is dropped.
Await the returned task in the adapter's receive handler. For the MQTT adapter this pauses the broker-to-provider receive loop, so backpressure reaches the broker and QoS 1 device publishes are retried by the protocol instead of being lost.
Publish retry and dead letter
A JetStream publish that is not acknowledged is retried up to MaxPublishAttempts (default 3) times, with the delays in PublishRetryDelaysMs (default [100, 500]). When the attempts are used up, the message is published to the dead-letter stream (ingress-dlq, subjects ingress-dlq.>, Limits retention, at most DeadLetterMaxMessages = 1,000,000 messages) with the headers dlq-original-subject, dlq-attempts and dlq-reason. A message is lost only if the dead-letter publish also fails, which is counted on pipeline.dlq.failed.
Each message carries a Nats-Msg-Id, so a retry after a lost acknowledgement is deduplicated by JetStream within the stream's duplicate window (DuplicateWindowSeconds, default 120) instead of being stored twice. Set TelemetryMessage.MessageId to use your own id.
Confirmed send
SendAsync returns once the message is in the channel. SendAndConfirmAsync returns once the pipeline is done with it:
| Outcome | Meaning |
|---|---|
Stored | JetStream acknowledged the message (a duplicate acknowledgement included) |
DeadLettered | The message is preserved on the dead-letter stream |
Rejected | The pipeline refused the message by design |
In all three cases the adapter may acknowledge upstream. A TelemetryDeliveryException means the message was not stored (the pipeline was stopping, or both the publish and the dead-letter copy failed); do not acknowledge upstream. Use SendAndConfirmAsync when the adapter acknowledges its source only once the platform has the message, and await many sends concurrently rather than one at a time.
Configuration
{
"TelemetryPipeline": {
"ChannelCapacity": 50000,
"BatchSize": 256,
"FlushIntervalMs": 50,
"MaxReportedConcurrency": 16,
"StreamName": "ingress",
"SubjectPrefix": "ingress",
"MaxPublishAttempts": 3,
"PublishRetryDelaysMs": [100, 500],
"DeadLetterEnabled": true,
"DeadLetterStreamName": "ingress-dlq",
"DuplicateWindowSeconds": 120
}
}
| Option | Default | Description |
|---|---|---|
ChannelCapacity | 50,000 | Bounded channel size. Writers wait when it is full. Sized to absorb ≈5 s of replication lag at 10 k msg/s. |
BatchSize | 256 | Maximum messages per batch before flush. |
FlushIntervalMs | 50 | Maximum wait time before flushing a partial batch. |
MaxReportedConcurrency | 16 | Parallel reported-property DB updates. Bounds connection-pool use under burst. |
StreamName | ingress | JetStream stream the pipeline publishes to. |
SubjectPrefix | ingress | Subject prefix; must match the NATS server mapping and the asset processor. |
MaxPublishAttempts | 3 | Publish attempts before the message goes to the dead-letter stream. |
PublishRetryDelaysMs | [100, 500] | Delays between attempts; length must be MaxPublishAttempts - 1. |
DeadLetterEnabled | true | When false, a message that exhausts its attempts is logged and counted, not preserved. |
DeadLetterStreamName | ingress-dlq | Dead-letter stream. |
DuplicateWindowSeconds | 120 | Duplicate window for streams the SDK creates. |
Metrics
| Metric | Type | Tags |
|---|---|---|
pipeline.messages.received | Counter | type=telemetry|reported |
pipeline.messages.published | Counter | — |
pipeline.messages.dropped | Counter | — |
pipeline.errors | Counter | stage=parse|db|nats-ack|nats-reported |
pipeline.batch.duration_ms | Histogram | — |
pipeline.batch.size | Histogram | — |
pipeline.nats.publish_ms | Histogram | scatter-gather duration |
pipeline.db.update_ms | Histogram | reported DB update + NATS publish |
pipeline.reported.semaphore_wait_ms | Histogram | wait for reported concurrency slot |
pipeline.channel.depth | Gauge | current channel reader count |
pipeline.channel.backpressure_wait_ms | Histogram | time a writer waited for room in a full channel |
pipeline.publish.retry | Counter | publish retries |
pipeline.dlq.published | Counter | messages preserved on the dead-letter stream |
pipeline.dlq.failed | Counter | messages lost: the dead-letter publish also failed |
JetStream stream provisioning
The pipeline creates the ingress JetStream stream (subjects: ingress.>, Workqueue retention) and the ingress-dlq stream at startup if they don't exist. An existing stream's configuration is not changed. Replication is decided by the NATS monitoring port (Nats:MonitoringPort, default 8222):
- Cluster size ≥
Nats:ClusterReplicaThreshold(default 3) →NumReplicas = 3. - Otherwise →
NumReplicas = 1.
The BEACONTOWER_EVENTS stream used by the CloudEvents publisher is created the same way.