Correction, 2026-11-25: this post originally described a "battle-tested" tuning recipe built around partition keys, materialized views and "the 3 settings that most people get wrong". That was not an accurate description of our system and has been replaced with what we actually run and measure.

The ClickHouse problems that cost us the most were not settings. They were four ordinary mistakes: filtering on a column outside the sort key, reading a deduplicating table before it had deduplicated, caching an expensive query without a lock, and comparing timestamps stored as text. Each one is below with the date we hit it and what it did. The largest feed involved held 17,749,718,292 rows on 2026-11-25, per the public /v1/world response.

Key facts

Four ClickHouse mistakes and their fixes

Lesson 1: filter on the first column of the sort key

A MergeTree table is stored sorted by its ORDER BY key, and the sparse primary index lets ClickHouse skip the parts of each file that cannot match. That only works for a filter on a prefix of the key. A filter on any other column makes ClickHouse read every granule in the time range and test each row.

Our tick feed is sorted by source first, then symbol, then time. Each row also has a sector, the collector domain it belongs to, which is how people think about the data: seismic, rail, maritime. So the natural query filters by sector. Sector is not in the key.

-- illustrative table and names: ORDER BY (source, symbol, ts)

-- slow: sector is outside the sort key, so every part in the time range is read
SELECT count() FROM ticks
WHERE sector = 'SEISMIC' AND ts >= now() - INTERVAL 7 DAY;

-- fast: the first key column narrows the read before anything is decompressed
SELECT count() FROM ticks
WHERE source IN ('seismic_feed_a', 'seismic_feed_b') AND ts >= now() - INTERVAL 7 DAY;

On 2026-09-27 the first form, over seven days, read tens of gibibytes. Nothing was wrong with the result. The cost landed on everything else using the database at that moment, and we killed the query. The fix is a habit, not a setting: resolve the sector to its list of sources first, then filter on source and a time range. Check read_rows and read_bytes for any new query against a large table before it goes into a scheduled job.

The time filter matters for the same reason. An unbounded query against a table that takes in more than a hundred million rows a day reads history nobody asked for.

Lesson 2: ReplacingMergeTree does not deduplicate on read

ReplacingMergeTree removes rows with the same sorting key during background merges. Until a merge happens, both versions are on disk and a plain SELECT returns both. The documentation says this clearly, and we still shipped a route that selected from such a table directly.

The daily history feed has one row per day, network and metric, and is rebuilt from raw observations. A rebuild writes a new version of a day's row. For a period after each rebuild the old and new rows coexisted, and /v1/history returned both. Across the days 2026-08-29 to 2026-08-31 it served tens of thousands of duplicate points. The worse detail is that on 2026-08-30 there were keys where the two rows held different values, so a client had two answers for the same network, metric and day and no way to tell which was current.

-- illustrative names

-- find the problem
SELECT day, network, metric, count() AS versions, uniqExact(value) AS distinct_values
FROM daily
GROUP BY day, network, metric
HAVING versions > 1;

-- fix: ask for the merged view at read time
SELECT day, network, metric, value FROM daily FINAL WHERE network = 'AKT';

FINAL costs read performance, because the merge is done at query time. On a table with one row per day and metric that cost is small, and correctness is not optional on a route people build charts from. On a very large table, an explicit argMax over a version column in a GROUP BY is the usual alternative. Either way, test a ReplacingMergeTree read immediately after a write, not an hour later, or the test passes for the wrong reason.

Lesson 3: a cache needs a lock, or it stampedes

The most expensive query our API runs is an aggregate over the tick feed that builds the latest value per series. It is called from several routes. It was uncached at first, so every concurrent request launched its own copy. On 2026-09-19 we found many copies running at once. The effect compounds: a slow response makes the caller retry, and the retry adds another scan.

A time-to-live cache alone does not fix this. When the cache is cold or has just expired, every request that arrives in that instant misses and starts the query. The part that fixes it is a lock with a second check inside it:

import threading, time

_cache = {"at": 0.0, "value": None}
_lock = threading.Lock()
TTL = 300

def latest():
    if _cache["value"] is not None and time.time() - _cache["at"] < TTL:
        return _cache["value"]
    with _lock:
        # another thread may have refreshed while this one waited
        if _cache["value"] is not None and time.time() - _cache["at"] < TTL:
            return _cache["value"]
        value = run_expensive_query()
        if value:  # never cache an empty result
            _cache.update(at=time.time(), value=value)
        return value

The first caller computes; the rest wait on the lock and then read the cached value. Blocking a few threads is far cheaper than running the same scan many times.

Two refinements are worth copying. First, never cache an empty result: a transient database error would otherwise pin an empty answer for the whole time-to-live and the API would publish nothing as if it were the truth. Second, a lock alone still makes every caller behind it wait for the rebuild. On our catalog route, since 2026-10-23, an expired snapshot is served while one background thread rebuilds it, and only a cold cache rebuilds inside a request.

Lesson 4: timestamps stored as strings compare as text

Our observation timestamp, as_of, is stored as a string, and two formats are in use. Both are visible in public responses on 2026-11-25: the Helium supply row carries "as_of": "2026-11-25 05:53:04.122" and the Helium market-tier row carries "as_of": "2026-11-25T05:34:01Z".

Both are valid UTC timestamps. Compared as text they are not ordered by time, because the eleventh character differs: a space sorts before the letter T.

SELECT '2026-11-25 23:00:00' < '2026-11-25T01:00:00Z';
-- 1: the string comparison says 23:00 is earlier than 01:00

SELECT parseDateTimeBestEffort('2026-11-25 23:00:00')
     < parseDateTimeBestEffort('2026-11-25T01:00:00Z');
-- 0: parsed, the order is right

On 2026-09-26 one of our own checks compared as_of values as text to decide whether repaired collectors had written since their fix. Several of them had, and the check reported them as still pending, because the two sides of the comparison used different formats. Functions such as parseDateTimeBestEffort accept both forms. Better still is a real DateTime64 column from the start, which is the change we would make if we rebuilt the table. The same two formats are why API clients should parse as_of before comparing it, as noted in data freshness for AI agents.

How these ClickHouse lessons show up in the API

Some of this is visible from outside. The history route's disclosure describes the one-row-per-day rule. Withheld and stale series are listed with reasons, as shown in handling missing data when an upstream API goes silent. The volume this runs at is measured in data ingestion rate, measured, and the small transactional store beside it is covered in SQLite in production.

curl -s https://kairossignal.com/v1/world
// trimmed
{
  "estate": {
    "rows_ingested_24h": 114597196,
    "rows_total": 17749718292
  },
  "measured_utc": "2026-11-25T06:32:21Z"
}

Frequently asked questions

Why is my ClickHouse query slow when I filter on a column that is not in ORDER BY?

The primary index only helps with filters on a prefix of the sort key. Any other filter reads every granule in the selected partitions. Add a condition on the first key column and a time range, or add a projection or skip index for that column.

When should I use FINAL in ClickHouse?

Whenever you read a ReplacingMergeTree, CollapsingMergeTree or similar table and need exactly one row per key. Without it, unmerged parts return every stored version.

How do I stop a cache stampede on an expensive query?

Put a lock around the rebuild and re-check the cache after acquiring it, so one caller computes and the others reuse the result. Serving the previous snapshot while one thread refreshes removes the wait as well.

Should timestamps be stored as String in ClickHouse?

No. Use DateTime or DateTime64. Strings in mixed formats compare by character, which puts a space-separated timestamp before a T-separated one on the same date regardless of the time.

How many rows does the Kairos Signal warehouse hold?

The tick feed held 17,749,718,292 rows at 2026-11-25T06:32:21Z. The figure is returned live by /v1/world, so read it there instead of quoting this post.

To check the public figures, call https://kairossignal.com/v1/world and read the disclosure field of any /v1/history response, documented in the API documentation. The incidents are from our own engineering record, which cannot be checked from outside, and are dated so they can be read as history, not as current state. The status page is a manually maintained snapshot; for current health call /health.

This is a data product. Kairos Signal publishes measurements with their sources, not trading signals.