How to Backup My Database Safely: Steps and Restore Tests
Learn How to Backup My Database: pick a method, set a schedule, and test restores before you need them.
You're about to run a migration, your application finally has real users, and the only copy of its data lives on the database server. There may be a backup toggle in your hosting dashboard, but you haven't checked what it captures or tried restoring anything.
If you're searching for “how to backup my database,” start with a stricter definition of done: you need a separate recovery copy and evidence that your application can use it. Creating the file is the easy part. Choosing a consistent backup method, preserving its dependencies, and testing recovery are what make it useful.
Choose the Backup Method That Fits Your Database
Write down your database engine, size on disk, and maximum tolerable data loss before choosing a tool. PostgreSQL, MySQL, MongoDB, and Redis don't share interchangeable backup procedures. Database size also affects whether a portable export is practical or whether you need a physical recovery path.
Your recovery point objective, or RPO, is the most data, measured in time, you can afford to lose. A database containing disposable development fixtures needs a different policy from one recording customer payments.
Backup methods by database setup and recovery goal
| Method | Typical Recovery Point | Restore Effort | Best Fit |
|---|---|---|---|
Logical dump (pg_dump, mysqldump, mongodump) | State captured by the last consistent dump | Low initially, but loading and rebuilding indexes can take time | Small to medium databases, portability, selective restores |
| Filesystem or physical backup | Last database-consistent copy | Medium, restore the data directory and required configuration | Large databases with supported physical-backup tools or consistent snapshots |
| Base backup plus continuous log archiving | Chosen point covered by the retained log chain | High, restore the base and replay logs | Production PostgreSQL requiring point-in-time recovery |
| Provider-managed automated backups | Latest recoverable point supported by the configured schedule and logs | Low operational effort, subject to provider restore options | Teams on managed hosting |
| Replication alone | Replica's current state, including propagated mistakes | Low for failover, unsuitable for recovering deleted history | High availability, never a replacement for backups |
The PostgreSQL backup documentation distinguishes SQL dumps, filesystem backups, and continuous archiving. Logical dumps give you object-level flexibility; physical backups favor whole-instance recovery but require compatible files and a consistent capture method. Don't copy a live data directory with an ordinary file-copy command and assume it's recoverable.
Choose recovery behavior, not just storage
For PostgreSQL, a base backup plus archived write-ahead logs, or WAL, supports recovery to a chosen pre-incident moment. Other engines have their own logging and recovery mechanisms; PostgreSQL commands aren't a universal recipe.
Managed hosting removes work, not decisions. As a concrete retention example, Fujitsu's PostgreSQL disaster-recovery guide notes that Azure Database for PostgreSQL defaults to seven days, extendable to 35 days. Retention tells you how far back you can recover, not how fresh the latest recovery point is.
When evaluating free cloud database hosting, treat recoverability as a selection criterion rather than assuming hosted means protected.
Decision check: Record the engine, database size, chosen method, and the failure it must recover from. If your answer is only “promote the replica,” you haven't chosen a backup method.
How to Run Your First Database Backup Step by Step
For a first backup, use the engine's supported logical-export tool unless your recovery requirements already demand physical backups and log archiving. Keep the first run manual so you can inspect errors before putting it on a schedule.
This workflow separates creating a copy from validating it.

Prepare the destination and identity
Check versions and available space. For PostgreSQL, run
psql -d appdb -c 'SELECT version();'andpg_dump --version, then inspect the destination withdf -h /backups. Use a separate mounted volume with comfortable headroom; compression and indexes make dump size different from database size, so measure rather than assuming a fixed ratio.Create a dedicated backup identity. Grant the database permissions needed to read the intended objects, including any row-security considerations, without granting application write privileges. Separately restrict the storage identity so it can upload backups without deleting retained copies.
Set connection details securely. Use a protected credential file or your job runner's secret store rather than putting a password in the command line. Confirm the host and database name, especially when development and production use similar names.
If you're still creating the database, record those details alongside the setup instructions. A SQL database creation workflow isn't complete until the backup job knows which resource it protects.
Create and inspect the export
Run the engine-appropriate command. For PostgreSQL, use
pg_dump -Fc -f /backups/app_today.dump appdb; the custom archive supports selective restoration withpg_restore. For MySQL InnoDB tables, usemysqldump --single-transaction --routines --events --triggers appdb > /backups/app_today.sql, and avoid concurrent schema changes during the export.Handle MongoDB and Redis deliberately. For MongoDB,
mongodump --archive=/backups/app_today.gz --gzip --db appdbcreates an archive, but a changing deployment needs a topology-appropriate consistency strategy rather than assuming this command captures a coordinated snapshot. For Redis, runBGSAVE, inspectINFO persistenceuntil the background save has finished successfully, then copy the configured RDB file.Check readability and transfer integrity. PostgreSQL's
pg_restore --list /backups/app_today.dumpshould list expected objects without errors; MongoDB'smongorestore --dryRun --archive=/backups/app_today.gz --gzipcan check archive readability with a tool version supporting that option. Generate a checksum withsha256sum /backups/app_today.dump, transfer the file and checksum to separate storage, and compare the destination checksum.Schedule and record the result. Use cron or your job runner with explicit executable paths, protected credentials, and alerts for failures or missing output. Log the source database, capture time, tool version, filename, checksum, and destination, using unique filenames so the next run doesn't overwrite the previous copy.
A readable archive still doesn't prove application recovery. The Unitrends State of Backup and Recovery report highlights restore validation as a distinct operational concern, including compatibility and missing dependencies.
Run this check: Confirm the file exists off-server, its checksum matches, and its contents can be inspected. Mark it awaiting restore validation, not production-ready.
Match Backup Frequency and Retention to Your Recovery Goals
A backup taken just before yesterday's scheduled run can leave almost an entire day of missing transactions. NIST's cyberattack recovery guidance explains why a 24-hour interval can expose nearly a day of changes, while hourly backups reduce that exposure to about an hour, assuming the latest copy is valid and available.
Your recovery time objective, or RTO, is the target time for returning the service to usable operation. It includes retrieving the copy, provisioning capacity, restoring dependencies, loading data, and validating the application, not just the database restore command.
Backup frequency and retention by recovery point target
The following are hypothetical planning examples, not guaranteed recovery levels or universal retention recommendations. Adopt a row only after testing that your workload can meet it.
| Max Data Loss (RPO) | Backup Approach | Schedule | Retention Starting Point |
|---|---|---|---|
| 24 hours | Nightly full dump or consistent snapshot | Daily, during an off-peak window | Example policy: 7 daily plus 4 weekly copies |
| 1 hour | Hourly snapshot or supported incremental backup, with a daily full | Hourly and daily | Keep hourly history through the expected discovery delay, with daily copies for older recovery |
| 5 to 15 minutes | Base backup plus continuous WAL archiving | Example policy: weekly base backup, continuous archiving configured to meet the target | Example policy: base backups retained 14 days, with every required WAL segment |
| Near zero | Replica plus independent backups | Continuous replication plus an appropriate backup schedule | Retain independent recovery history; don't count the replica as a backup |
Retain history long enough to notice the problem
Frequency answers how much recent work you might lose. Retention answers whether you can recover from an older mistake that nobody noticed immediately.
Say an agent changes a cleanup query and starts removing valid records. If you discover the error after the oldest usable recovery point has expired, a fast backup schedule won't recover the earlier records. Choose retention around realistic discovery delays, investigation time, and applicable recordkeeping requirements.
For PostgreSQL point-in-time recovery, preserve the complete dependency chain. A retained base backup isn't enough if the WAL required to reach your intended recovery point has expired.
Retention cleanup must understand recovery dependencies. Deleting an apparently old log segment can invalidate a recovery point you still advertise as available.
Run this check: Write the RPO and RTO in your runbook, then inspect actual backup timestamps and the oldest recoverable point. Confirm that the schedule meets the freshness target and that retention reaches beyond your expected discovery delay.
Prove Your Backup Restores With a Test Drill
Treat every new backup configuration as unproven until a restore passes. NIST's storage security guidance recommends at least monthly integrity and restore testing for critical data, alongside controls for consistency, security, retention, and access.
Use the following validation checklist while you perform the drill.

Restore without touching production
Select a recent backup and an older retained copy. Verify each checksum before loading it, then provision an isolated destination with compatible database software, required extensions, and enough storage.
For PostgreSQL, create a disposable database with createdb restore_check, then run pg_restore --exit-on-error --no-owner -d restore_check /backups/app_today.dump. Supply connection settings for the isolated server explicitly; never rely on a shell environment that might still target production.
Our downloaded backups are verified with SHA-256. A checksum mismatch deletes the partial file and exits with code 1, but that safeguard proves transfer integrity, not successful database recovery.
Keep outbound email, payments, webhooks, and background workers disabled in the test environment. A restored database can contain valid production credentials or pending jobs, and an isolated database alone doesn't prevent an application from calling external services.
Validate usable data and elapsed time
Compare row counts against a baseline recorded at backup time, rather than against a production database that has continued changing. Check critical indexes, constraints, extensions, and representative recent transactions, then run an application workflow such as loading an account and its associated orders.
For point-in-time recovery, choose a deliberate target around a known test transaction and verify that recovery includes or excludes it as intended. Start the timer before retrieving the backup and stop only when the application passes its acceptance checks.
Use this video alongside the written drill if a visual walkthrough helps.
Record failures with their causes and owners. A restore that finishes but misses the required data or exceeds the downtime target hasn't passed.
Close the drill by recording these metrics:
- Backup success rate: Did scheduled captures finish as intended?
- Restore-test success rate: Did validation pass?
- Achieved recovery point: What is the latest confirmed recovered transaction?
- Achieved recovery time: How long until usable service?
- Time since a successful test: How stale is your recovery evidence?
Common Backup Failures and How to Fix Them
Two failure patterns deserve immediate attention: the job creates an artifact without capturing what you intended, or the database restores but its surrounding application doesn't work. An exit code can't tell you whether you exported the correct database, preserved required extensions, or retained usable credentials.
Kaseya's backup-testing guide treats recovery testing as an operational control and identifies problems such as incomplete archives, missing credentials, unavailable encryption keys, and insufficient restore capacity. Diagnose the actual symptom rather than repeatedly rerunning the same command.
Backup and restore failures by symptom
| Symptom | Likely Cause | Fix |
|---|---|---|
| Dump file is tiny or empty | Wrong database, failed command, or insufficient read access | Verify the database identity, inspect standard error, correct permissions, and rerun |
| Restore fails with a version error | Unsupported tool, archive, or target-version combination | Match compatible tools and targets; don't assume backward compatibility |
| Restore runs but the app errors | Missing extension, configuration, or mismatched schema migration | Install required extensions and match application code to the recovered schema |
| Point-in-time restore stops early | Missing or expired WAL segment | Find the archive gap, recover the segment if available, and repair archive monitoring |
| Backup disk fills during the run | Output shares production storage or exceeds available space | Write to a separate destination and check free space before starting |
| Encrypted backup cannot be opened | Missing key or unavailable key-management access | Recover the correct key version and test the documented decryption procedure |
| Restore exceeds the recovery time target | Slow storage, insufficient capacity, or serial restore work | Benchmark larger temporary capacity, supported parallel restoration, or a physical recovery method |
Fix the surrounding recovery environment
Keep a recovery manifest containing engine and tool versions, extension requirements, application release, schema migration state, and configuration references. Store secrets in a protected recovery system with separate access rules, not as plaintext beside an otherwise encrypted dump.
A PostgreSQL database dump also doesn't automatically preserve every cluster-level dependency. Roles, tablespaces, and server configuration need their own documented recovery path where applicable.
For a slow custom-format PostgreSQL restore, consider pg_restore --jobs with an appropriate worker count. Parallelism can help, but it won't remove a storage bottleneck or make an undersized destination adequate.
Repair rule: A corrected setting isn't proof of a corrected backup. Repeat the failed operation and the application acceptance checks.
Run this check: Select the table row matching your failure, save the complete error output, apply the fix, and rerun the restore drill. Record the successful result so the next operator has a working procedure rather than an untested suggestion.
Store Backup Copies Where Attackers Cannot Reach Them
Backups disappear when the same compromised identity can remove both the production database and its recovery copies. A bucket on another machine doesn't provide meaningful isolation if the attacker can still delete everything with the credentials they already hold.
In 2025, 53% of surveyed organizations reported using backups to recover from ransomware incidents, a four-year low, according to Sophos's survey of 3,400 IT and cybersecurity leaders across 17 countries. That finding doesn't establish why each organization chose another recovery method, but it reinforces why backup availability should be tested rather than assumed.
Separate writing, deletion, and administration
Use a separate account or project for recovery storage where practical. A different region can address a regional failure, but it doesn't by itself prevent deletion through shared administrative credentials.
- Restrict the writer: Allow the backup job to create objects without granting deletion or retention-administration rights.
- Protect retained objects: Use immutable retention or object lock where supported, and review who can bypass or change those controls.
- Preserve an isolated path: Maintain an offline or otherwise independently protected copy when the business impact warrants it.
- Recover the keys: Encrypt copies and keep the key-recovery procedure accessible outside the systems those copies protect.
Apply the same care to database access management and recovery storage. Rotating a database credential doesn't revoke a forgotten storage token.
Our policy is explicit: customers should not store anything on the service they could not stand to lose. For irreplaceable records, maintain an independently controlled recovery path rather than relying entirely on a single service.
Run this check: Using only the backup-job identity, attempt to delete a disposable test object protected by the same policy as your retained backups. Confirm the operation fails, then verify that the identity also cannot shorten retention or disable the protection.
Schedule Your First Backup and Restore Test This Week
Put dates and an owner against the work. A scheduled backup without a scheduled restore test leaves the most important question unanswered.
Use this checklist to turn the plan into calendar tasks.

Make the first week concrete
- Today: Record the engine, database size, acceptable data loss, and tolerated downtime. Run the first backup and save its manifest.
- Within the next few days: Confirm the off-server copy, verify its checksum, and deliberately trigger a harmless job failure to test alert delivery.
- Before the week ends: Restore into an isolated environment, run an application query, and record the achieved recovery point and elapsed recovery time.
- Before closing the task: Assign an owner for recurring drills and repeat testing after significant engine, schema, extension, or infrastructure changes.
Don't make the first exercise depend on rebuilding every operational detail perfectly. Start with a recoverable database and a documented application check, then expand the exercise to include replacement infrastructure and dependent services.
Use automation without outsourcing the decision
For teams using ExtraOrbital, our backups command lists, downloads, and syncs backups and project archives, and sets backup policies. Our standard preset retains 7 daily, 4 weekly, and 12 monthly backups, and it's the default for paid resources.
That preset is a starting configuration, not evidence that your particular recovery targets are satisfied. Compare its retained history with your discovery risks, then test recovery using the same permissions and instructions an operator would have during an incident.
Run this check: Open your calendar now and create the first restore-test appointment, including the backup location, isolated destination, acceptance query, and responsible person. Don't mark the backup work complete until that appointment produces a recorded result.
ExtraOrbital brings backup policies, downloads, and project resource management into one workflow, so you can organize the recovery copies your application needs. Visit ExtraOrbital to review the backup controls, choose a policy that fits your recovery goals, and schedule a restore test before relying on it.