Skip to content
Jeremy
Go back

Few Bytes, Many Requests: Migrating 100,000 Small Tables

In a benchmark of 100,000 small tables in GreptimeDB (3.2 million rows total, roughly 198 MiB uploaded), exporting to MinIO with 100 ms of injected latency per request took 51 minutes, restoring took nearly two hours, and the two phases together sent 700,315 S3 HTTP requests. On the same dataset and the same hardware, the redesigned path finished export in 25 seconds and restore in 29 seconds, using 42 and 32 requests.

I published the user-facing walkthrough and CLI examples on the Greptime blog. This post covers the storage and systems side: why table count overwhelmed data size, how eliminating each per-table fixed cost shifted the bottleneck somewhere else, what broke on wide schemas, and what I ended up cutting from my own RFC. The 15-PR implementation in #9120 was also one of the storage tracks I ran through my Tech Lead AI workflow.

Why 100,000 Tables

One physical wide table holding __table_id, timestamp, one numeric value column, and hundreds of string tag columns, projected into 100,000 logical tables that each expose only their own tags

In observability workloads, it is common to map every Prometheus metric name to its own table. GreptimeDB’s Metric Engine handles that without creating 100,000 separate storage partitions (regions) by multiplexing many logical tables onto a few physical tables.

A physical table holds one timestamp column, one numeric value column, internal columns such as __table_id, and the union of all string tag columns across the logical tables sharing it. Each logical table exposes only the tag columns it actually uses. That layout makes ingestion and storage metadata cheap, so a single database can easily accumulate 100,000 small logical tables holding only a few GiB of data. Users in Discussion #7394 reported exports taking days at that scale.

Export/Import v2 (RFC) had already fixed the outer shell: the CLI schedules time-windowed chunks and tracks progress, while the source and target servers read and write snapshots directly through COPY DATABASE over a standard file:// or s3:// URI. What v2 did not fix was what happened inside each chunk. Every logical table still paid its own per-table tax.

Where the Time Went

When total data is ~200 MiB, bandwidth is irrelevant. Wall-clock time is roughly:

tables × requests_per_table × round_trip_latency

In the baseline restore of 100,000 tables, explicit-file COPY (#9126) had already removed per-table directory listing, yet GreptimeDB still issued 600,204 S3 requests: 204 for directory listing pages and reading the manifest and DDL files, plus 6 requests per table. Tracing the restore path through GreptimeDB’s Parquet COPY reader, the parquet crate, and OpenDAL shows where each one went:

#MethodWhere it came from
1HEADFile check calls stat() to verify the explicit input path is a regular file
2HEADMetadata loader calls stat() a second time to get the file length
3GETParquet metadata reader (with no prefetch hint) reads the last 8 bytes for the footer length
4GETSeeks backwards to read the Thrift footer; OpenDAL’s async reader only reuses buffered bytes on forward seeks, so seeking back triggers a new GET
5HEADStream builder calls stat() a third time before opening the data reader
6GETStream builder opens a 256 KiB chunked reader and fetches the rest of the ~2 KiB file on the first column; remaining columns seek forward inside that buffer

It also explains why the narrow (4-column) and wide (12-column) benchmark fixtures described below issued the exact same 600,204 restore requests. As long as a small table fits inside the 256 KiB read chunk, per-table request count is independent of column width.

Even with both duplicate HEADs gone and the footer fetched in one read, each file still costs three requests: 300,000 in total. The floor is one GET per file, 100,000 requests, and at 100 ms each that is still tens of minutes. The export baseline was already tight: conditional object creation (#9296) had removed the per-file HEAD, leaving about one PUT per table (100,111 requests), and export still took 51 minutes.

We had to stop paying per table at every stage: scanning, storing, reading, and creating tables.

One Scan per Physical Table

Shared physical table scan ordered by __table_id feeding a catalog-whitelist router that drops residual rows from dropped tables, projects logical tags before dictionary expansion, and sends encoded Parquet streams either into pack-000000.bin (<= 8 MiB) or standalone table-1024.parquet (> 8 MiB)

Instead of planning and running 100,000 queries, the exporter groups selected logical tables by their underlying physical table and issues one query per physical table per chunk:

SELECT __table_id, ts, <selected tag union>, val
FROM public.phy
WHERE ts >= '...' AND ts < '...'
ORDER BY __table_id;

Rows stream out grouped by __table_id. A router hands each contiguous run to a Parquet encoder for that logical table, and once __table_id advances, the finished table’s encoder closes under a shared concurrency cap (where those encoded streams land is the next section).

Three details took more work than the SQL suggests:

  • Catalog descriptors are the whitelist, not the physical rows. Dropped logical tables can leave residual rows in a physical table. The exporter captures the selected logical-table descriptors up front, drops any __table_id outside that set, and emits a valid zero-row Parquet stream for every selected table that produced no rows in the window.
  • Project before expanding Arrow dictionaries. A physical table can hold hundreds of string tag columns. Projecting each run down to its logical schema before expanding dictionary-encoded columns avoids doing conversion work on columns the logical table does not own.
  • Multi-region ordering can trigger a wide sort. In GreptimeDB, a physical table can be split across multiple storage partitions (regions) on storage nodes (datanodes). The query frontend can preserve __table_id order via streaming merge only when its execution partition count is at least the region count. With more regions than execution partitions, the planner inserts an extra sort over the wide physical column union before per-table projection, and downstream Parquet writer caps cannot bound that sort’s memory.

We kept ORDER BY __table_id as the contract instead of rejecting extra-sort plans or silently falling back to per-table queries, verified both streaming-merge and extra-sort plans across two datanodes, and required cancellation and retry to fail the chunk cleanly if query memory runs out.

Packing Small Tables

pack-index.json mapping logical tables to byte ranges inside pack-000000.bin, where one 8 MiB S3 range GET fills a request-local read cache with at most two 8 MiB windows serving neighboring per-table Parquet decoders

Shared scans eliminate 100,000 queries, not 100,000 PUTs. To cut object count, multiple logical tables had to share one object.

The obvious alternative was exporting each physical table directly as one wide Parquet file. I rejected that for two reasons. First, a physical table’s tag columns are mostly NULL on any given row (in a 300-column physical table where each logical table uses 10 tags, over 96% of tag cells are empty); carrying and padding sparse columns across every row is slow and bloats the data path. Second, exporting raw physical rows forces restore to carry __table_id and map source IDs into the target cluster, instead of reusing GreptimeDB’s normal per-table COPY schema checks and insertion path.

Instead, the packed layout (RFC) concatenates complete, independent Parquet streams (each with its own logical schema and Parquet footer) back to back into pack-000000.bin. A companion pack-index.json records each object’s length and every table’s (table_name, object, offset, length, row_count):

data/public/1/
├── pack-000000.bin        # concatenated complete Parquet streams (<= 8 MiB each)
├── table-1024.parquet     # spilled large logical table or ordinary table
└── pack-index.json        # object lengths + per-table (offset, length, row_count)

Five guardrails keep memory bounded on both sides:

  • 8 MiB spill boundary without splitting a table. Each small-table encoder buffers up to 8 MiB in memory. Tables within 8 MiB append intact into the active pack object; larger ones flush their prefix into a standalone table-{table_id}.parquet and stream the rest there.
  • 8 MiB write and part cap. Single writes and multipart upload parts stay at or below 8 MiB. A pack object itself can grow past 8 MiB and rolls to pack-000001.bin at a table boundary before hitting backend part limits.
  • 64 MiB request-wide payload budget. Retained and queued Arrow batches share a 64 MiB budget per request that counts shared underlying Arrow buffers, not only visible slice sizes.
  • Request-local read windows on restore. Restore schedules tables in (object, offset) order through a read cache owned by that single COPY request (never a process-global cache, so credentials and authorization stay isolated).
  • Bounded eviction. The cache holds at most two 8 MiB windows (16 MiB total), evicts a window only when no active decoder still references a slice of it, and copies into an exact window allocation so a cached window cannot hold onto a larger HTTP transport buffer.

Because pack-index.json already gives the exact byte range of every table and object length is checked once per object, restore does zero per-table HEADs. A Parquet decoder still reads its own footer, but that read becomes an in-memory slice out of the shared 8 MiB window instead of an extra S3 round trip.

Packing does not shrink the upload. Every table keeps its own Parquet footer in both layouts, and the packed run adds a pack-index.json with one entry per table. Upload payload went from 197.6 MiB to 203.1 MiB.

Then DDL Was the Slow Part

DDL statements walked in dependency order where database, physical-table, ordinary-table, and view statements run sequentially while contiguous logical CREATE TABLE statements referencing the same physical table batch into POST /v1/ddl/logical-tables up to 128 statements per request

Once packing and the range reader brought restore data COPY down from 6,569 seconds to 17.5 seconds, table creation stood out immediately. In the baseline run, schema creation and preflight took 71.5 seconds, barely 1% of a two-hour restore, so it was easy to ignore. The RFC’s PoC had already shown that once data restore got fast, running 100,000 CREATE TABLE statements one by one would dominate.

We did not copy the Metric Engine’s internal metadata tables or source table IDs into the target. Recreating tables through GreptimeDB’s normal CREATE path ensures the target allocates fresh table IDs and valid routing metadata.

To speed that up without bypassing validation, we added an authenticated batch endpoint (POST /v1/ddl/logical-tables, capped at 128 statements and 1 MiB of decoded SQL) that runs GreptimeDB’s existing batch logical-table creation path. On restore, import-v2 walks the DDL file in order, treats database, physical-table, ordinary-table, and view statements as ordering barriers, and groups contiguous logical CREATE TABLE statements referencing the same physical table into batches of up to 128. On the wide fixture (10 physical × 10,000 logical tables, described below), that reduced 100,000 logical-table creation tasks to 790 batches.

Even after batching, schema and DDL still took 11.2 seconds out of a 28.8-second narrow restore (39%), and schema export took 6.7 seconds out of 25.4 seconds (26%). Object storage is no longer where the time goes. What is left is database work: catalog DDL and per-table inserts.

What the Benchmark Found

Two notes on version and setup:

  • Version boundary: Shared scans and packed snapshots are in the v1.3 line behind experimental flags (use v1.3.2, which also carries the L0 scan fix backported in v1.3.1). Batched schema export (#9408), batched logical DDL, and --pack-metric-data are on main only, and the server no longer needs the experimental_metric_export option. The numbers below come from an October 12, 2026 main build (macOS release, 16 GiB M2 Pro).
  • Test setup: Both paths ran on the same binary (so the baseline already includes explicit-file COPY, conditional object creation, and batched schema export), frozen source dataset, and resource caps (2 GiB query pool, export parallelism 4, chunk parallelism 1, import task parallelism 1), against local MinIO running in a 2 GiB Docker VM with swap disabled, behind a proxy injecting +100 ms once per S3 HTTP request (every HEAD, GET, PUT, LIST, and multipart call, not SQL or DDL). Synthetic delay models high-RTT object storage; it does not represent a specific cloud provider.

Primary pair: 1 physical table × 100,000 logical tables

Each logical table had 2 string tags, a timestamp, a DOUBLE value, and 32 rows (3.2 million rows total). This single baseline-then-optimized pair met our agreed resource-validity rule (zero host swap-out, 32.5 MiB disclosed swap-in, no Docker VM paging or OOM, no concurrent builds):

MetricBaselineOptimizedRatio
Full export3055.6 s (~51 min)25.4 s120.3x
↳ Schema / preflight6.4 s6.7 s—
↳ Data COPY3034.5 s18.3 s166x
Export server CPU1085.8 s37.3 s29x
Export peak RSS1940 MiB1039 MiB—
Export S3 requests (objects)100,111 (100,003)42 (5)-99.96%
Export upload payload197.6 MiB203.1 MiB—
Full restore6640.4 s (~111 min)28.8 s230.7x
↳ Schema / preflight71.5 s11.2 s6.4x
↳ Data COPY6568.8 s17.5 s374x
Restore server CPU320.5 s44.4 s7.2x
Restore peak RSS1268 MiB1139 MiB—
Restore S3 requests600,20432-99.99%
Restore download payload355.7 MiB236.3 MiB—

Compare CPU with wall-clock. Export CPU fell 29x while wall-clock fell 120.3x; restore CPU fell 7.2x while wall-clock fell 230.7x. The gap is mostly round-trip waiting. That also shows when not to expect triple-digit speedups: on low-latency local storage, or on a handful of large tables (>8 MiB each, which spill to standalone files anyway), the gain should narrow.

The RFC’s early PoC showed higher peak memory on the packed path. In the accepted pair, sampled peak RSS was lower on the optimized run for both export and restore (though RSS is a sampled resident figure with disclosed swap-in, not total allocated memory).

Wide tables and the L0 scan bug

Two tags per table is not what production looks like. We ran a supplementary shape closer to Prometheus workloads: 10 physical tables × 10,000 logical tables, 300 columns per physical table, 10 overlapping tags per logical table, 32 rows each.

The first attempt exhausted the 2 GiB query pool. The cause was in Mito (GreptimeDB’s LSM-tree storage engine), not in the packed writer. During merge scans, Level-0 SST files were always split into per-series batches. Across many short series on a 300-column schema, that left the merge holding too many tiny batches in memory.

The scan-side fix in #9505 was small: apply the existing series-density check to L0 files whenever series statistics are available, only split batches when a merge reader actually has multiple overlapping sources (later refined in #9818), and compact unused tag dictionary values before merge retention. After that fix, the wide export finished with a sampled query-pool peak of 229.2 MiB:

  • Wide export: 3416.7 s → 38.2 s (89.5x); S3 requests 100,115 → 77
  • Wide restore: 6745.2 s → 37.5 s (180x); S3 requests 600,204 → 63; table-creation tasks 100,000 → 790

Both comparisons are single pairs, not three-round medians, and on the wide comparison the baseline restore saw ~18 MiB of host swap-out while the optimized restore had zero. Earlier debug-build and paging-contaminated runs were discarded rather than reported.

What I Cut from My Own RFC

Looking back at my original December 2025 Export/Import v2 RFC, two pieces I promised never shipped. That RFC specified JSON table and view definitions (tables.json and views.json) plus file-, chunk-, and snapshot-level SHA256 checksums. What actually shipped is schemas.json alongside plain SQL DDL (schema/ddl/*.sql) and a structural-only verify that checks manifest completeness, index byte ranges, and object lengths.

Rather than pretending S3 ETags are content hashes, version-2 writers omit the optional checksum fields and readers explicitly reject any non-null value until a versioned checksum specification exists. In the September 2026 Metric RFC, we also deferred merged database inserts across logical tables to keep the first release small, leaving normal per-table COPY insertion intact. Later, in #9120, we narrowed benchmark acceptance from three alternating rounds across every intermediate combination to a single resource-valid baseline-vs-optimized pair once the direction was clear.

Lessons So Far

  1. Count requests, not bytes. Total database size tells you almost nothing about migration time once table count reaches five or six figures. Even after removing duplicate stat() calls and extra footer probes on the read path, per-file reader fixes still hit a 100,000-request floor; changing the object layout is what changed the order of magnitude.
  2. Make old readers fail before they touch the target. The failure I worried about most was silent: an older binary lists *.parquet, restores only the spilled tables, and reports success. Bumping manifest.version to 2 with a required data_layout marker stopped that cold, and we verified against a real v1.2.1 release binary that version-2 manifests are rejected before any DDL runs.
  3. Clean fixtures hide bugs in other layers. The 2-tag fixture passed every check and looked ready to ship. Switching to a 300-column schema immediately exposed an unrelated batch-splitting assumption deep in the storage engine.

What It Costs

Every optimization traded simplicity or compatibility for fewer requests:

CostWhat it looks like in practice
Non-standard pack objectspack-*.bin concatenates Parquet streams back to back, so external tools cannot open a pack file directly as Parquet. Standalone table-*.parquet files remain standard Parquet.
Slightly larger uploadsPacking saves requests, not bytes (+5.5 MiB in the narrow run).
Manifest version bumpPacked snapshots write manifest.version = 2 with data_layout: "metric-parquet-packs". Older importers cannot read them and fail before DDL.
No cross-table snapshot isolationChunks and tables scan at different times. This is a range slice for archived data or a write-freeze window, not WAL replication.
Structural-only verificationverify validates the manifest, index ranges, and object lengths, not row contents or content hashes.
No automatic fallback after submissionAn HTTP 504 timeout does not prove the server stopped writing, and a submitted DDL batch has no cross-table rollback. Failures stop cleanly and require explicit retry instead of silently degrading to per-table execution.
Deferred insert batchingRestore still feeds decoded batches through normal per-table COPY insertion, leaving database insert batching for a follow-up.

For step-by-step CLI commands, v1.3.2 experimental flags, and production tuning knobs, see the official GreptimeDB Export/Import v2 user guide. For design details and acceptance records, see the Export/Import v2 RFC, the Metric Export/Import Optimization RFC, and tracking issue #9120.



Previous Post
One Tech Lead, Many Workers: My AI Coding Workflow