{"slug": "few-bytes-many-requests-migrating-100000-small-tables", "title": "Few Bytes, Many Requests: Migrating 100,000 Small Tables", "summary": "A GreptimeDB engineering benchmark of 100,000 small logical tables (3.2 million rows, roughly 198 MiB) cut export time from 51 minutes to 25 seconds and restore time from nearly two hours to 29 seconds by eliminating per-table fixed costs, reducing S3 HTTP requests from 700,315 to 42 for export and 32 for restore. The baseline restore issued 600,204 S3 requests — 204 for directory listing, manifest and DDL reads plus 6 per table — traced through GreptimeDB's Parquet COPY reader, the parquet crate and OpenDAL, with three separate stat() HEAD calls and two backward-seek GETs per file. The 15-PR implementation in GreptimeDB issue #9120 follows the Export/Import v2 RFC, which had already moved chunk scheduling and snapshot reads to COPY DATABASE over file:// or s3:// URIs.", "body_md": "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.\n\nI published the user-facing walkthrough and CLI examples on the [Greptime blog](https://greptime.com/blogs/2026-12-02-greptimedb-export-import-v2). 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](https://github.com/GreptimeTeam/greptimedb/issues/9120) was also one of the storage tracks I ran through my [Tech Lead AI workflow](https://fengjiachun.github.io/posts/tech-lead-ai-workflow/).\n\n## Why 100,000 Tables\n\nIn 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**.\n\nA 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](https://github.com/orgs/GreptimeTeam/discussions/7394) reported exports taking days at that scale.\n\nExport/Import v2 ([RFC](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/rfcs/2025-12-30-export-import-v2.md)) 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.\n\n## Where the Time Went\n\nWhen total data is ~200 MiB, bandwidth is irrelevant. Wall-clock time is roughly:\n\n```\ntables × requests_per_table × round_trip_latency\n```\n\nIn the baseline restore of 100,000 tables, explicit-file `COPY` ([#9126](https://github.com/GreptimeTeam/greptimedb/pull/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:\n\n| # | Method | Where it came from | \n|---|---|---|\n| 1 | `HEAD` | File check calls `stat()` to verify the explicit input path is a regular file | \n| 2 | `HEAD` | Metadata loader calls `stat()` a second time to get the file length | \n| 3 | `GET` | Parquet metadata reader (with no prefetch hint) reads the last 8 bytes for the footer length | \n| 4 | `GET` | Seeks backwards to read the Thrift footer; OpenDAL’s async reader only reuses buffered bytes on forward seeks, so seeking back triggers a new `GET` | \n| 5 | `HEAD` | Stream builder calls `stat()` a third time before opening the data reader | \n| 6 | `GET` | Stream 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 | \n\nIt 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.\n\nEven with both duplicate `HEAD` s 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](https://github.com/GreptimeTeam/greptimedb/pull/9296)) had removed the per-file `HEAD`, leaving about one `PUT` per table (100,111 requests), and export still took 51 minutes.\n\nWe had to stop paying per table at every stage: scanning, storing, reading, and creating tables.\n\n## One Scan per Physical Table\n\nInstead 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:\n\n```\nSELECT __table_id, ts, <selected tag union>, val\nFROM public.phy\nWHERE ts >= '...' AND ts < '...'\nORDER BY __table_id;\n```\n\nRows 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).\n\nThree details took more work than the SQL suggests:\n\n- **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.\n- **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.\n- **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.\n\nWe 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.\n\n## Packing Small Tables\n\nShared scans eliminate 100,000 queries, not 100,000 `PUT` s. To cut object count, multiple logical tables had to share one object.\n\nThe 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.\n\nInstead, the `packed` layout ([RFC](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/rfcs/2026-09-11-metric-export-import.md)) 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)`:\n\n```\ndata/public/1/\n├── pack-000000.bin        # concatenated complete Parquet streams (<= 8 MiB each)\n├── table-1024.parquet     # spilled large logical table or ordinary table\n└── pack-index.json        # object lengths + per-table (offset, length, row_count)\n```\n\nFive guardrails keep memory bounded on both sides:\n\n- **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.\n- **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.\n- **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.\n- **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).\n- **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.\n\nBecause `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 `HEAD` s. 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.\n\nPacking 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.\n\n## Then DDL Was the Slow Part\n\nOnce 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.\n\nWe 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.\n\nTo 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.\n\nEven 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.\n\n## What the Benchmark Found\n\nTwo notes on version and setup:\n\n- **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](https://github.com/GreptimeTeam/greptimedb/pull/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).\n- **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.\n\n### Primary pair: 1 physical table × 100,000 logical tables\n\nEach 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):\n\n| Metric | Baseline | Optimized | Ratio | \n|---|---|---|---|\n| Full export | 3055.6 s (~51 min) | 25.4 s | 120.3x | \n| ↳ Schema / preflight | 6.4 s | 6.7 s | — | \n| ↳ Data `COPY` | 3034.5 s | 18.3 s | 166x | \n| Export server CPU | 1085.8 s | 37.3 s | 29x | \n| Export peak RSS | 1940 MiB | 1039 MiB | — | \n| Export S3 requests (objects) | 100,111 (100,003) | 42 (5) | -99.96% | \n| Export upload payload | 197.6 MiB | 203.1 MiB | — | \n| Full restore | 6640.4 s (~111 min) | 28.8 s | 230.7x | \n| ↳ Schema / preflight | 71.5 s | 11.2 s | 6.4x | \n| ↳ Data `COPY` | 6568.8 s | 17.5 s | 374x | \n| Restore server CPU | 320.5 s | 44.4 s | 7.2x | \n| Restore peak RSS | 1268 MiB | 1139 MiB | — | \n| Restore S3 requests | 600,204 | 32 | -99.99% | \n| Restore download payload | 355.7 MiB | 236.3 MiB | — | \n\nCompare 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.\n\nThe 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).\n\n### Wide tables and the L0 scan bug\n\nTwo 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.\n\nThe 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.\n\nThe scan-side fix in [#9505](https://github.com/GreptimeTeam/greptimedb/pull/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](https://github.com/GreptimeTeam/greptimedb/pull/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:\n\n- **Wide export:** 3416.7 s → 38.2 s (89.5x); S3 requests 100,115 → 77\n- **Wide restore:** 6745.2 s → 37.5 s (180x); S3 requests 600,204 → 63; table-creation tasks 100,000 → 790\n\nBoth 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.\n\n## What I Cut from My Own RFC\n\nLooking back at my original [December 2025 Export/Import v2 RFC](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/rfcs/2025-12-30-export-import-v2.md), 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.\n\nRather 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](https://github.com/GreptimeTeam/greptimedb/issues/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.\n\n## Lessons So Far\n\n1. **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.\n2. **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.\n3. **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.\n\n## What It Costs\n\nEvery optimization traded simplicity or compatibility for fewer requests:\n\n| Cost | What it looks like in practice | \n|---|---|\n| Non-standard pack objects | `pack-*.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. | \n| Slightly larger uploads | Packing saves requests, not bytes (+5.5 MiB in the narrow run). | \n| Manifest version bump | Packed snapshots write `manifest.version = 2` with`data_layout: \"metric-parquet-packs\"` . Older importers cannot read them and fail before DDL. | \n| No cross-table snapshot isolation | Chunks and tables scan at different times. This is a range slice for archived data or a write-freeze window, not WAL replication. | \n| Structural-only verification | `verify` validates the manifest, index ranges, and object lengths, not row contents or content hashes. | \n| No automatic fallback after submission | An 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. | \n| Deferred insert batching | Restore still feeds decoded batches through normal per-table `COPY` insertion, leaving database insert batching for a follow-up. | \n\nFor step-by-step CLI commands, v1.3.2 experimental flags, and production tuning knobs, see the [official GreptimeDB Export/Import v2 user guide](https://docs.greptime.com/user-guide/deployments-administration/disaster-recovery/export-import-v2/). For design details and acceptance records, see the [Export/Import v2 RFC](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/rfcs/2025-12-30-export-import-v2.md), the [Metric Export/Import Optimization RFC](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/rfcs/2026-09-11-metric-export-import.md), and tracking issue [#9120](https://github.com/GreptimeTeam/greptimedb/issues/9120).", "url": "https://wpnews.pro/news/few-bytes-many-requests-migrating-100000-small-tables", "canonical_source": "https://fengjiachun.github.io/posts/migrating-100k-small-tables/", "published_at": "2026-12-04 16:00:00+00:00", "updated_at": "2026-12-05 07:14:40.257267+00:00", "lang": "en", "topics": ["ai-infrastructure", "mlops", "ai-tools"], "entities": ["GreptimeDB", "GreptimeTeam", "MinIO", "OpenDAL", "Parquet", "Prometheus"], "also_reported_by": [], "takeaway": "For 100,000 small tables totaling ~198 MiB, removing per-table stat() and backward-seek requests cut S3 calls from 700,315 to 74 and restore from nearly two hours to 29 seconds, since per-table request count stays at 6 regardless of column width as long as a table fits in the 256 KiB read chunk.", "recommendation": {"advice": "When exporting or restoring many small tables over object storage, eliminate per-table HEAD and backward-seek GET calls and batch metadata reads; the source cut 700,315 S3 requests to 74 and restore time from nearly two hours to 29 seconds.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/few-bytes-many-requests-migrating-100000-small-tables", "markdown": "https://wpnews.pro/news/few-bytes-many-requests-migrating-100000-small-tables.md", "text": "https://wpnews.pro/news/few-bytes-many-requests-migrating-100000-small-tables.txt", "jsonld": "https://wpnews.pro/news/few-bytes-many-requests-migrating-100000-small-tables.jsonld"}}