IMD SolutionComputing LibraryShop main store

How-to

Keep both arrival time and payload timestamp in Telegraf

Edge computing and IIoT Published 7 min read

Short answer

Setting json_time_key replaces the metric timestamp with the payload time, so the arrival time is lost before any output sees it. Drop that option, keep the payload timestamp as a field, and use a Starlark processor that returns two metrics: one point keeps the arrival timestamp with the payload time as a field, the clone takes the payload value as its timestamp.

On this page
  1. Where the arrival timestamp gets lost
  2. Step 1: drop json_time_key and keep the payload timestamp as a field
  3. Step 2: split the message into two points with a Starlark processor
  4. Sizing the nanosecond multiplier for an epoch-seconds field at 1718700000.123
  5. Step 3: route each point to its own output
  6. What breaks when the clock or the payload disagrees
  7. Prove the end-to-end path
  8. Questions asked

The conflict is inside the parser: with json_time_key set, the MQTT consumer overwrites the metric timestamp with the payload time, so the arrival time is gone before any processor or output runs. The fix is to drop that option, carry the payload timestamp as a field, and split the metric in a Starlark processor that returns two metrics — a journal point stamped at arrival and a data point stamped from the payload. Each step below sets one thing and ends with a check.

Where the arrival timestamp gets lost #

The path is publisher, broker, inputs.mqtt_consumer, the JSON parser inside that input, processors, then the outputs. The parser creates the metric. Without json_time_key, the metric time is the moment Telegraf parsed the message — the arrival time at the agent. With json_time_key set, the parser replaces that time with the payload value and nothing downstream can recover the original.

Arrival time here means arrival at Telegraf, not broker receipt time. Broker queuing, a persistent session replaying backlog after reconnect, or retained messages all widen the gap between the payload time and the arrival time, so treat that delta as end-to-end latency, not network latency. If you are debugging why a value never reached the output at all, the failure is usually downstream of the parser, as in the case of a Telegraf MQTT consumer that connects but writes no data to InfluxDB.

Step 1: drop json_time_key and keep the payload timestamp as a field #

Remove json_time_key and json_time_format from the input. The timestamp key then parses like any other JSON member:

[[inputs.mqtt_consumer]]
  servers = ["tcp://broker.example.lan:1883"]
  topics = ["plant/line1/#"]
  data_format = "json"
  tag_keys = ["device"]
  # json_time_key intentionally not set
  # json_string_fields = ["ts"]  # only if the publisher sends the timestamp as a string

The field type decides the next step. A numeric epoch arrives as a float field. Epoch seconds and epoch milliseconds survive a float64 exactly, because both need fewer significant digits than a float64 carries. Epoch nanoseconds do not: they need 19 significant digits and a float64 holds roughly 15 to 17, so the value rounds. If the publisher emits nanoseconds, send them as a JSON string or reduce the resolution at the source. Read the unit from the publisher documentation rather than from the digit count alone.

Check: run Telegraf with --test. The printed line must show the payload timestamp field (called ts in these examples) with the expected value, and the metric time must sit close to the wall clock regardless of the payload time.

Step 2: split the message into two points with a Starlark processor #

The Starlark processor's apply function may return a list of metrics — that is the documented way to turn one input metric into several. Clone the incoming metric, leave the original untouched as the journal point, and rewrite the clone so its timestamp comes from the ts field, which is then dropped:

[[processors.starlark]]
  namepass = ["mqtt_consumer"]
  source = '''
def apply(metric):
    journal = metric
    journal.tags["stream"] = "journal"
    data = Metric(metric)
    data.tags["stream"] = "data"
    if "ts" in data.fields:
        ts = data.fields.pop("ts")
        data.time = int(ts * 1000000000)  # ts in epoch seconds
    return [journal, data]
'''

Set the multiplier to the real unit: 1000000000 for seconds, 1000000 for milliseconds, 1 for nanoseconds. Starlark integers are arbitrary precision, so the multiplication itself is safe; the precision limit is the float field the parser produced, as described in step 1. If ts is a string, convert it in the script — Telegraf ships a time.star module with a parse function, and you should confirm its exact signature in the Starlark processor documentation for your Telegraf version before relying on it.

Guard the pop in production: a message without ts raises an error in the script and the metric is dropped. The if "ts" in data.fields: test lets such messages pass through to the journal only.

Check: --test must print two lines per message. The stream=journal line carries ts as a field and a timestamp near the wall clock; the stream=data line has no ts field and its timestamp equals the payload value.

Sizing the nanosecond multiplier for an epoch-seconds field at 1718700000.123 #

Inputs: the publisher documents its timestamp as epoch seconds, so the parser delivers ts as a float field; an example value is 1718700000.123 (three fractional digits, millisecond resolution). The Starlark script converts to nanoseconds because that is the unit a metric timestamp uses.

Rule in words: multiply the epoch-seconds value by 1,000,000,000 and assign the integer result to the clone's timestamp. The result must not lose digits to the float field.

Arithmetic: 1718700000.123 has 13 significant digits, well inside the roughly 15 to 17 a float64 carries, so the value round-trips exactly. 1718700000.123 * 1000000000 = 1718700000123000000, a 19-digit integer stored exactly because Starlark integers are arbitrary precision. Had the publisher sent the same instant as epoch nanoseconds — 1718700000123000000 — the parser's float64 would have rounded it before the script ever ran, at about the microsecond level.

Result: the clone is stamped at 2024-06-18 in UTC with millisecond resolution; the journal point keeps the arrival timestamp plus ts as a field.

Decision: epoch seconds or milliseconds as a numeric field → convert in the script with the matching multiplier. Epoch nanoseconds → carry the value as a JSON string and parse it in the script, or drop to millisecond resolution at the publisher.

Step 3: route each point to its own output #

Both points share the measurement name, so separate them with the stream tag added above. Run two outputs and filter each with tagpass, then strip the routing tag with tagexclude so it does not pollute the stored series. Order of evaluation matters: tagpass is evaluated before tagexclude, so the filter still sees the tag it removes. If a target is InfluxDB 2.x, use outputs.influxdb_v2 with a bucket and token instead of the 1.x output. Once the points land, they behave like any other history — a historian query for the timestamp of a max value then reads the data stream at payload times, not arrival times. For an audit you may also need to know when a value reached the server versus when it was measured, which is the distinction covered in what the historian write timestamp proves in an audit.

Check: query each database after a few messages. The journal series must show ts with timestamps clustered at arrival times; the data series must show timestamps equal to payload times and no ts field.

What breaks when the clock or the payload disagrees #

  • Data points land in 1970 or far in the future — the multiplier is wrong for the unit. Compare ts to a known epoch and fix the multiplier.
  • Sub-second jitter or silently overwritten points — two messages with identical payload time, measurement and tags overwrite each other in InfluxDB, because the same series plus the same timestamp is one point. Add a distinguishing tag or raise the resolution.
  • Journal arrival times bunch together — broker replay of a backlog after reconnect. Interpret the bunch as delayed delivery and compare against the payload delta. Whether a value shows at all is separate from its timestamp; a bad quality update can hide a historian value even when the point arrived.
  • Arrival time drifts from true time — the Telegraf host clock is unsynchronised. Sync it; arrival time is only as good as that clock.
  • Only one line printed per message — the processor returns a single metric or namepass does not match. Confirm the metric name matches and the function returns a list.

Payload timestamps come from the device clock and go wrong for different reasons than the host clock. Storing both is what makes the delta usable as a diagnostic: a growing difference flags a device clock fault or delivery delay, and the journal field is where you read it.

Prove the end-to-end path #

Work through the checks in this order:

  1. Start the Telegraf service and confirm the processor loads without a script error in the log.
  2. Send one message with a known payload timestamp from the publisher or a test client.
  3. Query the journal target: the point must carry the ts field with an arrival-time timestamp near the wall clock.
  4. Query the data target: the point must carry the payload-time timestamp and no ts field.
  5. Compare the two timestamps; the delta is your end-to-end latency for that message.

For the timestamp math itself — epoch conversions come up again when you build dashboards or filters — the walkthrough of converting Starlark epoch time in Telegraf to a date covers the same arithmetic from the other direction, and calculating Ignition epoch milliseconds from date tags shows the millisecond side when Ignition is the consumer.

Questions asked

Can I keep json_time_key and still get the arrival time?

No. With json_time_key set, the JSON parser replaces the metric timestamp with the payload value before any processor or output runs, and the arrival time is not stored anywhere. Remove the option, let the parser stamp the metric with the parse time, and carry the payload timestamp as a field instead.

Does the Starlark processor need a copy of the metric to emit two points?

Yes. Build the clone with Metric(metric), change only the clone, and return both the original and the clone. If you modify the original in place and return only one metric, you get one point.

Why do my payload timestamps in 1970 or far future look wrong?

The multiplier in the script is wrong for the unit the publisher sends. The script assumes epoch seconds and multiplies by 1000000000; for epoch milliseconds use 1000000. Compare one payload value against a known epoch to confirm the unit, then fix the multiplier.

Can epoch nanoseconds survive as a numeric JSON field?

No. The JSON parser delivers numbers as float64 values, and a float64 holds about 15 to 17 significant digits, while epoch nanoseconds need 19. Seconds and milliseconds fit exactly. If the publisher emits nanoseconds, carry them as a JSON string and convert them in the Starlark script, or reduce the resolution at the source.

Can the two points go to different InfluxDB databases from one Telegraf instance?

Yes. Give each point a stream tag in the Starlark script, then run two outputs: each filters on that tag with tagpass and removes it from stored fields with tagexclude. tagpass is evaluated before tagexclude, so the filter still sees the tag it strips.

Keep reading

  • How-to

    Turn an MQTT topic into InfluxDB fields with Telegraf

    Telegraf reads /temperature/boiler/room3 with payload 21.7 as a metric carrying a topic tag and a value field. A five-processor chain (regex, converter, regex, regex, pivot) renames the measurement, builds location=room3 and pivots the middle segment into the field key; one Starlark processor does the same in eight lines. Either way the output line is temperature,location=room3 boiler=21.7 with the original timestamp.

    Edge computing and IIoT

  • Explainer

    Does an MQTT broker store historic data you can query

    No. An MQTT broker transports publications and keeps only delivery state: the newest retained value per topic and messages queued for offline persistent sessions, with no time-range query and nothing else to query. To move many timestamped samples in one delivery, the publisher must buffer them and send a multi-sample payload such as Sparkplug B; to query history later, something must store it when it arrives, in a historian or database.

    Edge computing and IIoT

  • Troubleshooting

    Why a Node-RED timestamp creates a new InfluxDB tag

    Your timestamp is landing in the tag set, and InfluxDB line protocol gives every distinct tag value its own series, so each sample is written as a separate one-point series and the trend is blank. Put the epoch time in the point's time slot with the node's time precision set to match, and keep tags to identifiers that repeat, such as machine and sensor.

    Edge computing and IIoT