-
Notifications
You must be signed in to change notification settings - Fork 328
feat: add retry layer for push metrics exporters #9036
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
5d87f69
Add retry layer for push metrics exporters
rohan-b99 a6a1360
Apply clippy suggestion
rohan-b99 2d979c1
Add changeset
rohan-b99 a40d32d
Merge branch 'dev' into rohan-b99/otlp-push-exporter-retries
rohan-b99 21b4b7a
Remove misleading "configurable" doc comment from retry exporter
rohan-b99 9d84319
Implement jitter for backoff in RetryMetricExporter
rohan-b99 4e8f404
Merge branch 'dev' into rohan-b99/otlp-push-exporter-retries
rohan-b99 8576676
Update feat_rohan_b99_otlp_push_exporter_retries.md
rohan-b99 42b2668
Fix lint issue
rohan-b99 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| ### Add retry layer for push metrics exporters ([PR #9036](https://github.com/apollographql/router/pull/9036)) | ||
|
|
||
| Add `RetryMetricExporter`, which will retry up to 3 times with jittered exponential backoff to the `apollo metrics` and `otlp` named exporters. | ||
|
|
||
| By [@rohan-b99](https://github.com/rohan-b99) in https://github.com/apollographql/router/pull/9036 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,203 @@ | ||
| //! Retry wrapper for push metric exporters. | ||
| //! | ||
| //! Wraps a `PushMetricExporter` and retries failed exports a number | ||
| //! of times with jittered exponential backoff. Only surfaces the error | ||
| //! after all attempts are exhausted, keeping transient failures out of the logs. | ||
| //! We use this approach as recommended by the OpenTelemetry Spec: | ||
| //! <https://opentelemetry.io/docs/specs/otel/protocol/exporter/#retry> | ||
|
|
||
| use std::fmt::Debug; | ||
| use std::time::Duration; | ||
|
|
||
| use opentelemetry_sdk::error::OTelSdkResult; | ||
| use opentelemetry_sdk::metrics::Temporality; | ||
| use opentelemetry_sdk::metrics::data::ResourceMetrics; | ||
| use opentelemetry_sdk::metrics::exporter::PushMetricExporter; | ||
| use rand::Rng; | ||
|
|
||
| const DEFAULT_MAX_RETRIES: usize = 3; | ||
| const BASE_BACKOFF: Duration = Duration::from_millis(100); | ||
|
|
||
| pub(crate) struct RetryMetricExporter<T> { | ||
| inner: T, | ||
| max_retries: usize, | ||
| } | ||
|
|
||
| impl<T> RetryMetricExporter<T> { | ||
| pub(crate) fn new(inner: T) -> Self { | ||
| Self { | ||
| inner, | ||
| max_retries: DEFAULT_MAX_RETRIES, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<T: Debug> Debug for RetryMetricExporter<T> { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| f.debug_struct("RetryMetricExporter") | ||
| .field("max_retries", &self.max_retries) | ||
| .field("inner", &self.inner) | ||
| .finish() | ||
| } | ||
| } | ||
|
|
||
| impl<T: PushMetricExporter> PushMetricExporter for RetryMetricExporter<T> { | ||
| async fn export(&self, metrics: &ResourceMetrics) -> OTelSdkResult { | ||
| let mut last_err = None; | ||
| for attempt in 0..self.max_retries { | ||
| match self.inner.export(metrics).await { | ||
| Ok(()) => return Ok(()), | ||
| Err(err) => { | ||
| tracing::debug!( | ||
| attempt = attempt + 1, | ||
|
conwuegb marked this conversation as resolved.
|
||
| max_retries = self.max_retries, | ||
| error = %err, | ||
| "metric export attempt failed, will retry" | ||
| ); | ||
| last_err = Some(err); | ||
| if attempt + 1 < self.max_retries { | ||
| tokio::time::sleep(jittered_backoff(BASE_BACKOFF, attempt as u32)).await; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Err(last_err.expect("max_retries must be >= 1")) | ||
| } | ||
|
|
||
| fn force_flush(&self) -> OTelSdkResult { | ||
| self.inner.force_flush() | ||
| } | ||
|
|
||
| fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult { | ||
| self.inner.shutdown_with_timeout(timeout) | ||
| } | ||
|
|
||
| fn temporality(&self) -> Temporality { | ||
| self.inner.temporality() | ||
| } | ||
| } | ||
|
|
||
| /// Full jitter: uniform random duration in `[0, base_backoff * 2^attempt]`. | ||
| fn jittered_backoff(base: Duration, attempt: u32) -> Duration { | ||
| let max = base * 2u32.pow(attempt); | ||
| let max_millis = max.as_millis() as u64; | ||
| if max_millis == 0 { | ||
| return Duration::ZERO; | ||
| } | ||
| let jittered = rand::rng().random_range(0..=max_millis); | ||
| Duration::from_millis(jittered) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::sync::atomic::AtomicUsize; | ||
| use std::sync::atomic::Ordering; | ||
| use std::time::Duration; | ||
|
|
||
| use opentelemetry_sdk::error::OTelSdkError; | ||
| use opentelemetry_sdk::error::OTelSdkResult; | ||
| use opentelemetry_sdk::metrics::Temporality; | ||
| use opentelemetry_sdk::metrics::data::ResourceMetrics; | ||
| use opentelemetry_sdk::metrics::exporter::PushMetricExporter; | ||
|
|
||
| use super::*; | ||
|
|
||
| #[derive(Debug)] | ||
| struct CountingExporter { | ||
| call_count: AtomicUsize, | ||
| fail_until: usize, | ||
| } | ||
|
|
||
| impl CountingExporter { | ||
| fn new(fail_until: usize) -> Self { | ||
| Self { | ||
| call_count: AtomicUsize::new(0), | ||
| fail_until, | ||
| } | ||
| } | ||
|
|
||
| fn calls(&self) -> usize { | ||
| self.call_count.load(Ordering::SeqCst) | ||
| } | ||
| } | ||
|
|
||
| impl PushMetricExporter for CountingExporter { | ||
| async fn export(&self, _metrics: &ResourceMetrics) -> OTelSdkResult { | ||
| let n = self.call_count.fetch_add(1, Ordering::SeqCst) + 1; | ||
| if n <= self.fail_until { | ||
| Err(OTelSdkError::InternalFailure("transient".into())) | ||
| } else { | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| fn force_flush(&self) -> OTelSdkResult { | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn shutdown_with_timeout(&self, _timeout: Duration) -> OTelSdkResult { | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn temporality(&self) -> Temporality { | ||
| Temporality::Delta | ||
| } | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn succeeds_on_first_try() { | ||
| let inner = CountingExporter::new(0); | ||
| let exporter = RetryMetricExporter::new(inner); | ||
| let result = exporter.export(&ResourceMetrics::default()).await; | ||
| assert!(result.is_ok()); | ||
| assert_eq!(exporter.inner.calls(), 1); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn succeeds_after_transient_failures() { | ||
| let inner = CountingExporter::new(2); | ||
| let exporter = RetryMetricExporter::new(inner); | ||
| let result = exporter.export(&ResourceMetrics::default()).await; | ||
| assert!(result.is_ok()); | ||
| assert_eq!(exporter.inner.calls(), 3); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn fails_after_all_retries_exhausted() { | ||
| let inner = CountingExporter::new(usize::MAX); | ||
| let exporter = RetryMetricExporter::new(inner); | ||
| let result = exporter.export(&ResourceMetrics::default()).await; | ||
| assert!(result.is_err()); | ||
| assert_eq!(exporter.inner.calls(), DEFAULT_MAX_RETRIES); | ||
| } | ||
|
|
||
| #[test] | ||
| fn jittered_backoff_within_bounds() { | ||
| let base = Duration::from_millis(100); | ||
| for attempt in 0..4 { | ||
| let max = base * 2u32.pow(attempt); | ||
| for _ in 0..200 { | ||
| let d = jittered_backoff(base, attempt); | ||
| assert!(d <= max, "attempt {attempt}: {d:?} exceeded max {max:?}"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn jittered_backoff_zero_base() { | ||
| assert_eq!(jittered_backoff(Duration::ZERO, 0), Duration::ZERO); | ||
| assert_eq!(jittered_backoff(Duration::ZERO, 5), Duration::ZERO); | ||
| } | ||
|
|
||
| #[test] | ||
| fn jittered_backoff_has_spread() { | ||
| let base = Duration::from_millis(100); | ||
| let samples: Vec<Duration> = (0..100).map(|_| jittered_backoff(base, 2)).collect(); | ||
| let min = *samples.iter().min().unwrap(); | ||
| let max = *samples.iter().max().unwrap(); | ||
| assert!( | ||
| max - min > Duration::from_millis(50), | ||
| "expected spread across samples, got min={min:?} max={max:?}" | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.