Scaling Mastodon: A Measurement-First Architecture Guide
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
htopandjournalctl) - A log aggregation tool (optional but helpful, like Loki or ELK)
Step-by-Step
- 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/healthendpoint. Store these numbers for comparison. - 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
pidstatto see per-process usage. - Measure per-component load. Mastodon has three main parts: web (Puma), background jobs (Sidekiq), and the database (PostgreSQL). Check each separately. For Sidekiq, use
sidekiqmonor the Sidekiq web UI to see queue lengths and job latencies. For PostgreSQL, runpg_stat_statementsto find slow queries. - Set up proper monitoring. Install Prometheus and Grafana if you haven’t. Use the
mastodon-prometheusexporter or the built-in metrics endpoint (if enabled). Create dashboards for request rate, error rate, latency, Sidekiq queue sizes, and database connections. - Scale the web layer. If Puma is the bottleneck, increase the number of workers or threads. Edit
WEB_CONCURRENCYandMAX_THREADSin your environment file. Restart Mastodon and watch the metrics. Increase gradually—one worker at a time—until latency improves or CPU is saturated. - Scale Sidekiq. If background jobs are delayed, increase the number of Sidekiq processes. Set
SIDEKIQ_CONCURRENCYto 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. - Optimize the database. PostgreSQL is often the silent bottleneck. Enable
pg_stat_statements(add topostgresql.confand restart). Look for slow queries and add indexes. Mastodon’s schema already has many indexes; check for missing ones usingpg_stat_user_indexes. Increaseshared_buffersto about 25% of RAM if you have headroom. - Add caching. Mastodon uses Redis for caching. Ensure Redis has enough memory (set
maxmemoryandmaxmemory-policy allkeys-lru). Move Redis to its own machine if it’s competing with web or Sidekiq. Use a local cache likeRails.cache(already configured) and consider a CDN for static assets. - 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.
- Load test before going live. Use a tool like
aborwrkto 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. - 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_bufferstoo 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_POOLto match the total number of threads. - Forgetting to restart after config changes. Changes to
.env.productionrequire a restart of the affected services. Usesystemctl restart mastodon-webetc.
Tips
- Use a separate Redis database for Sidekiq and cache (e.g.,
REDIS_URL=redis://.../0for cache,/1for Sidekiq). - Enable
RACK_TIMEOUTto 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
htopfor 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_POOLin your environment file, but also check for slow queries that hold connections open. Usepg_stat_activityto see what’s running. - Symptoms: Redis memory full. Check
redis-cli info memory. Ifused_memoryis nearmaxmemory, 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 ANALYZEon 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.