Skip to content

Export task-sdk metrics from the API server - #74046

Open
xBis7 wants to merge 1 commit into
apache:mainfrom
xBis7:task-metrics-delta
Open

xBis7 wants to merge 1 commit into
apache:mainfrom
xBis7:task-metrics-delta

Conversation

@xBis7

@xBis7 xBis7 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Issue

When using OpenTelemetry, every metric exported from the task-sdk while a task is running (including custom user-defined metrics) is broken. Note here that this issue doesn't exist for StatsD.

For every task, a new task runner is created along with a new MeterProvider. As a result, each series of metrics is treated as new and unique and values don't accumulate.

For example, if we had 5 successful tasks, we would expect to see a value 5 for the counter airflow_ti_successes_total. Instead we end up with a series of 1, 1, 1, 1, 1.

Solution

These metrics

  • ti.start
  • ti.finish
  • ti_successes and ti_failures
  • operator_successes and operator_failures
  • task.duration

are the most important and they have been moved under the API server.

There have been some other small changes for allowing the rest of the task-sdk metrics to continue working along with any user-defined custom metrics.

The temporality environment variable defaults to cumulative if unset. For the task-sdk, now it defaults to delta if unset.

Also, the OTel SDK assigns a random and unique service.instance.id per process. Just for the task-sdk, this is set to a fixed value so that all task runners are treated as the same process.

For backends that support delta values natively, no config changes are needed. But for backends that don't, such as prometheus, the user will need to extend the otel-collector.yml file so that it converts the delta values back to cumulative. The required config changes have been added to the documentation. They are simple and they could be just copy-pasted.

Testing

I've added an integration test that reads the metrics directly from the otel-collector and checks the value of task metrics to make sure that a counter is increased.

I've also added unit tests for the in-memory accumulating logic as well as the forwarding.


Was generative AI tooling used to co-author this PR?
  • Yes (please specify the tool below)

Claude-code Fable 5.1 xhigh


  • Read the Pull Request Guidelines for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
  • For fundamental code changes, an Airflow Improvement Proposal (AIP) is needed.
  • When adding dependency, check compliance with the ASF 3rd Party License Policy.
  • For significant user-facing changes create newsfragment: {pr_number}.significant.rst, in airflow-core/newsfragments. You can add this file in a follow-up commit after the PR is created so you know the PR number.

@boring-cyborg boring-cyborg Bot added area:API Airflow's REST/HTTP API area:task-sdk labels Oct 1, 2026
@ashb

ashb commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

@stuart23 I know you've been looking at similar issues

@jedcunningham

Copy link
Copy Markdown
Member

Also @dstandish, worth you looking at this.

@dstandish dstandish left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not sure about adding all the complexity to forward all metrics through the api server. adding all the extra calls would also increase load on api server.

we already log an event whenever we increment these counters so, we could just move the stats emission to the api server when those events are handled and this would be much simpler and lighter weight.

the cost is users would not have custom metrics -- though, perhaps that's just -- if they do it they will have to figure out how wo make it work properly in backend processing (which is possible)

another approach is use a daemon process to handle the metrics emission, either launched at worker startup or run in a sidecar container.

@xBis7
xBis7 force-pushed the task-metrics-delta branch from e5a30bd to e9014cf Compare October 1, 2026 18:50
@xBis7
xBis7 requested a review from jason810496 as a code owner October 1, 2026 18:50
@dstandish

Copy link
Copy Markdown
Contributor

Thanks for digging into this. The 1, 1, 1, 1, 1 counter problem is real and worth fixing. I'm hesitant about the approach, though, because it adds a lot of moving parts:

  • a new Execution API endpoint and version (plus Go/TS SDK model changes)
  • a new comms message
  • an aggregating backend
  • a background flush thread in every task process

Before we commit to maintaining all of that, I'd like to check whether a simpler fix covers most of the need.

Most task metrics could be emitted by the API server instead

These are the first-party metrics emitted from task_runner:

  • ti.start
  • ti.finish
  • ti_successes and ti_failures
  • operator_successes and operator_failures
  • task.duration

Each of them corresponds to a state transition the API server already handles: ti_run for start, and ti_update_state for the terminal state and end date. The TI row has operator, start_date and end_date, so every tag and the duration can be computed there. The API server is a long-lived process with its own MeterProvider, so the counters would accumulate correctly with no forwarding at all.

It would also make the metrics more accurate. A task that gets OOM-killed or SIGKILLed never emits ti_failures today. Emitting wherever the failure state is recorded (the state update route, or the scheduler's heartbeat-timeout handling) would count those failures too.

The remaining case is narrow

With lifecycle metrics on the server side, the only thing left broken is OTel combined with custom metrics emitted from inside a task:

  • StatsD already works, because the StatsD server does the aggregating (the PR description says this too).
  • As far as I can tell, Stats isn't part of the public airflow.sdk API. I'm not sure how much in-task custom-metric usage we're committed to supporting.

For OTel users who do this, delta temporality (OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta) is the standard answer for short-lived processes. It's the same model StatsD uses: each process reports what it added, and the backend sums it up. Backends that accept deltas natively handle this with no extra work. Prometheus via deltatocumulative is messier, but that's a general OTel limitation with short-lived processes rather than something Airflow needs to route through its API server.

Suggestion

  1. Emit the lifecycle metrics from the execution API routes and the scheduler, and remove them from task_runner.
  2. Leave in-task Stats as is, and document delta temporality for OTel users who emit custom metrics from tasks.
  3. Revisit a forwarding mechanism separately if there's real demand for accumulating custom OTel metrics on Prometheus.

The trade-off is that the emitting component changes, so dashboards that filter on worker host or service tags would need updating. That would need a newsfragment. Still, it seems much cheaper than a permanent new Execution API surface. What do you think? Are there use cases I'm missing that need worker-side emission?


Drafted-by: Claude Code (Opus 5.5); reviewed by @dstandish before posting

@xBis7
xBis7 marked this pull request as draft October 1, 2026 20:20
@xBis7

xBis7 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor Author

The current approach adds too much complexity and so I converted this to a draft while I'm exploring some alternatives.

@xBis7
xBis7 force-pushed the task-metrics-delta branch 6 times, most recently from 50299de to 179b8cb Compare October 7, 2026 16:45
@xBis7
xBis7 force-pushed the task-metrics-delta branch 5 times, most recently from 334f2b7 to 1667a99 Compare October 15, 2026 18:16
@xBis7
xBis7 marked this pull request as ready for review October 15, 2026 18:17
@xBis7
xBis7 force-pushed the task-metrics-delta branch 3 times, most recently from 0b5a0db to 7536fe3 Compare October 16, 2026 13:13
# either raised above or was a duplicate request from a running task.
if previous_state == TaskInstanceState.QUEUED:
dr._team_name = dr.team_name
stats.incr("ti.start", tags={**dr.stats_tags, "task_id": ti.task_id})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

personally i am of the belief that we should remove dag_id and task_id as attrs. too high cardinality if api server configured with delta to cumulative -- you're likely to get non-increasing series anyway. you should also see what else is in stats_tags.

@xBis7 xBis7 Oct 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree but I thought we discussed leaving them as they are for now because users might prefer to filter them in their backend.

So dr.stats_tags are

  • always: dag_id, run_type
  • sometimes: team_name and one tag per Dag tag if enabled in the config

If [metrics] dag_tags_in_metrics is enabled, then tags such as tags=["team:data", "env:prod", "critical"] become in the metrics team=data, env=prod, and critical with an empty value.

ti.stats_tags are the same as dr.stats_tags with some additions

  • always: dag_id, task_id, run_type
  • sometimes: team_name, state(on ti.finish), operator_name (on operator counters) and Dag tags if enabled

@@ -787,6 +803,26 @@ def _build_rejected_gate_payload(
return TITerminalStatePayload(state=TerminalStateNonSuccess.FAILED, retry_reason=reason, **carried)


def _emit_task_finish_metrics(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not sure we need all of these attributes. and they can cause problems.

even on api server, you are relying on the same worker getting hit with the same event type for the same team / operator / task / dag before the series gets expired (if delta to cumulative) or before the worker gets cycled (if cumulative), aren't you? otherwise you'll get non-incrementing series.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These aren't new. These are the old ones that have been moved.

Statsd has an option to disable tags

https://github.com/apache/airflow/blob/main/airflow-core/src/airflow/config_templates/config.yml#L1328-L1336

    statsd_disabled_tags:
      description: |
        If you want to avoid sending all the available metrics tags to StatsD,
        you can configure a block list of prefixes (comma separated) to filter out metric tags
        that start with the elements of the list (e.g: ``job_id,run_id``)
      version_added: 2.6.0
      type: string
      example: job_id,run_id,dag_id,task_id
      default: job_id,run_id

what if we do the same for OTel? That way it's up to the users whether they want the cardinality or not.

@@ -481,7 +485,11 @@ def get_otel_logger(
otel_env_config = load_metrics_env_config()

effective_service_name: str = otel_env_config.service_name or service_name or "airflow"
resource = Resource.create(attributes={SERVICE_NAME: effective_service_name})
resource_attributes = {SERVICE_NAME: effective_service_name}
if service_instance_id:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not leave it to optional env var configuration to preserve the flexibility ordinarily provided to users?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is, but it's decided at the caller. The caller checks the environment and if the user has provided a value, then this is None. If there isn't a value, this gets a fixed one which is then set here.

Comment on lines +32 to +39
def get_otel_logger(short_lived: bool = False) -> SafeOtelLogger:
service_instance_id = None
temporality_preference_env = "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE"

if short_lived:
# The temporality env variable defaults to `CUMULATIVE` if unset.
# If the process is `short_lived`, then set the default fallback to `DELTA`.
os.environ.setdefault(temporality_preference_env, "DELTA")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel we should still be leaving this to the user. the user has env vars they can use for this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just setting the default. If a user has provided a value, then the user value wins

@dstandish dstandish left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reviewed and left comments.

@xBis7
xBis7 force-pushed the task-metrics-delta branch 2 times, most recently from a32764d to abf209b Compare October 21, 2026 11:35
# LOWMEMORY also exports counters and histograms as deltas.
if (
os.environ[temporality_preference_env].strip().upper() in ("DELTA", "LOWMEMORY")
and SERVICE_INSTANCE_ID not in load_metrics_env_config().resource_attributes

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dstandish See here, if the service instance id isn't provided by the user, then we set a fixed value.

@xBis7
xBis7 force-pushed the task-metrics-delta branch 5 times, most recently from 0fc78fd to e4783f3 Compare October 21, 2026 16:52
@xBis7

xBis7 commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

@dstandish Thank you for the review! I've addressed your comments and made the changes. Please take a look and let me know how it looks. I've rewritten the documentation changes.

@xBis7
xBis7 force-pushed the task-metrics-delta branch from e4783f3 to 145a60a Compare October 21, 2026 17:34
@xBis7
xBis7 force-pushed the task-metrics-delta branch from 145a60a to 01301e8 Compare October 29, 2026 15:02
@xBis7
xBis7 force-pushed the task-metrics-delta branch from 01301e8 to fd451c1 Compare November 11, 2026 14:39
@xBis7
xBis7 force-pushed the task-metrics-delta branch from fd451c1 to 212f672 Compare November 23, 2026 17:19
@xBis7
xBis7 force-pushed the task-metrics-delta branch from 212f672 to 8cd17d3 Compare November 27, 2026 17:06

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:API Airflow's REST/HTTP API area:task-sdk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants