> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to handle duplicates, retry storms and bad timestamps from log shippers such as Vector or Cribl

> Log pipelines that deliver at least once cause duplicate rows, retry storms and rejected batches. How to recognize each of them in ClickHouse and what to change in the pipeline.

A log pipeline that buffers events and re-sends them when a request fails or times out (for example Vector agents that feed a central processor such as Cribl) delivers every event at least once.
That is correct behavior, but it produces three symptoms that look like ClickHouse problems:

| Symptom | Fix in the pipeline | What ClickHouse can do |
| - | - | - |
| Duplicate rows | Acknowledge upstream from a durable queue | Deduplicate identical retries, `ReplacingMergeTree` |
| Retry storm ending in `TOO_MANY_SIMULTANEOUS_QUERIES` | Limit concurrency, back off exponentially | Limit the concurrent queries of the inserting user |
| Whole batches rejected because of a few bad timestamps | Normalize timestamps, use a dead-letter output | Skip unparsable rows, relax the partition limit |

The pipeline-side fixes are the ones that remove the cause. Their names differ between products, so look for the retry, concurrency, batch and buffer settings of your shipper.

## Duplicate rows

Every hop that delivers at least once can create copies. ClickHouse removes only the copies that it can recognize: a retry of the same `INSERT` with the same data. A copy that an earlier hop re-sent arrives inside a different batch and is inserted again:

```sql theme={null}
CREATE TABLE app_logs
(
    timestamp DateTime64(3, 'UTC'),
    event_id String,
    service LowCardinality(String),
    message String
)
ENGINE = MergeTree
ORDER BY (service, timestamp)
SETTINGS non_replicated_deduplication_window = 1000;

-- First attempt
INSERT INTO app_logs VALUES
    ('2025-12-01 10:00:01.000', 'evt-001', 'api', 'request started'),
    ('2025-12-01 10:00:02.000', 'evt-002', 'api', 'request finished');

-- Retry of the same request: recognized as a duplicate and not inserted
INSERT INTO app_logs VALUES
    ('2025-12-01 10:00:01.000', 'evt-001', 'api', 'request started'),
    ('2025-12-01 10:00:02.000', 'evt-002', 'api', 'request finished');

-- The same event re-sent by an earlier hop arrives in a different batch: inserted again
INSERT INTO app_logs VALUES
    ('2025-12-01 10:00:02.000', 'evt-002', 'api', 'request finished'),
    ('2025-12-01 10:00:03.000', 'evt-003', 'api', 'cache miss');
```

If the events carry a unique id, count the copies per time interval. Copies of an event have the same event time, so they fall into the same interval:

```sql theme={null}
SELECT
    toStartOfInterval(timestamp, INTERVAL 15 MINUTE) AS t,
    count() AS events,
    events - uniqExact(event_id) AS duplicates,
    round(100 * duplicates / events, 2) AS duplicate_pct
FROM app_logs
GROUP BY t
ORDER BY t;
```

```text theme={null}
   ┌───────────────────────t─┬─events─┬─duplicates─┬─duplicate_pct─┐
1. │ 2025-12-01 10:00:00.000 │      4 │          1 │            25 │
   └─────────────────────────┴────────┴────────────┴───────────────┘
```

What helps:

* **Find the hop that makes the copies.** If every hop adds its own metadata to the event (a processing time, a worker id), compare the copies of one id. Copies that differ in the metadata of the last hop were made before it. Copies that are identical in every column were re-sent by the last hop.
* **Acknowledge upstream early.** When the central processor confirms a batch to the edge shipper only after the insert into ClickHouse, every slow insert makes the edge re-send. A durable queue on the input of the processor removes this dependency.
* **Keep retries identical.** [Insert deduplication](https://clickhouse.com/docs/concepts/features/operations/insert/deduplicating-inserts-on-retries.md) works for a table that keeps a deduplication log: `Replicated*MergeTree` tables do by default, a plain `MergeTree` table needs [`non_replicated_deduplication_window`](https://clickhouse.com/docs/reference/settings/merge-tree-settings/other#non_replicated_deduplication_window) as in the example. Since ClickHouse 26.2 it also covers asynchronous inserts by default. It only helps if the shipper re-sends the same rows in the same request.
* **Deduplicate by id.** For exact results, store the events in a [`ReplacingMergeTree`](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/replacingmergetree) table whose sorting key contains the id, here `ORDER BY (service, timestamp, event_id)`, and read it with `FINAL` or with the [`final`](https://clickhouse.com/docs/reference/settings/session-settings/other#final) setting set to `1`. Merges remove the copies in the background at an unknown time, and `FINAL` makes reads more expensive, so decide whether your dashboards need it.

## Retry storms

A retry storm starts when inserts become slow, for example because the server is short of memory or busy with merges:

1. Requests time out in the shipper, and it sends them again while the first attempts are still running.
2. Every running insert occupies one slot of the server limit [`max_concurrent_queries`](https://clickhouse.com/docs/reference/settings/server-settings/settings/max-concurrent#max_concurrent_queries). In ClickHouse Cloud the limit is [1000 concurrent queries per replica](https://clickhouse.com/docs/products/cloud/guides/cloud-compatibility.md#max_concurrent_queries-1000).
3. When all slots are taken, new queries fail with the error `TOO_MANY_SIMULTANEOUS_QUERIES` (code 202, `Too many simultaneous queries. Maximum: 1000`). The shipper retries them too, so the load grows while nothing completes. Dashboards and your own diagnostic queries are rejected as well.

A higher limit rarely helps: the slots are held by inserts that can't finish, and more slots fill up the same way. A storm ends when the server completes inserts faster than they are re-sent. To prevent the next one:

* In the shipper, limit the number of concurrent requests to ClickHouse and retry with exponential backoff, in particular after `TOO_MANY_SIMULTANEOUS_QUERIES` (202) and `MEMORY_LIMIT_EXCEEDED` (241).
* In ClickHouse, insert as a dedicated user and set [`max_concurrent_queries_for_user`](https://clickhouse.com/docs/reference/settings/session-settings/max-concurrent#max_concurrent_queries_for_user) for it, well below the limit of the server. Then the shipper alone can't take all slots:

```sql theme={null}
CREATE SETTINGS PROFILE log_ingest SETTINGS
    max_concurrent_queries_for_user = 100,
    async_insert = 1,
    wait_for_async_insert = 1,
    async_insert_busy_timeout_min_ms = 1000,
    async_insert_busy_timeout_max_ms = 2000;

CREATE USER log_shipper IDENTIFIED BY 'Str0ng_password_here'
SETTINGS PROFILE 'log_ingest';

GRANT INSERT ON default.app_logs TO log_shipper;
```

To see a storm from ClickHouse, count the inserts by outcome. During a storm the failures overtake the successes:

```sql theme={null}
SELECT
    toStartOfInterval(event_time, INTERVAL 10 MINUTE) AS t,
    user,
    countIf(type = 'QueryFinish') AS succeeded,
    countIf(type != 'QueryFinish') AS failed,
    topKIf(3)(errorCodeToName(exception_code), exception_code != 0) AS top_errors,
    round(median(query_duration_ms)) AS median_ms
FROM system.query_log
WHERE query_kind = 'Insert'
    AND type != 'QueryStart'
    AND event_time >= now() - INTERVAL 6 HOUR
GROUP BY t, user
ORDER BY t, user;
```

In ClickHouse Cloud, read `clusterAllReplicas(default, system.query_log)` instead of `system.query_log` to [see all replicas](https://clickhouse.com/docs/products/cloud/features/monitoring/system-tables.md#querying-across-nodes).

## Bad timestamps

One row that can't be parsed or stored fails the insert. A batch of the usual size for a shipper is a single block, and a block is written entirely or not at all, so the whole batch is rejected. The shipper then retries a batch that can never succeed, and the share of failing requests grows. A large insert that is split into several blocks, or into several partitions, can fail after earlier blocks are already stored, see [the conditions for an atomic insert](https://clickhouse.com/docs/concepts/features/operations/insert/transactions.md); a retry of such a request inserts those rows again unless they are deduplicated. Two errors come from event timestamps:

```sql theme={null}
CREATE TABLE raw_logs
(
    timestamp DateTime64(9, 'UTC'),
    message String
)
ENGINE = MergeTree
PARTITION BY toDate(timestamp)
ORDER BY timestamp;

-- Accepted: epoch seconds and ISO 8601
INSERT INTO raw_logs FORMAT JSONEachRow {"timestamp": 1764583200, "message": "epoch seconds"}
{"timestamp": "2025-12-01T10:00:01.5Z", "message": "ISO 8601"}

-- Rejected: epoch milliseconds
INSERT INTO raw_logs FORMAT JSONEachRow {"timestamp": 1764583202, "message": "good row"}
{"timestamp": 1764583203000, "message": "epoch milliseconds"}
```

```text theme={null}
Code: 407. DB::Exception: Numeric value is out of range for DateTime64: (while reading the value of key timestamp): While executing ParallelParsingBlockInputFormat. (DECIMAL_OVERFLOW)
```

Since ClickHouse 26.8, an unquoted number in a JSON format is a Unix timestamp in seconds, also for `DateTime64`, so milliseconds and nanoseconds are out of range. Before 26.8 such a number was read as a count of ticks of the column (nanoseconds for `DateTime64(9)`); [`input_format_read_datetime_number_as_raw_value`](https://clickhouse.com/docs/reference/settings/formats/input-format#input_format_read_datetime_number_as_raw_value) restores that.

The second error comes from events dated 1970 or months in the past, which spread one batch over many partitions:

```sql theme={null}
INSERT INTO raw_logs
SELECT
    toDateTime64('2025-12-01 10:00:00', 9, 'UTC') - toIntervalDay(number),
    'old event'
FROM numbers(150);
```

```text theme={null}
Code: 252. DB::Exception: Too many partitions for single INSERT block (more than 100). The limit is controlled by 'max_partitions_per_insert_block' setting. [...] (TOO_MANY_PARTS)
```

Despite the error code, this isn't the ["too many parts"](https://clickhouse.com/docs/resources/support-center/knowledge-base/troubleshooting/exception-too-many-parts.md) condition of a table. Read the text of the exception, which is in the `exception` column of `system.query_log`, to tell the two apart.

The fix belongs in the pipeline: convert the timestamp to ISO 8601 or to epoch seconds, drop or clamp values outside a sensible window around the current time, and route what remains to a dead-letter output where you can see it. Settings of the inserting user can bridge the time until then:

* [`input_format_allow_errors_num`](https://clickhouse.com/docs/reference/settings/formats/input-format#input_format_allow_errors_num) and [`input_format_allow_errors_ratio`](https://clickhouse.com/docs/reference/settings/formats/input-format#input_format_allow_errors_ratio) skip rows of text formats that can't be parsed, such as `"timestamp": "yesterday"`. They don't skip a number that is out of range (`DECIMAL_OVERFLOW`), and the skipped rows are lost.
* Setting [`throw_on_max_partitions_per_insert_block`](https://clickhouse.com/docs/reference/settings/session-settings/throw-on#throw_on_max_partitions_per_insert_block) to `0` writes the batch and logs a warning instead of throwing the exception. The 150 rows above then become 150 parts in 150 partitions, so remove the setting once the pipeline is fixed.

## Batch small requests on the server

Shippers send many small requests. With [asynchronous inserts](https://clickhouse.com/docs/concepts/features/operations/insert/asyncinserts.md) (enabled by default since ClickHouse 26.2) the server collects them in a buffer and writes the buffer when the first of these limits is reached:

| Setting | Default | In ClickHouse Cloud |
| - | - | - |
| [`async_insert_busy_timeout_max_ms`](https://clickhouse.com/docs/reference/settings/session-settings/async-insert#async_insert_busy_timeout_max_ms) | `200` | `1000` |
| [`async_insert_max_data_size`](https://clickhouse.com/docs/reference/settings/session-settings/async-insert#async_insert_max_data_size) | `10485760` | `104857600` |
| [`async_insert_max_query_number`](https://clickhouse.com/docs/reference/settings/session-settings/async-insert#async_insert_max_query_number) | `450` | |

The timeout is adaptive: frequent inserts raise it step by step from `async_insert_busy_timeout_min_ms` (default `50`) to the maximum. Every flush writes at least one part per partition, so a steady stream with the default timeouts creates several small parts per second. Higher timeouts in the profile of the inserting user, as in `log_ingest` above, give fewer and larger parts. With `wait_for_async_insert = 1` the client gets its answer only after the flush, so set the request timeout of the shipper well above `async_insert_busy_timeout_max_ms`.

To check how often buffers are flushed and which timeout was used:

```sql theme={null}
SELECT
    toStartOfMinute(flush_time) AS minute,
    table,
    uniqExact(flush_query_id) AS flushes,
    count() AS insert_queries,
    max(timeout_milliseconds) AS max_timeout_ms
FROM system.asynchronous_insert_log
WHERE event_time >= now() - INTERVAL 1 HOUR
GROUP BY minute, table
ORDER BY minute, table;
```
