You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/17 09:01:23 UTC

(seatunnel) 01/01: [Improve][Connector-V2][Prometheus] Retry retryable remote-write failures and tolerate duplicate/out-of-order rejections (#11974)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-11974-42bd53094a4bb4f6b22134b5239870c7d370456b
in repository https://gitbox.apache.org/repos/asf/seatunnel.git

commit 34acb089a3c0d9a86b8cd0a0416f62ec099665f5
Author: surafel <72...@users.noreply.github.com>
AuthorDate: Thu Sep 17 09:00:59 2026 +0000

    [Improve][Connector-V2][Prometheus] Retry retryable remote-write failures and tolerate duplicate/out-of-order rejections (#11974)
---
 docs/en/connectors/sink/Prometheus.md              |  34 ++--
 docs/zh/connectors/sink/Prometheus.md              |   6 +-
 .../seatunnel/prometheus/sink/PrometheusSink.java  |  12 ++
 .../prometheus/sink/PrometheusWriter.java          | 183 ++++++++++++++++++---
 .../prometheus/sink/PrometheusWriterTest.java      | 158 ++++++++++++++++++
 5 files changed, 353 insertions(+), 40 deletions(-)

diff --git a/docs/en/connectors/sink/Prometheus.md b/docs/en/connectors/sink/Prometheus.md
index d80a0e8766..b0408fc741 100644
--- a/docs/en/connectors/sink/Prometheus.md
+++ b/docs/en/connectors/sink/Prometheus.md
@@ -50,7 +50,7 @@ downloaded from Maven Central.
 | key_value                   | String | Yes      | -       | Name of the upstream field that contains the Prometheus sample value. A `double` field is recommended. |
 | key_timestamp               | String | No       | -       | Name of the upstream field that contains the Prometheus sample timestamp. If omitted, the sink uses the current system time. |
 | headers                     | Map    | No       | -       | HTTP request headers. |
-| retry                       | Int    | No       | -       | Maximum retry times when the HTTP request throws an `IOException`. |
+| retry                       | Int    | No       | 3       | Maximum retry attempts for a failed remote-write request. Retries transport `IOException`s and retryable HTTP statuses (`5xx` and `429`); other `4xx` responses fail fast. Set to `0` to disable retries. |
 | retry_backoff_multiplier_ms | Int    | No       | 100     | Retry backoff multiplier in milliseconds. |
 | retry_backoff_max_ms        | Int    | No       | 10000   | Maximum retry backoff in milliseconds. |
 | batch_size                  | Int    | No       | 1024    | Positive number of rows buffered before writing to Prometheus. |
@@ -113,20 +113,24 @@ expected; tune `sink.flush.interval` and the checkpoint interval together if req
 ### Checkpoint Flush and Failure Handling
 
 The checkpoint flush is a single remote-write request, and a failed flush fails the checkpoint rather
-than dropping the batch. Two consequences are worth knowing:
-
-- **Transient failures fail the checkpoint.** A network blip, a receiver restart, or a `5xx` response
-  fails the current checkpoint. On Flink the default `tolerableCheckpointFailureNumber` is `0`, so a
-  single failure restarts the job; on Spark and Flink you may want to raise the engine's tolerable
-  checkpoint failure setting for a low-throughput job. A bounded retry with backoff inside the flush
-  is tracked as a follow-up in [#11911](https://github.com/apache/seatunnel/issues/11911).
-- **Replay safety depends on the receiver.** After a failed checkpoint the job restarts and the source
-  replays from the last successful checkpoint, so the buffered samples are re-sent. This is safe only
-  when the remote-write receiver accepts an exact duplicate (same labels, timestamp, and value). A
-  receiver that rejects a same-timestamp sample with a different value, or an out-of-order sample
-  (Prometheus TSDB, and receivers such as Cortex, Mimir, and Thanos, return `400` for these), can fail
-  the replayed flush and keep failing the checkpoint. Enable the receiver's out-of-order window, or
-  ensure replays are exact duplicates, if this matters for your deployment.
+than dropping the batch. The sink retries transient failures before giving up, and tolerates the
+replay case:
+
+- **Transient failures are retried.** A transport error (connection refused, reset, timeout) or a
+  retryable HTTP status (`5xx` or `429`) is retried up to `retry` times with exponential backoff
+  (`retry_backoff_multiplier_ms`, capped at `retry_backoff_max_ms`); only once the retries are
+  exhausted does the flush fail the checkpoint. Other `4xx` responses are not retryable and fail fast.
+  On Flink the default `tolerableCheckpointFailureNumber` is `0`, so an exhausted-retry failure
+  restarts the job; for a low-throughput job on Spark or Flink you may also want to raise that engine
+  setting.
+- **Replay after a failed checkpoint is tolerated.** After a failed checkpoint the job restarts and
+  the source replays from the last successful checkpoint, so the buffered samples are re-sent. If the
+  remote-write receiver rejects a re-sent sample as a duplicate (same labels and timestamp) or as
+  out-of-order (Prometheus TSDB, and receivers such as Cortex, Mimir, and Thanos, return `400` for
+  these), the sink treats that `400` as delivered rather than failing, so a replay does not loop the
+  job. The delivery guarantee remains at-least-once. This is a best-effort match on receiver-specific
+  error wording; a receiver that returns `400` with different wording is not recognized and the flush
+  fails as with any other `4xx`, and each tolerated rejection is logged at `WARN`.
 
 ## Example
 
diff --git a/docs/zh/connectors/sink/Prometheus.md b/docs/zh/connectors/sink/Prometheus.md
index 76f5ae6955..04d4125b34 100644
--- a/docs/zh/connectors/sink/Prometheus.md
+++ b/docs/zh/connectors/sink/Prometheus.md
@@ -47,7 +47,7 @@ Prometheus 数据接收器把上游数据写入 Prometheus remote write API。
 | key_value                   | String | 是       | -      | 上游数据中保存 Prometheus 指标值的字段名。推荐使用 `double` 类型字段。 |
 | key_timestamp               | String | 否       | -      | 上游数据中保存 Prometheus 指标时间戳的字段名。不配置时使用当前系统时间。 |
 | headers                     | Map    | 否       | -      | HTTP 请求头。 |
-| retry                       | Int    | 否       | -      | HTTP 请求出现 `IOException` 时的最大重试次数。 |
+| retry                       | Int    | 否       | 3      | remote-write 请求失败时的最大重试次数。会重试传输层 `IOException` 以及可重试的 HTTP 状态码(`5xx` 和 `429`);其他 `4xx` 响应会快速失败。设为 `0` 可禁用重试。 |
 | retry_backoff_multiplier_ms | Int    | 否       | 100    | 重试退避时间倍数,单位毫秒。 |
 | retry_backoff_max_ms        | Int    | 否       | 10000  | 最大重试退避时间,单位毫秒。 |
 | batch_size                  | Int    | 否       | 1024   | 写入 Prometheus 前缓存的行数,必须大于 0。 |
@@ -96,8 +96,8 @@ env {
 
 检查点刷新是一次 remote-write 请求,刷新失败会让检查点失败,而不会丢弃这批数据。有两点需要了解:
 
-- **瞬时失败会导致检查点失败。** 网络抖动、接收端重启或 `5xx` 响应都会让当前检查点失败。Flink 的 `tolerableCheckpointFailureNumber` 默认是 `0`,因此一次失败就会重启作业;在 Spark 和 Flink 上,对于低吞吐作业你可能需要调高引擎的可容忍检查点失败次数。刷新内部的有界重试(带退避)作为后续项跟踪在 [#11911](https://github.com/apache/seatunnel/issues/11911)。
-- **重放的安全性取决于接收端。** 检查点失败后作业会重启,Source 从上一次成功的检查点重放,因此缓存的采样点会被重新发送。只有当 remote-write 接收端接受完全相同的重复样本(相同的 labels、timestamp 和 value)时,这才是安全的。如果接收端拒绝相同 timestamp 但 value 不同的样本,或拒绝乱序样本(Prometheus TSDB,以及 Cortex、Mimir、Thanos 等接收端对这些情况会返回 `400`),重放的刷新就会失败并持续让检查点失败。如果这对你的部署很重要,请启用接收端的乱序窗口,或确保重放的是完全相同的重复样本。
+- **瞬时失败会被重试。** 传输层错误(连接被拒、重置、超时)或可重试的 HTTP 状态码(`5xx` 或 `429`)会按 `retry` 次数进行重试,采用指数退避(`retry_backoff_multiplier_ms`,上限为 `retry_backoff_max_ms`);只有在重试耗尽后,刷新才会让检查点失败。其他 `4xx` 响应不可重试,会快速失败。Flink 的 `tolerableCheckpointFailureNumber` 默认是 `0`,因此重试耗尽后的失败会重启作业;在 Spark 和 Flink 上,对于低吞吐作业你可能还需要调高该引擎设置。
+- **检查点失败后的重放会被容忍。** 检查点失败后作业会重启,Source 从上一次成功的检查点重放,因此缓存的采样点会被重新发送。如果 remote-write 接收端把重新发送的样本作为重复(相同的 labels 和 timestamp)或乱序样本拒绝(Prometheus TSDB,以及 Cortex、Mimir、Thanos 等接收端对这些情况会返回 `400`),Sink 会把该 `400` 视为已投递而不失败,因此重放不会让作业陷入循环。投递语义仍为 at-least-once。这是基于接收端特定错误文案的尽力而为匹配;如果某个接收端以不同文案返回 `400`,则不会被识别,刷新会像其他 `4xx` 一样失败;每次被容忍的拒绝都会以 `WARN` 记录日志。
 
 ## 示例
 
diff --git a/seatunnel-connectors-v2/connector-prometheus/src/main/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusSink.java b/seatunnel-connectors-v2/connector-prometheus/src/main/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusSink.java
index 533364f057..abe6c93946 100644
--- a/seatunnel-connectors-v2/connector-prometheus/src/main/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusSink.java
+++ b/seatunnel-connectors-v2/connector-prometheus/src/main/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusSink.java
@@ -59,6 +59,18 @@ public class PrometheusSink extends AbstractSimpleSink<SeaTunnelRow, Void>
             httpParameter.getHeaders().put("Content-Encoding", "snappy");
             httpParameter.getHeaders().put("X-Prometheus-Remote-Write-Version", "0.1.0");
         }
+
+        // Wire the retry options into the HTTP parameter so a transient remote-write failure is
+        // retried instead of failing the caller (a checkpoint flush, batch_size, timer flush, or
+        // close()) on the first blip. The base HttpClientProvider retries transport IOExceptions;
+        // the writer additionally retries retryable HTTP statuses (5xx/429). Retries default to on
+        // (3) when `retry` is not set, since the checkpoint-flush path added in #11827 makes an
+        // un-retried transient failure able to fail a checkpoint.
+        httpParameter.setRetry(pluginConfig.getOptional(PrometheusSinkOptions.RETRY).orElse(3));
+        httpParameter.setRetryBackoffMultiplierMillis(
+                pluginConfig.get(PrometheusSinkOptions.RETRY_BACKOFF_MULTIPLIER_MS));
+        httpParameter.setRetryBackoffMaxMillis(
+                pluginConfig.get(PrometheusSinkOptions.RETRY_BACKOFF_MAX_MS));
     }
 
     @Override
diff --git a/seatunnel-connectors-v2/connector-prometheus/src/main/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusWriter.java b/seatunnel-connectors-v2/connector-prometheus/src/main/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusWriter.java
index a1eec20251..7b2ea0dcc9 100644
--- a/seatunnel-connectors-v2/connector-prometheus/src/main/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusWriter.java
+++ b/seatunnel-connectors-v2/connector-prometheus/src/main/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusWriter.java
@@ -54,6 +54,13 @@ public class PrometheusWriter extends HttpSinkWriter {
 
     private final List<Point> batchList;
     private final Integer batchSize;
+    // Retry configuration for the remote-write flush, sourced from the shared HTTP retry options
+    // (retry / retry_backoff_multiplier_ms / retry_backoff_max_ms). The base HttpClientProvider
+    // retries transport IOExceptions with these; the writer reuses the same values to retry
+    // retryable HTTP statuses (5xx/429), which the base retryer cannot see.
+    private final int retry;
+    private final int retryBackoffMultiplierMs;
+    private final int retryBackoffMaxMs;
     private final PrometheusSinkConfig sinkConfig;
     private final Serializer serializer;
     protected final HttpClientProvider httpClient;
@@ -68,6 +75,9 @@ public class PrometheusWriter extends HttpSinkWriter {
         this.batchList = new ArrayList<>();
         this.sinkConfig = PrometheusSinkConfig.loadConfig(pluginConfig);
         this.batchSize = sinkConfig.getBatchSize();
+        this.retry = Math.max(0, httpParameter.getRetry());
+        this.retryBackoffMultiplierMs = httpParameter.getRetryBackoffMultiplierMillis();
+        this.retryBackoffMaxMs = httpParameter.getRetryBackoffMaxMillis();
         this.serializer =
                 new PrometheusSerializer(
                         seaTunnelRowType,
@@ -139,33 +149,162 @@ public class PrometheusWriter extends HttpSinkWriter {
             if (batchList.isEmpty()) {
                 return;
             }
+            final byte[] body;
             try {
-                byte[] body = snappy(batchList);
-                ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body);
-                HttpResponse response =
-                        httpClient.doPost(
-                                httpParameter.getUrl(),
-                                httpParameter.getHeaders(),
-                                byteArrayEntity);
-                if (HttpStatus.SC_NO_CONTENT == response.getCode()) {
-                    batchList.clear();
-                    return;
-                }
-                // Propagate the failure to the engine instead of silently dropping the batch, so a
-                // flush that did not succeed is not treated as a successful flush.
-                throw new PrometheusConnectorException(
-                        CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
-                        String.format(
-                                "Writing records to prometheus failed, http response status code:[%d], content:[%s]",
-                                response.getCode(), response.getContent()));
-            } catch (PrometheusConnectorException e) {
-                throw e;
-            } catch (Exception e) {
+                body = snappy(batchList);
+            } catch (IOException e) {
+                // Encoding failure is a bug, not a transient error, so do not retry it.
                 throw new PrometheusConnectorException(
                         CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
-                        "Writing records to prometheus failed.",
+                        "Failed to compress records for the prometheus remote-write request.",
                         e);
             }
+            // The base HttpClientProvider already retries transport IOExceptions (using the same
+            // retry / retry_backoff_* options). Here we additionally retry retryable HTTP statuses
+            // (5xx and 429), which the base retryer cannot see because they come back as responses
+            // rather than exceptions. Other 4xx fail fast, and a duplicate/out-of-order 400 is
+            // treated as delivered (see sendOnce). After the retries are exhausted flush() throws,
+            // so a genuine outage fails the caller (a checkpoint via prepareCommit, batch_size, the
+            // timer flush, or close()) instead of silently dropping the batch.
+            //
+            // `retry` is the total attempt budget here, matching the base transport
+            // retryer (which uses stopAfterAttempt(retry)). The base uses a Fibonacci
+            // backoff while this status path uses a capped exponential backoff, both
+            // bounded by the retry_backoff_* options.
+            int maxAttempts = Math.max(1, retry);
+            for (int attempt = 1; ; attempt++) {
+                try {
+                    sendOnce(body);
+                    batchList.clear();
+                    return;
+                } catch (RetryableFlushException e) {
+                    if (attempt >= maxAttempts) {
+                        throw new PrometheusConnectorException(
+                                CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                                String.format(
+                                        "Writing records to prometheus failed after %d attempt(s).",
+                                        attempt),
+                                e);
+                    }
+                    log.warn(
+                            "Prometheus remote-write attempt {}/{} failed with a retryable response, "
+                                    + "retrying: {}",
+                            attempt,
+                            maxAttempts,
+                            e.getMessage());
+                    sleepBeforeRetry(attempt);
+                }
+            }
+        }
+    }
+
+    private void sleepBeforeRetry(int attempt) {
+        // Exponential backoff (multiplier * 2^(attempt-1)) capped at retry_backoff_max_ms. The
+        // attempt >= 31 guard keeps the left shift from overflowing on a large attempt count.
+        long backoff =
+                attempt >= 31
+                        ? retryBackoffMaxMs
+                        : Math.min(
+                                (long) retryBackoffMultiplierMs << (attempt - 1),
+                                retryBackoffMaxMs);
+        if (backoff <= 0) {
+            return;
+        }
+        try {
+            Thread.sleep(backoff);
+        } catch (InterruptedException ie) {
+            Thread.currentThread().interrupt();
+            throw new PrometheusConnectorException(
+                    CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                    "Interrupted while backing off before a prometheus remote-write retry.",
+                    ie);
+        }
+    }
+
+    /**
+     * Send the current batch once. Returns normally when the batch is delivered (HTTP 204) or when
+     * the receiver rejects it as a duplicate/out-of-order sample (HTTP 400 with a matching body),
+     * which per the remote-write spec must not be retried and is safe to treat as delivered on a
+     * replay. Throws {@link RetryableFlushException} for a retryable HTTP status (5xx and 429) so
+     * flush() retries it, and a non-retryable {@link PrometheusConnectorException} for a
+     * transport-level failure (already retried by the base client) or any other response.
+     */
+    private void sendOnce(byte[] body) {
+        HttpResponse response;
+        try {
+            response =
+                    httpClient.doPost(
+                            httpParameter.getUrl(),
+                            httpParameter.getHeaders(),
+                            new ByteArrayEntity(body));
+        } catch (Exception e) {
+            // Transport-level failure (connect/read timeout, reset, DNS, etc.). The base
+            // HttpClientProvider has already applied its own IOException retries via the retry /
+            // retry_backoff_* options, so surface it here rather than retrying a second time.
+            throw new PrometheusConnectorException(
+                    CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                    "Prometheus remote-write request failed to complete.",
+                    e);
+        }
+        int code = response.getCode();
+        if (HttpStatus.SC_NO_CONTENT == code) {
+            return;
+        }
+        if (HttpStatus.SC_BAD_REQUEST == code
+                && indicatesDuplicateOrOutOfOrder(response.getContent())) {
+            // A replay after a restore can re-send samples the receiver already has or that are
+            // older than its head for the series; the receiver returns 400 for these. Per the
+            // remote-write spec 4xx must not be retried, and failing here would loop the job on the
+            // same batch, so treat it as delivered. The match on the response body is best effort
+            // (see indicatesDuplicateOrOutOfOrder), so log at WARN: it discards an error response,
+            // and a false positive would drop the batch rather than resend it.
+            log.warn(
+                    "Prometheus returned HTTP 400 whose body matches a duplicate/out-of-order "
+                            + "rejection; treating the batch as delivered. If this receiver returns "
+                            + "400 for an unrelated reason, the batch would be dropped. content:[{}]",
+                    response.getContent());
+            return;
+        }
+        if (isRetryableStatus(code)) {
+            throw new RetryableFlushException(
+                    String.format(
+                            "Writing records to prometheus failed with retryable http status "
+                                    + "code:[%d], content:[%s]",
+                            code, response.getContent()));
+        }
+        throw new PrometheusConnectorException(
+                CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                String.format(
+                        "Writing records to prometheus failed, http response status code:[%d], content:[%s]",
+                        code, response.getContent()));
+    }
+
+    private static boolean isRetryableStatus(int code) {
+        // Per the remote-write spec 5xx should be retried; 429 (Too Many Requests) is a transient
+        // backpressure signal, so retry it too.
+        return code == 429 || (code >= 500 && code <= 599);
+    }
+
+    private static boolean indicatesDuplicateOrOutOfOrder(String content) {
+        if (content == null) {
+            return false;
+        }
+        String lower = content.toLowerCase();
+        return lower.contains("duplicate sample")
+                || lower.contains("out of order")
+                || lower.contains("out-of-order")
+                || lower.contains("too old")
+                || lower.contains("out of bounds");
+    }
+
+    /** Internal marker for a flush failure that should be retried. */
+    private static class RetryableFlushException extends RuntimeException {
+        RetryableFlushException(String message) {
+            super(message);
+        }
+
+        RetryableFlushException(String message, Throwable cause) {
+            super(message, cause);
         }
     }
 
diff --git a/seatunnel-connectors-v2/connector-prometheus/src/test/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusWriterTest.java b/seatunnel-connectors-v2/connector-prometheus/src/test/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusWriterTest.java
index 26a7a3aa2b..3e6c9bab5b 100644
--- a/seatunnel-connectors-v2/connector-prometheus/src/test/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusWriterTest.java
+++ b/seatunnel-connectors-v2/connector-prometheus/src/test/java/org/apache/seatunnel/connectors/seatunnel/prometheus/sink/PrometheusWriterTest.java
@@ -227,10 +227,168 @@ class PrometheusWriterTest {
         }
     }
 
+    /** A retryable failure (HTTP 5xx) is retried, and a following success delivers the batch. */
+    @Test
+    void shouldRetryRetryableFailureThenSucceed() throws Exception {
+        SinkWriter.Context context = mock(SinkWriter.Context.class);
+        HttpResponse unavailable =
+                new HttpResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, "unavailable");
+        HttpResponse ok = new HttpResponse(HttpStatus.SC_NO_CONTENT);
+
+        try (MockedConstruction<HttpClientProvider> ignored =
+                mockConstruction(
+                        HttpClientProvider.class,
+                        (mockClient, ctx) ->
+                                when(mockClient.doPost(
+                                                anyString(), any(), any(ByteArrayEntity.class)))
+                                        .thenReturn(unavailable, ok))) {
+
+            PrometheusWriter writer = createWriter(context, 3);
+            writer.write(newPoint());
+
+            // First attempt is 503 (retryable), second is 204: no exception, batch delivered.
+            writer.prepareCommit();
+            verify(writer.httpClient, times(2))
+                    .doPost(anyString(), any(), any(ByteArrayEntity.class));
+
+            // Buffer cleared after delivery: a second flush sends nothing more.
+            writer.prepareCommit();
+            verify(writer.httpClient, times(2))
+                    .doPost(anyString(), any(), any(ByteArrayEntity.class));
+        }
+    }
+
+    /** After the retries are exhausted, the flush throws and the batch is not cleared. */
+    @Test
+    void shouldThrowAfterRetriesExhausted() throws Exception {
+        SinkWriter.Context context = mock(SinkWriter.Context.class);
+        HttpResponse unavailable =
+                new HttpResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, "unavailable");
+
+        try (MockedConstruction<HttpClientProvider> ignored =
+                mockConstruction(
+                        HttpClientProvider.class,
+                        (mockClient, ctx) ->
+                                when(mockClient.doPost(
+                                                anyString(), any(), any(ByteArrayEntity.class)))
+                                        .thenReturn(unavailable))) {
+
+            PrometheusWriter writer = createWriter(context, 3);
+            writer.write(newPoint());
+
+            Assertions.assertThrows(
+                    PrometheusConnectorException.class, () -> writer.prepareCommit());
+            // retry is the total attempt budget, so retry=3 means 3 doPost calls.
+            verify(writer.httpClient, times(3))
+                    .doPost(anyString(), any(), any(ByteArrayEntity.class));
+        }
+    }
+
+    /**
+     * After the retries are exhausted the batch stays buffered (not cleared), so a later flush
+     * re-sends the same records. This pins down the at-least-once guarantee explicitly.
+     */
+    @Test
+    void shouldRetainBufferAfterRetriesExhausted() throws Exception {
+        SinkWriter.Context context = mock(SinkWriter.Context.class);
+        HttpResponse unavailable =
+                new HttpResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, "unavailable");
+        HttpResponse ok = new HttpResponse(HttpStatus.SC_NO_CONTENT);
+
+        try (MockedConstruction<HttpClientProvider> ignored =
+                mockConstruction(
+                        HttpClientProvider.class,
+                        (mockClient, ctx) ->
+                                when(mockClient.doPost(
+                                                anyString(), any(), any(ByteArrayEntity.class)))
+                                        .thenReturn(unavailable, ok))) {
+
+            // retry=1 means a single attempt, so the first flush exhausts immediately.
+            PrometheusWriter writer = createWriter(context, 1);
+            writer.write(newPoint());
+
+            Assertions.assertThrows(
+                    PrometheusConnectorException.class, () -> writer.prepareCommit());
+            verify(writer.httpClient, times(1))
+                    .doPost(anyString(), any(), any(ByteArrayEntity.class));
+
+            // The row is still buffered: a second flush re-sends it and now succeeds.
+            writer.prepareCommit();
+            verify(writer.httpClient, times(2))
+                    .doPost(anyString(), any(), any(ByteArrayEntity.class));
+        }
+    }
+
+    /** A non-retryable response (other 4xx) fails fast without retrying. */
+    @Test
+    void shouldFailFastOnNonRetryable4xx() throws Exception {
+        SinkWriter.Context context = mock(SinkWriter.Context.class);
+        HttpResponse forbidden = new HttpResponse(HttpStatus.SC_FORBIDDEN, "forbidden");
+
+        try (MockedConstruction<HttpClientProvider> ignored =
+                mockConstruction(
+                        HttpClientProvider.class,
+                        (mockClient, ctx) ->
+                                when(mockClient.doPost(
+                                                anyString(), any(), any(ByteArrayEntity.class)))
+                                        .thenReturn(forbidden))) {
+
+            PrometheusWriter writer = createWriter(context, 5);
+            writer.write(newPoint());
+
+            Assertions.assertThrows(
+                    PrometheusConnectorException.class, () -> writer.prepareCommit());
+            // Non-retryable: exactly one attempt despite retry=5.
+            verify(writer.httpClient, times(1))
+                    .doPost(anyString(), any(), any(ByteArrayEntity.class));
+        }
+    }
+
+    /**
+     * A 400 the receiver reports as a duplicate/out-of-order sample is treated as delivered, so a
+     * replay after restore does not fail the checkpoint or loop the job.
+     */
+    @Test
+    void shouldTreatDuplicateOrOutOfOrder400AsDelivered() throws Exception {
+        SinkWriter.Context context = mock(SinkWriter.Context.class);
+        HttpResponse duplicate =
+                new HttpResponse(HttpStatus.SC_BAD_REQUEST, "duplicate sample for timestamp");
+
+        try (MockedConstruction<HttpClientProvider> ignored =
+                mockConstruction(
+                        HttpClientProvider.class,
+                        (mockClient, ctx) ->
+                                when(mockClient.doPost(
+                                                anyString(), any(), any(ByteArrayEntity.class)))
+                                        .thenReturn(duplicate))) {
+
+            PrometheusWriter writer = createWriter(context, 3);
+            writer.write(newPoint());
+
+            // No throw: the duplicate rejection is tolerated as delivered.
+            writer.prepareCommit();
+            verify(writer.httpClient, times(1))
+                    .doPost(anyString(), any(), any(ByteArrayEntity.class));
+
+            // And the buffer is cleared, so a second flush sends nothing more.
+            writer.prepareCommit();
+            verify(writer.httpClient, times(1))
+                    .doPost(anyString(), any(), any(ByteArrayEntity.class));
+        }
+    }
+
     private PrometheusWriter createWriter(SinkWriter.Context context) {
+        return createWriter(context, 0);
+    }
+
+    private PrometheusWriter createWriter(SinkWriter.Context context, int retry) {
         HttpParameter httpParameter = new HttpParameter();
         httpParameter.setUrl("http://localhost:9090/api/v1/write");
         httpParameter.setHeaders(new HashMap<>());
+        httpParameter.setRetry(retry);
+        // No backoff sleep in tests so retries run instantly and deterministically.
+        httpParameter.setRetryBackoffMultiplierMillis(0);
+        httpParameter.setRetryBackoffMaxMillis(0);
         SeaTunnelRowType rowType =
                 new SeaTunnelRowType(
                         new String[] {"value"}, new SeaTunnelDataType[] {BasicType.DOUBLE_TYPE});