Backups are automatically triggered before a deployment, in AWS CodeDeploy BeforeInstall step. In this step, our Lambda function is invoked to run mongodump.
Snapshots are taken and named the AWS CodeDeploy Deployment Id (eg: "d-ABCDEFG-123.archive"). The snapshots reflect the database state before the deployment happens, before any database migrations run.
Snapshots stored in S3:
s3://your-backup-bucket/backups/applicationName/deploymentId.archive{
ApplicationName: string
// Default: "backup"
Action?: "backup" | "restore" | undefined
// Default: new Date().toISOString()
DeploymentId?: string | undefined
// Default: undefined
// Note: if given, we assume it's a valid AWS CodeDeploy deployment
LifecycleEventHookExecutionId?: string | undefined
}MONGO_URI_SECRET_ID: used to connect to your db to performmongodumpandmongorestore. This should align with a JSON in AWS SecretsManager with{ mongo_uri }BUCKET_NAMEAWS_REGION
aws lambda invoke --function-name backup-restore-function --payload '{ "ApplicationName": "MyApplication" }' --cli-read-timeout 600 --cli-binary-format raw-in-base64-out out.txtThis will create the s3 object: backups/MyApplication/YYYY-MM-DDT00:00:00.000Z.archive
aws lambda invoke --function-name backup-restore-function --payload '{ "ApplicationName": "MyApplication", "DeploymentId": "YYYY-MM-DDT00:00:00.000Z" "Action": "restore" }' --cli-read-timeout 600 --cli-binary-format raw-in-base64-out out.txtThis will restore the database using the s3 object: backups/MyApplication/YYYY-MM-DDT00:00:00.000Z.archive
NOTE that --cli-read-timeout 600 is required as it takes a while. After 1 minute, the AWS CLI attempts to invoke again because it detects a timeout.
The flow is this:
- Backend code pushed
- Deploy with AWS CodeDeploy
BeforeInstall: perform the backup- Backup uploaded to S3
ContinueDeploymentInstall: places the task (new backend version deployed) ...
- On an unsuccessful deployment, restore manually.
BeforeInstall – You can use this deployment lifecycle event for preinstall tasks, such as decrypting files and creating a backup of the current version.
A successful deployment looks like:
| Lifecycle Event | Duration | Status | Start Time (UTC+8:00) | End Time (UTC+8:00) |
|---|---|---|---|---|
| BeforeInstall | < 1 second | Succeeded | Dec 15, 2025 2:50 PM | Dec 15, 2025 2:50 PM |
| Install | 3 min 23 sec | Succeeded | Dec 15, 2025 2:50 PM | Dec 15, 2025 2:53 PM |
| AfterInstall | < 1 second | Succeeded | Dec 15, 2025 2:53 PM | Dec 15, 2025 2:53 PM |
| BeforeAllowTraffic | < 1 second | Succeeded | Dec 15, 2025 2:57 PM | Dec 15, 2025 2:57 PM |
| AllowTraffic | < 1 second | Succeeded | Dec 15, 2025 2:57 PM | Dec 15, 2025 2:57 PM |
| AfterAllowTraffic | < 1 second | Succeeded | Dec 15, 2025 2:57 PM | Dec 15, 2025 2:57 PM |
