ThisCalculator

Everyday

Scaling Mastodon: A Measurement-First Architecture Guide

Updated · Standard formula, shown below

This guide walks you through scaling a Mastodon server by first measuring what’s actually under load, then applying targeted fixes. You’ll learn which metrics matter, what tools to use, and how to grow your instance in a controlled, data-driven way—avoiding common pitfalls like over-provisioning or premature optimization.

What You’ll Need

  • Root or sudo access to your Mastodon server(s)
  • Basic familiarity with Linux command line and systemd
  • Access to your Mastodon configuration file (usually .env.production)
  • An existing monitoring setup (e.g., Prometheus + Grafana, or at least htop and journalctl)
  • A log aggregation tool (optional but helpful, like Loki or ELK)

Step-by-Step

  1. Establish a baseline. Before changing anything, record current metrics: CPU, memory, disk I/O, network I/O, number of active users, and request latency. Use top, iostat, vmstat, and Mastodon’s built-in /health endpoint. Store these numbers for comparison.
  2. Identify bottlenecks. Look at which resource is maxed out first. Is it CPU (likely the web or sidekiq processes), memory (maybe RAM is low), disk (SQLite or PostgreSQL writes), or network? Use pidstat to see per-process usage.
  3. Measure per-component load. Mastodon has three main parts: web (Puma), background jobs (Sidekiq), and the database (PostgreSQL). Check each separately. For Sidekiq, use sidekiqmon or the Sidekiq web UI to see queue lengths and job latencies. For PostgreSQL, run pg_stat_statements to find slow queries.
  4. Set up proper monitoring. Install Prometheus and Grafana if you haven’t. Use the mastodon-prometheus exporter or the built-in metrics endpoint (if enabled). Create dashboards for request rate, error rate, latency, Sidekiq queue sizes, and database connections.
  5. Scale the web layer. If Puma is the bottleneck, increase the number of workers or threads. Edit WEB_CONCURRENCY and MAX_THREADS in your environment file. Restart Mastodon and watch the metrics. Increase gradually—one worker at a time—until latency improves or CPU is saturated.
  6. Scale Sidekiq. If background jobs are delayed, increase the number of Sidekiq processes. Set SIDEKIQ_CONCURRENCY to a higher value (e.g., 10-15 per process). Run multiple Sidekiq processes by creating additional systemd services (e.g., mastodon-sidekiq-2.service). Monitor queue latency; it should stay under a few seconds.
  7. Optimize the database. PostgreSQL is often the silent bottleneck. Enable pg_stat_statements (add to postgresql.conf and restart). Look for slow queries and add indexes. Mastodon’s schema already has many indexes; check for missing ones using pg_stat_user_indexes. Increase shared_buffers to about 25% of RAM if you have headroom.
  8. Add caching. Mastodon uses Redis for caching. Ensure Redis has enough memory (set maxmemory and maxmemory-policy allkeys-lru). Move Redis to its own machine if it’s competing with web or Sidekiq. Use a local cache like Rails.cache (already configured) and consider a CDN for static assets.
  9. Consider horizontal scaling. Once a single server is optimized, you can split components across machines: one for PostgreSQL, one for Redis, one for web, and one for Sidekiq. Use a reverse proxy (Nginx) to load balance web requests. For Sidekiq, ensure all processes share the same Redis and database.
  10. Load test before going live. Use a tool like ab or wrk to simulate traffic. Send requests to your web endpoint and watch the metrics. Increase load until you see errors or latency spikes. This tells you your real capacity.
  11. Iterate. Scaling is not a one-time task. After each change, re-measure, compare to baseline, and adjust. Document what you did and why, so you can revert if needed.

Common Mistakes

  • Scaling without measuring. Adding more workers when the database is the bottleneck just makes things worse.
  • Ignoring Sidekiq queues. Mastodon has multiple queues (default, push, mailers). If one is stuck, it can block everything. Monitor each queue separately.
  • Over-provisioning memory. Setting shared_buffers too high can cause swapping. Keep it below 25% of total RAM.
  • Not using connection pooling. Puma and Sidekiq need to share database connections. Set DB_POOL to match the total number of threads.
  • Forgetting to restart after config changes. Changes to .env.production require a restart of the affected services. Use systemctl restart mastodon-web etc.

Tips

  • Use a separate Redis database for Sidekiq and cache (e.g., REDIS_URL=redis://.../0 for cache, /1 for Sidekiq).
  • Enable RACK_TIMEOUT to prevent slow requests from hogging Puma workers.
  • Set up alerts for critical metrics: high Sidekiq latency, low disk space, and database connection saturation.
  • Consider using a managed PostgreSQL or Redis service (like AWS RDS or DigitalOcean Managed Redis) to offload maintenance.
  • Regularly vacuum and analyze your PostgreSQL database to keep query plans fresh.

Troubleshooting

  • Symptoms: High CPU but low latency. Likely a runaway Sidekiq job. Check htop for a process using 100% CPU, then look at Sidekiq logs for the job class. Consider adding a timeout or breaking the job into smaller chunks.
  • Symptoms: Database connections exhausted. Increase DB_POOL in your environment file, but also check for slow queries that hold connections open. Use pg_stat_activity to see what’s running.
  • Symptoms: Redis memory full. Check redis-cli info memory. If used_memory is near maxmemory, increase the limit or reduce cache TTLs. Also check for large values (e.g., redis-cli --bigkeys).
  • Symptoms: Web requests time out. Increase Puma threads, but also check if the database is slow. Run EXPLAIN ANALYZE on slow queries. Also ensure Nginx is configured with proper timeouts.
  • Symptoms: Sidekiq jobs stuck in queue. Restart Sidekiq. If that doesn’t help, check for deadlocks in PostgreSQL. Use SELECT * FROM pg_stat_activity WHERE state = 'active' to see long-running queries.

Frequently Asked Questions

How many users can a single Mastodon server handle?

It depends on usage patterns. A well-optimized server with 8 CPU cores and 16GB RAM can handle a few thousand active users, but heavy media uploads or federation can reduce that. Measure your own baseline to find your limit.

Should I scale vertically or horizontally first?

Vertical scaling (adding more CPU/RAM to the same server) is simpler and often sufficient up to a point. Horizontal scaling (splitting services across machines) is more complex but allows near-unlimited growth. Start vertical, then go horizontal when you hit hardware limits.

How do I know if my database is the bottleneck?

If CPU on the database server is high while web/Sidekiq CPUs are moderate, or if there are many slow queries in pg_stat_statements, the database is likely the bottleneck. Also watch for high connection counts.

What is the ideal number of Puma workers?

A common rule is 1-2 workers per CPU core, but you must account for memory. Each worker uses ~200-400MB. Start with 2 workers on a 4-core server, then increase while monitoring memory.

Do I need a CDN for Mastodon?

Not strictly, but a CDN can offload static asset delivery (images, CSS, JS) and reduce load on your web server. Cloudflare or similar works well. Just ensure you don’t cache dynamic API responses.

Can I run Mastodon on Kubernetes?

Yes, but it’s overkill for most instances. Kubernetes adds complexity for stateful services like PostgreSQL and Redis. Only consider it if you have a large team and need auto-scaling.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.