Skip to main content

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:

  1. Scatter — fire all publishes in the batch without awaiting acks.
  2. 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:

HeaderValue
messageTypeProviderClientTelemetry
providerIdthe provider's id
providerClientIdthe device id
enqueuedTimeISO 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:

  1. Update device_twin_entity atomically — the report replaces the whole reported document (it is not merged), increments ReportedVersion, sets LastActivity.
  2. If the twin row doesn't exist yet, it is created in the same call.
  3. 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:

OutcomeMeaning
StoredJetStream acknowledged the message (a duplicate acknowledgement included)
DeadLetteredThe message is preserved on the dead-letter stream
RejectedThe 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
}
}
OptionDefaultDescription
ChannelCapacity50,000Bounded channel size. Writers wait when it is full. Sized to absorb ≈5 s of replication lag at 10 k msg/s.
BatchSize256Maximum messages per batch before flush.
FlushIntervalMs50Maximum wait time before flushing a partial batch.
MaxReportedConcurrency16Parallel reported-property DB updates. Bounds connection-pool use under burst.
StreamNameingressJetStream stream the pipeline publishes to.
SubjectPrefixingressSubject prefix; must match the NATS server mapping and the asset processor.
MaxPublishAttempts3Publish attempts before the message goes to the dead-letter stream.
PublishRetryDelaysMs[100, 500]Delays between attempts; length must be MaxPublishAttempts - 1.
DeadLetterEnabledtrueWhen false, a message that exhausts its attempts is logged and counted, not preserved.
DeadLetterStreamNameingress-dlqDead-letter stream.
DuplicateWindowSeconds120Duplicate window for streams the SDK creates.

Metrics​

MetricTypeTags
pipeline.messages.receivedCountertype=telemetry|reported
pipeline.messages.publishedCounter—
pipeline.messages.droppedCounter—
pipeline.errorsCounterstage=parse|db|nats-ack|nats-reported
pipeline.batch.duration_msHistogram—
pipeline.batch.sizeHistogram—
pipeline.nats.publish_msHistogramscatter-gather duration
pipeline.db.update_msHistogramreported DB update + NATS publish
pipeline.reported.semaphore_wait_msHistogramwait for reported concurrency slot
pipeline.channel.depthGaugecurrent channel reader count
pipeline.channel.backpressure_wait_msHistogramtime a writer waited for room in a full channel
pipeline.publish.retryCounterpublish retries
pipeline.dlq.publishedCountermessages preserved on the dead-letter stream
pipeline.dlq.failedCountermessages 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.