DRYCODEWORKS
← Case studies

Worked example: ClickHouse too many parts and insert batching

Daniel Young
Daniel YoungFounder, DRYCodeWorks

Why ClickHouse refuses inserts with "too many parts", how to find the cause in query_log, and what async inserts changed in a local test.

Small tiles stream onto a stack faster than a press can merge them into a few larger blocks.

ClickHouse writes every insert to disk as at least one new part, and merges parts in the background. Send it many small inserts and it makes parts faster than it can merge them, until it refuses new ones with TOO_MANY_PARTS. This page explains the error from ClickHouse's documentation and from a test I ran on a local ClickHouse 26.3 server.

An illustrative animation, not measured results

Illustration: many small inserts

Swipe sideways to see the whole figure.

refused, then retriedWaiting upstreamred: refused, retriedinserts held backClickHouseone partition of a replicated MergeTree tableParts on diskevery insert writes a new oneMerge poolcombines parts, one merge at a timeActive partsparts_to_delay_insert · 1,000parts_to_throw_insert · 3,000Inserts refused, and retriedOPOQPRSQTRUSVWXYZABCYDEOFZGAHIJKLMWritersone insert each
  1. 1Many small example inserts. This overloaded toy input sends many small inserts, and each one draws a small part.
  2. 2Modeled merges fall behind. The illustrative merge animation runs more slowly than the insert animation. Parts accumulate.
  3. 3A schematic delay boundary. The model delays inserts after its first drawn threshold. These are animation thresholds, not recommended settings.
  4. 4A schematic refusal boundary. After the second drawn threshold the model refuses inserts and sends them back as retries.
  5. 5Retries add work. In this deliberately overloaded model, refused inserts return behind new work and the upstream queue grows.

Why ClickHouse rejects writes with "too many parts"

Every insert into a MergeTree table creates at least one part per partition it touches. Background merges combine small parts into bigger ones. Hundreds of concurrent inserts of a few rows each produce parts faster than the merge pool can combine them. Once a partition crosses its part limit, ClickHouse refuses new inserts.

How MergeTree merges scale

Parts are immutable and sorted by the table's ORDER BY key. A background merge takes a continuous range of parts from one partition and streams them through a k-way merge into one new sorted part. The merge keeps one cursor per input part in a heap, and each output row is one O(log k) heap step. For k parts holding n rows in total, that's O(n log k), and every row is read and written once.

Merged parts get merged again later, so the parts form a tree. ClickHouse's merge selector aims to keep it balanced, with each level roughly b times bigger than the one below (the base in its SimpleMergeSelector). A row is rewritten once per level. If inserts arrive as parts of s rows and parts grow to S rows, each row is written about log_b(S/s) times. Making inserts 100 times smaller adds only log_b(100) levels.

The part count is what scales linearly. Each insert creates at least one part per partition it touches, and every part has fixed costs whatever its size: metadata, index and mark files, checksums, any skip indexes rebuilt on merge, and in a replicated table its own entry in Keeper. At q inserts a second, the merge pool has to retire about q parts a second, and for tiny parts most of that work is overhead. When the pool falls behind, the active parts in a partition climb past parts_to_delay_insert (1,000 by default on current versions), where ClickHouse starts slowing inserts down, and then past parts_to_throw_insert (3,000), where it refuses them.

Find the insert shape first

Before changing memory, indexes or merge settings, look at how many rows each insert carries. This query reads one server's log for a table named default.events. On a cluster, read every replica.

rows per insert: the first number to checksql
SELECT
    toStartOfFiveMinutes(event_time)  AS t,
    count()                           AS inserts,
    round(avg(written_rows))          AS rows_per_insert,
    countIf(exception_code = 252)     AS too_many_parts
FROM system.query_log
WHERE query_kind = 'Insert'
  AND has(tables, 'default.events')
  AND type != 'QueryStart'
  AND event_time > now() - INTERVAL 1 HOUR
GROUP BY t
ORDER BY t;

ClickHouse recommends at least 1,000 rows per insert, and ideally 10,000 to 100,000. If rows_per_insert is in single digits, the inserts are the problem, and a bigger server only moves the limit.

Too many parts is usually a problem with the shape of the inserts, not the size of the server.

Batch on the client, or let the server do it

If one process writes the data, collect rows there and insert them in large blocks. If many small writers can't share a buffer, let ClickHouse collect the rows with asynchronous inserts. With async_insert = 1, the server holds incoming rows in memory and writes them together. With wait_for_async_insert = 1, each insert is acknowledged only after its rows reach disk.

I sent the same 2,000 single-row inserts to a local ClickHouse 26.3 server, 50 at a time, and counted new parts in system.part_log. I ran each setting twice:

SettingNew parts, run 1New parts, run 2Time
async_insert = 02,0002,0000.6 s
async_insert = 1, wait_for_async_insert = 15765about 9 s

The parts fell by about 97%, and each insert waited longer, because its acknowledgement came with a flush. That wait is the cost. Setting wait_for_async_insert = 0 removes it, but then a failed flush loses rows the client believes were stored.

Retries and duplicates

An insert can succeed while its acknowledgement gets lost, and the client will send it again. ClickHouse can drop the repeat, under two conditions.

  • The retry has to look the same. Send the identical block again, or set the same insert_deduplication_token on each attempt.
  • The table has to remember. Replicated and Shared tables keep recent block hashes. A plain MergeTree table keeps none unless you set non_replicated_deduplication_window.

On the local server, with that window set to 100, I inserted one row with the token order-1001, sent it again with the same token, then sent it with order-1002. The table held two rows: the retry was dropped, and the new token was stored.

Asynchronous inserts need async_insert_deduplicate = 1 as well, and it was off by default on my server. Check how it behaves with your materialized views before relying on it.

What to check on your own pipeline

  • Rows per insert before capacity. Aim for thousands of rows per insert and about one insert per second per table.
  • Effective settings, not defaults. async_insert was already on for my 26.3 server. Query system.settings as the user that writes.
  • DelayedInserts, not only rejections. ClickHouse slows inserts at parts_to_delay_insert before it refuses them at parts_to_throw_insert, 1,000 and 3,000 on my server.
  • Partitions. The limit applies per partition, and an insert that spans many partitions makes at least one part in each.

A Buffer table also groups small writes, but it loses buffered rows if the server restarts abnormally. Use one only where that's acceptable.