Skip to content

About

A comprehensive, production-ready maintenance and cleanup script for Mastodon instances. This script provides safe, automated maintenance operations that can run while your Mastodon instance is online.

Resources

Stars

6 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

27 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Mastodon Maintenance Script

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.

πŸ“‹ Table of Contents

πŸš€ Features

  • βœ… Safe defaults for every operation
  • βœ… Honest exit codes: a failed step fails the run, and "already running" has its own code
  • βœ… --dry-run with real previews where Mastodon supports them
  • βœ… One confirmation per run for destructive work, --yes for automation
  • βœ… --daily, --weekly and --monthly presets, 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_ENV checks at startup, in a single Rails boot

⬆️ Upgrading to 3.0

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.

πŸ“‹ Prerequisites

  • 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 under set -u)
  • Mastodon commands: found in this order
    1. --exec PREFIX (Docker and other wrappers)
    2. bin/tootctl and bin/rails in --mastodon-dir or the current directory
    3. tootctl and rails on PATH
  • Optional: curl (notifications), timeout (--step-timeout), ionice (--nice)
  • Environment: RAILS_ENV is set to production automatically if unset

πŸ› οΈ Installation

  1. Download a release and verify it

    Releases attach clean.sh and a SHA256SUMS file. 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
  2. Verify it runs (works outside a Mastodon directory)

    ./clean.sh --version
    ./clean.sh --help
  3. 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 mastodon user on source installs. The script warns when run as root, because new files under public/system would end up owned by root.

πŸ“– Usage

./clean.sh [OPTIONS] OPERATION [OPERATION...]

Scheduled Presets

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 maintenance

accounts cull contacts every remote account not updated in the last week, and search deploy re-imports every index, which is why both are monthly.

Basic Operations

./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 maintenance

Combining Operations and Skipping Steps

Operations 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

Previewing Changes

./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 as media 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.

Advanced Options

# 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

πŸ”§ Available Operations

Basic Operations

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

Scheduled Presets

Operation Steps
--daily media, profile-media, preview-cards
--weekly daily + prune, remote-statuses, orphaned-media
--monthly weekly + cull, elasticsearch

Combined Operations

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

Audits (read-only)

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.

Operation Modifiers

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)

βš™οΈ Configuration

Options

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.

Config File and Environment

Settings are applied in this order, later sources winning:

  1. Built-in defaults
  2. The config file
  3. MM_* environment variables (e.g. MM_MEDIA_DAYS=30)
  4. 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-maintenance

The 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.conf

It 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.

Content Retention in the Admin UI

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 --media and --preview-cards, but without --keep-interacted protection and without pruning avatars and headers.
  • Remote content retention period deletes remote statuses older than the period regardless of local interactions. --remote-statuses is far more conservative: it keeps anything locals interacted with, pinned, or were mentioned in.

Both approaches work; pick whichever matches your policy.

⏰ Scheduling

contrib/ has ready-to-use schedules:

  • contrib/crontab.example: crontab entries for the mastodon user
  • contrib/systemd/mastodon-maintenance@.service and .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.timer

For 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.

πŸ”” Notifications and Summaries

Every run ends with a step summary showing each step's result (ok, failed, or skipped) and duration.

  • --json-summary PATH writes the same result as JSON (mode 0600).
  • --notify-url URL sends 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): one POST with the JSON summary when the run finishes. Works with n8n, Home Assistant, or any endpoint that takes JSON.
    • --notify-mode healthchecks: pings URL/start when the run starts, then URL on success or URL/fail on 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}]}

Exit Codes

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

πŸ›‘οΈ Safety Features

Dry-run

See Previewing Changes. Dry runs are the recommended first step for any operation you have not run before.

Confirmation gate

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.

Run locking

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:

  1. LOCK_FILE in the config, or $MM_LOCK_FILE
  2. /run/mastodon-maintenance.lock when running as root
  3. $XDG_RUNTIME_DIR/mastodon-maintenance.lock
  4. .mastodon-maintenance.lock in 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.

Failure reporting

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.

Safe exports

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.

πŸ“Š Logging and Output

  • Colour on a terminal, plain text otherwise (cron mail, pipes); NO_COLOR and --no-color turn it off
  • All messages carry a timestamp
  • --log-file writes to cleanup_<timestamp>.log, or to the path you supply
  • The log captures tootctl and rails runner output 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 0600 because they can contain account handles
  • --quiet keeps the terminal to warnings and errors, while the log still gets everything
  • --verbose shows the exact command and working directory

🚨 Destructive Operations

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

Inactive Local Accounts

--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 suspend blocks are purged by default. A purge deletes every account and status from a domain, which only matches the intent of a suspension. --severity all also purges silenced (limited) domains. noop blocks, which only reject media or reports, are never purged.
  • --include-subdomains is opt-in and off by default. Enabling it purges every subdomain of every blocked domain as well.
  • --purge-domain-blocks is opt-in and off by default. By default the DomainBlock records 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 Probing

--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.

Batching

--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.

πŸ” Monitoring and Health

./clean.sh --system-health

Read-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 statuses take 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

🧩 Version Support

  • 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.

🀝 Contributing

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 install

The 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.

πŸ“„ License

This is free and unencumbered software released into the public domain under the Unlicense. See the LICENSE file for details.

πŸ”„ Version History

See CHANGELOG.md for the full history.

v3.0.0

Safety, features and new defaults. Read Upgrading to 3.0 before updating scheduled jobs.

v2.0.0

Compatibility and correctness release. Requires Mastodon 4.7.3 or newer.


Made with ❀️ for the Mastodon community.

About

A comprehensive, production-ready maintenance and cleanup script for Mastodon instances. This script provides safe, automated maintenance operations that can run while your Mastodon instance is online.

Resources

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages