Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
Cleanup Unused SFS Files
This binary deletes unused SFS files and their corresponding database mappings using the SFS bulk delete API. It streams UUIDs from a file, batches them, and sends bulk delete requests to efficiently remove files and their mappings from the email_sfs_mappings table.
Purpose
Part of a three-step workflow to identify and clean up unused SFS files:
find_used_sfs_ids→ Finds SFS UUIDs referenced in email message bodiesfind_unused_sfs_ids→ Compares all mappings against used UUIDs to find orphans- This tool → Deletes the unused files and mappings
How It Works
- Counts UUIDs in the input file (streaming, no loading into memory)
- Streams UUIDs from the file and groups them into batches
- For each batch (default: 50 files per batch):
- Sends bulk delete request to SFS API (
POST /file/bulk-delete) - SFS endpoint deletes files from S3 and removes its own DynamoDB metadata
- For each successful SFS deletion, removes mapping from PostgreSQL
email_sfs_mappingstable - Tracks success/failure for each individual file
- Sends bulk delete request to SFS API (
- Processes batches concurrently (default: 5 concurrent requests)
- Falls back to individual deletions if bulk request fails
- Logs progress every 100 files
- Provides detailed summary of deletions at the end
Key Improvements Over Individual Deletes:
- 50x fewer API calls: Deletes 50 files in 1 request vs 50 requests
- Faster execution: Concurrent batch processing reduces total time
- Better error handling: Per-file results even in bulk operations
- Automatic fallback: Falls back to individual deletes if bulk fails
Memory Efficient: UUIDs are streamed from file and processed in configurable-size batches. Only the current batch is in memory.
Environment Variables
Required
DATABASE_URL: PostgreSQL connection string for the MacroDB databaseSFS_URL: The URL for the Static File Service (e.g.,https://static-file-service.macro.com)INTERNAL_AUTH_KEY: Internal auth key for SFS authenticationDESTINATION_URL_PREFIX: URL prefix for reconstructing destination URLs- Example:
https://static-file-service.macro.com/file/ - Used to build full destination URL:
{prefix}{uuid}
- Example:
Optional
UNUSED_UUIDS_FILE: Path to file containing unused UUIDs (default:unused_sfs_uuids.txt)- Generated by
find_unused_sfs_ids
- Generated by
BULK_BATCH_SIZE: Number of files to include in each bulk delete request (default:50)- Maximum is 100 (enforced by SFS bulk delete endpoint)
- Larger batches = fewer API calls but less granular error handling
BULK_CONCURRENCY: Number of concurrent bulk delete requests (default:5)- Increase for faster deletions, decrease if overwhelming SFS or database
Usage
Basic Usage
cargo run --bin cleanup_unused_sfs
With Custom Configuration
export DATABASE_URL="postgresql://user:pass@localhost/macrodb"
export SFS_URL="https://static-file-service-dev.macro.com"
export INTERNAL_AUTH_KEY="your-auth-key-here"
export DESTINATION_URL_PREFIX="https://static-file-service-dev.macro.com/file/"
export BULK_BATCH_SIZE="100"
export BULK_CONCURRENCY="10"
cargo run --bin cleanup_unused_sfs
From Release Binary
./cleanup_unused_sfs
Using .env File
Create a .env file in the binary's directory:
SFS_URL="https://static-file-service.macro.com"
INTERNAL_AUTH_KEY="2a46d3ed0abe6d45118e0eb03f61e7bc"
DESTINATION_URL_PREFIX="https://static-file-service.macro.com/file/"
BULK_BATCH_SIZE="50"
BULK_CONCURRENCY="5"
Then run:
cargo run --bin cleanup_unused_sfs
Input File
unused_sfs_uuids.txt (required)
Must be generated first by running find_unused_sfs_ids. Contains one UUID per line.
Example:
e1f2a3b4-c5d6-4e7f-8a9b-0c1d2e3f4a5b
f2a3b4c5-d6e7-4f8a-9b0c-1d2e3f4a5b6c
a3b4c5d6-e7f8-4a9b-0c1d-2e3f4a5b6c7d
Deletion Behavior
For each UUID, the tool performs two operations:
1. Delete from SFS
- Calls SFS bulk delete API:
POST /file/bulk-delete(batches of 50 by default) - SFS endpoint deletes files from S3 and removes its own DynamoDB metadata
- Success: File was deleted from S3
- Already Deleted (404): File doesn't exist (counted separately, not an error)
- Error: Network issue, auth failure, or other error
- Falls back to individual
DELETE /file/{uuid}calls if bulk request fails
2. Delete from PostgreSQL Database
- Only attempted for files that successfully deleted from SFS
- Executes:
DELETE FROM email_sfs_mappings WHERE destination = '{prefix}{uuid}' - Success: Mapping row deleted
- Error: Database connection issue or permission error
The database cleanup only happens after successful SFS deletion to maintain consistency.
Safety Features
- Dry run not available: This tool permanently deletes files
- No confirmation prompt: Assumes you've verified the unused UUIDs
- Continues on errors: Individual failures don't stop the entire batch
- Progress tracking: Can be interrupted and resumed (just run again with same file)
- Concurrent limits:
BULK_CONCURRENCYsetting prevents overwhelming services
Performance
- Streaming architecture: Reads UUIDs from file in 1000-item batches
- Concurrent deletions: Configured via
BULK_CONCURRENCY(default: 5) - Memory usage: Constant, regardless of total file count
- Typical speed: 100-500 deletions per second (depends on SFS/DB latency)
Typical performance at different bulk concurrency levels:
- BULK_CONCURRENCY 5 (default): ~250 deletions/sec, conservative
- BULK_CONCURRENCY 10: ~500 deletions/sec, recommended
- BULK_CONCURRENCY 20: ~1000 deletions/sec, aggressive (may overwhelm services)
Note: With bulk operations, each request deletes up to 50 files (BULK_BATCH_SIZE), so performance scales much better than individual deletions.
Example Run
=== Cleanup Unused SFS Files ===
Loading configuration...
Configuration:
SFS URL: https://static-file-service.macro.com
Unused UUIDs file: unused_sfs_uuids.txt
Destination URL prefix: https://static-file-service.macro.com/file/
Concurrency: 20
Counting UUIDs in unused_sfs_uuids.txt...
Found 221720 UUIDs to delete in 1.2s
Connecting to the database...
Deleting 221720 files with concurrency 20...
Progress: 100/221720 processed (SFS: 87 deleted, 13 already deleted, 0 failed)
Progress: 200/221720 processed (SFS: 175 deleted, 25 already deleted, 0 failed)
Progress: 300/221720 processed (SFS: 264 deleted, 34 already deleted, 2 failed)
...
Progress: 221700/221720 processed (SFS: 194523 deleted, 27145 already deleted, 32 failed)
Progress: 221720/221720 processed (SFS: 194541 deleted, 27147 already deleted, 32 failed)
=== Summary ===
Total UUIDs processed: 221720
SFS deletions: 194541 deleted, 27147 already deleted, 32 failed
DB deletions: 221688 succeeded, 32 failed
Total time: 18m 32s
Exit Behavior
- Exit code 0: Always, even if some deletions fail
- Individual failures: Logged to stderr but don't stop execution
- Final summary: Shows success/failure counts for review
Next Steps
After running this tool:
- Review the summary statistics
- Check if any files failed to delete (investigate errors in output)
- Optionally re-run to attempt failed deletions again
- Archive or delete the
unused_sfs_uuids.txtfile
Troubleshooting
"File does not exist: unused_sfs_uuids.txt"
- Run
find_unused_sfs_idsfirst to generate this file
"No UUIDs to delete"
- The input file is empty
- Run
find_unused_sfs_idsto generate unused UUIDs - Or verify the file path is correct
High SFS failure rate
- Check
SFS_URLis correct and service is reachable - Verify
INTERNAL_AUTH_KEYis valid - Check network connectivity
- Reduce
BULK_CONCURRENCYto avoid rate limiting
High DB failure rate
- Check
DATABASE_URLis correct and database is reachable - Verify user has DELETE permissions on
email_sfs_mappingstable - Check
DESTINATION_URL_PREFIXmatches format in database - Reduce
BULK_CONCURRENCYto avoid connection pool exhaustion
"Already deleted" count is high
- Normal behavior if tool has been run before on same file
- Files may have been manually deleted
- SFS may have already cleaned up some files
Process is too slow
- Increase
BULK_CONCURRENCY(try 10, 15, or 20) - Check network latency to SFS
- Verify database connection pool is adequate
Process is too fast / overwhelming services
- Decrease
BULK_CONCURRENCY(try 2 or 1) - Monitor SFS and database server load
Want to test without deleting
- Not recommended: This tool has no dry-run mode
- Alternative: Manually test with a small file (1-10 UUIDs)
- Copy a few UUIDs to a test file and run with that file
Safety Checklist
Before running in production:
- Verified
unused_sfs_uuids.txtcontains only truly unused files - Checked percentage of unused files is reasonable (in
find_unused_sfs_idsoutput) - Confirmed
SFS_URLandDESTINATION_URL_PREFIXmatch your environment - Tested with small batch first (optional but recommended)
- Have database backup (for peace of mind)
- Set appropriate
BULK_CONCURRENCYfor your infrastructure - Ready to monitor the deletion progress
Recovery
If you accidentally delete files that shouldn't have been deleted:
- Database mappings: Can be restored from database backup
- SFS files: If you have S3 versioning enabled, files may be recoverable
- Prevention: Next time, spot-check unused UUIDs before running cleanup