Cardinality Cost, Batch Writes, Compression and Benchmarks

Article · 9:00

Measuring the cost of cardinality, batching and ingestion throughput, compression and the storage layout per generation, query pruning against aggregation cost, and benchmarking honestly.

Ingestion throughput is mostly about batching, and the numbers are dramatic enough to be worth measuring once. A point written per HTTP request costs an HTTP round trip per point. A batch of five thousand points in one request costs one. On any realistic network that is two or three orders of magnitude, and it is the first thing to check in a slow writer.

The variables: batch size (larger is better until the request size limit), flush interval (how long you are willing to buffer, which is a durability decision because a buffered point is a point you can lose), compression on the wire (gzip, which trades client CPU for bandwidth) and parallelism (several concurrent batches, which helps until the server is saturated). The client libraries have a batching writer; configure it deliberately rather than taking the defaults, because the defaults are conservative.

Compression is where time-series databases earn their reputation, and understanding why makes the storage numbers predictable. Time-ordered data compresses extraordinarily well because consecutive values are similar: timestamps are delta-encoded (a one-second interval becomes a repeated delta, which is nearly free), floats are compressed with an XOR-based scheme that exploits similar bit patterns, integers are delta-and-zigzag encoded, and strings and booleans have their own schemes. Ten to twenty times compression is normal, and the ratio depends on how predictable your data is - a sensor drifting slowly compresses far better than a random value.

The storage layout differs by generation. 2.x writes TSM files with a time-ordered index and a series index held in memory - which is why cardinality has a hard ceiling. 3.x writes Parquet files to object storage with min and max statistics per file and column, which is why pruning is effective and cardinality is far less punishing, and which makes the storage cost an object storage cost rather than a local disk one.

Query cost has two components and separating them is the diagnostic skill. Pruning determines how much data is read, and it comes from the time range and from tag predicates. Aggregation determines what is done with it. A slow query is either reading too much - a missing or wide time range, a field predicate where a tag predicate would do - or aggregating too much, which is what rollups exist to prevent. Reading EXPLAIN ANALYZE in 3.x gives you the file count and the row count, which tells you which half you have.

Benchmarking honestly means: a realistic cardinality, because a benchmark with a hundred series tells you nothing about a deployment with a million; a realistic write rate sustained long enough for compaction to run, because the first minutes are unrepresentative; queries over realistic time ranges, not just the last five minutes; and p50, p95 and p99 from the client. A time-series benchmark with low cardinality and a short duration will always look wonderful.

Laboratory exercise 4 - a measured improvement.

Load at least 500 million points with realistic cardinality - at least 100,000 series. Declare a baseline: five queries with p50, p95 and p99, plus the rows and files scanned for each, and the on-disk size against the raw line protocol size.

Measure the cardinality cost curve: build the same dataset at 1,000, 10,000, 100,000, 1 million and - if your generation survives it - 10 million series, recording query latency, memory use and ingestion rate at each. On 2.x, record the failure point. This is the module's main artefact and it is the number that sizes your deployment.

Measure ingestion four ways: one point per request, batches of 100, batches of 5,000, and batches of 5,000 with gzip and four concurrent writers. Record points per second for each.

Measure compression: the raw line protocol size, the on-disk size, and the ratio - then repeat with a deliberately random field value and compare. The difference shows you what compression depends on.

Compare raw against rollup for the same dashboard query at one hour, one day, one week and one year, recording rows scanned and latency for each.

Separate the two query costs: find a query that is slow from reading too much and one that is slow from aggregating too much, and show the explain output distinguishing them.

Deliverable: the baseline, the cardinality cost curve with the failure point if reachable, the four ingestion measurements, the compression ratios for predictable and random data, the raw-against-rollup table, the two slow-query diagnoses, and one change that did not help.

-- ==================================================================
-- *** INGESTION IS MOSTLY ABOUT BATCHING. *** Measure it once.
-- ==================================================================
--   1 point per HTTP request          ~     400 points/s
--   batches of 100                    ~  32,000 points/s
--   batches of 5,000                  ~ 410,000 points/s
--   batches of 5,000 + gzip + 4 writers ~ 920,000 points/s
--
-- *** TWO OR THREE ORDERS OF MAGNITUDE, AND IT IS THE FIRST THING TO
-- *** CHECK IN A SLOW WRITER. ***
--
--   from influxdb_client_3 import InfluxDBClient3, WriteOptions
--   client = InfluxDBClient3(
--       host="localhost:8181", database="telemetry", token=TOKEN,
--       write_client_options=WriteOptions(
--           batch_size=5000,        # larger until the request limit
--           flush_interval=1000,    # ms - A DURABILITY DECISION:
--                                   # a buffered point is a point you
--                                   # CAN LOSE if the writer dies
--           max_retries=5, max_retry_delay=30000,
--           exponential_base=2))
--
-- *** CONFIGURE THE BATCHING WRITER DELIBERATELY RATHER THAN TAKING
-- *** THE DEFAULTS *** - they are conservative, and they are chosen
-- for safety rather than throughput.
--
-- And the trade to state: flush_interval is HOW MUCH DATA YOU ARE
-- WILLING TO LOSE if the process dies. One second at 900,000
-- points/s is 900,000 points. For telemetry that is usually
-- acceptable; say so rather than default to it.

-- ==================================================================
-- *** THE CARDINALITY COST CURVE. The module's main artefact, and
-- *** the number that sizes your deployment. ***
-- ==================================================================
--   series        ingest/s    query p95   memory    2.x status
--      1,000      920,000        14 ms     1.2 GB   fine
--     10,000      880,000        21 ms     1.8 GB   fine
--    100,000      790,000        48 ms     4.1 GB   fine
--  1,000,000      410,000       310 ms    18.0 GB   *** struggling ***
-- 10,000,000       40,000      4,100 ms   OOM       *** DEAD ***
--
--   3.x at 10,000,000 series:  ~380,000/s, p95 620 ms, 9 GB
--   -> *** FAR BETTER, AND NOT FREE. *** The ceiling moved; the
--      design concern did not go away.
--
-- Produce this for YOUR generation and YOUR hardware. It is the
-- table that answers "can we add a tag?" with a number.

-- ==================================================================
-- COMPRESSION: where time-series databases earn their reputation.
-- ==================================================================
-- Time-ordered data compresses extraordinarily well because
-- CONSECUTIVE VALUES ARE SIMILAR:
--   TIMESTAMPS  delta-encoded. A fixed 1-second interval becomes a
--               REPEATED DELTA, which is nearly free.
--   FLOATS      an XOR-based scheme exploiting similar bit patterns.
--   INTEGERS    delta + zigzag.
--   STRINGS     dictionary / Snappy.
--   BOOLEANS    bit-packed.
--
--   measured:
--     raw line protocol              48.2 GB
--     on disk (predictable sensors)   2.9 GB   -> *** 16.6x ***
--     on disk (RANDOM field values)  21.4 GB   ->       2.3x
--
-- *** TEN TO TWENTY TIMES IS NORMAL, AND THE RATIO DEPENDS ON HOW
-- *** PREDICTABLE YOUR DATA IS. *** A sensor drifting slowly
-- compresses far better than a random value - which also means a
-- storage estimate from a synthetic random benchmark is badly wrong
-- in the pessimistic direction.

-- ==================================================================
-- THE STORAGE LAYOUT, per generation.
-- ==================================================================
--   2.x  TSM files, a time-ordered index, and a SERIES INDEX HELD IN
--        MEMORY -> *** which is exactly why cardinality has a hard
--        ceiling. ***
--        influx_inspect report-tsm -dir /var/lib/influxdb2/engine/data
--
--   3.x  *** PARQUET FILES IN OBJECT STORAGE ***, with MIN AND MAX
--        STATISTICS PER FILE AND COLUMN -> which is why pruning is
--        effective and cardinality is far less punishing, and which
--        makes the storage cost AN OBJECT STORAGE COST rather than a
--        local disk one.
SELECT table_name, SUM(size_bytes)/1024/1024 AS mb, COUNT(*) AS files,
       MIN(min_time), MAX(max_time)
FROM system.parquet_files
GROUP BY table_name ORDER BY mb DESC;

-- ==================================================================
-- *** QUERY COST HAS TWO COMPONENTS. Separating them is the
-- *** diagnostic skill. ***
-- ==================================================================
--   PRUNING      how much data is READ. From the TIME RANGE and the
--                TAG predicates.
--   AGGREGATION  what is DONE with it.

-- SLOW BECAUSE IT READS TOO MUCH:
EXPLAIN ANALYZE
SELECT AVG(value) FROM machine_telemetry WHERE job_id = 'J-88412';
--   ParquetExec: files=3,104/3,104  rows=2,100,000,000
--                      ^^^^^^^^^^^ *** EVERY FILE. *** No time
--                      range, and job_id is a FIELD so it cannot
--                      prune. Add the time range:
EXPLAIN ANALYZE
SELECT AVG(value) FROM machine_telemetry
WHERE job_id = 'J-88412' AND time >= now() - INTERVAL '7 days';
--   ParquetExec: files=182/3,104   rows=120,960,000

-- SLOW BECAUSE IT AGGREGATES TOO MUCH:
EXPLAIN ANALYZE
SELECT machine, date_bin(INTERVAL '1 hour', time) AS h, AVG(value)
FROM machine_telemetry
WHERE time >= now() - INTERVAL '1 year'
GROUP BY machine, h;
--   files pruned CORRECTLY to the year, and it still aggregates
--   31,000,000,000 rows. *** THAT IS WHAT ROLLUPS EXIST TO
--   PREVENT: ***
SELECT machine, time, mean_value FROM machine_telemetry_1h
WHERE time >= now() - INTERVAL '1 year' ORDER BY time;
--   8,760 rows per machine. 14 ms.
--
--   raw vs rollup, same dashboard query:
--     range     raw rows        raw ms    rollup rows   rollup ms
--     1 hour       720,000          18            60           4
--     1 day     17,280,000         290         1,440           6
--     1 week   120,960,000       2,140        10,080          11
--     1 year 31,536,000,000   timed out       525,600         140
--                                  ^^^^^^^^^  *** and this is the
--                                  whole argument for Module 3. ***

-- ==================================================================
-- *** BENCHMARKING HONESTLY. ***
-- ==================================================================
--   * REALISTIC CARDINALITY. A benchmark with 100 series tells you
--     NOTHING about a deployment with a million.
--   * a realistic write rate SUSTAINED LONG ENOUGH FOR COMPACTION TO
--     RUN - the FIRST MINUTES ARE UNREPRESENTATIVE, because nothing
--     has been compacted and everything is in the write buffer.
--   * queries over REALISTIC TIME RANGES, not just the last five
--     minutes.
--   * p50, p95 and p99 FROM THE CLIENT.
--
-- *** A TIME-SERIES BENCHMARK WITH LOW CARDINALITY AND A SHORT
-- *** DURATION WILL ALWAYS LOOK WONDERFUL. *** That is the single
-- most common way these databases are mis-sized, in both
-- directions.
SELECT * FROM system.queries ORDER BY start_time DESC LIMIT 20;

Discussion

No questions on this topic yet. Sign in to ask the first one.