Skip to content

fix(asgi): exclude background task duration from HTTP server metrics#4656

Open
grvmishra788 wants to merge 2 commits into
open-telemetry:mainfrom
grvmishra788:worktree-issue-3591
Open

fix(asgi): exclude background task duration from HTTP server metrics#4656
grvmishra788 wants to merge 2 commits into
open-telemetry:mainfrom
grvmishra788:worktree-issue-3591

Conversation

@grvmishra788

@grvmishra788 grvmishra788 commented Jun 3, 2026

Copy link
Copy Markdown

Description

Duration metrics include background task execution time because the ASGI middleware measures duration in the finally block, which blocks until background tasks complete.

This PR captures a timestamp when the final response body is sent and uses that for duration calculation. If no response is sent, it falls back to default_timer().

Fixes #3591

Type of change

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

  • Ran ASGI instrumentation tests
  • Added tests to verify background task time is excluded

Does This PR Require a Core Repo Change?

  • No.

Checklist:

  • Followed the style guidelines of this project
  • Changelogs have been updated
  • Unit tests have been added
  • Documentation has been updated

@grvmishra788 grvmishra788 requested a review from a team as a code owner June 3, 2026 19:28
Comment on lines +714 to +717
for metric in metrics:
if metric.name == "http.server.duration":
data_points = list(metric.data.data_points)
for point in data_points:

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.

This logic of finding the duration data point appears to be duplicated in each of the three tests cases, could we create a small helper function to clean up these tests a bit?

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

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

Opentelemetrymiddleware: Background task duration is recorded in metrics

2 participants