Dremio is now part of SAP
Dremio Blog

33 minute read · November 9, 2026

Relocating Apache Iceberg Tables with rewrite_table_path: Buckets, Regions, and Recovery

Relocating Apache Iceberg Tables with rewrite_table_path: Buckets, Regions, and Recovery
Copied to clipboard

How rewrite_table_path works and the safe relocation summary

The Iceberg rewrite_table_path procedure rewrites metadata references and produces a plan that lists files to copy. It does not copy the files. For a safe physical relocation you must freeze or otherwise control concurrent writes, stage the rewritten metadata without switching readers, copy every planned object, validate that every new reference resolves to the copied objects, perform a controlled cutover that leaves a rollback checkpoint, and delay source cleanup until readers and any rollback window are satisfied.

A production relocation needs a rewrite and copy plan, validation gates, a controlled cutover, and a tested rollback. The procedure behavior described here was checked on November 9, 2026 against the Iceberg maintenance documentation, Spark procedures, and the Iceberg specification.

Why rewrite_table_path does not move data, and what it does instead

The rewrite_table_path procedure rewrites a table's metadata so that file locations point at a different object store path. The procedure emits rewritten metadata files and a file-copy plan that enumerates which data and metadata objects must be physically copied to make the new locations valid. It does not perform the object storage copy on your behalf. This behavior is obvious in the Iceberg maintenance documentation and the Spark procedures reference, which describe the procedure as creating new manifests and metadata pointers rather than transferring blobs.

Because rewrite_table_path only updates metadata, a run that omits copying will leave the table pointing at non-existent objects. Copying objects without switching metadata leaves readers seeing the old location. A safe relocation coordinates both sides: metadata and object movement. Bucket-to-bucket, region-to-region, and prefix-to-prefix moves also change latency, request cost, and credential boundaries.

Control plane diagram and responsibilities

TABLE RELOCATION CONTROL PLANE1Generate a rewrite and cop…2Validate object counts and…3Cut over readers with a ro…4Verify the resultA useful implementation has an observable result at every boundary. A successful command alone is not the acceptance test.
Table relocation control plane. Each stage has a result that can be checked before the next stage begins.

Relocation requires a small control plane to coordinate actors: the operator, the Iceberg catalog (the metadata store), the object stores in source and destination, and the query fleet. Control actions you will perform include:

  • Freeze or coordinate writes, either with an application-level pause, a DDL lock if your catalog supports it, or by temporarily routing writers to a safe staging table.
  • Run rewrite_table_path to produce rewritten metadata and a file-copy plan. Do not commit the new metadata until copies are verified.
  • Copy objects listed in the plan into the destination, preserving object keys, sizes, and ETags where possible, or recording checksums if ETag semantics differ across providers.
  • Run validation queries that confirm object counts, manifest pointers, and snapshot lineage match expectations.
  • Switch readers by committing the new metadata in the catalog, optionally keeping the old metadata as a rollback checkpoint.
  • Delay cleanup; only remove source objects after the rollback window and when you confirm no readers, long-running jobs, or third-party references still use the old paths.

The operator coordinates the move, the catalog holds metadata pointers, object stores hold the files, and query nodes read through both layers. Cloud object storage moves also require coordinated IAM or credential changes when they cross account or region boundaries.

Generate a rewrite and copy plan, worked example

Start from a snapshot you want to relocate. The example commands below use Spark SQL procedures as documented in the Iceberg Spark procedures docs. Adapt to your engine and catalog conventions. Replace table identifiers and paths to match your environment.

<!-- wp:code -->
-- Example: create a rewrite plan without committing
CALL spark_catalog.system.rewrite_table_path(
  'db.tbl',
  's3a://old-bucket/prefix',
  's3a://new-bucket/new-prefix',
  false -- dryRun or commit flag may vary by implementation
);
-- Check the procedure output for a generated plan location and manifest list
<!-- /wp:code -->

The procedure will produce rewritten metadata files and an explicit plan listing every object that must be copied, typically a JSON or CSV output. In some implementations the procedure writes the rewritten metadata into a staging area in the destination path. In others you must specify an output location. If the procedure created staged metadata, do not publish it to the catalog yet. Use it only as a source to drive your object copy process.

<!-- wp:code -->
-- Example: inspect the plan file produced by the procedure
-- The file is often a newline-delimited JSON where each record has sourcePath and targetPath
cat /tmp/rewrite-plan.json | jq '. | {src: .sourceFile, dst: .destinationFile, size: .size}'
<!-- /wp:code -->

From the plan you will generate parallel copy jobs. Use workers that stream objects between stores without writing intermediate local state to avoid local disk bottlenecks. Preserve object metadata where possible. If the destination provider computes different ETags for multipart uploads, compute and store your own checksum columns in an external audit record so you can validate exact object content after copy.

Metadata rewrite and file-copy plan details

METADATA REWRITE AND FILE-COPY PLANRisk 1The procedure does not copy data or metadata filesTest itRisk 2Shared files can make source cleanup unsafeBound itRisk 3Cross-region moves can change latency, request cost, and…Monitor it
Metadata rewrite and file-copy plan. Each technical risk needs a matching test, boundary, or operating signal.

Manifests and manifest lists in Iceberg reference data files by path. rewrite_table_path updates those references to point at a new path namespace or bucket. The procedure will also produce rewritten manifest lists and root metadata that reference the rewritten manifests. The file-copy plan enumerates the original data files, manifest files, and any ancillary metadata objects that must exist at the destination so the rewritten metadata is complete.

Important cautions when you read the plan:

  • The procedure does not copy the data or metadata files, it only lists them. Verify that your copy phase will copy both data files and manifest/meta files listed by the plan.
  • Shared files, such as data files referenced by multiple snapshots or tables, make automatic source cleanup unsafe. The plan lists file paths to copy, but it cannot decide whether a source object is referenced elsewhere outside your target table. You must check snapshot lineage and other tables before deleting source objects.
  • Cross-region moves change latency and request cost. Copying between regions can double requests and add egress costs. They can also require new credentials or bucket policies. Confirm these changes with cloud billing and security owners before you schedule large transfers.

The Iceberg spec describes snapshot and manifest references and shows why the metadata must be consistent after a copy. If you copy only some files, readers will encounter missing-file errors when the committed metadata points at files that were not copied. If you copy files but do not update metadata, readers will still point at the old location. Both halves must be correct together.

Copy implementation pattern and worked example

Practical copy implementations use a deterministic plan and idempotent copy steps. Here is a minimal worker pattern, in pseudocode you can implement with aws s3 cp, gsutil, rclone, or a cloud SDK that supports multipart and checksums. The worker marks each plan entry as copied in an audit table or object store key-value so you can resume safely.

<!-- wp:code -->
# pseudocode copy worker logic
for entry in read_plan_lines(plan_file):
  if audit_table.has(entry.dst):
    continue  # idempotent

  copy_object(entry.src, entry.dst)
  src_meta = head_object(entry.src)
  dst_meta = head_object(entry.dst)

  if not compare_content(src_meta, dst_meta):
    raise Exception('Mismatch after copy: ' + entry.src)

  audit_table.put(entry.dst, {copiedAt: now(), size: entry.size, checksum: checksum_of(dst)})
<!-- /wp:code -->

Run copies in parallel, but cap concurrency to avoid saturating egress or the source bucket's request limits. Use exponential backoff for 429 or 503 responses. For large objects prefer multipart copy or server-side copy APIs when offered by the cloud provider, they are faster and cheaper. For cross-cloud moves you will need client-side streaming copies.

Validate object counts, manifests, and metadata references

CUTOVER AND VALIDATION SEQUENCEObservecollect the signalCompareuse a baselineDiagnoselocate the boundaryActchange one variablemeasured evidenceunexpected changesmallest safe responsenew baseline
Cutover and validation sequence. The loop turns table or catalog signals into controlled operational changes.

Validation has multiple levels. Do them all. Validation failures are the dominant cause of failed cutovers in my experience.

  • Plan completeness: confirm the number of plan entries matches the count you expect from manifests and snapshot lineage. The plan should include all data files, manifest files, manifest lists, and table metadata files required by the rewritten root metadata.
  • Object presence: for each destination path in the plan, HEAD the object and compare size and checksum to the source. Where ETags differ because of multipart uploads, compare P-Hashes or pre-computed checksums stored in the audit table.
  • Metadata consistency: stage a root metadata file in a staging catalog or a non-committed bucket path and run a dry-run Iceberg table open to enumerate snapshots from the staged metadata. Confirm that the staged metadata resolves every manifest and data file from the destination bucket.
  • Query smoke tests: run read-only queries against the staged metadata in a read-only catalog binding, using representative workloads. Confirm row counts and checksums against the source snapshot. The Dremio guide to monitoring Iceberg table health shows queries and metrics to run for surface-level checks and long-running metrics to watch during and after cutover.

Example commands to validate counts with Spark or your engine of choice:

<!-- wp:code -->
-- Count rows from original snapshot
SELECT count(*) FROM db.tbl@
  -- snapshot id syntax depends on catalog, replace with explicit snapshot id
;

-- Count rows using the staged metadata, without committing
-- Use the staged metadata path or catalog binding to open the table
SELECT count(*) FROM staged_catalog.db.tbl;
<!-- /wp:code -->

If your row counts do not match, inspect for missing manifests or data files, and run HEAD checks against destination objects to identify missing or corrupted copies. Recopy any failing objects, then re-run metadata validation and query smoke tests.

Cutover sequence and rollback checkpoint

The cutover must be atomic from the clients' point of view. You achieve that by preparing a commit that becomes visible to readers and at the same time preserving the old root metadata snapshot as a rollback checkpoint. Iceberg supports snapshot references; the typical pattern is to write the new root metadata to the catalog and keep the old root metadata file or snapshot id stored in a recovery location. The recovery location must allow you to repoint the catalog to the previous metadata if you need to roll back.

<!-- wp:code -->
-- Conceptual cutover steps
1) Ensure all copies are validated and audit entries show success
2) Write the new metadata root file to the catalog location atomically
   (exact mechanism depends on your catalog; some catalogs offer a transactional commit API)
3) Record the previous metadata root file location or snapshot id in a persistent recovery key
4) Allow readers to resume normal operations
<!-- /wp:code -->

Worked example: create a rollback checkpoint before committing. This steps assumes your catalog is a filesystem-based metadata store or a metastore that stores a metadata location pointer.

<!-- wp:code -->
-- Pseudocode for checkpointing
old_root = catalog.getMetadataLocation('db.tbl')
write_kv('recovery:db.tbl:preCutover', old_root)

-- After successful validation
catalog.commitNewMetadata('db.tbl', staged_new_root)
<!-- /wp:code -->

If your catalog supports atomic rename semantics for the file that stores the metadata pointer, prefer that. If it does not, coordinate a short write freeze so the commit does not race with clients that concurrently write to the table.

Rollback and delayed cleanup timeline

ROLLBACK AND DELAYED CLEANUP TIMELINEInventoryversions and consumersTestfeature and failure pathsCanaryone bounded workloadDecideexpand or stopA failed gate returns to inventory with evidence. It does not become a production exception.
Rollback and delayed cleanup timeline. A reversible canary keeps an unsupported client or unsafe policy from becoming a fleet-wide incident.

After cutover you must delay deleting the source objects. The delay must cover:

  • Client cache windows. Some query engines cache object locations or keep long-lived file handles. These caches can last minutes to hours depending on your fleet and configuration.
  • Long-running queries or streaming consumers that started before cutover. They may still refer to old manifests or files.
  • Rollback window length. Keep source objects at least until you are comfortable you will not need to revert. This is often measured in hours, sometimes days. Pick a duration based on business risk and SLA impact.

Do not rely on snapshot garbage collection to remove source objects. Garbage collection policies may be configured cluster-wide and may not account for cross-table sharing. Instead, run an explicit, audited cleanup after you confirm there are no remaining references.

Rollback example, using the previously stored checkpoint:

<!-- wp:code -->
-- To rollback
old_root = read_kv('recovery:db.tbl:preCutover')
catalog.commitNewMetadata('db.tbl', old_root)
-- After rollback, clients will see the old metadata again
<!-- /wp:code -->

Only after the rollback window passes and you have audited that no other tables reference the source objects should you remove the source files. To check for shared references, enumerate snapshots across tables or run programmatic scans for references to the source path. If you find shared files, isolate those objects and keep them in the source until you have a migration plan for the other references.

Failure modes, operational consequences, and how to handle them

Below are common failures I have seen and concrete mitigations.

  • Missing or partial copies. Cause: worker crash or object permission error. Mitigation: audit table will show missing entries. Re-run copy workers for missing objects, validate checksums, then resume validation. Do not commit metadata until the plan is fully satisfied.
  • Metadata commit succeeded but object copy missed some files. Cause: mistaken validation or race. Mitigation: Immediately rollback using the checkpoint, fix copying issues, then retry cutover. Keep a long enough rollback window to allow this.
  • Shared files cause accidental deletion. Cause: cleaning source objects without checking cross-table references. Mitigation: never delete source objects until you audit snapshot lineage across tables. Use the Iceberg metadata tables and manifest inspection to find references. The Dremio post on querying metadata tables explains how to inspect manifests for references.
  • Credential or permission failures in cross-account moves. Cause: missing bucket policies or keys. Mitigation: test a small subset of copies under production credentials and confirm HEAD and GET operations work from the copy workers before starting the large transfer. Coordinate with cloud security for temporary roles if needed.
  • Unexpected cost due to cross-region egress. Cause: copying terabytes across regions without budget signoff. Mitigation: estimate egress cost using known object counts and sizes from manifests, then schedule the transfer during a cost window or negotiate provider discounts. The Dremio article about storage costs covers object request pricing and lifecycle implications you should check before migrating large tables.

Rollout checklist

  • Pre-checks: record current snapshot id, catalog metadata location, and table size. Export the snapshot metadata for offline reference.
  • Write freeze: pause writers or redirect them to a staging path. Confirm no in-flight transactions are active.
  • Generate plan: run rewrite_table_path in dry-run or plan mode. Store plan file in a durable place.
  • Prepare copy workers: configure concurrency, retry policies, and audit table. Test workers on a small sample of objects for permission and performance validation.
  • Run full copy: copy all plan entries and populate the audit table. Monitor request rates and throttling errors.
  • Validate: run object HEAD checks, metadata dry-open using staged metadata, and query smoke tests, including row counts and checksums.
  • Checkpoint: store old metadata root in a recovery key and ensure you can commit the old root in a rollback scenario.
  • Cutover: commit the new root metadata and monitor read traffic and error rates closely.
  • Post-cutover: monitor queries, metrics, and cost. Wait through the rollback window before deleting source objects.
  • Cleanup: after confirming no references, delete source objects or apply lifecycle policies, and record the deletion in an audit log.

What to measure after deployment

After cutover measure both technical and cost metrics for at least one full business cycle. Key metrics:

  • Query latency and success rate, before and after cutover. Cross-region moves often increase latency. Track p50, p95, p99 for representative queries and scans.
  • Object request rates and egress/ingress costs. Monitor cloud billing for unexpected egress charges if you moved data across regions or providers.
  • Catalog update errors and metadata read latency. Larger metadata files or new object store prefixes can change how quickly the catalog locates metadata.
  • Concurrency throttling or 429 errors from the destination bucket during peak reads. If you see throttling, add retries and request rate caps, or request increased quotas from the provider.
  • Snapshot lineage and manifest counts. Track the number of manifests and the total size of metadata to spot metadata growth or fragmentation that will affect compaction plans.

The Dremio guide to Apache Iceberg contains operational guidance that complements these metrics, including how to profile query costs after moving storage. The internal Dremio monitoring article gives practical dashboards you can adapt to watch Iceberg table health after a relocation.

Engine and catalog-specific notes

Different catalogs and compute engines have different primitives. For example, Spark's procedure calls are documented in the Spark procedures docs. Some engines will stage rewritten metadata into a path you must specify. Some catalogs provide transactional commit APIs. Verify your engine and catalog behavior by running the rewrite procedure on a test table and inspecting the outputs. If your catalog is a metastore that stores only a pointer to a metadata file, ensure you know how to atomically replace that pointer or plan a maintenance window for the commit.

If you use Dremio as a query engine, read the Dremio blog post about Apache Iceberg metadata tables to learn how to query internals for manifests and snapshot lineage. That post provides concrete SQL you can run to find references which is crucial before deleting any source objects.

For ongoing monitoring, the Dremio article on monitoring Iceberg table health describes metrics and queries you can adopt. Use those metrics to detect slow reads or anomalies after you change object storage location or region. Finally, if cost is a factor, the Dremio storage costs analysis explains where request volume and lifecycle rules can blow up costs after migration.

Test design and pre-production validation

Design tests that exercise edge cases: snapshot branching, shared files, multipart objects, and long-running scans. Test steps:

  • Create a table with multiple snapshots and a data file referenced by two snapshots. Run rewrite_table_path and ensure the plan includes that file once, and your cleanup logic preserves it until all references are removed.
  • Test multipart upload differences: create large files that will be multipart uploaded in the destination. Confirm your checksum strategy detects differing ETags and that you validate content with a stronger checksum after copy.
  • Simulate writer activity: run a short write storm during the planning phase to confirm your freeze or redirection strategy catches concurrent writers or fails the cutover cleanly.
  • Test rollback: intentionally fail a subset of copies, commit nothing, then follow the rollback path to ensure it returns the system to the original, working state.

Record test artifacts: plan files, audit tables, and staged metadata. They will be invaluable when debugging migrations in production.

Practical notes about permissions and credentials

Cross-region or cross-account copies require credentials with both read privileges on the source and write privileges on the destination. Prefer scoped, temporary roles for the copy workers. Test minimal privileges by running HEAD and GET on sample objects, then PUT to the destination for a small object. Also test listing permissions only if your copy plan needs bucket listings; prefer explicit plans that list objects rather than relying on LIST for large buckets to avoid permission issues and listing costs.

Store recovery checkpoints and audit tables in a location reachable by the operator and protected from accidental deletion. Avoid storing them solely in the destination bucket if destination access is governed by separate IAM that might be revoked during a rollback.

Summary and operational guidance

rewrite_table_path is a metadata-only procedure that outputs a copy plan. The safe operational sequence is: 1) freeze writers, 2) generate a plan, 3) copy objects reliably and idempotently, 4) validate metadata and queries against staged metadata, 5) checkpoint old metadata, 6) commit new metadata, and 7) delay cleanup until the rollback window passes and no references remain.

When in doubt, run everything on a small test table until you have repeated the sequence in a non-production environment. The Iceberg maintenance and Spark procedures docs are the authoritative references for procedure semantics and supported behavior. The Iceberg specification details how manifests and snapshots reference files and why a consistent metadata state is required for correctness. All three were consulted for the procedural behavior described here and checked on November 9, 2026.

FAQ

Does rewrite_table_path copy my data for me?

No. The procedure rewrites metadata and produces a copy plan. You must copy the listed objects yourself or with a tool that consumes the plan.

Can I delete source files immediately after committing the new metadata?

No. Delay deletion until client caches and long-running jobs have cleared, and until the rollback window expires. Also verify there are no shared references from other tables.

How do I detect shared files that prevent safe cleanup?

Query manifests and snapshot lineage to see which snapshots or tables reference the same data files. Use metadata tables and manifest inspection SQL. The Dremio post on metadata tables gives concrete queries to help with this exploration.

What extra costs can I expect when moving between regions?

Expect egress charges from the source, ingress charges at the destination in some clouds, and additional request costs. Copying large amounts of data may materially increase your bill during the migration. Check the Dremio analysis on storage costs and lifecycle rules for guidance on estimating these costs.

How long should the rollback window be?

That depends on your workload. Consider client cache TTLs, maximum job runtimes, and business risk. In practice I have used windows from one hour for low-risk tables up to several days for analytics tables with long-running jobs. Document the choice and rationale ahead of the migration.

Which logs and metrics are most useful during cutover?

Track copy worker success/failure counts, HEAD/GET latency to destination, catalog commit errors, query error rates and latency, and cloud billing metrics for egress. Instrument an audit table recording per-object copy status and checksums for post-mortem analysis.

Continue with these related implementation guides.

Keep learning

For a deeper treatment, download Apache Iceberg: The Definitive Guide, co-authored by Alex Merced and available free from Dremio.

To put the catalog and table-format ideas into practice, explore Dremio's Apache Iceberg platform.

Sources

Additional Dremio resources referenced in the article for operational queries and monitoring:

Try Dremio Cloud free for 30 days

Deploy agentic analytics directly on Apache Iceberg data with no pipelines and no added overhead.