Skip to main content

Ingest a database with scheduled dumps

When a database is too small or changes too little to justify a CDC service, a scheduled dump is the cheapest way to bring it into the lakehouse. Once a day, read every table from a copy of the database, write Parquet to object storage, and load it into Bauplan. This page builds an exporter, a manifest that lists the files of each run, and a script that points the tables at the new dump on a data branch and publishes them in one merge. The examples use this layout:

    • export.pyreads the database copy, writes Parquet and the manifest
    • main.pyreads the manifest, registers the tables on a branch, merges

Use it when a daily snapshot is fresh enough and the table exports fit in a nightly window. When you need changes within minutes, or the tables are too large to export again every day, use CDC instead. See how to ingest a database from CDC files or how to stream CDC into Bauplan.

Read from a copy, never from production

Reading every row of every table puts heavy load on a database. Read from a read replica, or from a copy restored from the nightly backup, never from the primary that serves your application.

A replica is the simpler option if you need a second database anyway. Restoring a backup, however, proves that the backup is usable. The export then reads one consistent snapshot, where foreign keys between tables point to rows from the same moment. Reading tables one by one from a live database at different times does not guarantee that.

Trigger the export when the copy is ready, not at a fixed time. If you restore a backup, start when the backup has finished, for example when the dump tool writes its completion marker. An export started at a fixed time can read a copy that is not ready yet.

Export tables in batches, write files by size

Read each table in batches to keep the memory of the exporter bounded, whatever the table size. Do not write one file per batch. A batch that fits in memory is usually too small for a good file. Accumulate batches in a buffer and write a Parquet file only when the buffer reaches your target size.

With DuckDB, COPY does both. It streams the table and splits the output by file size.

export.py
import boto3
import duckdb

run_date = "2026-09-27"
target_file_size = "256MB"
connection = duckdb.connect()
connection.execute("INSTALL mysql; LOAD mysql;")
connection.execute("ATTACH 'host=replica.internal user=reader database=app' AS app (TYPE mysql, READ_ONLY)")
# Bounded memory and a spill directory, so one wide table fails alone instead of freezing the machine
connection.execute("SET memory_limit = '4GB'; SET temp_directory = '/tmp/duckdb'; SET preserve_insertion_order = false")

# Delete the folder of this run first: a rerun that writes fewer files must not leave stale ones behind
boto3.resource("s3").Bucket("my-bucket").objects.filter(Prefix=f"raw/app_db/orders/date={run_date}/").delete()

connection.execute(f"""
COPY (SELECT * FROM app.orders)
TO 's3://my-bucket/raw/app_db/orders/date={run_date}'
(FORMAT parquet, COMPRESSION zstd, FILE_SIZE_BYTES '{target_file_size}', FILENAME_PATTERN 'part_{{i}}')
""")

How large to make the files is covered in how to lay out data on object storage.

Write each day under its own prefix, and delete the prefix before writing it, as in the example above. Otherwise a rerun that produces fewer files leaves stale ones behind.

After writing, compare the row count of the source table with the row count of the written files, and fail the table if they differ. Exporters can stop early on values they cannot convert without raising an error.

Legacy types (zero dates, out-of-range times, unsigned decimals) are the usual source of silent export failures. Export them as text and parse them in Bauplan. See how to control types at import.

Hand over with a manifest

When all tables are uploaded, write a manifest listing, for each table, the exact files of this run. main.py reads the manifest and passes exactly these files to Bauplan, without a glob pattern that could also match files from other runs. Bauplan never reads the manifest itself. The manifest is also a record of what each run loaded.

raw/app_db/_manifests/date=2026-09-27/manifest.json
{
"run_date": "2026-09-27",
"source": "app_db",
"tables": [
{"table": "orders", "files": ["s3://my-bucket/raw/app_db/orders/date=2026-09-27/part_0.parquet"]},
{"table": "customers", "files": ["s3://my-bucket/raw/app_db/customers/date=2026-09-27/part_0.parquet"]}
]
}

Write the manifest last, after every file it lists exists, under a prefix that no table glob matches and with the date of the run, for example raw/app_db/_manifests/date=2026-09-27/. Give each run's manifest a unique name so reruns and backfills never overwrite each other.

Register the tables on a branch and publish

A dump is a full snapshot, and each run replaces the tables. Register each table as an external table over the files of this run, on a fresh data branch, then publish every table in one merge. Readers of main never see some tables from today and others from yesterday.

main.py
from datetime import datetime, timezone

import bauplan

client = bauplan.Client()
# manifest: the parsed JSON file written by export.py for this run
stamp = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")
branch = f"{client.info().user.username}.app_db-ingestion-prod-{stamp}"
client.create_branch(branch=branch, from_ref="main", if_not_exists=False)
client.create_namespace(namespace="app_db", branch=branch, if_not_exists=True)

try:
for entry in manifest["tables"]:
# Point the table at the files of this run. Nothing is copied
state = client.create_external_table_from_parquet(
table=entry["table"],
search_patterns=entry["files"],
branch=branch,
namespace="app_db",
overwrite=True,
)
if state.error:
raise RuntimeError(f"registration of {entry['table']} failed: {state.error}")
client.merge_branch(source_ref=branch, into_branch="main")
finally:
client.delete_branch(branch=branch, if_exists=True)

External tables copy nothing. A managed table would copy the whole database into the warehouse on every run, and storage costs would grow with every day of history. The tables take the exact file list from the manifest, and no glob pattern is needed.

Each day's tables only need that day's files. Move older dumps to cheaper storage, such as S3 Glacier, or delete them with a lifecycle rule. Older commits of main still point at those dumps, and reading them fails once the files are moved. See how to choose between managed and external tables.

note

If you need to read older days after the dumps expire, or to partition the tables, import the dump into managed tables instead, as in replace a table.

If any table fails, nothing is merged and main keeps the previous day's data. Do not fall back to another source for the missing table. The finally block deletes the branch whether the run succeeds or fails. To keep failed branches for debugging, drop the finally and delete them later, as in how to clean up branches.

The branch name carries a timestamp and is created with if_not_exists=False, which fails if two runs pick the same branch. To schedule this step, see the orchestrator integrations.