Directory Backup to R2 and Container Filesystem Snapshots
How Cloudflare Sandbox and Containers persist project files after sleep: R2 directory backups, overlay restore, and full filesystem snapshots.
This page summarises Cloudflare Sandbox and Containers documentation on keeping files when a sandbox or container stops. Disk is ephemeral by default: after sleep, the next start uses a fresh image unless you save state. You can snapshot one directory into R2, or capture the whole writable root filesystem with a container snapshot—each fits a different goal.
Ephemeral disk: why backups and snapshots exist
Section titled “Ephemeral disk: why backups and snapshots exist”When a container instance sleeps or restarts, local changes are lost unless you saved them first.
All disk is ephemeral by default. When a Container instance goes to sleep, the next time it starts, it uses a fresh disk from the container image.
— Cloudflare, Frequently Asked Questions
The writable disk holds repositories, installed packages, config, and command output; memory holds processes and connections. All of that ends when the instance stops.
The disk of an instance holds the repository, installed packages, configuration files, and output written by commands. Its memory holds running processes, open terminals, and network connections. All of it ends when the instance stops, and the next instance starts from its image or from a snapshot.
— Cloudflare, Sandbox lifetime
Your Worker decides when to save; the platform does not restore snapshots on its own.
| Goal | Mechanism | Trade-off |
|---|---|---|
| Continue a workspace in a later session | Save and restore a sandbox with snapshots | Root filesystem; not separately mounted paths |
| Idle save without explicit calls | Save a sandbox automatically | Same as snapshots, plus Durable Object alarms |
| Project across images or beyond 30 days | Back up a directory to R2 | One directory; you store each backup record |
| Share I/O with other systems | Mount an R2 bucket (see Work with files in a sandbox) | Not native disk semantics for renames and locks |
Directory backup to R2: one folder as one object
Section titled “Directory backup to R2: one folder as one object”Directory backup saves a single directory as an archive in R2 and restores it later—including into a container running a newer image.
The DirectoryBackup class from @cloudflare/sandbox saves one directory as one object in your R2 bucket and restores it as ordinary files. A backup restores after the instance stops or after you deploy a new image. R2 keeps each backup until you delete it.
— Cloudflare, Back up a directory to R2
Use this when a project path such as /workspace should return after the sandbox sleeps. For a separate storage path that should persist independently of the sandbox filesystem, mount a bucket instead; mounting over /workspace overlays files seeded by your image in production.
Sandbox SDK createBackup() and restoreBackup() (0.x)
Section titled “Sandbox SDK createBackup() and restoreBackup() (0.x)”The high-level Sandbox SDK exposes point-in-time directory snapshots stored in R2.
Create point-in-time snapshots of directories and restore them from R2.
— Cloudflare, Backups API
createBackup() builds a compressed SquashFS archive, uploads it to R2 (presigned URL in production, or the BACKUP_BUCKET binding with localBucket: true in wrangler dev), then deletes the local archive. The directory must be an absolute path under /workspace, /home, /tmp, /var/tmp, or /app.
const backup = await sandbox.createBackup({ dir: "/workspace" });const result = await sandbox.restoreBackup(backup);Default TTL is 3 days (259200 seconds). The SDK rejects restore when TTL has elapsed; it does not delete R2 objects—you delete them or use R2 lifecycle rules. Objects live at backups/{backupId}/data.sqsh and backups/{backupId}/meta.json.
DirectoryBackup handles are serializable—store them in KV, D1, or Durable Object storage and pass the parsed object back to restoreBackup().
DirectoryBackup class (1.0): gateway and records
Section titled “DirectoryBackup class (1.0): gateway and records”The DirectoryBackup API runs backup and restore inside the container while the Worker’s DirectoryBackupGateway moves data to R2—the container needs no Internet access and no R2 credentials.
Requirements:
- An R2 bucket binding on the Worker
export { DirectoryBackupGateway } from "@cloudflare/sandbox";in the main module (do not route HTTP to the gateway)
Records use keys <prefix><id>.tar.zst with SHA-256 verification on restore. One backup() or restore() runs at a time per container; operations serialize across restarts.
Production overlay restore vs local extract
Section titled “Production overlay restore vs local extract”Restore behavior differs between production and wrangler dev; the public API is the same.
Backup and restore snapshot a sandbox directory into an R2 archive, then bring that tree back later. The public API is the same in production and in wrangler dev. The restore mechanism is not.
— Cloudflare, Directory backups
Production: FUSE overlayfs (SDK 0.x restoreBackup())
Section titled “Production: FUSE overlayfs (SDK 0.x restoreBackup())”In production, restoreBackup() mounts the archive with FUSE overlayfs:
- The backup is a read-only lower layer; new writes go to a writable upper layer
- The R2 archive does not change; restoring the same handle again discards the upper layer
- The overlay exists only while the container runs—after sleep or restart the mount is gone and the directory is empty. Keep the
DirectoryBackuphandle and restore again
Stop processes that write to the target directory before restoring. The restore target is backup.dir, which may differ from the path you originally backed up.
Local development: unsquashfs replace
Section titled “Local development: unsquashfs replace”With localBucket: true, wrangler dev extracts the archive and replaces the directory—no overlay, so behavior does not match production FUSE restore.
EXDEV and generated caches
Section titled “EXDEV and generated caches”Overlayfs treats lower and upper layers as different devices. Renames that move a directory from the restored tree into the writable upper layer can fail with EXDEV (cross-device link not permitted). Vite’s node_modules/.vite/deps is a common case.
Omit disposable directories from the backup or delete them after restore—for example excludes: ["node_modules/.vite"] with createBackup(), then rm -rf after restore. This failure does not occur in wrangler dev, which extracts the archive instead of mounting overlay.
Exclusions, TTL, permissions, and cleanup
Section titled “Exclusions, TTL, permissions, and cleanup”Leave out files with exclude, excludes, and gitignore
Section titled “Leave out files with exclude, excludes, and gitignore”For DirectoryBackup, patterns use .gitignore syntax relative to the directory: node_modules/ matches that name at any depth; /build matches only at the top.
For SDK 0.x, excludes are glob patterns passed to mksquashfs; gitignore: true applies .gitignore files inside the repo when dir is in a git repository (nested .gitignore applies). If git is not installed, the SDK logs a warning and continues without git-based exclusions.
Permissions and concurrent writes
Section titled “Permissions and concurrent writes”createBackup() / mksquashfs must read every file under dir. Mode 0600 or directories owned by another user cause BackupCreateError. Fix permissions in the image (chmod -R a+rX) or before backup. Partially written files may not be captured consistently; for a consistent backup, avoid writes to dir during the operation (DirectoryBackup.backup() has the same caveat).
Delete backups and lifecycle gaps
Section titled “Delete backups and lifecycle gaps”Delete both R2 objects and any stored record. An object lifecycle rule that expires objects under backups/ removes objects but can leave records; restore then throws BACKUP_NOT_FOUND. A failed backup does not leave an object; interrupted multipart uploads may remain until the bucket’s default abort rule (often seven days).
For 1.0, delete() on the backup record removes the object; the container does not need to be running.
Container filesystem snapshots: full root state
Section titled “Container filesystem snapshots: full root state”For the entire writable root filesystem—not one directory—use snapshotContainer() on the Durable Object Container API. Snapshots are supported only for applications with the durable_object scheduling policy; image and containerSnapshot are mutually exclusive when starting a container.
snapshotContainer() creates a point-in-time snapshot of the writable root filesystem of a running container. It does not capture memory, running processes, or separately mounted filesystems. A container started from the snapshot runs its entrypoint again.
— Cloudflare, Durable Object Container API
const containerSnapshot = await this.ctx.container.snapshotContainer({ name: "before-upgrade",});await this.ctx.storage.put("containerSnapshot", containerSnapshot);// later:this.ctx.container.start({ containerSnapshot, enableInternet: false });Snapshots are immutable: after restore, file changes require a new snapshot. They are tied to the image version they were created from; after updating the image, create new snapshots from containers on that image. A snapshot ID can restore in any Durable Object of the same class (useful for copying sandboxes—only between sandboxes that belong to the same user).
Retention: implicit 30-day TTL from creation or most recent restore (restoring refreshes TTL). Maximum snapshot size is 20 GB (Limits). You cannot set a custom TTL on snapshots yet; for longer retention, copy data to a bucket.
snapshotContainer() does not save /run (in-memory), separately mounted filesystems, memory, or processes. Process IDs may be reused on the new instance after restore.
Common mistakes
Section titled “Common mistakes”- Expecting overlay files to survive sleep (0.x restore) — production restore is ephemeral; persist the handle and call
restoreBackup()again after wake. - Mounting R2 over
/workspaceand expecting image-seeded files — the mount overlays seeded files in production. - Restoring over a path that contains an S3 mount —
DirectoryBackup.restore()fails withEBUSY; unmount first. - Sharing sandbox names or snapshot IDs across users — the name decides which saved files a request reaches; authenticate in the Worker and derive names from identity (Sandbox security).
- Assuming TTL deletes R2 objects — expiry is enforced at restore time only; clean up objects with
delete()or lifecycle rules.
How to check this on your site
Section titled “How to check this on your site”- Confirm ephemeral behavior: stop or idle the sandbox, start again without restore, and verify whether files under
/workspace(or your target path) reset as described in Sandbox lifetime. - After configuring
BACKUP_BUCKETand R2 credentials per Backup and restore, runcreateBackup()/restoreBackup()(orDirectoryBackup.backup()/restore()), then list objects underbackups/in the R2 dashboard (Manage R2 API Tokens for Object Read & Write). - In production, restore, write a test file, restart the container, and confirm the overlay is gone until you restore from the stored handle again (Directory backups).
- If you use
snapshotContainer(), verify scheduling policy isdurable_object, store the returned handle, and start withcontainerSnapshotper Use snapshots. - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.