Skip to content

Horizontal scalability PeerTube >= 9.0 ​

A PeerTube platform runs as one Node.js process that serves the API, the client, the ActivityPub routes, the static files, every job worker and the live-streaming RTMP endpoint.

Horizontal scalability lets you run additional PeerTube Node.js processes for that same platform, on the same machine or on other machines, to take most of the HTTP traffic off the main process. These extra processes are called secondary processes, and they are started with --role=secondary.

WARNING

This is an advanced deployment option. It requires object storage, a reverse proxy routing contract, a second set of processes to upgrade and monitor, and it only helps with a specific kind of load (see Do you need it?).

INFO

This is clustering, not federation: there is only one PeerTube platform, one database, one Redis, one object storage and several Node.js processes.

It is unrelated to following other platforms or video redundancy, which involve separate PeerTube platforms.

Overview ​

Primary processSecondary process
How manyExactly oneAs many as you want
Commandnode dist/servernode dist/server --role=secondary
HTTP APIThe whole APIThe whole API, except a few endpoints
/static/ filesYesNo
Built-in BitTorrent trackerYesNo
Job workersAll job typesA small subset
RTMP ingest (for lives)YesNo
TranscodingYesNo (use remote runners instead)
Database migrations at bootYesNo (use the same database as primary)
Scheduled tasks (redundancy, cleanups...)YesA small subset
EmailsSends themQueues them, the primary sends them
ConfigurationRead from its own config filesRead from its own config files for a few keys, everything else is published by the primary
Plugins & themesInstalled and updated hereInstalled by itself, to match what the primary recorded
Storage directoriesIts ownIts own: the files of the platform are in object storage

All processes share the same PostgreSQL database, the same Redis, the same object storage, the same public URL and the same secrets. They don't share storage directories. A reverse proxy in front of them decides which process gets which request.

Do you need it? ​

A secondary process helps when your platform is CPU-bound on the Node.js process itself: API requests, web client pages, ActivityPub traffic (incoming activities and outgoing broadcasts), view/watch-time tracking, socket.io connections or uploads.

That is typically a platform with many concurrent viewers or a large federation, where the main process saturates one CPU core while the machine (or your infrastructure) still has idle cores.

It does not help with:

  • Transcoding → use remote runners instead
  • Serving video files → use remote storage (S3) and a CDN instead
  • Live streaming → RTMP ingest and muxing stay on the primary process by design
  • P2P with many viewers → the built-in tracker runs on the primary process only, use an external WebTorrent tracker instead
  • Database or Redis saturation → every process hits the same database and the same Redis, so adding processes adds load there rather than removing it

Requirements ​

  • PeerTube 9.0 or newer, and the exact same version on every process
  • A shared PostgreSQL database, reachable from every process
  • A shared Redis, reachable from every process
  • Object storage (object_storage.enabled), reachable from every process, with every local file already moved to it (see Move your files to object storage)
  • A reverse proxy able to route on the request method and path, and to replay a request on the primary when a secondary answers 421 (see Configure your reverse proxy)
  • The same public URL (webserver config) and the same secrets.peertube on every process
  • Separate storage directories for every process (see Configuration files)
  • If you install plugins or themes from a local path rather than from npm, that path must exist on every process (see Plugins)

A secondary process never reads or writes the files of the primary on the file system: avatars, thumbnails, video files, captions, uploads in progress etc. all go through object storage. A secondary refuses to start if object storage is disabled or if some local files are still on the file system of the primary.

A secondary process can run on the same server as the primary (the simplest option: a machine with idle cores) or on a server of its own. Both are supported and can be mixed. A dedicated server adds network requirements, described in Run a secondary on another server.

Endpoints only served by the primary process ​

A secondary process serves the whole HTTP API, the web client, ActivityPub, feeds and socket.io. For the few endpoints below, it answers 421 Misdirected Request before doing anything, so your reverse proxy can replay the request on the primary.

MethodPathWhy
any/static/*Files of the primary file system (lives, private files...), or redirections to object storage
any/tracker/*Built-in BitTorrent tracker
PUT DELETE/api/v1/config/customThe primary writes the configuration file and publishes it to the secondaries
POST/api/v1/plugins/install, /update, /uninstallThe primary installs plugins, the secondaries sync from it
any/plugins/:name/router/*, /plugins/:name/:version/router/*Plugin custom routes can keep state in the memory of the process
GET/plugins/:name/:version/auth/:authNamePlugin external authentication
POST/api/v1/runners/jobs/:jobUUID/updateRunner live transcoding updates, handled by the live session of the primary
GET/api/v1/server/logs, /api/v1/server/audit-logsLog files of the primary
POST/api/v1/server/logs/clientWritten in the log file of the primary
GET POST/api/v1/server/debug, /api/v1/server/debug/run-commandDebug tools of the primary

Plugin websockets go to the primary in the shipped nginx template.

The other endpoints run the same plugin hooks as on the primary, provided plugins are installed for the secondary too.

Jobs processed by a secondary process ​

A secondary process also consumes the following jobs:

  • activitypub-http-broadcast (one job at a time across every process, to keep activities in order)
  • activitypub-http-broadcast-parallel
  • activitypub-http-unicast
  • import-user-archive
  • video-redundancy

Every other job (transcoding, studio edition, imports, emails, etc.) is processed by the primary, or by your remote runners.

Configure a secondary process ​

Move your files to object storage ​

Do this on the primary, before starting any secondary process.

  1. Configure object_storage in the configuration of the primary, as described in Remote storage (S3), and restart it. Every section must point to an existing bucket, otherwise PeerTube exits at startup.

  2. Move the existing files (see Migrate files from filesystem to object storage for more options):

    bash
    cd /var/www/peertube/peertube-latest
    sudo -u peertube NODE_CONFIG_DIR=/var/www/peertube/config NODE_ENV=production npm run create-move-file-storage-job -- --to-object-storage --all

    It creates one job per video, playlist, avatar/banner and uploaded image. Wait for them to complete in Administration → System → Jobs.

  3. User exports still on the file system are not moved: wait for them to expire (export.users.export_expiration, 2 days by default).

If a secondary still finds local files on the file system, it refuses to start and lists them in its logs. If files are moved back to the file system while it runs, it logs errors until you fix the problem or stop it.

Configuration files ​

The primary process is the source of truth for the platform configuration. A secondary reads only the keys that describe its own process from its own configuration files, and receives everything else from the primary through Redis.

The keys a secondary configures itself:

KeyMust be identical to the primary?
webserverYes → it is the public URL that identifies the platform
secretsYes → signs tokens, decrypts the configuration published by the primary and hashes viewer session ids
databaseYes (same database)
redisYes (same Redis)
trust_proxyDepends on your topology
listenNo → each process binds its own address/port
storageNo → every directory belongs to exactly one process
logNo → log level and rotation of this process (log files live in storage.logs)
open_telemetryNo → the Prometheus exporter binds a port, two processes on one host cannot share it

Everything else (instance name, object storage, transcoding settings, etc.) comes from the primary. Setting those keys in a secondary configuration file has no effect: they are overridden by the published configuration.

WARNING

If the primary reads its object storage credentials from the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables rather than from object_storage.credentials, set them for every secondary process too.

INFO

Watch database.pool.max (5 by default): it is a pool per process, so the connections your platform opens against PostgreSQL grow with the number of processes. Check that max_connections is comfortably above the total.

Run a secondary on the same server ​

webserver, secrets, database and redis must be identical on every process, so the simplest layout is to let the secondaries read the config/ directory of the primary and add one small file per secondary that overrides only what belongs to that process.

PeerTube uses the node-config file resolution, so with NODE_ENV=production and NODE_APP_INSTANCE=secondary-1 it loads, in that order:

  1. config/default.yaml
  2. config/production.yaml → the configuration of your platform, shared by every process
  3. config/production-secondary-1.yaml → the overrides of this secondary process

Values are deep merged, so config/production-secondary-1.yaml only contains what differs from the primary:

yaml
listen:
  # A port of its own
  port: 9100

# Must be different for each PeerTube process
storage:
  tmp: '/var/www/peertube/storage-secondary-1/tmp/'
  tmp_persistent: '/var/www/peertube/storage-secondary-1/tmp-persistent/'
  bin: '/var/www/peertube/storage-secondary-1/bin/'
  avatars: '/var/www/peertube/storage-secondary-1/avatars/'
  web_videos: '/var/www/peertube/storage-secondary-1/web-videos/'
  streaming_playlists: '/var/www/peertube/storage-secondary-1/streaming-playlists/'
  original_video_files: '/var/www/peertube/storage-secondary-1/original-video-files/'
  redundancy: '/var/www/peertube/storage-secondary-1/redundancy/'
  logs: '/var/www/peertube/storage-secondary-1/logs/'
  previews: '/var/www/peertube/storage-secondary-1/previews/'
  thumbnails: '/var/www/peertube/storage-secondary-1/thumbnails/'
  storyboards: '/var/www/peertube/storage-secondary-1/storyboards/'
  torrents: '/var/www/peertube/storage-secondary-1/torrents/'
  captions: '/var/www/peertube/storage-secondary-1/captions/'
  cache: '/var/www/peertube/storage-secondary-1/cache/'
  plugins: '/var/www/peertube/storage-secondary-1/plugins/'
  client_overrides: '/var/www/peertube/storage-secondary-1/client-overrides/'
  well_known: '/var/www/peertube/storage-secondary-1/well-known/'
  uploads: '/var/www/peertube/storage-secondary-1/uploads/'

# The primary already exposes its metrics on 9091
open_telemetry:
  metrics:
    prometheus_exporter:
      port: 9092

PeerTube creates those directories at startup, so just create a parent with write permissions:

bash
sudo -u peertube mkdir -p /var/www/peertube/storage-secondary-1

Files of the platform are in object storage, so most of those directories stay empty on a secondary.

Run a secondary on another server ​

You can also spawn a secondary on a remote server: it only needs to reach PostgreSQL, Redis and object storage, and to be reachable by your reverse proxy.

1. Install PeerTube on the secondary server ​

The secondary runs the same code as the primary, so the second server needs the same PeerTube version, the same Node.js major version and the same dependencies as a regular install (/var/www/peertube/peertube-latest, a peertube user, etc.).

You can skip what a secondary doesn't need: local PostgreSQL, local Redis and local nginx.

2. Replicate the configuration ​

Copy config/production.yaml from the primary to the secondary server:

bash
# On the primary
sudo rsync -a /var/www/peertube/config/production.yaml \
  peertube@10.x.x.x:/var/www/peertube/config/production.yaml

Repeat that copy whenever you change production.yaml on the primary.

Then, write the per-process overrides next to it, in config/production-secondary-1.yaml:

yaml
listen:
  # Must be reachable by the reverse proxy, so not 127.0.0.1 if the proxy runs elsewhere
  # Protect direct access using a VPN or firewall rules
  hostname: '10.0.0.2'
  port: 9100

# Must be different for each PeerTube process
storage:
  tmp: '/var/www/peertube/storage-secondary-1/tmp/'
  tmp_persistent: '/var/www/peertube/storage-secondary-1/tmp-persistent/'
  bin: '/var/www/peertube/storage-secondary-1/bin/'
  avatars: '/var/www/peertube/storage-secondary-1/avatars/'
  web_videos: '/var/www/peertube/storage-secondary-1/web-videos/'
  streaming_playlists: '/var/www/peertube/storage-secondary-1/streaming-playlists/'
  original_video_files: '/var/www/peertube/storage-secondary-1/original-video-files/'
  redundancy: '/var/www/peertube/storage-secondary-1/redundancy/'
  logs: '/var/www/peertube/storage-secondary-1/logs/'
  previews: '/var/www/peertube/storage-secondary-1/previews/'
  thumbnails: '/var/www/peertube/storage-secondary-1/thumbnails/'
  storyboards: '/var/www/peertube/storage-secondary-1/storyboards/'
  torrents: '/var/www/peertube/storage-secondary-1/torrents/'
  captions: '/var/www/peertube/storage-secondary-1/captions/'
  cache: '/var/www/peertube/storage-secondary-1/cache/'
  plugins: '/var/www/peertube/storage-secondary-1/plugins/'
  client_overrides: '/var/www/peertube/storage-secondary-1/client-overrides/'
  well_known: '/var/www/peertube/storage-secondary-1/well-known/'
  uploads: '/var/www/peertube/storage-secondary-1/uploads/'

# Must be different for each PeerTube process
open_telemetry:
  metrics:
    prometheus_exporter:
      port: 9092

# The reverse proxy is on another host, so trusting the loopback is not enough:
# without this, `req.ip` is the address of the proxy for every viewer, which breaks
# rate limiting, viewer session hashing and GeoIP
trust_proxy:
  - 'loopback'
  - '10.x.x.x' # IP of the machine that runs the nginx reverse proxy

WARNING

production.yaml contains secrets.peertube, your database password and your object storage credentials, so the secondary server is as sensitive as the primary one. Keep the file owned by the peertube user with 600 permissions, and treat the machine accordingly.

3. Open PostgreSQL and Redis to the secondary server ​

A standard PeerTube install binds both to the loopback interface, so they have to be opened to the secondary server, on a private network:

  • PostgreSQL → set listen_addresses in postgresql.conf, add a pg_hba.conf rule for the secondary with scram-sha-256, and enable TLS if the link is not trusted (database.ssl and database.ssl_settings in the PeerTube configuration)
  • Redis → set bind, set requirepass (redis.auth in the PeerTube configuration) since protected-mode alone does not authenticate, and enable TLS if needed (redis.enable_tls and redis.tls_settings)

Keep the secondary server close to PostgreSQL and Redis, ideally on the same local network.

4. Nothing to do for plugins, unless you install them from a path ​

Plugins need no shared filesystem: each process installs them itself, from npm, into its own storage.plugins (see Plugins).

The exception is a plugin installed from a local path rather than from npm. Either make that path available on the secondary server, or publish the plugin to npm.

Run it ​

Run the secondary using --role=secondary option or PEERTUBE_PROCESS_ROLE=secondary env variable:

bash
cd /var/www/peertube/peertube-latest
NODE_ENV=production NODE_CONFIG_DIR=/var/www/peertube/config NODE_APP_INSTANCE=secondary-1 node dist/server --role=secondary

systemd ​

PeerTube ships a template unit for secondary processes. Install it:

bash
sudo cp /var/www/peertube/peertube-latest/support/systemd/peertube-secondary@.service /etc/systemd/system/

Check the service file (PeerTube paths and security directives):

bash
sudo vim /etc/systemd/system/peertube-secondary@.service

WARNING

If the secondary runs on another machine than the primary process, remove the After=peertube.service and Wants=peertube.service lines.

Tell systemd to reload its config:

bash
sudo systemctl daemon-reload

Then run one instance per secondary process. The instance name (after @) selects the configuration file: peertube-secondary@1 runs with NODE_APP_INSTANCE=secondary-1 and therefore reads config/production-secondary-1.yaml.

bash
sudo systemctl enable --now peertube-secondary@1
sudo systemctl enable --now peertube-secondary@2

sudo journalctl -feu peertube-secondary@1

Adding a secondary later only means writing a new config/production-secondary-3.yaml (a listen.port and storage paths of its own) and running systemctl enable --now peertube-secondary@3.

To act on all of them at once:

bash
sudo systemctl restart 'peertube-secondary@*'
sudo systemctl stop 'peertube-secondary@*'

INFO

On the machine of the primary, the template is ordered after peertube.service and Wants it, so starting a secondary starts the primary if it is not running, while stopping the primary does not stop the secondaries.

Everywhere, it retries every 5 seconds, so a secondary that boots before the primary has published its configuration waits for it instead of failing.

The units of PeerTube also raise UV_THREADPOOL_SIZE (16 for the primary, 8 for the secondaries), because password hashing and actor key generation run on the libuv thread pool.

Plugins ​

Plugins and themes are registered by secondary processes too, so that the hooks run by the endpoints they serve behave exactly as on the primary.

Plugins are automatically synchronized with the secondary process storage.plugins directory during plugin installation, update and uninstallation. A secondary that fails to register a plugin the primary runs exits.

Plugins installed from a local path ​

Installing from a path (npm run plugin:install --plugin-path, or the Install from a local path field) records that path. A process that cannot reach it cannot install the plugin, so a secondary exits and restarts until the path is available.

A process only reinstalls a plugin when the version recorded in the database differs from the one it has, so if you iterate on a plugin from a local path, prefer uninstalling it and re-installing it.

Native modules ​

Plugins with native modules are compiled on each process at install time, so secondaries do not have to match the architecture of the primary. Each process rebuilds its own when its Node.js ABI changes, tracked in <storage.plugins>/.peertube-node-abi.

BitTorrent tracker ​

The built-in tracker runs on the primary only. If many viewers use P2P, replace it with an external WebTorrent tracker.

Configure your reverse proxy ​

The routing contract is:

  • Any request may go to a secondary
  • A secondary answers 421 Misdirected Request to the endpoints only the primary serves: the reverse proxy must replay them on the primary
  • A request whose body is streamed to PeerTube must target a primary-only endpoint

The nginx template shipped with PeerTube (support/nginx/peertube) implements this contract.

To scale out, add one server line per secondary to both pools:

nginx
upstream secondary_pool {
  # A secondary sharing the machine of the primary
  server 127.0.0.1:9100;
  # A secondary on a remote server
  server 10.0.0.2:9000;

  # Keep the primary in the pool, so requests survive every secondary going down
  # Add `backup` keyword if you run many secondaries and prefer to keep the primary for jobs, lives and its other duties
  server ${PEERTUBE_HOST};

  keepalive         16;
  keepalive_timeout 4s;
}

upstream secondary_sticky_pool {
  hash $remote_addr consistent;

  server 127.0.0.1:9100;
  server 10.0.0.2:9000;

  # `hash` does not support `backup`: keep the primary as a regular server
  server ${PEERTUBE_HOST};

  keepalive         16;
  keepalive_timeout 4s;
}

Notes:

  • View tracking doesn't require stickiness. The template still hashes on $remote_addr because keeping a session on one process is cheaper (because of local cache usage)
  • Socket.io requires stickiness: any process can hold a socket.io connection, but a socket.io client first connects with HTTP long-polling requests that must reach the same process
  • Uploads don't require stickiness: the chunks of a resumable upload are stored in the object storage staging bucket, so they can reach different processes
  • If a CDN or another load balancer sits in front of nginx, configure set_real_ip_from / real_ip_header, otherwise every viewer hashes to the same process
  • Websockets of the tracker and of plugins go to the primary in the shipped template
  • keepalive_timeout of the upstreams must stay below the keep-alive timeout of PeerTube (5 seconds), otherwise nginx may reuse a connection PeerTube is closing and answer 502
  • HAProxy is also a valid choice, as long as it replays 421 responses on the primary or routes primary-only endpoints there
  • Use GET /api/v1/ping as the health check endpoint for your pools

Operations ​

Upgrading ​

Only the primary runs database migrations, and two processes must never run different PeerTube versions against the same database. Upgrade in this order:

  1. Stop every secondary process: sudo systemctl stop 'peertube-secondary@*'
  2. Upgrade PeerTube and restart the primary as usual, letting it run the migrations
  3. Upgrade the PeerTube files of every other server to the same version, and copy config/production.yaml again if it changed
  4. Once the primary is up, start the secondaries on the new version: sudo systemctl start 'peertube-secondary@1' 'peertube-secondary@2'

Your reverse proxy keeps serving requests from the primary while the secondaries are down, as long as you kept ${PEERTUBE_HOST} in the pools.

When a process stops, it waits a few seconds for the ActivityPub activities it received to be processed.

Monitoring ​

Each process exposes its own Prometheus metrics on its own port, and writes its own log file (storage.logs configuration). Scrape and collect them all: a request served by a secondary appears only in that secondary's metrics and logs, so a platform monitored on the primary alone looks like it stopped receiving traffic.

The logs displayed in the PeerTube administration are the logs of the primary only.

On a secondary running on another server, remember that the exporter binds open_telemetry.metrics.prometheus_exporter.hostname, 127.0.0.1 by default, so Prometheus must either scrape it from that host or be given an address it can reach.

Checking that it works ​

  • GET /api/v1/videos returns the same result on a secondary as on the primary, including with a plugin installed that filters the video list
  • A video uploaded through your reverse proxy is published, whatever the processes that received its chunks
  • Under federation load, the secondary's logs show activitypub-http-broadcast-parallel jobs being processed
  • After installing a plugin on the primary, the secondary logs Installed plugin <name>@<version> to match the database. within seconds

Limitations ​

For now:

  • Live streaming (RTMP ingest, muxing) stays on the primary process
  • Most jobs (transcoding, studio edition, imports, emails...) are processed by the primary or by remote runners
  • The /static/ files, the built-in BitTorrent tracker, plugin custom routes, plugin external authentication and plugin websockets are served by the primary only
  • The order of incoming ActivityPub activities is preserved on a best-effort basis
  • A plugin installed from a local path makes processes that cannot reach that path exit, see Plugins
  • Each process resolves its plugins from npm on its own, so during the seconds that follow an install the processes do not all run the same plugin version yet