Relational databases: collection tree

Relational databases

Backup, restore and reconciliation

Deep diveAbout 12 minutes AI-generated

A backup preserves material from which a database can be recovered after its live history is lost or becomes unwanted. A restore uses that material to build a usable database. The useful promise is a state you can recover, within the time the service can afford to be unavailable.

Start with a separate recovery branch of the shop example. Order 103 already exists: one blue mug, P7, at an agreed 20.00 and two packets of tea at 4.50 each, total 29.00. The order is pending and has no payment. Then a mistaken transaction sets P7’s catalogue price to 2.20. Later, a valid partial payment records 10.00 against order 103 as payment 504. A payment provider has already accepted the corresponding charge.

Restoring a database from before the price mistake can bring back 20.00. It also removes the later payment record. The provider’s charge remains. This article follows that recovery through three questions: which history can be restored, where to stop, and how to account for the work left outside that point. The worked history establishes that ordering without claiming measured commit times or log positions.

Choosing recovery from the loss

Restart recovery should keep the committed 2.20, just as it would keep a correct change. A replica can faithfully copy it too. Durability and replication preserve database history; they do not decide whether the shop intended a price. Storage and durability establishes that boundary.

If only the current catalogue price is wrong and the rest of the history is sound, correcting it in the current database may be enough. Keep the evidence and any dependent business adjustments, as History, correction and deletion explains. Restoring the whole database is a wider action: it replaces sound facts alongside the unwanted ones. Recovering a separate copy to inspect or extract the earlier price may avoid that replacement.

Lost storage needs a surviving copy. An existing live copy may be suitable for a transfer of service, covered by Failover and fencing. A backup gives another route, including earlier states that a live replica has already passed. Choose the route by what was lost and what must be recovered.

Recovery point and recovery time

A recovery point objective, or RPO, states how much recent work the service can afford to lose, commonly expressed as a time window. An RPO of five minutes requires a recoverable point no more than five minutes behind the relevant loss boundary. “We run a backup every five minutes” does not establish that coverage: the latest job might be incomplete or inaccessible.

A recovery time objective, or RTO, states how long the service can afford to be interrupted. Count obtaining recovery access and material, restoring and replaying, checking the result, reconciling necessary work and returning callers to service. Starting the database is one stage. A shop that can display orders while payments remain suspended has recovered a different level of service from one accepting purchases.

These are objectives to design and test against, not properties conferred by naming them. An unwanted change may force an older restore than a storage failure would. Record the chosen point and the omitted operations as well as the time gap; later reconciliation may recover some of that work.

A backup and the history it needs

A backup job can succeed while the recovery path you need is incomplete. Some methods restore a complete saved state. Others require an earlier copy and later material that depends on it. Point-in-time recovery needs enough retained history to reach the selected point.

Consider a PostgreSQL-style recovery path: a base backup, the WAL needed to make it consistent, then three successive intervals of later write-ahead log. Call them A, B and C. They include the purchase of order 103, the mistaken price change and the later payment, in that order. Each interval extends the history established by the preceding material.

Later files cannot bridge a gap
Figure 1. Symbolic dependencies, not actual filenames or log positions.
Figure as text

A base backup and its consistency WAL lead through required history A, B and C. Missing B stops this path at A even when C’s files remain. A complete different backup path might reach later.

If B is missing, retaining C’s files does not make C recoverable through this path: replay cannot cross the missing history. Taking more backups does not repair that particular chain. Another complete starting copy and its dependencies might provide a different path. Retention must preserve at least one complete path for every point you promise to recover.

Logical and physical backups

A logical backup exports data and object definitions for reconstruction: rows, tables and the other objects selected by the tool. A physical backup preserves the engine’s stored representation through a supported backup procedure. The choice depends on the recovery task, object scope, compatibility and restoration work.

A PostgreSQL dump can be useful for restoring selected objects or moving to a compatible newer version. It cannot be advanced using WAL. PostgreSQL physical archive recovery restores a whole database cluster; taking an arbitrary copy of live data files is not a supported substitute for its backup protocol. A supported consistent filesystem snapshot is another method with its own requirements. The SQL dump and filesystem backup documentation explain those distinctions.

Check what the selected scope actually includes. A table export may omit its dependencies. PostgreSQL’s single-database dump does not include cluster-wide role definitions. A database that restores correctly can still need compatible extensions, software, configuration and access arrangements before its application can use it.

Full backups, increments and retained history

Full and incremental describe a separate choice. A full backup supplies the complete data for its defined scope. An incremental backup saves changes relative to earlier backups. Restoring it requires the dependencies specified by that method, which may include several increments and a full backup. Physical methods can be incremental too: PostgreSQL’s pg_combinebackup reconstructs a full backup from such a chain.

More frequent full backups can trade extra copying and storage for less reconstruction or replay. Increments can reduce what each backup copies while increasing the material a restore must obtain. Neither frequency nor the word “incremental” promises arbitrary stopping points. CockroachDB, for example, needs captured revision history to restore arbitrary points within that history, rather than only the available backup points. CockroachDB backup and recovery develops its coverage and scope.

Keeping recovery material usable

Test the failure against the backup as well as the live database. A second file on the lost disk is lost too. A backup account controlled by the same compromised credentials may allow the same deletion. Choose separate failure boundaries and restrictions appropriate to the loss you intend to survive.

Keep an inventory of backup identity, source, dependencies, supported restore points, compatible software and the access and decryption material needed to recover. Test that those materials can be obtained when normal service access is unavailable. Encryption protects a backup only while its key remains controlled; losing the key can also make the backup unusable.

Expire material by the recovery coverage it supports. An old full backup may still be the root of a retained incremental chain. Removing it because of its age can invalidate newer files. When replacing a path, establish and test its replacement before relying on the resulting retention window.

Choosing the restore target

The latest available point and the desired point answer different questions. After storage loss, the latest sound recoverable state may be the aim. After the price mistake, replaying through all available history would faithfully bring back 2.20.

A target before the mistake restores P7 at 20.00, with order 103 retained but no payment 504. A target through the mistake restores 2.20. Extending that same history through payment 504 restores the payment as well, without undoing the earlier price change.

A restore chooses a prefix of history
Figure 2. Order 103’s agreed £29 total is unchanged by the catalogue price.
Figure as text

Order 103 commits, then a catalogue price mistake, then payment 504. Restoring before the mistake also omits the payment. Restoring through the payment retains the mistake. The external provider still has the accepted £10 charge.

Stopping before the mistake also stops before payment 504. Reaching the payment includes the earlier mistake. Recovery selects a supported state of the chosen history; it does not provide a general instruction to replay everything except one transaction. The later payment needs a separate reconciliation if we choose the earlier state.

Finding the boundary

Identify the unwanted committed change from evidence. The time someone noticed 2.20 is later than its arrival. An application’s updated_at may be assigned before commit, overwritten by later work or taken from a different clock. Neither alone establishes the correct recovery boundary.

Use the engine’s supported target mechanism and establish whether the boundary includes the unwanted commit. Check the recovered facts to confirm the result. PostgreSQL supports several target forms and an inclusive or exclusive boundary for some of them; its transaction identifiers are assigned before completion and need not finish in numerical order. Native target syntax, timeline selection and the actual restore drill belong in Restoring PostgreSQL to a recovery target.

Record the source history and object scope alongside the target. The same time applied to a different source or branch is not the same recovered state. Preserve the original material for investigation and repeat attempts. Work from copies rather than modifying the only remaining evidence.

Proving a restore works

Restore into an isolated destination first. Keep ordinary writers, payment workers, email senders and other external dispatch disabled. A restored outbox can contain work whose effect already happened. Letting workers poll it during a test can turn a rehearsal into a second delivery.

What each check establishes
CheckEvidence to keepStill unproved
Material integrityRequired files and dependencies; applicable checksum and manifest resultsThat the engine can recover the intended state
Engine recoverySuccessful restore/replay and its reported source and stopping pointThat this is the state the shop wanted
Recovered factsExpected orders, agreements, stock, payments and exceptionsThat the application can use them correctly
Service recoveryPermissions, application reads and controlled readiness checksThat omitted work and external outcomes are all accounted for

These checks build on one another. PostgreSQL’s pg_verifybackup explicitly leaves test restores and checking the resulting data necessary. A green backup job and a server accepting connections are useful observations, but neither proves the shop is ready.

Check the recovered facts

For the cut before the mistake, expect P7 at 20.00, pending order 103 and agreed line total 29.00, with no payment for that order. Stock stays P3 10, P7 0, P9 4: the original purchase is already included. Check the expected presence or absence of payment 504 for the selected target.

SELECT
  (SELECT price FROM products
   WHERE product_id = 'P7') AS p7_price,
  o.status,
  (SELECT sum(quantity * unit_price)
   FROM order_items WHERE order_id = o.order_id) AS line_total,
  (SELECT coalesce(sum(amount), 0)::numeric(8,2)
   FROM payments WHERE order_id = o.order_id) AS paid
FROM orders o
WHERE o.order_id = 103;
-- Before the mistake: 20.00 | pending | 29.00 | 0.00
-- After reconciliation: 20.00 | pending | 29.00 | 10.00

The query keeps the line sum and payment sum separate, so joining several payments cannot multiply order lines. Also inspect representative other orders, constraints and application permissions. Exercise an application read under the intended runtime identity with external dispatch still disabled.

Measure the whole path

Rehearse with representative data size, retained history and recovery access. Keep the achieved point and elapsed stages: access, transfer, reconstruction/replay, validation, necessary reconciliation and return to service. Record unfinished work and any restricted service. Use that result to change the backup design or the objective.

The small shop example establishes no production restore rate. A fast replay on a tiny fixture cannot show that a large backup can be fetched, decrypted, restored and checked inside an outage budget. Repeat a rehearsal when changes to size, infrastructure or recovery arrangements make its earlier evidence inapplicable.

Close the source history

A restored candidate can be prepared while the source remains live. Reconciliation cannot be declared complete against a source that keeps adding work. Every new payment or purchase can move the boundary again.

Before final accounting, stop new source writes and external dispatch. Resolve or explicitly account for operations already in flight, including commits whose replies were lost and provider calls still awaiting outcomes. Preserve the final source evidence and prevent stale clients or workers from continuing to use the old authority. Failover and fencing owns the mechanisms that enforce that authority change.

Figure 3 A finite set of later work
Source still accepting work

Restore cut → mistake → payment 504 → more writes …

Later-work set keeps growing

Source history closed

Restore cut → mistake → payment 504 → final boundary │

Final evidence → classify → reconcile → verify

Restored candidate

Kept isolated from callers and external dispatch while its state and omitted work are checked.

A controlled boundary includes in-flight outcomes. Turning off a web page alone does not stop an old worker or a transaction already running. No elapsed times are implied.

Build the omitted-work set from retained source outcomes and independent evidence, not only rows with a recent application timestamp. Deleted rows, related changes and operations whose local records were lost can be absent from that query. Requests may also have been accepted without a commit, or committed without an acknowledgement.

If the source is destroyed, use the history and independent evidence that actually survived. A caller’s belief that a payment completed is a lead to investigate, not proof of its database or provider outcome. State any gap you cannot establish. Closing an unavailable source means preventing its return as a writer too; it does not make missing evidence appear.

Reconcile valid later work

Reconciliation accounts for the operations that do not simply carry across in the restored history. For each operation, establish its identity, original meaning, known outcome, dependencies and chosen disposition.

The shop’s work across the cut
WorkWhat the earlier restore containsRecovery decision
Order 103 purchaseOrder, agreed lines and stock decrementRetain; do not place it again
Mistaken 2.20 priceAbsentExclude the unwanted change
Valid payment 504AbsentEstablish provider outcome, then reconcile
Any decision based on 2.20Outside this example’s supplied workInvestigate its agreement and validity; do not blindly replay it

The last category matters even when the example has no such purchase. A later order priced using the mistake may be an agreement the shop must honour, a request to decline or a case needing a business adjustment. Restore tools cannot make that decision. Replaying its original SQL against different stock and prices may produce a different operation altogether.

Preserve identity and apply once

Use the original logical operation identity. In this branch, order-103-part-payment-1 identifies the 10.00 partial payment for order 103 and maps to payment 504. The identity must keep that meaning. A new amount under the same identity is a disagreement, not a retry.

Check whether the accepted operation is already represented in the recovered database. If it is, verify the mapping and the resulting facts. If it is omitted and valid, apply the database repair and record its identity and outcome in one transaction. A failed repair leaves neither a partial result nor a misleading “done” record. A repeat verifies the same outcome instead of adding another payment.

A uniqueness constraint can refuse a second mapping for an identity. It does not establish that the first mapping was correct. Compare the canonical order, amount, method and resulting payment; stop on a mismatch. A restored absence of an old request record does not prove that the original operation never committed or never caused an external effect.

Recheck the business rule

Apply accepted repairs in a valid dependency order, with relevant ordinary writers excluded or coordinated. Payment 504 still needs order 103 and its unchanged 29.00 agreement. Under this example’s rule, recorded payments must not exceed that amount. Recording the known 10.00 leaves 19.00 due and the order pending. It does not consume stock: that happened in the retained purchase.

A later purchase would require its own capacity check and related records. Copying a stock decrement twice or accepting incompatible dependent work would not recover its original meaning. Keep conflicts and unprovable cases open for an explicit decision rather than counting every copied row as recovered.

External effects do not roll back

The restored database has no payment 504. The provider has still taken 10.00. Query the provider using the retained identity and its actual lookup contract. The result must establish both whether the operation was accepted and whether its order, amount and meaning match the retained request. A conflicting result needs investigation; an unavailable result leaves the operation unresolved.

Record the charge that already happened
Figure 4. A controlled reconciliation with hypothetical queryable provider evidence.
Figure as text

Look up the retained operation identity at the provider. A known accepted matching £10 result supports one local payment record, leaving £19 due. An unavailable or mismatching result leaves the repair unresolved. No branch issues a new charge.

A known accepted result supports recording the charge that already occurred. There is no reason to send another charge. An unavailable result leaves uncertainty. An established absence may support carrying out the original operation, but only when the provider’s lookup and safe execution contract make that conclusion sound. A missing local row or a missing reply establishes neither case.

Check the lifetime and scope of any duplicate protection. A receiver might remember keys only for a limited period. For example, Stripe’s API v1 idempotency contract permits pruning keys after at least 24 hours. It treats reuse of a pruned key as a new request. Restoring local “sent” records or request mappings can remove the shop’s own protection too. The hypothetical provider here offers a retained queryable result; no such capability is assumed for ordinary email.

The worked SQL fixture models the database side after that external outcome has been supplied as evidence. It records payment 504 and its operation mapping together, verifies a repeat, refuses changed meaning and rolls back the payment if recording the mapping fails. It creates temporary example tables and a temporary-session function; use a disposable session. It neither restores a backup nor contacts a provider. Those checks ran in PGlite 0.5.8, a WebAssembly build of PostgreSQL 18.3.

Outboxes and database-backed jobs develops worker delivery and receiver contracts. For recovery, the obligation is to account for earlier effects before those workers resume. Keep unresolved effects visible, with an owner and a decision about which operations can safely return to service.

Return one recovered service to use

Readiness now has a concrete meaning. The intended source and target have been verified, and the old source cannot accept further authoritative work. The finite later-work set has recorded dispositions. External outcomes are reconciled or explicitly unresolved. In the completed shop branch, P7 is 20.00 and order 103 is pending for 29.00. Payment 504 is recorded once, 19.00 remains due and stock is still 10/0/4.

Carry forward still-applicable correction and deletion decisions before returning older data to ordinary use. A restore may bring removed information back. Apply the agreed treatment before rebuilding search copies or documents from it, following History, correction and deletion. Rebuild or reconcile derived stores against the chosen recovered authority; they may otherwise retain a different history.

Route callers and workers to one authority through a controlled handover. Resume external dispatch only after outstanding identities and effects are accounted for. Establish and test backup coverage for the resulting history, retaining the old evidence as required. Record the achieved loss, elapsed recovery time, restricted service and remaining exceptions. The recovery is the service and its obligations brought back into a known state.

Sources and further reading