Skip to content

TIMESERIES: last point for one tag is 3-5x slower than the same query on an indexed DOCUMENT type in the same database #8179

Closed

Description

@tae898

Summary

SELECT ts, uu FROM Point WHERE host = 'host_50' ORDER BY ts DESC LIMIT 1 against a native TIMESERIES type is 3-5x slower than the identical query, over the identical points, against an ordinary DOCUMENT type with a (host, ts) index in the same database. Both arms return the same row.

This is the residual after the three fixes that already landed on this query, and it is not a report that any of them regressed. #5414 gave the sealed layer a newest-first block scan, #5416 made the unsealed tail read newest-first, and #7322 pointed the REST/gRPC latest path at queryDescending. They worked: on 2,592,000 points the query that cost 208 ms before #5414 costs about 2 ms now, which is faster than the bounded 2.45 ms that #5414 quoted as its reference. The SQL path here is the one #7322 notes was already using queryDescending via FetchFromTimeSeriesStep.

The question is what is left: why the purpose-built type is still several times slower than a generic indexed one at the query that type exists for.

Measured

My TSBS cpu-only benchmark, one dedicated machine, one cell at a time, cpuset 0-11, 16 GiB cap, 8 GiB heap, five repetitions, median. Engine 26.10.1-dev (417314c18), embedded. Every engine below returns the byte-identical answer, checked by digest.

arm 2,592,000 points 25,920,000 points
ArcadeDB, native TIMESERIES 2.112 ms 3.183 ms
ArcadeDB, DOCUMENT + (host, ts) index 0.373 ms 0.836 ms
QuestDB 0.554 ms 1.232 ms
TimescaleDB 0.092 ms 0.055 ms
DuckDB 1.240 ms 2.300 ms
MongoDB 0.566 ms 0.638 ms

It scales sub-linearly - ten times the data costs about 1.5x the time - so this is not a series scan. It looks like a fixed per-query cost.

The control, and what it is not

The comparison that matters is ArcadeDB against ArcadeDB: same database, same SQL text, same answer, only the storage path differs. That rules out my client, my schema, the corpus and the machine in one step.

It is emphatically not "the TIMESERIES type is slow". On the same corpus the native type ingests in 2.1 s where the document path takes 57 s, and answers a 12-hour aggregate in 3.4 ms where the document path takes 1463 ms. The type is 27x better at ingest and 430x better at aggregation. This is one query, and it happens to be the one an operational dashboard polls most.

Reproduction

TsLastPointVsDocument.java, attached below: one file, no dependencies beyond the engine jars, no Maven.

docker run --rm -v "$PWD":/repro -w /repro arcadedata/arcadedb:<tag> \
  java -Xmx6g -cp "/home/arcadedb/lib/*" TsLastPointVsDocument.java
build TIMESERIES DOCUMENT + index ratio
26.8.1 (published release) 2.658 ms 0.630 ms 4.2x
26.10.1-SNAPSHOT 1.986 ms 0.650 ms 3.05x

Two notes for anyone re-running it, both of which cost me a run:

Create the document index before the inserts. Built afterwards instead, the same query on the same rows answers in 2.221 ms rather than 0.650 ms, and the document arm stops being a fair reference.

Put the database on a real filesystem. On a tmpfs /tmp the ingest and any flush are memory operations.

A possible direction, with what I did not check

TimeSeriesEngine.queryDescending walks every shard in sequence and merges, raising a lowerBound as it goes. For a tag-filtered last point each shard still has to find its own newest row for that tag, and page pruning is by the DATA_MIN_TS / DATA_MAX_TS headers - by time, not by tag - so every shard pays at least one block decompression before the tag filter can reject anything. The document index answers the same question with a single seek.

This is the second half of what #5414 originally proposed and did not get: that issue asked for "a per-shard/per-tag latest-timestamp shortcut ... O(shards) instead of O(series)" and was fixed with the descending scan, which solved the O(series) part. A per-(shard, tag) max-ts map, maintained on append and consulted before any page is touched, would turn this into a lookup plus one row fetch. Whether that is worth the memory per tag is your call - with high-cardinality tags it is not free, and a per-shard map alone would already cut the work.

I have not profiled where the 2 ms actually goes, so treat the mechanism above as the reading of the code that motivated the measurement, not as a diagnosis. If the answer is "this is the floor for a merged multi-shard read and a single-seek index will always win", that is a perfectly good answer and worth having in the open.

Activity

  1. tae898 commented on Sep 22, 2026

    @tae898
    ContributorAuthor

    The repro, for completeness. Save as TsLastPointVsDocument.java and run it with the command in the issue body.

    /*
     * Last point for one tag: the native TIMESERIES type against an indexed DOCUMENT
     * type, in the same database, with the same SQL and the same answer.
     *
     * Context. #5414 made the unbounded last-point query walk sealed blocks
     * newest-first, and #5416 made the unsealed tail read newest-first too. Both are
     * fixed and both helped: on 2,592,000 points the query that cost 208 ms before
     * #5414 costs about 2.1 ms now. This is not a report that those regressed.
     *
     * The question here is what remains. The same query, over the same points, in
     * the same database, answered by an ordinary DOCUMENT type with a (host, ts)
     * index is several times faster than the purpose-built TIMESERIES type. Both
     * arms return the identical row.
     *
     * Build (no Maven needed; compile against the image's own jars):
     *   docker run --rm -v "$PWD":/repro -w /repro arcadedata/arcadedb:<tag> \
     *     java -cp "/home/arcadedb/lib/*" TsLastPointVsDocument.java
     *
     * Options: -Dhosts=100 -DperHost=25920 -Dshards=4 -Diters=100 -Dwarmup=20
     *
     * NOTE ON FILESYSTEM: give it a path on a real filesystem. On a tmpfs /tmp the
     * ingest and any flush are memory operations and the timings are not comparable
     * with a disk-backed run.
     */
    
    import com.arcadedb.database.Database;
    import com.arcadedb.database.DatabaseFactory;
    import com.arcadedb.database.MutableDocument;
    import com.arcadedb.query.sql.executor.Result;
    import com.arcadedb.query.sql.executor.ResultSet;
    import com.arcadedb.schema.LocalTimeSeriesType;
    
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.List;
    
    public class TsLastPointVsDocument {
      static final int  HOSTS    = Integer.getInteger("hosts", 100);
      static final int  PER_HOST = Integer.getInteger("perHost", 25_920);   // 2,592,000 points, the TSBS cpu-only shape
      static final int  SHARDS   = Integer.getInteger("shards", 4);
      static final int  ITERS    = Integer.getInteger("iters", 100);
      static final int  WARMUP   = Integer.getInteger("warmup", 20);
      static final long BASE_TS  = 1_700_000_000_000L;
      static final long STEP_MS  = 10_000L;
      // A TAG THAT EXISTS AT EVERY SIZE. Hardcoded as host_42, a run with fewer
      // hosts timed a query that matched nothing and reported a ratio for two
      // empty results -- both arms agreed, because both returned no row.
      static final String TAG    = "host_" + (HOSTS / 2);
    
      static final String NO_ROW = "(no row)";
    
      public static void main(String[] args) throws Exception {
        final Path root = Files.createTempDirectory(
            Path.of(System.getProperty("user.home")), "tslastpoint");
        final String dbPath = root.resolve("db").toString();
        final int total = HOSTS * PER_HOST;
    
        System.out.printf("points=%,d hosts=%d shards=%d iters=%d (+%d warmup)%n",
            total, HOSTS, SHARDS, ITERS, WARMUP);
        System.out.println("db: " + dbPath);
    
        try (final Database db = new DatabaseFactory(dbPath).create()) {
    
          // ---- arm 1: the native TIMESERIES type -------------------------------
          db.command("sql", "CREATE TIMESERIES TYPE Point TIMESTAMP ts "
              + "TAGS (host STRING) FIELDS (uu DOUBLE) SHARDS " + SHARDS);
          final var engine = ((LocalTimeSeriesType) db.getSchema().getType("Point")).getEngine();
    
          final long[] ts = new long[total];
          final Object[] hosts = new Object[total];
          final Object[] uu = new Object[total];
          int i = 0;
          for (int t = 0; t < PER_HOST; t++)
            for (int h = 0; h < HOSTS; h++) {
              ts[i] = BASE_TS + t * STEP_MS;
              hosts[i] = "host_" + h;
              uu[i] = (double) (t * HOSTS + h);
              i++;
            }
          long t0 = System.nanoTime();
          engine.appendBatch(ts, new Object[][] { hosts, uu });
          engine.compactAll();                       // seal, so nothing is measured against a live tail
          System.out.printf("timeseries ingest+seal: %.1f s%n", (System.nanoTime() - t0) / 1e9);
    
          // ---- arm 2: an ordinary DOCUMENT type with a (host, ts) index --------
          db.command("sql", "CREATE DOCUMENT TYPE PointDoc");
          db.command("sql", "CREATE PROPERTY PointDoc.host STRING");
          db.command("sql", "CREATE PROPERTY PointDoc.ts LONG");
          db.command("sql", "CREATE PROPERTY PointDoc.uu DOUBLE");
          // INDEX FIRST, MAINTAINED DURING INGEST. Built AFTER the inserts instead,
          // the same query on the same rows answered in 2.221 ms rather than the
          // 0.373 ms our benchmark measures, which is the whole reason this file
          // exists: the order the index is created in changes the query by 6x, and
          // an arm built the other way makes the type it is compared against look
          // slow for a reason that has nothing to do with that type.
          db.command("sql", "CREATE INDEX ON PointDoc (host, ts) UNIQUE");
          t0 = System.nanoTime();
          db.begin();
          for (int n = 0; n < total; n++) {
            final MutableDocument d = db.newDocument("PointDoc");
            d.set("host", hosts[n]);
            d.set("ts", ts[n]);
            d.set("uu", uu[n]);
            d.save();
            if ((n + 1) % 10_000 == 0) { db.commit(); db.begin(); }   // same batch size as the lane
          }
          db.commit();
          System.out.printf("document ingest+index: %.1f s%n%n", (System.nanoTime() - t0) / 1e9);
    
          // ---- the same question, twice ---------------------------------------
          final String qTs  = "SELECT ts, uu FROM Point WHERE host = '" + TAG + "' ORDER BY ts DESC LIMIT 1";
          final String qDoc = "SELECT ts, uu FROM PointDoc WHERE host = '" + TAG + "' ORDER BY ts DESC LIMIT 1";
    
          final String aTs = answer(db, qTs), aDoc = answer(db, qDoc);
          System.out.println("answer (timeseries): " + aTs);
          System.out.println("answer (document)  : " + aDoc);
          // BOTH GUARDS MATTER, AND THE SECOND ONE CAUGHT A REAL MISTAKE. Two arms
          // that agree on NOTHING agree; a run whose tag matched no row timed an
          // empty result on both sides and printed a ratio for it.
          if (NO_ROW.equals(aTs) || NO_ROW.equals(aDoc))
            throw new IllegalStateException("tag " + TAG + " matched no row; nothing was measured");
          if (!aTs.equals(aDoc))
            throw new IllegalStateException("the two arms disagree; the comparison is meaningless");
    
          final double medTs  = medianMs(db, qTs);
          final double medDoc = medianMs(db, qDoc);
          System.out.printf("%n  %-34s %8.3f ms%n", "TIMESERIES type, last point", medTs);
          System.out.printf("  %-34s %8.3f ms%n", "DOCUMENT type + index, same row", medDoc);
          System.out.printf("  %-34s %8.2fx%n", "timeseries / document", medTs / medDoc);
        } finally {
          try (var walk = Files.walk(root)) {
            walk.sorted(Comparator.reverseOrder()).forEach(p -> { try { Files.delete(p); } catch (Exception ignored) {} });
          }
        }
      }
    
      static String answer(final Database db, final String sql) {
        try (final ResultSet rs = db.query("sql", sql)) {
          if (!rs.hasNext())
            return NO_ROW;
          final Result r = rs.next();
          // ONE INSTANT, ONE SPELLING. The TIMESERIES type knows `ts` is a
          // timestamp and hands back a Date; the DOCUMENT type stores a LONG and
          // hands back the long. Same instant, and the equality check below is
          // about whether the two arms found the same ROW, not about how each
          // type renders a column, so both are reduced to epoch millis.
          return epochMillis(r.getProperty("ts")) + "," + r.getProperty("uu");
        }
      }
    
      static long epochMillis(final Object v) {
        if (v instanceof java.util.Date d)
          return d.getTime();
        // The TIMESERIES type hands back a LocalDateTime, which carries no zone,
        // so Instant.from() refuses it outright. The column was written from epoch
        // millis, so read it back at UTC.
        if (v instanceof java.time.LocalDateTime ldt)
          return ldt.toInstant(java.time.ZoneOffset.UTC).toEpochMilli();
        if (v instanceof java.time.Instant ins)
          return ins.toEpochMilli();
        if (v instanceof Number n)
          return n.longValue();
        throw new IllegalStateException("ts is a " + (v == null ? "null" : v.getClass().getName()));
      }
    
      /** p50 of ITERS runs, after WARMUP untimed ones. The row is consumed every time. */
      static double medianMs(final Database db, final String sql) {
        for (int i = 0; i < WARMUP; i++)
          answer(db, sql);
        final List<Double> ms = new ArrayList<>(ITERS);
        for (int i = 0; i < ITERS; i++) {
          final long t0 = System.nanoTime();
          answer(db, sql);
          ms.add((System.nanoTime() - t0) / 1e6);
        }
        ms.sort(null);
        return ms.get(ms.size() / 2);
      }
    }
  2. added
    severity:minor
    timeseries
    on Sep 22, 2026
  3. added this to the 26.10.1 milestone on Sep 22, 2026
  4. self-assigned this
    on Sep 22, 2026
  5. added
    in progress
    on Sep 22, 2026
  6. added 6 commits that reference this issue on Sep 22, 2026
  7. added a commit that references this issue on Sep 22, 2026
  8. lvca commented on Sep 22, 2026

    @lvca
    Member

    Fixed in #8194, released in 26.10.1.

    What was actually slow. Not the tag filtering: a TimeSeries type already skips compacted blocks that don't contain the tag you asked for, and in your benchmark 3 of the 4 shards were correctly skipping everything without reading a byte. The cost was on the one shard that did hold host_50. A compacted block holds up to 65,536 samples stored one compressed column at a time, and there was no cache of decoded blocks - so returning a single row meant decoding 65,536 timestamps, 65,536 host values and 65,536 measurements, and the next poll decoded all of them again. That is also why you measured a flat cost that barely grew with the dataset: it was always "decode one block", never "scan the series".

    The fix. Compacted blocks never change once written, so a decoded block can be kept and reused. Reading the same block again now costs nothing extra. On a repeated last-point query the measured time went from 0.089 ms to 0.004 ms in our test - comfortably below the indexed DOCUMENT arm.

    On your suggested per-(shard, tag) max-timestamp map: it wouldn't have closed the gap. Knowing which block holds the newest row for a tag still leaves you decoding that block to read the row out of it, which is where the time was going.

    Tuning. The new arcadedb.timeSeriesDecodedBlockCacheRAM setting controls the memory budget, in MB and per shard. It sizes itself from the JVM heap by default, so you don't need to set anything; set it to 0 to switch caching off. Note a shard picks up a change when it is opened, so reopen the database to apply it everywhere.

    Thanks for the unusually careful report - the ArcadeDB-vs-ArcadeDB control, the note about creating the document index before the inserts, and the guard against timing a query that matched no rows all made this much faster to pin down.


    ❤️ Thanks for helping make ArcadeDB better! ArcadeDB is free and open source, sustained by its community. If it's useful to you or your company, please consider becoming a sponsor to keep development going.

  9. removed
    in progress
    on Sep 22, 2026
  10. tae898 commented on Sep 22, 2026

    @tae898
    ContributorAuthor

    Verified on my side, and the gap does not just close — it reverses.

    Same repro, same machine, same 2,592,000-point TSBS shape, cpuset 0-11, 8 GiB cap, 6 GiB heap, p50 of 100 iterations after 20 warmup. Only the engine differs: the "before" is the 26.10.1-SNAPSHOT image as it stood earlier today, the "after" is the same tag rebuilt with #8194.

    TIMESERIES DOCUMENT + (host, ts) index ratio
    before 1.986 ms 0.650 ms 3.05x
    after 0.418 ms 0.680 ms 0.61x

    4.75x on the TIMESERIES path, and the document arm is unchanged at 0.650 → 0.680 ms, which is the control: the fix moved the thing it was supposed to move and nothing else.

    Your reading of where the time went also explains something my own measurement had shown and I had not accounted for. I reported the query scaling sub-linearly — 2.112 ms at 2.59M points against 3.183 ms at 25.92M, 10x the data for 1.5x the time — and read that as "fixed per-query overhead, not a scan". "Always decode one block, never scan the series" is the same observation with the mechanism attached.

    Thank you for the note on the per-(shard, tag) max-timestamp map not being the answer. That was the part of my suggestion I was least sure of, and it is useful to know that knowing which block still leaves you decoding it — that is the half I could not see from outside.

    I will pick this up on the benchmark page at my next engine re-pin rather than immediately: the campaign currently running holds one engine from first cell to last, so a mid-run swap would split its rows. The numbers above are from the verification host, which is why they are here and not on the page yet.

  11. added a commit that references this issue on Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

performanceseverity:minortimeseries

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions