BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
SQL and Relational Database Engineering

Expert · Lesson 11 of 12

Software Architecture

Prove Point-in-Time Recovery

Restore a PostgreSQL shop to a named marker, match receipts and inventory, and measure the time to a verified recovery.

Three receipts and a stopwatch on a shop counter beside a cash drawer.

At 10:04 a price import changes every notebook in a stationery shop to AED 1. The cashier has already sold two notebooks at their correct prices. A third customer pays moments after the import. The backup dashboard is green. The owner has a more useful question: can you show the two good sales, with their original prices, on another machine before the shop’s twenty-minute recovery budget runs out?

This drill gives you evidence for an answer. Use a disposable PostgreSQL shop with synthetic purchases and a separate recovery environment. The timestamps and durations below form a worked example, not a benchmark. Run the same sequence with your own clock and keep the actual results. The deliverable is a queryable copy at a known boundary, an account of the transactions on each side, and a time measured all the way to a business check.

Give the recovery point a witness

Create three small tables on the disposable source. A product has an SKU and a current price in fils. A sale has a receipt ID, an SKU, a quantity and the unit price captured at checkout. A stock row holds the units remaining. Keep money in integer fils for this exercise. Start notebook N7 at 1,800 fils with ten units in stock. In each checkout transaction insert the sale and decrement inventory together. Leave background writers out of this fixture so the boundary between its business transactions is unambiguous.

Finish a physical base backup of this initial state while continuous WAL archiving is active. The backup must reach consistency before the target you intend to recover. Record the backup identifier, system identifier, PostgreSQL major version, source timeline and the archive location. Preserve the manifest separately from the working directory used for restoration. If your service manages these details, record its backup identifier and available recovery window and use its restore-to-new-instance operation. Check that the service supports the target type you plan to test.

Now run the following events in order. At 10:03:10 UTC receipt A701 buys two notebooks for 3,600 fils. Commit it. At 10:03:40 receipt A702 buys one for 1,800 and commits. Immediately after the second commit, have the drill operator create a uniquely named restore point. Use a fresh name each time you repeat the exercise. Keep an independent copy of the two receipt IDs, amounts, quantities and the marker name. The independent record is what lets you test the recovered database without taking its word for the result.

SELECT pg_create_restore_point('sq11_shop_after_a702_run01');

At 10:04:00 the synthetic import commits the incorrect price of 100 fils. At 10:04:20 receipt A703 buys one notebook at that price. Leave this later transaction in the source. It is useful evidence that a sale can be genuine even when it followed the mistake. For the lab, switch the WAL segment on the source after generating these events and confirm successful archival through the target. A request to switch segments alone is no evidence that remote storage has received the file.

The base backup gets you the ten starting units. WAL replay carries the physical cluster forward through the two sales and their stock movements. A named restore point gives replay an explicit place to stop before the import. Without an earlier marker in a real incident, you might choose a timestamp or a known transaction boundary after investigating commit order. A receipt's creation timestamp often predates its commit. Do not assume a time printed on a till slip is an exact database recovery target. PostgreSQL explains how the base image and archived history fit together in Continuous Archiving and Point-in-Time Recovery.

Restore into a destination that cannot act as the shop

Give the recovery cluster its own data directory, tablespace paths, network endpoint and credentials. The operator needs read access to the backup and archive. The restored server must have no path to overwrite the source archive or contact the production primary. Review copied configuration, including inherited connection settings and archive commands, before its first startup. Keep order workers, email dispatchers and payment integrations disconnected. A perfectly restored queue containing yesterday's jobs should never send yesterday's receipts again.

Start the stopwatch when the simulated service interruption begins. Include time to identify the backup, provision the destination, retrieve and unpack it, replay WAL and verify the business data. If you start after the files are ready on a warm disk, label that measurement separately. It answers a narrower question. Record each transition using one clock. For a team drill, give one observer responsibility for recording milestones so the operator can concentrate on choosing and proving the target.

Check the base backup's manifest against the restored source files before modifying their configuration. With a compatible physical backup and tool version, pg_verifybackup can detect missing or changed files and certain problems with WAL needed by the backup. It cannot certify that every subsequent segment up to this morning's sales is available. A passing check also says nothing about the notebook price at checkout. Use the pg_verifybackup reference to interpret what was actually checked, including the format and WAL checks supported by your version.

On a self-managed practice instance, restore the verified base to the new paths. Configure archive retrieval to fetch the requested file into the path supplied by PostgreSQL and return failure for unavailable files. Set the known source timeline, enable hot standby for inspection, and select the single named target. Place recovery.signal in the restored data directory before starting the isolated instance. The following fragment shows the two decisions specific to this drill. Archive retrieval and filesystem paths depend on the lab.

recovery_target_name = 'sq11_shop_after_a702_run01'
recovery_target_action = 'pause'

Watch the startup log for evidence that recovery reached that marker and paused there. Confirm a read-only connection to the isolated endpoint and check recovery and replay pause state. Merely accepting SQL connections proves too little because a hot standby can accept reads while replay is still advancing. If the log reports that the configured target was never reached, stop the test at that failure and investigate the archive chain. Removing the target to get a green startup would change the recovery question. PostgreSQL documents target selection, inclusion and the possible end actions in Recovery Target settings.

Ask the recovered database what a cashier can prove

Check all three tables on the paused copy. For the sample schema below, the receipt query must return A701 for 3,600 fils and A702 for 1,800. A703 must be absent. The product price must still be 1,800 and stock must equal seven. Save the exact query results and the endpoint identity next to the marker from the server log. The last intact business transaction in this controlled sequence is A702, including its inventory decrement.

SELECT receipt_id, quantity, quantity * unit_fils AS total_fils
FROM sale WHERE sku = 'N7' ORDER BY receipt_id;
SELECT price_fils FROM product WHERE sku = 'N7';
SELECT units FROM stock WHERE sku = 'N7';

A count of two receipts is weaker evidence. An earlier copy might contain two unrelated sales. A price check alone would pass on the initial backup with no sales at all. Even matching IDs and totals would miss a missing stock movement if the application wrote inventory separately. The conjunction of identity, positive and negative witnesses, price and inventory is what makes this test discriminating. For a shop with concurrent tills, use independent witnesses from more than one till and reason about their commit boundaries. The largest receipt number is not a global commit clock.

Suppose provisioning and backup retrieval take six minutes, verification and file preparation take three, replay takes four, and the business checks take two. Your measured interval to a validated read-only copy would be fifteen minutes. Against a twenty-minute objective for that milestone you have five minutes of margin. If the promise is a writable checkout service, fifteen minutes is an intermediate split. Promotion, routing, reconciliation and a successful test purchase still need timing before anyone can claim that broader objective.

State the data consequence separately. Relative to the bad import at 10:04:00, the last witnessed good sale committed twenty seconds earlier. In this fixture no other sale committed in that gap. Rolling the shop back to that point would also remove A703, although a customer may already hold its receipt or have a settled payment. Record it for reconciliation against the independent till or payment record. Never charge the customer again merely because the restored sale table has no matching row. A selective repair using the isolated copy may preserve more later activity than replacing the whole live cluster.

Make a failed rehearsal repeatable

Keep the untouched backup, archive inventory and target configuration together with the result. If a segment is unavailable, attempt retrieval from the same identity and network path as the restore server. A file visible to an administrator may be inaccessible to the recovery process. Distinguish a missing file from an unreadable one before revising retention. After fixing the cause, repeat from a fresh copy of the same backup and keep the original failure time in the report. Reusing a directory that already contains a retrieved segment can make the second run pass while the documented recovery procedure remains broken.

Exercise

Change one condition. The recovered copy reaches the named marker in fourteen minutes and contains both expected receipt IDs. The audit finds eight notebooks left. A colleague proposes accepting the restore because the marker and the time objective both passed. Write a two-sentence decision, then name the first piece of evidence you would check.

Reject the business check. Ten initial units minus two on A701 and one on A702 leaves seven. Verify the endpoint, SKU and initial inventory against the drill record, then inspect whether each committed sale included its stock update. The discrepancy could expose a fixture or application defect even when PostgreSQL replayed exactly what was committed. End the drill with the measured duration, last intact transaction and failed invariant recorded together. A fast recovery of the wrong shop state is a result worth discovering before opening time.

اقرأ الدرس بالعربية

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Migrate a Busy Table Online

Move a live parcel table from a Boolean to a service code. Backfill in batches, find stale values, and prove when label readers can switch.