A maintenance and cleanup script for Mastodon instances. It wraps tootctl with
safe defaults, honest error reporting, and explicit guards around destructive
operations, and it works the same on source and Docker installs.
Everything here has been verified against the Mastodon CLI source at v4.7.3
through v4.7.6 (lib/mastodon/cli/*.rb). The published tootctl
documentation lags the source in several places; see
Version Support.
- π Features
- β¬οΈ Upgrading to 3.0
- π Prerequisites
- π οΈ Installation
- π Usage
- π§ Available Operations
- βοΈ Configuration
- β° Scheduling
- π Notifications and Summaries
- π‘οΈ Safety Features
- π Logging and Output
- π¨ Destructive Operations
- π Monitoring and Health
- π§© Version Support
- π€ Contributing
- π License
- π Version History
- β Safe defaults for every operation
- β Honest exit codes: a failed step fails the run, and "already running" has its own code
- β
--dry-runwith real previews where Mastodon supports them - β
One confirmation per run for destructive work,
--yesfor automation - β
--daily,--weeklyand--monthlypresets, one cron line per cadence - β Combine operations in one run, skip individual steps
- β Read-only audits; inactive local account deletion is opt-in with safety rails
- β
Source installs (
bin/tootctl), PATH installs, and Docker (--exec) - β
Config file and
MM_*environment variables, parsed and never executed - β Webhook notifications (JSON or Healthchecks-style) and a JSON run summary
- β Run locking with stale-lock recovery
- β Storage-driver detection before orphan media removal (filesystem and S3)
- β Elasticsearch / OpenSearch index maintenance with per-index control
- β
Version and
RAILS_ENVchecks at startup, in a single Rails boot
Version 3.0 changes defaults and what some operations do. Before upgrading a scheduled job, check these:
| Change | Before | Now | To keep the old behaviour |
|---|---|---|---|
--maintenance |
accounts, media, statuses, orphans, search, feeds | alias of --weekly (no cull, search or feeds) |
--weekly --elasticsearch --feeds --accounts, or use --monthly |
--concurrency default |
16 | 5 (Mastodon's default) | --concurrency 16 or CONCURRENCY=16 |
--statuses-days default |
30 | 90 (Mastodon's default) | --statuses-days 30 |
--inactive-days default |
365 | 730 | --inactive-days 365 |
--account-cleanup |
deleted inactive local accounts | lists them; deletes only with --delete-inactive-local |
add --delete-inactive-local |
--media-audit |
also deleted orphans and old media | read-only | --media-audit --all-media --yes |
--domain-audit |
probed and purged domains | read-only list; probe with --probe-domains |
--domain-audit --probe-domains --domains --yes |
--domains |
purged every block, including silenced and noop | only suspend blocks |
--severity all adds silenced (noop is never purged) |
| Exit codes | 0 or 1 | 0, 1, 2 (usage), 3 (locked) | treat 3 as "already running" |
| Lock file | $TMPDIR/mastodon-maintenance.lock |
see Run locking | MM_LOCK_FILE=... |
Do a --dry-run of each scheduled job after upgrading.
- Mastodon: v4.7.3 or newer (tested against 4.7.6)
- Bash: 4.4 or newer
(older releases treat
"${array[@]}"on an empty array as unbound underset -u) - Mastodon commands: found in this order
--exec PREFIX(Docker and other wrappers)bin/tootctlandbin/railsin--mastodon-diror the current directorytootctlandrailsonPATH
- Optional:
curl(notifications),timeout(--step-timeout),ionice(--nice) - Environment:
RAILS_ENVis set toproductionautomatically if unset
-
Download a release and verify it
Releases attach
clean.shand aSHA256SUMSfile. Pinning a release means an update never reaches your server unreviewed.VERSION=v3.0.0 BASE=https://github.com/johndotpub/mastodon-maintenance/releases/download/$VERSION wget "$BASE/clean.sh" "$BASE/SHA256SUMS" sha256sum -c SHA256SUMS chmod +x clean.sh
The development version is on
main:wget -O clean.sh https://raw.githubusercontent.com/johndotpub/mastodon-maintenance/main/clean.sh
-
Verify it runs (works outside a Mastodon directory)
./clean.sh --version ./clean.sh --help
-
Point it at Mastodon
# Source install: run from the Mastodon directory as the mastodon user cd /home/mastodon/live /path/to/clean.sh --system-health # ...or from anywhere /path/to/clean.sh --mastodon-dir /home/mastodon/live --system-health # Docker Compose /path/to/clean.sh --exec "docker compose -f /opt/mastodon/docker-compose.yml exec -T web" --system-health
Run as the
mastodonuser on source installs. The script warns when run as root, because new files underpublic/systemwould end up owned by root.
./clean.sh [OPTIONS] OPERATION [OPERATION...]Most instances only need these. Each preset includes the one before it:
./clean.sh --daily --yes # cached remote media, avatars and preview cards
./clean.sh --weekly --yes # daily + prune accounts, remote statuses, orphaned media
./clean.sh --monthly --yes # weekly + cull dead accounts, search index maintenanceaccounts cull contacts every remote account not updated in the last week, and
search deploy re-imports every index, which is why both are monthly.
./clean.sh --domains # Export and purge suspended domains
./clean.sh --accounts # Cull and prune remote accounts
./clean.sh --media # Remove old cached remote media
./clean.sh --profile-media # Remove old cached avatars and headers
./clean.sh --preview-cards # Remove old preview card images
./clean.sh --remote-statuses # Remove old unreferenced remote statuses
./clean.sh --orphaned-media # Remove orphaned media files
./clean.sh --feeds # Rebuild all feeds
./clean.sh --clear-cache # Clear the Rails cache
./clean.sh --elasticsearch # Search index maintenanceOperations can be combined. Each one expands into steps, and a step shared by several operations runs once:
./clean.sh --media --preview-cards --yes
./clean.sh --accounts --weekly --yes # prune still runs once
./clean.sh --monthly --skip elasticsearch --yes
./clean.sh --list-operations # every operation and its steps./clean.sh --dry-run --weekly
./clean.sh --dry-run --domains
./clean.sh --dry-run --account-cleanup--dry-run behaves in one of two ways depending on the underlying command:
- Commands with native
--dry-run(such asmedia remove,domains purge,accounts cull,preview_cards remove) are executed with--dry-run, so Mastodon itself reports exactly what it would do. - Commands without it (such as
statuses remove,search deploy,cache clear) are printed and skipped with a notice. - Read-only steps (health checks,
media usage, listings) run normally.
A dry run never writes or deletes files of its own.
# Custom concurrency and retention
./clean.sh --concurrency 8 --domains
./clean.sh --media-days 60 --profile-media-days 60 --weekly --yes
# Lower priority and a hard per-command limit
./clean.sh --weekly --yes --nice --step-timeout 7200
# Quiet cron output, full detail in the log
./clean.sh --weekly --yes --quiet --log-file /var/log/mm.log| Operation | Description | Default |
|---|---|---|
--domains |
Export and purge suspended domains | n/a |
--accounts |
Cull non-existent accounts, then prune | n/a |
--media |
Remove cached remote media | 90 days |
--profile-media |
Remove cached remote avatars and headers | 90 days |
--preview-cards |
Remove cached preview card images | 30 days |
--remote-statuses |
Remove unreferenced remote statuses | 90 days |
--orphaned-media |
Remove media files with no database record | n/a |
--feeds |
Rebuild home and list feeds | n/a |
--clear-cache |
Clear the Rails cache | n/a |
--elasticsearch |
Run tootctl search deploy |
n/a |
| Operation | Steps |
|---|---|
--daily |
media, profile-media, preview-cards |
--weekly |
daily + prune, remote-statuses, orphaned-media |
--monthly |
weekly + cull, elasticsearch |
| Operation | Steps |
|---|---|
--maintenance |
alias of --weekly |
--all-media |
media, profile-media, preview-cards, orphaned-media |
--full |
domains + monthly + feeds, clear-cache |
--deep-cleanup |
alias of --full |
--account-cleanup |
inactive-list, inactive-delete (opt-in), cull, prune |
| Operation | Steps |
|---|---|
--media-audit |
media-usage, orphans-preview |
--domain-audit |
domain-list, domain-health (with --probe-domains) |
--system-health |
system-info, system-stats, queue-status, cache-status |
Audits never change anything, need no --yes, and run normally during
--dry-run. Run ./clean.sh --list-operations for the authoritative list.
| Flag | Applies to | Effect |
|---|---|---|
--severity suspend|all |
domains | Which blocks to purge (default suspend) |
--include-subdomains |
domains | Also purge subdomains |
--purge-domain-blocks |
domains | Also delete the DomainBlock rows |
--no-keep-interacted |
media | Stop protecting media locals interacted with |
--remove-headers |
profile-media | Remove headers only, keep avatars |
--include-follows |
profile-media | Include accounts with local follow relationships |
--preview-cards-link-only |
preview-cards | Only link cards, keep photo and video cards |
--skip-media-remove |
remote-statuses | Do not also remove unattached media |
--feeds-skip-filled |
feeds | Skip timelines that are already filled |
--es-only LIST |
elasticsearch | Only these indices: instances,accounts,tags,statuses,public_statuses |
--es-batch-size N |
elasticsearch | Import batch size |
--es-reset |
elasticsearch | Erase and rebuild every index from scratch |
--delete-inactive-local |
account-cleanup | Actually delete inactive local accounts |
--max-deletions N |
account-cleanup | Refuse to delete more than N in one run (default 25) |
--deletion-log PATH |
account-cleanup | Audit file of deleted handles (default deleted-accounts.log) |
--probe-domains |
domain-audit | Probe suspended domains over HTTPS |
--probe-timeout SECONDS |
domain-audit | Total time limit for the probe (default 300) |
| Option | Default | Notes |
|---|---|---|
--concurrency N |
5 | 1 to 32. Mastodon's default. Each command opens up to N+1 database connections |
--media-days N |
90 | Media retention |
--profile-media-days N |
90 | Avatar/header retention |
--preview-cards-days N |
30 | Mastodon recommends at least 14 days |
--statuses-days N |
90 | Mastodon's default |
--inactive-days N |
730 | Inactive local account threshold |
--domain-batch N |
25 | Domains per tootctl call |
--mastodon-dir DIR |
current directory | Directory holding bin/tootctl |
--exec PREFIX |
none | e.g. docker compose exec -T web |
--nice |
off | nice -n 10 and ionice -c 3 |
--step-timeout SECONDS |
0 (off) | Kill any single command that runs longer |
--yes, -y |
off | Required for destructive work without a TTY |
--quiet, -q |
off | Only warnings and errors on the terminal |
--no-color |
auto | Colour only on a terminal; NO_COLOR is honoured |
--verbose |
off | Show each command and working directory |
--log-file [PATH] |
off | Append everything to a log |
--json-summary PATH |
off | Write the run result as JSON |
--lock-file PATH |
see Run locking | Lock file location |
--notify-url URL |
off | Webhook for the run result |
--notify-mode MODE |
json |
json or healthchecks |
--config PATH |
see below | Config file |
--list-operations |
n/a | Operations, their steps, and which are destructive |
Numeric values are validated in base 10, so 08 means 8 and cannot slip past a
range check.
Concurrency and connection pools. Every tootctl command that runs in
parallel resizes its own database pool to concurrency + 1 and its Redis pool
to concurrency. Keep CONCURRENCY + 1 comfortably below Postgres
max_connections (or your PgBouncer pool size) minus what Puma and Sidekiq
already hold. The default of 5 is safe for any instance; raise it once you
know your headroom.
Settings are applied in this order, later sources winning:
- Built-in defaults
- The config file
MM_*environment variables (e.g.MM_MEDIA_DAYS=30)- Command-line flags
Every setting is available in all three forms from one definition: the flag
--media-days 30, the config key MEDIA_DAYS=30, and the environment variable
MM_MEDIA_DAYS=30. Boolean settings also take a --no- flag (for example
--no-keep-interacted), and accept true/false, yes/no, on/off or 1/0
in the config file and environment.
The config file is the first one found of --config PATH, $MM_CONFIG,
/etc/mastodon-maintenance.conf, and ~/.config/mastodon-maintenance.conf. It
holds KEY=VALUE lines:
MASTODON_DIR=/home/mastodon/live
MEDIA_DAYS=30
CONCURRENCY=8
QUIET=true
NOTIFY_URL=https://n8n.example.com/webhook/mastodon-maintenanceThe file is parsed, never sourced, so $(...) or backticks in a value are
taken literally. For /etc, install it as root:mastodon mode 0640 so the
mastodon user (and the systemd unit) can read it but not change it:
install -o root -g mastodon -m 640 contrib/mastodon-maintenance.conf.example /etc/mastodon-maintenance.confIt is refused if it is writable by group or others, or owned by
anyone other than root or the current user, because it can point the script at
another directory or command prefix. See
contrib/mastodon-maintenance.conf.example
for every key.
Mastodon has built-in Administration > Content retention settings that run daily in Sidekiq. They overlap with some operations here:
- Media cache retention period removes cached remote media and preview card
images, like
--mediaand--preview-cards, but without--keep-interactedprotection and without pruning avatars and headers. - Remote content retention period deletes remote statuses older than the
period regardless of local interactions.
--remote-statusesis far more conservative: it keeps anything locals interacted with, pinned, or were mentioned in.
Both approaches work; pick whichever matches your policy.
contrib/ has ready-to-use schedules:
contrib/crontab.example: crontab entries for themastodonusercontrib/systemd/mastodon-maintenance@.serviceand.timer: a templated unit where the instance name is the operation
install -m 755 clean.sh /usr/local/bin/mastodon-maintenance
install -m 644 contrib/systemd/mastodon-maintenance@.* /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now mastodon-maintenance@weekly.timerFor daily and monthly runs, enable mastodon-maintenance@daily.timer and
mastodon-maintenance@monthly.timer and set their OnCalendar with
systemctl edit (the timer file shows how).
The service treats exit code 3 (another run holds the lock) as success.
Every run ends with a step summary showing each step's result (ok, failed,
or skipped) and duration.
--json-summary PATHwrites the same result as JSON (mode0600).--notify-url URLsends it to a webhook. A failing webhook is a warning and never fails the run. The URL is shown redacted to its host in all output.--notify-mode json(default): onePOSTwith the JSON summary when the run finishes. Works with n8n, Home Assistant, or any endpoint that takes JSON.--notify-mode healthchecks: pingsURL/startwhen the run starts, thenURLon success orURL/failon failure, with the step list as the body. Works with Healthchecks.io, Uptime Kuma push monitors, and anything else using the same convention.
Example JSON:
{"script":"Mastodon Cleanup Script","version":"3.0.0","host":"mastodon",
"mastodon_version":"4.7.6","operations":["weekly"],"dry_run":false,
"exit_code":0,"success":true,"started_at":1764400000,"duration_seconds":812,
"steps":[{"name":"media","status":"ok","duration_seconds":95}]}| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | A step failed, a prerequisite was missing, or destructive work was refused |
| 2 | Usage or configuration error |
| 3 | Another run holds the lock |
See Previewing Changes. Dry runs are the recommended first step for any operation you have not run before.
Before anything runs, the script lists every destructive step in the plan. On a
TTY you confirm once for the whole run. In automation (cron, CI, piped input) you
must pass --yes; without it the script refuses before running any step and
exits non-zero.
Operations take a lock file so two overlapping runs cannot purge or cull
concurrently. The lock is claimed atomically with its owner's PID already in
it (no flock needed). If that process is gone, because the run was killed
with SIGKILL, hit the OOM killer, or the host rebooted, the next run reports
the stale lock, replaces it, and carries on. Stale-lock recovery is guarded so
two runs recovering at the same moment cannot both proceed.
The lock lives in the first usable location of:
LOCK_FILEin the config, or$MM_LOCK_FILE/run/mastodon-maintenance.lockwhen running as root$XDG_RUNTIME_DIR/mastodon-maintenance.lock.mastodon-maintenance.lockin the current (Mastodon) directory
World-writable directories such as /tmp and /run/lock are deliberately not
used: any local user could pre-create the lock there and block maintenance.
Every step reports its own result. A failed step makes the whole run exit non-zero, so cron and monitoring see the failure instead of a green light. Later steps still run, so one failure does not silently cancel the rest.
The domain export is written to a temporary file and renamed into place, so a
failed export never destroys the previous one. A dry run exports into a private
temporary directory and leaves existing files untouched. Exports are created
with mode 0600.
- Colour on a terminal, plain text otherwise (cron mail, pipes);
NO_COLORand--no-colorturn it off - All messages carry a timestamp
--log-filewrites tocleanup_<timestamp>.log, or to the path you supply- The log captures
tootctlandrails runneroutput as well as the script's own messages, without colour codes - An existing log file is appended to, never truncated; new log files are
created with mode
0600because they can contain account handles --quietkeeps the terminal to warnings and errors, while the log still gets everything--verboseshows the exact command and working directory
Every operation except --feeds and the audits deletes or rebuilds data, and
requires --yes when stdin is not a TTY:
| Operation | What is destroyed |
|---|---|
--domains |
Accounts, statuses, and media for every suspended domain |
--accounts |
Remote accounts that no longer exist or never interacted locally |
--media |
Cached remote media older than the retention period |
--profile-media |
Cached remote avatars and headers |
--preview-cards |
Cached preview card images |
--remote-statuses |
Unreferenced remote statuses |
--orphaned-media |
Files with no database record |
--clear-cache |
Rails cache contents in Redis |
--elasticsearch |
Search indices may be rebuilt |
--daily, --weekly, --monthly |
Everything in the preset (see Scheduled Presets) |
--all-media |
All of the media rows above, plus orphaned files |
--maintenance |
Same as --weekly |
--full, --deep-cleanup |
Everything above |
--account-cleanup |
Remote accounts (cull, prune); local accounts only with --delete-inactive-local |
--account-cleanup always lists inactive local accounts. It deletes them only
with both --delete-inactive-local and --yes (or a typed confirmation).
An account qualifies only when every signal says it is abandoned:
- no web sign-in within
--inactive-days(730 by default); an account that never signed in counts from its registration date - no status posted within that period
- no OAuth token used within that period, so apps and bots that post through the API are kept
- not disabled, suspended, a bot, or holding any role (owner, admin, moderator, or a custom role)
If more accounts qualify than --max-deletions (25 by default), nothing is
deleted and the step fails, so a wrong threshold cannot remove a large part of
the instance. Every deleted handle is appended with a timestamp to
--deletion-log (mode 0600), because deletion cannot be undone. Preview with
--account-cleanup --dry-run first.
Three behaviours are worth understanding before using --domains:
- Only
suspendblocks are purged by default. A purge deletes every account and status from a domain, which only matches the intent of a suspension.--severity allalso purges silenced (limited) domains.noopblocks, which only reject media or reports, are never purged. --include-subdomainsis opt-in and off by default. Enabling it purges every subdomain of every blocked domain as well.--purge-domain-blocksis opt-in and off by default. By default theDomainBlockrecords are kept, which is what prevents the domain from re-federating. Enabling this flag deletes the blocks too, which removes that protection. Only use it when you intend to stop blocking the domain.
--domain-audit --probe-domains sends one HTTPS HEAD request to every
suspended domain and reports the status. It is opt-in because it contacts
servers you blocked, from your instance's address. Requests go through
Mastodon's own HTTP client, so they follow its proxy settings and timeouts and
never reach private network addresses. Probes run --concurrency at a time
within --probe-timeout seconds overall.
--domains batches domains into single tootctl invocations. If a batch
fails, the batch is retried one domain at a time so the failing entries are
identifiable.
./clean.sh --system-healthRead-only, so it also runs during --dry-run. It reports:
- System: Mastodon, Ruby, Rails and PostgreSQL versions, database size, storage driver, Elasticsearch state
- Statistics: users, active users, local accounts, and planner estimates for
large tables (exact counts on
statusestake minutes on big instances) - Queues: Sidekiq processes, enqueued, scheduled, retry and dead set sizes, and per-queue latency
- Cache: Redis connectivity, key count and memory use
- Minimum: Mastodon 4.7.3. The script checks this at startup and refuses to run on older releases, because several flags it uses do not exist there.
- Tested: 4.7.3 through 4.7.6
- 5.0: release candidates exist. The version check warns on releases newer than the tested one; dry-run before automating on 5.0.
The published tootctl documentation at https://docs.joinmastodon.org/admin/tootctl/
does not yet describe every command and flag present in the source. Where the
two disagree, this script follows the source in lib/mastodon/cli/*.rb.
Contributions are welcome via pull request. For substantial changes, please open an issue first to discuss the approach.
Before submitting:
bash -n clean.sh # syntax check
shellcheck clean.sh # lint
bats tests/ # full test suite (no Mastodon required)
./clean.sh --help # smoke test outside an installThe test suite uses stubbed rails and tootctl binaries under tests/stubs/,
so it runs anywhere. CI runs ShellCheck, the Bats suite on the latest Bash and on
Bash 4.4, and documentation consistency checks on every push and pull request.
Changes to any tootctl invocation must be verified against the Mastodon source
at the supported version, not against the documentation alone.
This is free and unencumbered software released into the public domain under the Unlicense. See the LICENSE file for details.
See CHANGELOG.md for the full history.
Safety, features and new defaults. Read Upgrading to 3.0 before updating scheduled jobs.
Compatibility and correctness release. Requires Mastodon 4.7.3 or newer.
Made with β€οΈ for the Mastodon community.