24 min read · Business email and cloud

Many companies have run nightly backup jobs for years, and every morning the status is green, but nobody has ever done a real restore. So on the day a machine fails, three things hit at once: the backup file will not open, the restore is slower than management understood, and the data lost is more than the business can accept, because backups run once a day while orders arrive every hour.
This article turns "we have backups" into two numbers you can check: RPO (how much recent data you can afford to lose) and RTO (how long you can wait). It calculates RPO from the backup schedule, measures RTO from a real restore, and compares both with the target for each system. It includes TypeScript code that Node 24 runs directly, real output, and a test suite. A manager can read the tables and explanations and get the picture. An engineer can run the code and follow along.
The real problem: numbers nobody set, and files nobody ever restored
Consider three made-up situations. They are not projects of any BT San customer.
- An online shop backs up its database at 02:00 every night. The disk fails at 3 pm on its busiest day. Every order from 2 am to 3 pm is gone, even though everyone believed "we have a backup," because nobody ever asked how many hours of data they could afford to lose.
- An accounting office keeps its backup files on a NAS on the same network as the server. Malware encrypts the server and the NAS at the same time, because every copy can be reached with one account.
- A company that uses email and files in the cloud believes the provider already backs them up. An employee deletes a whole customer folder and notices after the time when the recycle bin can still restore it. There is no second copy to fetch.
All three cases have the same root: no target was set, nobody checked whether the backup schedule could meet a target, and nobody ever practiced a restore. The first is a decision the business must make. The last two can be calculated and tested, and that is what the example in this article does.
What the documentation says, and what we must not assume
| Topic | What the documentation says | Effect on what we do |
|---|---|---|
| Definition of RPO and RTO | NIST (citing SP 800-34 Rev. 1) defines RPO as the point in time to which data must be recovered after an outage, and RTO as the overall length of time a system component can be in the recovery phase before it harms the organization's main mission. | Both values are targets the business sets for each system. They are not values a tool gives you. |
| Backing up a live SQLite file | The SQLite Online Backup API gives a consistent snapshot copy even if the source database is written to during the backup. The Node documentation says backup() in node:sqlite returns a Promise, has a rate (default 100 pages) and a progress option, and a write from another connection during the backup makes the backup restart. | Use backup() instead of copying the .db file directly, which can produce a half-written file. You must await it. |
| Integrity check | PRAGMA integrity_check returns one row with the value ok when it finds no problem. It checks for missing pages, incomplete indexes, and UNIQUE, CHECK and NOT NULL constraints, but it does not check FOREIGN KEY. | Use it as one layer of checking, not the only layer. |
| PostgreSQL pg_dump | It makes a consistent copy even while the database is in use, without blocking readers or writers. But the documentation says that beyond simple cases, pg_dump is not the right choice for routine backups of a production database, and it cannot be used as part of continuous archiving. | It gives one point in time per run. A lower RPO needs another method. |
| PostgreSQL point-in-time recovery | Continuous archiving uses a base backup together with continuously archived WAL, and can restore to any time after the base backup. But you need a continuous sequence of WAL files going back to the time the backup started. The documentation advises setting up and testing WAL archiving before taking the first base backup, and watching that it really works. | You can get an RPO of minutes or less, but one missing WAL file makes the restore impossible. |
| Offline copies and testing | In its ransomware guide, CISA says to keep offline, encrypted backups of critical data, and to test the availability and integrity of backups regularly. | You need at least one copy that malware on the server cannot reach, and you must practice restores regularly. |
| Google Workspace | An administrator can restore permanently deleted email for 25 days, starting after 30 days from the day of deletion, for no more than 55 days in total. After that it cannot be restored. Spam, drafts, labels and the trash cannot be restored this way. | The restorable window is limited. Anyone who needs to keep data longer must have their own copy. |
| Microsoft 365 | We did not confirm retention figures or restore conditions from Microsoft's documentation in this round. | We quote no figures. The administrator should read the documentation and the terms of the plan the company actually uses. |
The 3-2-1 rule (three copies, two kinds of media, one copy off-site) is a widely used practice in the field. In this round we did not confirm its wording from any official document, so we use it as a practical guideline, not a requirement. The example adds a fourth item, following CISA's advice on offline copies: at least one copy that cannot be changed or deleted (immutable) or that is taken offline.
Overview of the example
All the code is in the folder examples/backup-restore-rpo-rto-business/. It uses only Node 24 built-ins, with no npm install and no network calls. TypeScript runs directly with node file.ts. All data is made up. The example creates the database and the backup files in os.tmpdir() and deletes them at the end. If your Node version prints an ExperimentalWarning for node:sqlite, run with --no-warnings.
| File | Role |
|---|---|
| systems.json | The backup schedules and copies of four made-up systems, with RPO and RTO targets that deliberately include both passes and failures |
| schedule.ts | Calculates the maximum span of data that can be lost and checks the 3-2-1 rule |
| db.ts | A made-up SQLite database (orders, invoices) and a data generator driven by a simulated clock |
| backup.ts | Backs up with backup(), writes a manifest, and runs three checks before use |
| restore.ts | Picks the latest backup that passes the checks, restores to a new file, times it, and runs test queries |
| demo.ts / backup.test.ts | A script that simulates one day where the machine goes down in the afternoon, and a node:test suite |
Step 1: calculate RPO from the backup schedule, before writing a single line of backup code
The most data you can lose is the longest gap between two consecutive backups. If the machine goes down shortly before the next run, all the data in that gap is lost. With backups at 02:00 and 06:00, a crash at 05:59 loses almost four hours. A run that crosses midnight has to wrap around when counting. If only one backup per day is left, the gap is always 24 hours.
export function worstCaseLossHours(copyHours: number[]): number {
if (copyHours.length === 0) return Infinity;
const h = [...copyHours].sort((a, b) => a - b);
let worst = 0;
for (let i = 0; i < h.length; i++) {
const next = i + 1 < h.length ? h[i + 1] : h[0] + 24;
worst = Math.max(worst, next - h[i]);
}
return worst;
}This value is a lower bound on the real damage. It does not include the time the backup job itself takes to run, runs that fail silently, or damaged files, which the example tests in later steps.
export function check321(copies: Copy[]): string[] {
const missing: string[] = [];
if (copies.length < 3) missing.push(`มี ${copies.length} สำเนา (ต้อง 3)`);
if (new Set(copies.map((c) => c.medium)).size < 2) missing.push("สื่อเก็บไม่ถึง 2 ชนิด");
if (!copies.some((c) => c.offsite)) missing.push("ไม่มีสำเนานอกสถานที่");
if (!copies.some((c) => c.immutable)) missing.push("ไม่มีสำเนาที่แก้ไม่ได้หรือออฟไลน์");
return missing;
}The example sets up four made-up systems in systems.json. Orders need an RPO of 1 hour but are backed up every four hours. Accounting needs 4 hours, which exactly fits its schedule. The file share needs 12 hours but is backed up once a day. Email needs 24 hours and has a single copy, held by the provider. These numbers are made up to show both passes and failures. The real target for each business comes from talking with the owner of the work.
Step 2: back up with backup() and write a manifest
backup() in node:sqlite uses SQLite's Online Backup API, so the file is consistent even while the system is writing, and it is async, so you must await it as soon as the backup finishes. The example reads the resulting file, calculates its SHA-256, and records the row counts and the time of the latest order in a manifest. This is the answer to the question at restore time: what should be inside this file?
export async function takeBackup(db: DatabaseSync, dir: string, takenAt: Date): Promise<Manifest> {
const file = `backup-${takenAt.toISOString().replace(/[:.]/g, "-")}.db`;
const path = join(dir, file);
await backup(db, path);
const s = stats(db);
return { file, takenAt: takenAt.toISOString(), sha256: sha256(path), bytes: statSync(path).size,
orders: s.orders, invoices: s.invoices, latestOrderAt: s.latestOrderAt };
}Simplified: the example makes a full copy every run, which is simple and easy to check. But SQLite has no built-in incremental backup. A large database needs a system that stores differences or a continuous log (see the section on real databases).
Step 3: check the backup file in three layers before trusting it
A successful backup does not mean the file is usable. The destination disk may fill up halfway, the file may be cut off during transfer, or it may be damaged in storage. The example checks three things in order: does the checksum match the manifest, does it open as a database and does integrity_check return ok, and does the row count match what was recorded at backup time. The last layer catches the case where the checksum was updated to match a damaged file, or where the backup was missing data to begin with. A file that fails any one of them must not be used for a restore.
export function verifyBackup(m: Manifest, dir: string): { ok: boolean; reasons: string[] } {
const path = join(dir, m.file);
const reasons: string[] = [];
let actual: string;
try { actual = sha256(path); } catch { return { ok: false, reasons: ["อ่านไฟล์ไม่ได้หรือไม่มีไฟล์"] }; }
if (actual !== m.sha256) reasons.push("checksum SHA-256 ไม่ตรง manifest");
let db: DatabaseSync | null = null;
try {
db = new DatabaseSync(path, { readOnly: true });
const rows = db.prepare("PRAGMA integrity_check").all() as { integrity_check: string }[];
if (rows.length !== 1 || rows[0].integrity_check !== "ok") reasons.push(`integrity_check: ${rows[0]?.integrity_check}`);
const s = stats(db);
if (s.orders !== m.orders || s.invoices !== m.invoices) reasons.push(`จำนวนแถว ${s.orders}/${s.invoices} ไม่ตรง manifest ${m.orders}/${m.invoices}`);
} catch (e) {
reasons.push(`เปิดเป็นฐานข้อมูลไม่ได้: ${(e as Error).message}`);
} finally {
db?.close();
}
return { ok: reasons.length === 0, reasons };
}Step 4: restore to a new file, time it, and ask test questions
The restore code sorts backups from newest to oldest and checks them one at a time. A backup that fails is recorded as skipped, with the reason. The first one that passes is copied to a new file (the existing file is not overwritten). The code then opens it and asks how many orders there are, how many invoices, what time the latest order is, and whether integrity_check passes. The timer covers everything from the start of the checks to the end of the test questions. This is the measured RTO for the database part.
export function restoreLatestValid(manifests: Manifest[], dir: string, target: string): RestoreResult {
const t0 = performance.now();
const skipped: RestoreResult["skipped"] = [];
const newestFirst = [...manifests].sort((a, b) => b.takenAt.localeCompare(a.takenAt));
for (const m of newestFirst) {
const v = verifyBackup(m, dir);
if (!v.ok) { skipped.push({ file: m.file, reasons: v.reasons }); continue; }
copyFileSync(join(dir, m.file), target);
const db = new DatabaseSync(target);
const s = stats(db);
const integrity = (db.prepare("PRAGMA integrity_check").get() as { integrity_check: string }).integrity_check;
db.close();
return { used: m, skipped, restoreMs: performance.now() - t0, sanity: { ...s, integrity } };
}
return { used: null, skipped, restoreMs: performance.now() - t0, sanity: null };
}A real run: simulate one day, with the machine going down at 13:30
demo.ts uses a simulated clock. It builds an order history, backs up at 02:00, 06:00 and 10:00, keeps adding orders until 13:30, and then treats the machine as down. It restores first from the latest set. Then it truncates the 10:00 file by half and restores again.
console.log("\n== 3) กู้คืนจากสำรองล่าสุด ==");
const orders = plans[0];
report("กรณี A", restoreLatestValid(manifests, work, join(work, "restored-a.db")), orders.rpoHours, orders.rtoHours);
console.log("\n== 4) ไฟล์สำรองล่าสุดถูกตัดท้าย ==");
const newest = join(work, manifests[2].file);
truncateSync(newest, Math.floor(statSync(newest).size / 2));
report("กรณี B", restoreLatestValid(manifests, work, join(work, "restored-b.db")), orders.rpoHours, orders.rtoHours);== 1) คำนวณจากตารางสำรอง ==
ออเดอร์ (ฐานข้อมูลร้านค้า): สูญเสียได้สูงสุด 4 ชม. เป้า RPO 1 ชม. => ไม่ผ่าน | 3-2-1: ขาด มี 2 สำเนา (ต้อง 3), ไม่มีสำเนานอกสถานที่, ไม่มีสำเนาที่แก้ไม่ได้หรือออฟไลน์
บัญชี (ฐานข้อมูลบัญชี): สูญเสียได้สูงสุด 4 ชม. เป้า RPO 4 ชม. => ผ่าน | 3-2-1: ครบ
อีเมลบริษัท: สูญเสียได้สูงสุด 24 ชม. เป้า RPO 24 ชม. => ผ่าน | 3-2-1: ขาด มี 1 สำเนา (ต้อง 3), สื่อเก็บไม่ถึง 2 ชนิด, ไม่มีสำเนาที่แก้ไม่ได้หรือออฟไลน์
ไฟล์แชร์: สูญเสียได้สูงสุด 24 ชม. เป้า RPO 12 ชม. => ไม่ผ่าน | 3-2-1: ครบ
== 2) จำลองวันทำงาน: สำรองทุก 4 ชม. ตั้งแต่ 02:00 ==
สำรอง 02:00 -> ออเดอร์ 388 รายการ ล่าสุด 02:00 sha256 78b5fa2d
สำรอง 06:00 -> ออเดอร์ 400 รายการ ล่าสุด 06:00 sha256 997b8d74
สำรอง 10:00 -> ออเดอร์ 412 รายการ ล่าสุด 10:00 sha256 2452c9e0
13:30 เครื่องล่ม ออเดอร์ในระบบจริงตอนนั้น 422 รายการ
== 3) กู้คืนจากสำรองล่าสุด ==
กรณี A: ใช้สำรองเวลา 10:00 | integrity ok | ออเดอร์ 412 ใบแจ้งหนี้ 412 ล่าสุด 10:00
RPO ที่ได้จริง 3 ชม. 30 นาที (หาย 10 ออเดอร์) เป้า 1 ชม. => ไม่ผ่าน
RTO ที่วัดได้ ต่ำกว่า 1 วินาที เป้า 2 ชม. => ผ่าน (วัดเฉพาะส่วนกู้ฐานข้อมูล ไม่รวมเวลาคนตัดสินใจและตั้งระบบ)
== 4) ไฟล์สำรองล่าสุดถูกตัดท้าย ==
ข้าม 2026-03-02T10-00-: checksum SHA-256 ไม่ตรง manifest; เปิดเป็นฐานข้อมูลไม่ได้: database disk image is malformed
กรณี B: ใช้สำรองเวลา 06:00 | integrity ok | ออเดอร์ 400 ใบแจ้งหนี้ 400 ล่าสุด 06:00
RPO ที่ได้จริง 7 ชม. 30 นาที (หาย 22 ออเดอร์) เป้า 1 ชม. => ไม่ผ่าน
RTO ที่วัดได้ ต่ำกว่า 1 วินาที เป้า 2 ชม. => ผ่าน (วัดเฉพาะส่วนกู้ฐานข้อมูล ไม่รวมเวลาคนตัดสินใจและตั้งระบบ)
ลบโฟลเดอร์ชั่วคราวแล้ว- Part 1 is calculation only, and no file has been created yet. Orders fail because backups run every four hours but one hour is needed. The file share fails because it is backed up once a day. Accounting passes exactly and has all four copies. Email passes on RPO but has only one copy. Passing on time does not mean it is safe.
- Part 2 takes three backups. The order count grows over time. The first eight characters of the sha256 are the fingerprint kept in the manifest.
- In case A, the machine goes down at 13:30 and the restore from the 10:00 set passes both the integrity and the row-count checks. Three and a half hours of data are lost (10 orders), which exceeds the order system's 1-hour RPO target. This matches what the table predicted in part 1 as a fail. The restore itself is fast and passes the RTO for the database part.
- In case B, the latest file has been cut in half. The checker catches it through both the checksum and opening the database, so it is not used. The system falls back to the 06:00 set. Seven and a half hours of data are lost. This is the price of not checking. Restoring from a damaged file without knowing it would mean hitting problems halfway through the restore, or worse, continuing to use wrong data.
- The last line confirms that the temporary folder was deleted. The example leaves no database on the machine.
A note on the RTO in the output: the figure "ต่ำกว่า 1 วินาที" (under 1 second) comes from a database smaller than one megabyte. It cannot be compared with a real system. In real life you must measure with a copy of real-size data on the hardware you will restore on, and then add the time that is not in the example: the time for people to realize the system is down, decide, find the file, set up a machine, point the app to the new database, and check that the system works.
The test suite
backup.test.ts has five groups: calculating the gap that wraps around midnight; the 3-2-1 rule; a normal backup that restores to the latest data; a file truncated at the end that must be skipped, falling back to the previous set; and a case where the checksum in the manifest has been edited to match a damaged file, which must still fail through another layer. The last group is when no usable backup exists at all, which must give used as null and create no restore file.
test("ไฟล์ถูกตัดท้ายถูกตรวจพบและไม่ถูกใช้กู้", async () => {
const { dir, older, newer } = await setup();
try {
truncateSync(join(dir, newer.file), Math.floor(statSync(join(dir, newer.file)).size / 2));
assert.equal(verifyBackup(newer, dir).ok, false);
const r = restoreLatestValid([older, newer], dir, join(dir, "r.db"));
assert.equal(r.used?.file, older.file);
assert.equal(r.skipped.length, 1);
} finally { rmSync(dir, { recursive: true, force: true }); }
});Real databases: PostgreSQL and what the example skips
- Set the target to match the kind of work: if RPO is in hours or days, a scheduled pg_dump may be enough. If RPO is in minutes, you need a base backup together with WAL archiving for point-in-time recovery (PITR), according to the PostgreSQL documentation.
- WAL must be continuous: one missing file means you cannot restore across that gap. Watch that archive_command really succeeds, and raise an alert when it stalls.
- Large databases: copying a full copy every run wastes both space and time. The PostgreSQL documentation has an incremental pg_basebackup, or you can use dedicated tools. Always measure RTO against the real size.
- Encryption and separated permissions: encrypt copies that leave the machine, keep the keys apart from the files, and use a separate account to write copies so it cannot delete old ones. The credentials for the copy storage must not be on the same server as the system being backed up. Otherwise an intruder who gets into the server can delete the copies too.
- Retention: decide how many days of daily copies and how many months of monthly copies to keep, according to law and contracts. The retention period for accounting documents under Thai law must be confirmed by the accounting department or a legal adviser. It is not stated in this article. Keeping data longer also means personal data stays around longer.
- Practice restores on a schedule: every quarter or after a system change, restore to a separate machine, measure the time, and check with questions the business understands (does yesterday's sales total match? which invoice is the latest?). Then write the result as a one-page document: who did it, when, how long it took, and what was found.
A concept that links to our other articles: if, before releasing a new version that changes the database structure, you need a rollback point you have practiced, read the article on releasing versions and recovering when a migration breaks. The record of who changed what, which helps check that restored data is correct, is in the article on edit history.
Email and files in the cloud: the provider has not set a target for you
Rented email and file services usually have a deleted-item recovery window that is limited in time. That helps with accidental deletion, but it is not the company's backup plan. An example from the Google Workspace documentation: permanently deleted email can be restored for no more than 55 days in total, and after that nobody can restore it. If a company needs to keep important customer email for years, it must have an export or another copy that it controls itself. And when an administrator account is taken over, copies held in the same account can be deleted too.
- Set an RPO and RTO for email and files as you would for any other system: how many days of loss you accept, how many hours you can wait, and who has the authority to order a restore.
- Read the terms of the plan you actually use: how long data can be restored, who can restore it, and what cannot be restored (for example, spam and drafts in Google Workspace). Do not use numbers from an article or from memory.
- Keep the backup account separate from the working account, and turn on multi-factor authentication for any account that can delete copies.
- Practice restoring one mailbox and one set of file folders on a schedule, and write down how long it took and what staff had to do.
Made-up cases: applying this to three businesses
An online shop with orders arriving every hour
If the owner sets an RPO of 15 minutes, a nightly backup schedule can never pass. The path is WAL archiving or the equivalent, adding an off-site copy, and practicing a point-in-time restore to show that you can really restore to 14:45 when the machine fails at 15:00.
An accounting office with client documents on a file share
An RPO of one day is enough, but the main risk is malware encrypting the whole network. Give priority to a copy that is taken offline or cannot be changed. The account that writes the copies must not be one that staff use every day. Then practice restoring the largest year-end file to measure RTO.
A company that uses only cloud email and documents
There is no server to back up, but there is still the risk of accidental deletion, account takeover, and the provider changing its terms. Set up a periodic export copy in storage from another vendor, using a separate account, and write down the restore steps so someone other than the system administrator can follow them.
Common mistakes and a checklist
- Looking only at the status "backup job succeeded," and never opening the resulting file.
- Keeping every copy in a place that one account can reach, which malware or someone who has taken over the account can also delete.
- Setting RPO to what the tool can do, instead of setting it to what the business can accept and then choosing the tool.
- Testing a restore with a small data set and then reporting that time to management.
- Backing up the database but forgetting attachments, configuration files, keys and the passwords the system needs when it starts again.
- Using a copy without knowing which WAL or run it is in, so after the restore you do not know up to what time the data goes.
- Not writing down the results of the practice restore, so next time nobody knows what the last one found.
- List the company's systems and data, with the impact when each one stops. A system whose outage prevents issuing tax invoices is near the top.
- Have the owner of each system set its RPO and RTO targets, and record who approved them.
- Calculate the longest backup gap and compare it with the RPO. A failure means fixing the schedule or fixing the target.
- Check the 3-2-1 rule, and make sure at least one off-site copy cannot be changed or deleted, or is offline.
- Write a manifest and check the checksum and integrity of every backup file before counting the backup as successful.
- Keep the credentials of the copy storage separate from the server being backed up, and encrypt copies that leave the machine.
- Practice restores to a separate machine on a schedule, measure the real time with real-size data, and write the result as a document.
- Do the same for email and files in the cloud, and read the restore terms of the plan you use.
Cautions for the example: it uses SQLite, a small database, with full copies. It has no real incremental backup or WAL archiving, no encryption, no off-site copy and no separated permissions. The clock is simulated, and the restore times cannot be compared with a real system. The RPO and RTO figures for the four systems are made up and are not advice for any business. It does not confirm Microsoft 365's restore policy.
References
- NIST CSRC Glossary: Recovery Point Objective (อ้าง SP 800-34 Rev. 1) (accessed 2026-11-21)
- NIST CSRC Glossary: Recovery Time Objective (อ้าง SP 800-34 Rev. 1) (accessed 2026-11-21)
- Node.js: SQLite (sqlite.backup, Database, สถานะ release candidate) (accessed 2026-11-21)
- SQLite: Online Backup API (accessed 2026-11-21)
- SQLite: PRAGMA integrity_check (accessed 2026-11-21)
- PostgreSQL: Continuous Archiving and Point-in-Time Recovery (PITR) (accessed 2026-11-21)
- PostgreSQL: pg_dump (accessed 2026-11-21)
- CISA: #StopRansomware Guide (offline encrypted backups, testing backups) (accessed 2026-11-21)
- Google Workspace: Restore a user's permanently deleted email (25 วัน) (accessed 2026-11-21)




