dbdr in Production
For the people who run dbdr rather than change it: backups, restores, moves between engines, and proving that a copy is right.
1Choosing a Format
Volume I was written for people who change dbdr. This volume is for
the people who run it: the ones who are paged when the nightly backup
fails, who move a production database to a new cluster, and who have to
prove to an auditor that the copy is the same as the original. It
assumes you have read Chapter 1 of Volume I, or at least run its
commands. Everything else it explains as it goes.
Every run starts with one decision: which format to use. It decides how fast the dump is, where the result can be restored, and what gets left behind.
Three formats, three jobs
graph TD
Q1{"Restoring into the<br/>same engine?"} -->|no| P["portable<br/>.dbschema + .dbdata"]
Q1 -->|yes| Q2{"Need to read or<br/>edit the output?"}
Q2 -->|yes| S["sql<br/>CREATE + INSERT text"]
Q2 -->|no| N["sql schema<br/>+ native data .zip"]Native is for speed, SQL for something you can read, and portable for crossing engines. Native and portable both keep schema and data in separate files.
sql |
native |
portable |
|
|---|---|---|---|
| Speed | slowest; every value is formatted as text | fastest; bytes are copied without decoding | close to native; values are decoded once into a compact form |
| Readable | yes | no | the schema is JSON, the rows are binary |
| Restore into | the same engine | the same engine | any supported engine |
| Data from Postgres | not yet | yes | yes |
| Files | one .sql per database |
schema.sql plus one .zip per database |
one .dbschema, plus a .dbdata and one file per large table |
The README reports the native format finishing a real production ClickHouse dump in 2 minutes 41 seconds, against 26 minutes for the SQL path. The gap grows with table size, because the SQL path's cost per row is fixed and the native path's is close to zero.
What each format leaves out
This is the half of the decision people forget. Each format leaves something behind, and you should know what before the restore, not after it.
| Object | sql (ClickHouse) |
sql (Postgres) |
native |
portable |
|---|---|---|---|---|
| Tables and their rows | yes | schema only | rows only (pair with a schema dump) | yes |
| Views | yes | yes | n/a | left out |
| Materialized views | yes, rebuilt by trigger | WITH NO DATA, refreshed after load |
n/a | left out |
| A materialized view's target table | schema; rows rebuilt by trigger | n/a | rows | schema and rows |
| Sequences and their values | n/a | yes, with setval |
n/a | left out |
| Constraints and indexes | as declared | as declared | n/a | sort key only, as a plain index |
| Column defaults | as declared | as declared | n/a | only now(), true, false, 0, 1; the rest are dropped with a warning |
| Column comments | as declared | not written | n/a | yes |
The portable format moves tables and their data. If the destination needs views, sequences or constraints, you recreate them there, by hand or with migration scripts you already keep. Chapter 8 works through what that means.
The usual pairings
Backups of one engine. Dump the schema as SQL and the data as native, with zip compression:
dbdr -db=shop -un=dumper --only=schema -o=schema.sql
dbdr -db=shop -un=dumper --only=data -fmt=native --compress=zip -o=data.zipOn the example shop database, --compress=zip brought the native
archive from 5.3 MB down to 365 KB. Compression costs some CPU on the
machine running dbdr, not on the database server.
A copy you can read or edit. Use SQL, with batched inserts:
dbdr -db=shop -un=dumper --split-insert-size=10000 --compress=gzip -o=shop.sqlAlways pass --split-insert-size. Without it every row is its own
INSERT, and on ClickHouse each INSERT becomes a separate part on
disk. In Volume I's test, single-row statements replayed more than a
thousand times slower than batches of 10,000.
A move between engines. Use portable, in two files:
dbdr -db=shop -un=dumper --only=schema -fmt=portable -o=shop.dbschema
dbdr -db=shop -un=dumper --only=data -fmt=portable -o=shop.dbdataAll databases on a server. -db=all dumps every database that
dbdr list-databases shows, one file (or archive) per database. Check
the list first, because ClickHouse leaves out system,
information_schema and default, and Postgres leaves out
template0 and template1. If you keep real tables in ClickHouse's
default database, name it explicitly.
Exercises
Exercise 1-1. Dump shop in all three formats, compressed and not,
and make a table of file size against time taken. Where does
compression pay for itself, and where doesn't it?
Exercise 1-2. List everything in one of your own databases that the portable format would leave out. For each item, write down how you would recreate it at the destination.
Exercise 1-3. Find out what -db=all would dump on one of your
servers, without dumping anything.
2Least Privilege
dbdr does whatever its database user is allowed to do. If you dump as
a superuser, a mistake on the command line has a superuser's reach. So
create one user for dumping, which can read and nothing else, and a
second for restoring, which can create and write to its target only.
Both engines make this easy. This chapter gives the smallest grants
that work. Every one of them was tested against ClickHouse 26.6 and
Postgres 16.
A user for dumping
ClickHouse. One grant is enough for every dump format and for
list-databases:
CREATE USER dumper IDENTIFIED BY '...';
GRANT SELECT ON shop.* TO dumper;system.tables and system.columns, which dbdr reads to find out
what's in the database, are readable by every user by default, filtered
down to what the user may see. A native dump uses the same user over
HTTPS.
Postgres. Use the built-in role that reads everything. It is available from Postgres 14 onwards:
CREATE ROLE dumper LOGIN PASSWORD '...';
GRANT pg_read_all_data TO dumper;With it, dumper can produce every format. That includes the
sequence values a schema dump records with setval, and the
pg_stats histograms a native dump uses to split large tables. A
schema dump taken as dumper is identical, byte for byte apart from
the timestamp, to one taken as postgres.
The trap: a user who can't see everything
This is the most important thing in the chapter. ClickHouse doesn't show a user the tables that user can't read. A dump run as a user with too few grants doesn't fail. It succeeds and leaves those tables out, with no warning at all:
$ dbdr -db=shop_dates -un=partial --only=data -fmt=portable -o=p.dbdata
shop_dates.events32: 250000 row(s) -> p_events32.dbdata
1 file(s) in 171ms # exit status 0shop_dates has two tables. The user partial had SELECT on only
one of them, so as far as dbdr could tell, the other didn't exist.
Three habits protect you:
- Grant on the whole database (
ON shop.*), not table by table. Then a table added next month is dumped too. - Check the count. Each SQL dump's header says
-- entities: N, and a native zip has one entry per table that stores data. Compare these with what you expect. The checks in Chapter 6 catch the rest. - When a user can see a table but not read it, the dump fails,
loudly:
dbdr: database "shop_dates": clickhouse: count rows for orders: code: 497, message: partial: Not enough privileges. ...That is the safe way to fail. It exits with status 1 and leaves no files behind.
Postgres doesn't hide tables like this. A role that can't read a table
still sees it in the catalog, and its dump fails with
permission denied.
A user for restoring
ClickHouse. For a portable restore into a new database, grant on the target database only:
CREATE USER restorer IDENTIFIED BY '...';
GRANT CREATE DATABASE, CREATE TABLE, INSERT, SELECT ON shop_r.* TO restorer;$ dbdr restore -un=restorer -db=shop_r -s=p.dbschema -d=p.dbdata
...
done in 407msA same-engine restore from schema.sql creates objects with the names
stored in the file, so the grants must be on that database. Add
CREATE VIEW if the schema has views or materialized views. If a grant
is missing, ClickHouse's error names the exact privilege:
dbdr: s.sql: statement 1/6: code: 497, message: restorer: Not enough privileges.
To execute this query, it's necessary to have the grant CREATE DATABASE ON shopPostgres. A role that can create databases is enough. It owns what it creates, so it needs nothing else:
CREATE ROLE restorer LOGIN CREATEDB PASSWORD '...';$ dbdr restore -e=postgres -un=restorer -db=shop_from_ch -s=p.dbschema -d=p.dbdata
...
shop=# select pg_get_userbyid(datdba) from pg_database where datname = 'shop_from_ch';
restorerRestoring into an existing database owned by someone else needs the
usual CREATE on its schemas and INSERT on its tables. Avoid it if
you can. Restoring into a fresh database and then renaming it is easier
to reason about, and easier to undo.
Never use the same user for both
A dumping user that can also write is one typo away from a restore into the wrong place. Keep the two apart, store their passwords separately, and give the dumping user's password to the backup job only.
Exercises
Exercise 2-1. Create the dumper user on one of your ClickHouse
servers and dump as it. Then revoke its SELECT on one table, dump
again, and find the difference without reading the data.
Exercise 2-2. On Postgres 13 or older, pg_read_all_data doesn't
exist. Work out the grants a dumping role needs there: tables,
sequences, and future tables through ALTER DEFAULT PRIVILEGES.
Exercise 2-3. Write the restore grants for a ClickHouse schema that
includes a dictionary. Which privilege does CREATE DICTIONARY need?
3Protecting Dump Files
A dump file holds the same data as the database, without the database's
access controls. Anyone who can read the file can read every row. This
chapter is about protecting that data in the two places it is exposed:
on disk, and on the network between dbdr and the server.
Where it helps, the controls are tied to SOC 2 and FedRAMP (NIST
800-53). Those are the references to use when a policy decision needs a
defensible basis. dbdr alone doesn't make anything compliant. The
point is to show what the tool does by default, and what the
operator still has to provide.
What dbdr does and doesn't do
| Concern | What dbdr does | What you must do |
|---|---|---|
| Password on the command line | never accepted; read from DBDR_PASSWORD, a prompt, or stdin |
supply it from a secret store |
| File permissions | creates every file 0600, owner only, whatever the umask |
nothing; share a file deliberately if you must |
| Encryption in transit | TLS by default (--tls=verify-full), with the certificate verified, on every engine and command |
give it the CA (--tls-ca) if the server's certificate isn't publicly trusted |
| Plain text | only with --tls=disable, and with a warning every time |
never across a network you don't control |
| Encryption at rest | none; --compress doesn't encrypt |
encrypt the files or the volume |
| A failed dump | removes everything it created | check the exit status |
DROP statements |
never, unless --add-drop-statement |
leave it off |
Versions before v0.6.1 sent ClickHouse traffic in plain text, with the
password in an HTTP Basic auth header on every native data request.
They used Postgres's sslmode=prefer, which falls back to plain text
silently, and created files world-readable. Those were issues #6, #7
and #8. If you run an older version, upgrade, or apply the network
workarounds at the end of this chapter.
In transit
By default every connection is encrypted, and the server must present a certificate that chains to a trusted CA and names the host you connected to (FedRAMP SC-8, SC-8(1); SOC 2 CC6.7):
# A certificate from a public CA, or one your system already trusts
dbdr -db=shop -un=dumper -hn=ch.example.com --only=schema -o=schema.sql
# A certificate signed by an internal CA
dbdr -db=shop -un=dumper -hn=ch.internal --tls-ca=/etc/dbdr/ca.pem --only=schema -o=schema.sqlClickHouse must have its secure ports turned on: tcp_port_secure
(9440) for the native protocol, and https_port (8443) for native
data. Those are the defaults dbdr uses when TLS is on. A plain-only
server will refuse, with an error rather than a fallback:
dbdr: clickhouse: ping localhost:9440: dial tcp [::1]:9440: connect: connection refused
dbdr: clickhouse: ping localhost:19000: tls: first record does not look like a TLS handshakePostgres negotiates TLS on its usual port. Turn on ssl = on with a
certificate. To make plain connections impossible on the server side,
too, give the dumping and restoring roles hostssl lines in
pg_hba.conf, and hostnossl ... reject:
hostssl all dumper 10.0.0.0/8 scram-sha-256
hostnossl all dumper 0.0.0.0/0 rejectA server without TLS is now an error:
dbdr: postgres: connect to database "postgres": ...: tls error: server refused TLS connectionWhen verification fails, the message says why. These are from a test server with its own CA:
tls: failed to verify certificate: x509: "localhost" certificate is not trusted # no --tls-ca
tls: failed to verify certificate: x509: certificate signed by unknown authority # the wrong CA
tls: failed to verify certificate: x509: certificate is valid for localhost, not wrong.exampleDon't fix these with --tls=require. That mode encrypts but accepts any
certificate, so anyone in the path can pretend to be the server. Pass
the right CA, or --tls-server-name when you connect by a name the
certificate doesn't carry (an SSH tunnel to localhost, say).
--tls=disable sends the password and every row in plain text, and
says so:
warning: --tls=disable: the password and all data cross the network in plain textUse it only for a server on the same machine or in a test container.
At rest
Owner-only files. Every file dbdr writes is mode 0600, even if
it replaces an existing file that was more open:
$ dbdr -db=shop -un=dumper --only=schema -o=s.sql
$ ls -l s.sql
-rw------- s.sqlThe backup script in Chapter 7 still sets
umask 077, which covers the other files it creates: the manifest, the
log and the directories.
Encryption. dbdr writes plain files. Encrypt them once they are
complete. With age, using a public key so the backup host can't
decrypt what it wrote:
age -r "$BACKUP_RECIPIENT" -o data.zip.age data.zip && rm data.zipor put the backup directory on an encrypted volume. Keep the decryption key away from the machine that runs the backups (SC-28, CC6.1).
Integrity. Write a checksum manifest as each backup finishes and check it before restoring:
shasum -a 256 schema.sql data.zip > SHA256SUMS
shasum -a 256 -c SHA256SUMSA checksum proves the file hasn't changed since the backup. It doesn't prove the backup was right. That is what Chapter 6 is for.
Retention and disposal. Decide how long dumps are kept, delete them when that time is up, and include every copy: the backup volume, the laptop someone restored to, and the bucket someone uploaded to. Production data in a forgotten dump file is a common finding in audits.
Keep dumps out of source control. By default dbdr writes to the
current directory. The repository's own .gitignore excludes
*.sql, *.gz and *.zip for exactly this reason: real dump files
were once found sitting in a working copy, one git add -A away from a
commit.
Passwords
- Never put the password on a command line.
dbdrcan't accept one there anyway, but a wrapper script could still leak it, for example asDBDR_PASSWORD=... dbdrin a crontab, which other users can read. - Read it from a file or a secret store at run time. Mount the secret
in Kubernetes. On a plain host, keep a file with mode
0600owned by the backup user. - An environment variable is visible to the same user, and to root,
through
/proc/<pid>/environon Linux. That's acceptable for a dedicated backup user, and another reason not to run backups as a shared account. - Use different passwords for the dumping and restoring users (Chapter 2), and rotate them on the same schedule as your other service credentials.
Older versions, and defence in depth
TLS from dbdr protects the connection it makes. You may still want
the network around it to protect against mistakes, or need it when an
older version is all you can run:
- Run
dbdron the database host, or on a host on the same private segment, and move only the finished, encrypted files. - Tunnel. Forward the ports over SSH and connect to
localhost. With TLS on, keep verifying, and use--tls-server-nameto check the certificate against the server's real name:bashssh -N -L 9440:localhost:9440 -L 8443:localhost:8443 db-host & dbdr -db=shop -un=dumper -hn=localhost --tls-server-name=ch.internal \ --tls-ca=/etc/dbdr/ca.pem --only=data -fmt=native -o=data.zip
Exercises
Exercise 3-1. Run a native ClickHouse dump with --tls=disable
while capturing the traffic with tcpdump -A -i lo port 8123. Find the
Authorization: header and decode it. Repeat it with TLS on port 8443,
and check that the capture shows nothing readable.
Exercise 3-2. Give the dumper role hostssl and
hostnossl ... reject lines in a Postgres pg_hba.conf. Confirm that
dbdr works by default and that --tls=disable is now refused by the
server itself.
Exercise 3-3. Write the retention rule for your organization's
backups as one sentence, then as a find command. Which copies would
the command miss?
4Big Tables
Small databases need no tuning. On big ones, three settings matter:
--fetch-batch-size, --fetch-retries and --split-insert-size. A
fourth thing, the table's sort key, isn't a setting at all, but it
decides how well the other three work.
How a big table is read
dbdr never reads a large table in a single query. A query held open
for hours is exactly what a busy server stalls, and one stall would
cost the whole table. Instead:
| Format | How a table is cut | Cut on |
|---|---|---|
sql (ClickHouse) |
pages of --fetch-batch-size rows, each continuing after the last row of the one before |
the whole sort key |
native |
about rows / --fetch-batch-size ranges, at most 256, worked out before reading |
the first sort-key column |
portable |
the same ranges, for tables over --fetch-batch-size rows |
the first sort-key column |
Postgres native / portable |
the same ranges | the first primary-key column, using pg_stats where it can |
A table with no sort key (ORDER BY tuple(), or a Log engine) is read
in one query. So is one whose first key column has a type ClickHouse's
quantiles() can't handle, such as String or Date32:
shop_dates.events32: computing 1 range boundaries on d... unsupported key type, falling back to a single unchunked fetchThat is always correct, but it gives up the protection. If a very large table shows this line, it is worth knowing why. See "Choosing a sort key" below.
--fetch-batch-size
The default is 100,000 rows. Each piece or range is held in memory in full before it is written, which is what makes a retry clean. So the batch size controls two things:
- Memory. Roughly the batch size times your average row size, for each table being dumped. A table with wide rows (large JSON or text columns) at 100,000 rows can need hundreds of megabytes.
- What a failure costs. A failed piece is fetched again. Smaller pieces mean less repeated work, but more queries.
Reasonable starting points:
| Situation | Try |
|---|---|
| Narrow rows, a healthy network | the default, 100000 |
Wide rows, or a small machine running dbdr |
10000 to 20000 |
| A flaky link, where failures are expected | smaller, plus more retries |
For native and portable dumps the batch size also decides the number of
ranges, rows / batch, capped at 256. On a table of a billion rows,
the cap is what applies, and each range is about four million rows.
--fetch-retries
The default is 5. Each retry waits longer, 1 s, 2 s, 4 s and so on up
to 30 s, and reconnects first. Only network errors are retried:
timeouts, resets, refused or closed connections, and unexpected EOF.
A permission error or a bad query fails at once, because it would only
fail the same way again. --fetch-retries=0 turns retries off, which
is useful when you would rather see the first failure than wait.
--split-insert-size
This applies to SQL dumps only. It sets how many rows go into each
INSERT. Leave it unset and every row is its own statement. That's
fine for reading, but terrible to replay into ClickHouse. Use thousands
or tens of thousands.
Choosing a sort key
You rarely choose a sort key for dbdr's sake. But when a table falls
back to a single query, it helps to know why:
- Date first. Sort keys such as
(event_date, id)split well and are the most common ClickHouse design. (Versions before the fix for issue #1 failed on them. Make sure yours has it.) - Numbers first. These split well. A column with only a few distinct values, such as a status with four values, gives only a few distinct ranges, so splitting is coarse but still correct.
StringorDate32first. These fall back to one query, as above.
Restore speed
On restore, a native ClickHouse archive is posted to the server as it
is, a Postgres native archive is streamed through COPY, and portable
data is loaded in batches of 100,000 rows into ClickHouse or streamed
through COPY into Postgres. The server's own write speed is usually
the limit, not dbdr. A few things that help:
- Restore into a fresh database with nothing else writing to it.
- On ClickHouse, check that the destination has enough free disk for the merges a large insert triggers.
- On Postgres, a database restored with
COPYis worth anANALYZEbefore it takes traffic.dbdrdoesn't run one.
Exercises
Exercise 4-1. Dump your largest table with --fetch-batch-size
set to 10,000, then 100,000, then 1,000,000. Record the time taken and
the peak memory (/usr/bin/time -l on macOS, -v on Linux).
Exercise 4-2. Find every table in one of your ClickHouse databases
whose first sort-key column has a type quantiles() can't handle.
(Hint: system.tables.sorting_key and system.columns.type.)
Exercise 4-3. Run a native dump while restarting the ClickHouse
server partway through. With the default retries, does the dump
survive? With --fetch-retries=0?
5When a Dump Fails
Every dump fails sooner or later. This chapter is about what a failure looks like, what it leaves behind (nothing), and what the common error messages mean.
The rules
- The exit status tells you. It is
0for success and1for any failure, with one line startingdbdr:on standard error. Check the status, not whether a file exists. - A failed dump leaves no files. Every file the failed run created is removed, whatever the format. A truncated archive that looks complete is worse than none, because a later restore would load it without complaint.
- Earlier databases are kept. When several databases are dumped and one fails, the files of the databases that finished before it stay. They are complete.
- Progress goes to standard error. Lines such as
shop.orders: range 1/2... done in 18msshow how far a run got. Keep them with2>dump.log.
This was tested with a user who could see a table but not read it, in every output mode:
== portable, large tables split: exit=1 left: []
== portable, grouped: exit=1 left: []
== sql: exit=1 left: []
== sql, gzip: exit=1 left: []
== native: exit=1 left: []In the first two runs, one table had already been written in full before the failure. Its file was removed as well.
Reading the error
The line after dbdr: names the stage that failed. The same stages
appear on both engines:
| Message starts with | Stage | Usual cause |
|---|---|---|
clickhouse: ping host:port or postgres: connect to database |
connecting | the wrong host, port or password, or a missing database |
--format=... requires ..., invalid --only |
parsing flags | a flag combination that isn't allowed |
count rows for, fetch range, fetch data |
reading rows | privileges, or the network during the dump |
<file>: statement N/M |
restore, schema | an object already exists, or a privilege is missing |
load <db>.<table> |
restore, data | a type mismatch or the network |
Common messages
These are real messages, from the scratch servers used to write this book, with their port numbers changed to the defaults (those servers listened on non-standard ports).
Wrong password (ClickHouse):
dbdr: clickhouse: ping localhost:9440: code: 516, message: default: Authentication
failed: password is incorrect, or there is no user with such nameWrong password (Postgres). The real reason is on the last line, so read to the end:
dbdr: postgres: connect to database "shop": failed to connect to `user=postgres database=shop`:
[::1]:5432 (localhost): dial error: dial tcp [::1]:5432: connect: connection refused
127.0.0.1:5432 (localhost): failed SASL auth: FATAL: password authentication failed for user "postgres" (SQLSTATE 28P01)The [::1] line is the driver trying IPv6 first, on a server that only
listens on IPv4. It isn't the problem.
TLS problems have their own messages. The common ones, with their
causes, are listed in Chapter 3: an
untrusted certificate (--tls-ca is missing or wrong), a name mismatch
(--tls-server-name), and server refused TLS connection or
first record does not look like a TLS handshake (the server or port
doesn't speak TLS).
Nothing listening:
dbdr: clickhouse: ping localhost:19999: dial tcp [::1]:19999: connect: connection refusedNo such host:
dbdr: clickhouse: ping no-such-host.invalid:9440: dial tcp: lookup no-such-host.invalid: no such hostNo such database:
dbdr: clickhouse: ping localhost:9440: code: 81, message: Database nosuch does not exist
...: server error: FATAL: database "nosuch" does not exist (SQLSTATE 3D000)A native dump that can't reach the HTTPS port. Introspection uses
the native port, and data uses --http-port, so this fails only once
it starts reading data:
dbdr: database "shop": shop.orders: fetch range (attempt 2/2): Post
"https://localhost:8443/?database=shop": dial tcp [::1]:8443: connect: connection refusedOpen port 8443 (or the one you set) between dbdr and the server, or
tunnel it as well. With --tls=disable the URL is http:// on 8123.
Native without --only=data:
dbdr: --format=native requires --only=data (Native-format files carry data only,
no schema; pair with a separate --only=schema SQL dump)Postgres SQL data:
dbdr: postgres: --format=sql data dump is not implemented yet; use --format=native
(paired with --schema-only) insteadRestoring over an existing object:
dbdr: s.sql: statement 2/6: code: 57, message: Table shop.daily_units already existsThis is deliberate. Without --add-drop-statement, a schema never
replaces what is already there. Restore into a fresh database, or drop
the old one yourself, on purpose.
No password available. With no DBDR_PASSWORD, and standard input
neither a terminal nor a pipe with a line in it, dbdr tries an empty
password, and the server's error says the login failed. Set the
variable in scheduled jobs.
Retrying
- A network failure during reading is already retried by
dbdr(Chapter 4). If it still fails, run the dump again. Nothing from the failed run remains to clean up. - A failure before reading (connecting, flags, privileges) won't go away by trying again. Fix the cause.
- A restore that failed partway has already written some objects and rows. Drop the destination database and restore again. Don't try to carry on from where it stopped.
Exercises
Exercise 5-1. Make each of the failures above happen on purpose, on a test server. Write down the first line of each message next to its cause, as a crib sheet for whoever is on call.
Exercise 5-2. Kill dbdr with SIGKILL in the middle of a native
dump. What does it leave behind, and why is this the one failure the
cleanup in this chapter can't handle? (Chapter 7's backup script has an
answer.)
Exercise 5-3. A restore failed at statement 4 of 6. Write the commands that put the destination back to how it was before the restore.
6Proving a Restore
A restore that finished without an error has proved one thing: nothing failed loudly. It hasn't proved the copy is right. This chapter is about how to prove that, and why counting rows isn't enough.
Counting rows isn't enough
Here is a ClickHouse table copied into Postgres with the portable format, then checked the way most people check: rows and a sum.
source (ClickHouse) copy (Postgres)
rows 250000 250000
sum_qty 1749985 1749985Both match. Now the rest of the column profile:
source (ClickHouse) copy (Postgres)
null_customer 35715 35715
sum_product 625000 625000
min_id 1 1
max_id 250000 250000
min_date 2026-01-01 2025-12-31 ← wrong
max_date 2026-09-07 2026-09-06 ← wrong
distinct_cust 500 500
customer_chars 809999 809999Every date in the copy is a day early. This was issue #5: before v0.5.1, portable dumps from a ClickHouse server whose timezone is ahead of UTC shifted dates back by one day. It was found exactly this way, with this profile, after counts and sums had already said the copy was fine. Only checking the date column itself shows a bug like this, and the next one will be just as quiet.
So the rule is: check every column, with a check that suits its type.
A column profile
For each column, compute a small set of aggregates on both sides and compare them:
| Column type | Compare |
|---|---|
| any | count(*), number of NULLs |
| integer, decimal | sum, min, max |
| float | min, max, and sum with a tolerance |
| date, time | min, max, and the count of distinct values |
| text | the count of distinct values, sum(length(...)) |
| key columns | min, max, and the count of distinct values (equal to the row count for a unique key) |
These are the queries behind the table above. The same profile is written once per engine:
-- ClickHouse
SELECT count() AS rows,
countIf(customer IS NULL) AS null_customer,
sum(qty) AS sum_qty,
sum(product_id) AS sum_product,
min(id), max(id),
min(order_date), max(order_date),
uniqExact(customer) AS distinct_customer,
sum(length(customer)) AS customer_chars
FROM shop.orders;
-- Postgres
SELECT count(*),
count(*) FILTER (WHERE customer IS NULL),
sum(qty),
sum(product_id),
min(id), max(id),
min(order_date), max(order_date),
count(DISTINCT customer),
sum(length(customer))
FROM orders;A profile is cheap: one scan of each table, on each side. It works across engines, because it compares values, not bytes. And it fails when one value in one column is wrong in a way that shifts an aggregate. It isn't a proof that every row is identical. For that you need a checksum.
Checksums, for copies within one engine
When the source and the copy are on the same engine, compare an order-independent hash of every row:
SELECT 'source', count(), sum(cityHash64(*)) FROM shop.orders
UNION ALL
SELECT 'copy', count(), sum(cityHash64(*)) FROM shop_r.orders;source 250000 7262196896336314414
copy 250000 2097887919754310651The hashes differ, so the copies differ. To see which rows differ, when both are on one server or you can join across them:
SELECT id, order_date FROM shop.orders
EXCEPT
SELECT id, order_date FROM shop_r.orders
ORDER BY id LIMIT 3;1 2026-01-01
2 2026-01-01
3 2026-01-01On Postgres, the same idea is
SELECT sum(hashtext(t::text)::bigint) FROM orders t. This only works
between two Postgres databases, because the text form of a row is
specific to each engine.
A same-engine native restore should always produce identical checksums, because native data is copied as raw bytes. If it doesn't, something is wrong.
What to check after every restore
- The exit status of the restore:
0. - The object count: tables, views, and materialized views, against the source. (Remember what each format leaves out: Chapter 1.)
- The row count of every table.
- A column profile of every table, or at least of the large and important ones.
- A checksum for same-engine copies.
- Sequences on Postgres: an
INSERTthat uses each sequence should get the next id, not collide with a restored row. - Materialized views: their totals against the source. ClickHouse rebuilds them by trigger, and Postgres refreshes them after loading.
Write these down once, as a script, and run it after every restore. Then a restore that "finished" can't quietly become the copy everyone relies on.
Exercises
Exercise 6-1. Write a program that generates both profile queries,
ClickHouse and Postgres, for any table, from its column list in
system.columns or information_schema.columns.
Exercise 6-2. Restore shop from ClickHouse into Postgres on a
ClickHouse server set to Asia/Kolkata, then again on one set to UTC.
Profile both copies, first with a version before v0.5.1 and then with a
current one. Which checks catch issue #5, and which ones don't?
Exercise 6-3. Prove a same-engine native restore of one of your own
databases with checksums. How long does sum(cityHash64(*)) take on
your largest table, compared with the dump itself?
7Running Unattended
A backup that someone has to remember to run isn't a backup. This
chapter turns everything in the earlier chapters into a job that runs
on a schedule and stops loudly when it fails. The script is
dbdr-backup.sh, next to this chapter. Copy it and
change the settings at the top.
What the script does
graph TD
L{"lock free?"} -->|no| X["exit 75"]
L -->|yes| P["mkdir NAME-STAMP.partial"]
P --> S["schema dump"]
S --> D["native data dump"]
D --> C["SHA256SUMS"]
C --> M["rename to NAME-STAMP"]
M --> R["delete backups older than KEEP_DAYS"]
S -->|fails| F["exit 1; .partial kept, with its log"]
D -->|fails| FOnly a complete backup gets its final name. Old backups are deleted only after a new one has succeeded.
Each design choice is there for a reason from an earlier chapter:
| Line | Why |
|---|---|
set -euo pipefail |
any failure stops the run with a nonzero status |
umask 077 |
owner-only files (Chapter 3) |
DBDR_PASSWORD_FILE |
the password comes from a secret file, never the command line or the crontab |
TLS_MODE, TLS_CA |
TLS with certificate verification by default; TLS_CA for an internal CA (Chapter 3) |
mkdir "$lock" |
two runs never write to the same place; mkdir is atomic, and works on macOS, where flock isn't installed |
$out.partial, then mv |
a directory without .partial is always complete; a SIGKILL can only ever leave a .partial behind |
SHA256SUMS |
the files can be checked before a restore |
| retention last | a failing run never deletes the last good backups |
exit 75 when locked |
"temporary failure", so a scheduler can tell it apart from a real error |
Running it
$ DB_NAME=shop BACKUP_ROOT=/var/backups/dbdr DBDR_PASSWORD_FILE=/run/secrets/dumper \
TLS_CA=/etc/dbdr/ca.pem ./dbdr-backup.sh
2026-11-28T12:50:04Z dumping clickhouse database shop from localhost into /var/backups/dbdr/shop-20261128T125004Z
2026-11-28T12:50:05Z ok: 372K in /var/backups/dbdr/shop-20261128T125004Z
$ ls -l /var/backups/dbdr/shop-20261128T125004Z
-rw------- SHA256SUMS
-rw------- data.zip
-rw------- dbdr.log
-rw------- schema.sql
$ (cd /var/backups/dbdr/shop-20261128T125004Z && shasum -a 256 -c SHA256SUMS)
schema.sql: OK
data.zip: OKFor Postgres, set ENGINE=postgres. The same script, with the same
settings otherwise, was tested over verified TLS against both engines,
with a ClickHouse server on its secure ports and a Postgres role
allowed only hostssl connections.
When the password is wrong:
2026-11-28T12:50:17Z dumping clickhouse database shop from localhost into .../shop-20261128T125017Z
$ echo $?
1
$ ls /var/backups/dbdr
shop-20261128T125004Z
shop-20261128T125017Z.partial
$ tail -1 /var/backups/dbdr/shop-20261128T125017Z.partial/dbdr.log
dbdr: clickhouse: ping localhost:9000: code: 516, message: dumper: Authentication failed: ...The good backup is untouched. The failed one is clearly marked, and
its log says why it failed. Delete .partial directories once you have
read them. The script leaves them alone on purpose.
Scheduling
cron. Put the settings in a file only the backup user can read, never in the crontab line itself:
# m h dom mon dow command
15 2 * * * . /etc/dbdr/shop.env && /usr/local/bin/dbdr-backup.sh >>/var/log/dbdr/shop.log 2>&1systemd. A service unit plus a timer. OnFailure= gives you
alerting for free:
# /etc/systemd/system/dbdr-shop.service
[Unit]
OnFailure=notify-oncall@%n.service
[Service]
Type=oneshot
User=dbdr
EnvironmentFile=/etc/dbdr/shop.env
ExecStart=/usr/local/bin/dbdr-backup.sh
SuccessExitStatus=75
# /etc/systemd/system/dbdr-shop.timer
[Timer]
OnCalendar=*-*-* 02:15:00
Persistent=true
[Install]
WantedBy=timers.targetKubernetes. A CronJob with concurrencyPolicy: Forbid, the
password mounted from a Secret as a file, and DBDR_PASSWORD_FILE
pointing at it. Write to a volume that outlives the pod, and give the
job's failure an alert like any other.
Alerting
Alert on these three things, and nothing else:
- The job exited nonzero. Any status other than 0 or 75.
- No new complete backup for longer than the interval. This catches the job that silently stopped running, which an exit-status alert never sees.
- The backup shrank sharply compared with the previous one. This catches the missing-privilege trap in Chapter 2, where a dump succeeds without some of its tables.
Test the restore, not just the backup
On a schedule, at least monthly, restore the latest backup into a scratch server and run the checks from Chapter 6. A backup that has never been restored is a hope, not a backup. Record the date and result of each test. An auditor will ask (SOC 2 A1.2, FedRAMP CP-4 and CP-9).
Exercises
Exercise 7-1. Extend the script to encrypt data.zip and
schema.sql with age before SHA256SUMS is written. Should the
checksums cover the encrypted or the plain files?
Exercise 7-2. Add the "backup shrank" check from the alerting
section to the script itself: compare the new data.zip with the last
complete backup, and exit with a distinct status if it is under half
the size.
Exercise 7-3. Write the monthly restore test as a second script that picks the newest complete backup, restores it into a scratch database, profiles one table, and drops the database again.
8Moving Between Engines
The portable format is what lets dbdr move a database from ClickHouse
to Postgres or back. The move itself is two commands. Doing it safely
takes a plan, because the two engines don't mean the same things by
their schemas. This chapter is that plan.
Before you start
Read the source schema and answer four questions:
Which objects won't come across? Views, materialized views, sequences, constraints other than the sort key, and most defaults (Chapter 1). Make a list, and decide how each will be recreated.
Which types will change? Look them up in the mapping table in Volume I, Appendix A.11. The ones to watch:
From To What changes ClickHouse UInt64Postgres numeric(20,0)arithmetic is slower; the type comes back as UInt64on a later dump, through the origin markerClickHouse UInt32Postgres bigintwider ClickHouse Enum8/16textthe labels survive, the codes and the allowed-value check don't ClickHouse IPv4/6,JSONtext, thenStringon the way backthe value survives, the type doesn't Postgres numericwith no precisionfloat(64-bit)precision can be lost Postgres json/jsonb,inetClickHouse Stringthe value survives, the type doesn't Postgres timestamptzClickHouse DateTimethe instant is kept; it's displayed in the server's timezone Postgres serialdefaultnone nextval(...)is dropped with a warninganything unrecognized stringwith a warning; read the warnings Was a portable file written by a version older than v0.5.1, from a ClickHouse server east of UTC? Those versions shifted every
Dateback one day (issue #5, fixed in v0.5.1). New dumps are correct on any server timezone, but an old.dbdatafile still holds the shifted dates, and nothing in the file says so. CheckSELECT timezone()on the source. If it is east of UTC, dump again with a current version rather than restoring an old file, and check every date column afterwards (Chapter 6).What will the destination's sort key or index be? From ClickHouse, the
ORDER BYbecomes a plain index on Postgres, never a primary key, because ClickHouse doesn't guarantee uniqueness. From Postgres, the primary key becomes ClickHouse'sORDER BY. A Postgres table with no primary key getsORDER BYits first column, which is rarely what you want. Decide beforehand.
The move
# 1. Dump, as the read-only user
dbdr -db=shop -un=dumper --only=schema -fmt=portable -o=shop.dbschema
dbdr -db=shop -un=dumper --only=data -fmt=portable -o=shop.dbdata
# 2. Read the warnings in what was printed, and the schema you're about to apply
jq '.Tables[] | {Name, OrderKey, cols: [.Columns[] | "\(.Name):\(.Type.Kind)"]}' shop.dbschema
# 3. Restore, as the restoring user, into a fresh database
dbdr restore -e=postgres -un=restorer -db=shop_new -s=shop.dbschema -d=shop.dbdata
# 4. Recreate what the portable format doesn't carry (views, constraints, sequences)
psql -d shop_new -f post-restore.sql
# 5. Prove it (Chapter 6), then switch trafficStep 2 is where you can still change your mind cheaply. The .dbschema
file is plain JSON. You can edit a type or a key there before
restoring, but if you do, keep the edit in version control next to the
post-restore.sql, so the move can be repeated.
After the move
- Postgres destination: run
ANALYZE, recreate foreign keys and unique constraints, and if ids will keep growing, create sequences andsetvalthem past the restored maximum. The portable format restores rows, not sequences. - ClickHouse destination: check every table's
ORDER BYwithSHOW CREATE TABLE, and look forSETTINGS allow_nullable_key = 1, whichdbdradds when a key column had to become nullable. Such a key works, but it usually means a default was dropped and the column should be fixed. - Both: keep the
.dbschemaand.dbdatafiles, encrypted (Chapter 3), until the old database is retired. They are your way back.
Round trips
A table that goes ClickHouse → Postgres → ClickHouse comes back with
its original types, thanks to the origin markers dbdr writes into
column comments: dbdr:origin={"Kind":"uint","Width":64}. Don't strip
those comments from the intermediate database if you might ever move
back. They are also harmless to leave in place for good.
Exercises
Exercise 8-1. Plan the move of one real database from one engine to
the other. Write the four answers from "Before you start" and the
post-restore.sql, without running anything.
Exercise 8-2. Move shop from Postgres to ClickHouse. Which
warnings does dbdr print, and what does the ClickHouse orders table
use as its ORDER BY?
Exercise 8-3. Take shop from ClickHouse to Postgres and back to
ClickHouse. Compare the final SHOW CREATE TABLE shop.orders with the
original, and explain every difference.
CRunbooks
Short checklists for the jobs in this volume, for printing or pasting into a ticket. Each step points to the chapter that explains it.
C.1 Set up backups for a new database
- [ ] Create a read-only dumping user:
GRANT SELECT ON <db>.*on ClickHouse, orpg_read_all_dataon Postgres. (Ch. 2) - [ ] Store its password as a file with mode
0600, or as a mounted secret. (Ch. 3) - [ ] TLS on the server: ClickHouse
tcp_port_secureandhttps_port, Postgresssl = onplushostssl-only lines for the role. Get the CA file. Never use--tls=disableacross a network you don't control. (Ch. 3) - [ ] Copy
dbdr-backup.sh, setDB_NAME,BACKUP_ROOT,KEEP_DAYS,DBDR_PASSWORD_FILEand, for an internal CA,TLS_CA. (Ch. 7) - [ ] Put the backup directory on an encrypted volume, or add encryption to the script. (Ch. 3)
- [ ] Schedule it with a timer or CronJob that doesn't allow overlapping runs. (Ch. 7)
- [ ] Alert on a nonzero exit, a missing backup, and a sharp drop in size. (Ch. 7)
- [ ] Restore the first backup into a scratch server and run the checks in C.3. (Ch. 6)
C.2 Restore from a backup
- [ ] Check the files:
shasum -a 256 -c SHA256SUMS. (Ch. 3) - [ ] Choose a fresh destination database. Never restore over live data. (Ch. 5)
- [ ] Use the restoring user, not the dumping one. (Ch. 2)
- [ ]
dbdr restore -e=<engine> -un=restorer -s=schema.sql -d=data.zip - [ ] Exit status
0? If not, drop the destination and start again. Don't try to continue. (Ch. 5) - [ ] Run C.3.
- [ ] Postgres:
ANALYZEbefore the database takes traffic. (Ch. 4)
C.3 Prove a copy
- [ ] Object count against the source, allowing for what the format leaves out. (Ch. 1, Ch. 6)
- [ ] Row count of every table.
- [ ] A column profile of every important table: NULLs, sums, min and max, distinct counts, text lengths, and every date column. (Ch. 6)
- [ ] Same engine:
sum(cityHash64(*))(ClickHouse) orsum(hashtext(t::text)::bigint)(Postgres) on both sides. (Ch. 6) - [ ] Postgres: one
INSERTper sequence gets the next id. (Ch. 6) - [ ] Materialized views: totals match the source. (Ch. 6)
- [ ] Record the date, the backup and the result.
C.4 Move between engines
- [ ] List what the portable format won't carry, and write the
post-restore.sqlthat recreates it. (Ch. 8) - [ ] Review the type changes for each table. (Ch. 8)
- [ ] Use a current version (v0.5.1 or later). Don't restore old portable files from a ClickHouse server east of UTC; dump them again instead (issue #5). (Ch. 8)
- [ ] Decide each destination's sort key or index. (Ch. 8)
- [ ] Dump the schema and data as portable; read every warning.
- [ ] Restore into a fresh database; apply
post-restore.sql. - [ ] Run C.3, using profiles, since checksums don't work across engines.
- [ ] Keep the encrypted portable files until the old database is retired. (Ch. 8)
C.5 A dump failed
- [ ] Read the
dbdr:line, and the stage it names. (Ch. 5) - [ ] Connecting or flags: fix the cause. Retrying won't help.
- [ ] Reading rows, from the network: run it again. Nothing from the failed run is left to clean up. (Ch. 5)
- [ ] Privileges: grant on the whole database, not the table. (Ch. 2)
- [ ] From the backup script: read
.partial/dbdr.log, then delete the.partialdirectory. (Ch. 7)