Skip to content

Deploying Citus (sharded PostgreSQL) — coordinator + workers on AlmaLinux 9

Stand up a Citus 12 cluster on AlmaLinux 9 with a coordinator and three workers, distribute tables by tenant id, and verify shard placement and query routing.

You operate a multi-tenant B2B SaaS on a single Postgres 16 node. The largest five tenants account for 80% of write traffic and they’re starting to compete for autovacuum, the WAL is moving fast enough that incremental backup windows are tight, and the largest fact table has crossed 800 GB. Vertical scaling buys you another six months. Horizontal sharding — sharding by tenant_id, where every tenant’s data is co-located on a single worker — is what gets you from “single-node Postgres on a very large VM” to “fleet of mid-sized workers behind a coordinator that routes every query.” Citus is the most direct path to that architecture without rewriting the application: distributed tables, reference tables, and a coordinator that plans queries against the shards.

What’s happening

Citus is a Postgres extension. The cluster has one coordinator (also called the coordinator node, formerly the “master”) and N workers. The application connects only to the coordinator. Tables are one of three types:

  • Distributed tables: split into shards by a distribution column (typically tenant_id). With 32 shards and 4 workers, each worker holds 8 shards. A query that filters on tenant_id = 42 is routed by the coordinator to exactly the worker that holds tenant 42’s shard — no fan-out, single-node performance. A query that doesn’t filter by tenant gets parallelized across all workers.
  • Reference tables: replicated in full to every worker. Use for small lookup tables (country list, plan tiers) so joins don’t need to cross the network.
  • Local tables: live only on the coordinator. Use sparingly — they’re an escape hatch, not a default.

Two architectural facts you must internalize:

  1. The shard key must appear in every distributed-table query that wants single-node performance. If your application has a query path that filters on email instead of tenant_id, that query fans out to every worker. Citus exposes citus_stat_statements so you can find these. For how to choose the distribution column and colocation groups before you create tables, read Citus sharding for PostgreSQL in depth.
  2. There is no automatic failover for workers in open-source Citus. Each worker is a single point of failure for the shards it holds. Production deployments either pair Citus with streaming replication on each worker (the worker pair becomes one logical worker via pg_auto_failover or Patroni) or accept that worker loss = partial cluster unavailability until restore. This article installs the single-instance worker variant; the HA worker variant is a layer on top.

The other gotcha is rebalancing. When you add a worker to grow the cluster, you must run SELECT rebalance_table_shards() — Citus does not move shards automatically. Rebalancing is online but is throttled, and it generates write load on the source worker.

How to verify

From the coordinator, confirm workers are registered:

SELECT nodeid, nodename, nodeport, isactive, noderole, shouldhaveshards
FROM pg_dist_node ORDER BY nodeid;

After creating distributed tables, confirm shards are placed across all workers:

SELECT logicalrelid::regclass AS table_name,
       count(*) AS shards,
       array_agg(DISTINCT (SELECT nodename FROM pg_dist_node WHERE nodeid = sp.groupid)) AS workers
FROM pg_dist_shard s
JOIN pg_dist_shard_placement sp USING (shardid)
GROUP BY logicalrelid;

Verify your query plan routes (not fans out) for a tenant-scoped query:

EXPLAIN (VERBOSE)
SELECT count(*) FROM orders WHERE tenant_id = 42;
-- Look for "Task Count: 1" — a single-shard query.
-- If "Task Count: 32" appears, the query is fanning out.

Cluster-wide shard imbalance:

SELECT nodename, count(*) AS shard_count, pg_size_pretty(sum(shard_size)) AS total
FROM citus_shards
GROUP BY nodename ORDER BY shard_count DESC;

The fix

The installer below runs on AlmaLinux 9. Run it on each node (one coordinator + three workers) after editing the NODE_ROLE, NODE_NAME, NODE_IP, and worker list at the top. It installs PostgreSQL 16 from PGDG, the Citus 12.x extension from the Citus repo, configures shared_preload_libraries = citus, opens pg_hba.conf for the private subnet, brings up the service, and (on the coordinator) registers each worker and creates the example schema with two distributed tables (tenants, orders) and one reference table (plans).

#!/usr/bin/env bash
set -euo pipefail

### AlmaLinux 9 — PostgreSQL 16 + Citus 12 installer
### Roles: coordinator | worker
### Edit the variables and run on each node

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER NODE ===
NODE_ROLE="coordinator"      # coordinator | worker
NODE_NAME="cit-coord"        # cit-coord | cit-worker1 | cit-worker2 | cit-worker3
NODE_IP="10.40.0.11"
COORDINATOR_IP="10.40.0.11"
WORKER_IPS=("10.40.0.21" "10.40.0.22" "10.40.0.23")
WORKER_NAMES=("cit-worker1" "cit-worker2" "cit-worker3")
PRIVATE_SUBNET="10.40.0.0/16"
SUPERUSER_PASSWORD="CHANGE_ME_SUPER"
APP_DB="saas"
APP_USER="app"
APP_PASSWORD="CHANGE_ME_APP"
# =====================

echo
echo "========================================"
echo "Citus ${NODE_ROLE} ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo

echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y install vim curl wget chrony fail2ban dnf-automatic \
  policycoreutils-python-utils lsof tcpdump bind-utils tar gzip \
  iproute net-tools jq socat firewalld

systemctl enable --now chronyd

echo "==> SELinux enforcing"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
setenforce 1 || true

echo "==> Kernel/sysctl tuning"
cat > /etc/sysctl.d/99-postgres.conf <<'SYSCTL'
vm.swappiness = 1
vm.overcommit_memory = 2
vm.overcommit_ratio = 90
vm.dirty_background_ratio = 3
vm.dirty_ratio = 10
fs.file-max = 2097152
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_local_port_range = 10240 65535
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-postgres.conf <<'LIMITS'
postgres soft nofile 200000
postgres hard nofile 200000
postgres soft nproc 65535
postgres hard nproc 65535
LIMITS

echo "==> Hardening SSH + fail2ban"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart sshd

cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
DNFAUTO
systemctl enable --now dnf-automatic.timer

echo "==> PGDG repo (PostgreSQL 16)"
dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf -qy module disable postgresql
dnf -y install postgresql16 postgresql16-server postgresql16-contrib

echo "==> Citus repository (community / open source)"
curl -fsSL https://install.citusdata.com/community/rpm.sh | bash
dnf -y install citus122_16 || dnf -y install citus_16

echo "==> Initializing Postgres data dir"
PGSETUP_INITDB_OPTIONS="--encoding=UTF8 --data-checksums --locale=en_US.UTF-8" \
  /usr/pgsql-16/bin/postgresql-16-setup initdb

PGDATA="/var/lib/pgsql/16/data"
PGCONF="${PGDATA}/postgresql.conf"
PGHBA="${PGDATA}/pg_hba.conf"

echo "==> postgresql.conf"
cat >> "${PGCONF}" <<EOF

# === Citus + tuning ===
shared_preload_libraries = 'citus'
listen_addresses = '${NODE_IP},127.0.0.1'
port = 5432
max_connections = 500
shared_buffers = 4GB
effective_cache_size = 12GB
work_mem = 32MB
maintenance_work_mem = 1GB
wal_level = replica
max_wal_senders = 10
max_replication_slots = 10
password_encryption = scram-sha-256
log_min_duration_statement = 500
log_line_prefix = '%m [%p] %q%u@%d '
log_checkpoints = on
checkpoint_timeout = 15min
max_wal_size = 4GB
min_wal_size = 1GB
EOF

echo "==> pg_hba.conf"
cat > "${PGHBA}" <<EOF
local   all             postgres                                peer
local   all             all                                     scram-sha-256
host    all             all             127.0.0.1/32            scram-sha-256
host    all             all             ::1/128                 scram-sha-256
host    all             all             ${PRIVATE_SUBNET}       scram-sha-256
host    replication     all             ${PRIVATE_SUBNET}       scram-sha-256
EOF
chown postgres:postgres "${PGHBA}"
chmod 640 "${PGHBA}"

echo "==> firewalld"
systemctl enable --now firewalld
firewall-cmd --permanent --zone=public --add-service=ssh
firewall-cmd --permanent --zone=public --add-rich-rule="rule family=ipv4 source address=${PRIVATE_SUBNET} port port=5432 protocol=tcp accept"
firewall-cmd --reload

echo "==> Starting PostgreSQL"
systemctl enable --now postgresql-16

sleep 5

echo "==> Setting superuser password"
sudo -u postgres /usr/pgsql-16/bin/psql -v ON_ERROR_STOP=1 -c \
  "ALTER USER postgres WITH PASSWORD '${SUPERUSER_PASSWORD}';"

echo "==> Creating Citus extension"
sudo -u postgres /usr/pgsql-16/bin/psql -v ON_ERROR_STOP=1 -c \
  "CREATE EXTENSION IF NOT EXISTS citus;"

if [[ "${NODE_ROLE}" == "coordinator" ]]; then
  echo "==> Coordinator: declare self + register workers"
  sudo -u postgres /usr/pgsql-16/bin/psql -v ON_ERROR_STOP=1 <<SQL
SELECT citus_set_coordinator_host('${COORDINATOR_IP}', 5432);
SQL
  for i in "${!WORKER_IPS[@]}"; do
    WIP="${WORKER_IPS[$i]}"
    echo "    Registering worker ${WIP}"
    sudo -u postgres /usr/pgsql-16/bin/psql -v ON_ERROR_STOP=1 -c \
      "SELECT citus_add_node('${WIP}', 5432);"
  done

  echo "==> Coordinator: create application DB + schema"
  sudo -u postgres /usr/pgsql-16/bin/psql -v ON_ERROR_STOP=1 <<SQL
CREATE DATABASE ${APP_DB};
CREATE ROLE ${APP_USER} WITH LOGIN PASSWORD '${APP_PASSWORD}';
GRANT ALL ON DATABASE ${APP_DB} TO ${APP_USER};
SQL

  sudo -u postgres /usr/pgsql-16/bin/psql -d "${APP_DB}" -v ON_ERROR_STOP=1 <<SQL
CREATE EXTENSION IF NOT EXISTS citus;

-- Reference table (replicated to every worker)
CREATE TABLE plans (
  plan_id    TEXT PRIMARY KEY,
  name       TEXT NOT NULL,
  monthly_quota_orders INTEGER NOT NULL
);
SELECT create_reference_table('plans');

-- Distributed tables, sharded by tenant_id
CREATE TABLE tenants (
  tenant_id  BIGINT NOT NULL,
  name       TEXT   NOT NULL,
  plan_id    TEXT   NOT NULL REFERENCES plans(plan_id),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id)
);
SELECT create_distributed_table('tenants', 'tenant_id');

CREATE TABLE orders (
  tenant_id   BIGINT NOT NULL,
  order_id    BIGINT NOT NULL,
  customer_id BIGINT NOT NULL,
  amount_cents INTEGER NOT NULL,
  status       TEXT NOT NULL,
  created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, order_id)
);
SELECT create_distributed_table('orders', 'tenant_id', colocate_with => 'tenants');

GRANT SELECT, INSERT, UPDATE, DELETE ON tenants, orders TO ${APP_USER};
GRANT SELECT ON plans TO ${APP_USER};
SQL

  echo "==> Seeding sample data"
  sudo -u postgres /usr/pgsql-16/bin/psql -d "${APP_DB}" -v ON_ERROR_STOP=1 <<SQL
INSERT INTO plans VALUES
  ('free', 'Free', 100),
  ('pro', 'Pro', 10000),
  ('enterprise', 'Enterprise', 1000000);

INSERT INTO tenants
SELECT g, 'tenant_' || g, CASE WHEN g % 5 = 0 THEN 'enterprise' WHEN g % 3 = 0 THEN 'pro' ELSE 'free' END
FROM generate_series(1, 1000) g;

INSERT INTO orders (tenant_id, order_id, customer_id, amount_cents, status)
SELECT (random()*999)::int + 1,
       g,
       (random()*99999)::int + 1,
       (random()*10000)::int,
       'paid'
FROM generate_series(1, 50000) g;
SQL

  echo "==> Verifying shard distribution"
  sudo -u postgres /usr/pgsql-16/bin/psql -d "${APP_DB}" <<SQL
SELECT logicalrelid::regclass AS table_name, count(*) AS shards
FROM pg_dist_shard
GROUP BY logicalrelid;

SELECT nodename, count(*) AS shard_count
FROM citus_shards
GROUP BY nodename ORDER BY nodename;
SQL

elif [[ "${NODE_ROLE}" == "worker" ]]; then
  echo "==> Worker: ready and waiting for coordinator to register it"
else
  echo "Unknown NODE_ROLE=${NODE_ROLE}"; exit 2
fi

echo
echo "========================================"
echo "DONE — ${NODE_NAME} (${NODE_ROLE})"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep ':5432' || true
echo
echo "Service status:"
systemctl is-active postgresql-16
echo
if [[ "${NODE_ROLE}" == "coordinator" ]]; then
  echo "Run a sample tenant-scoped query — expect Task Count: 1:"
  echo "  sudo -u postgres /usr/pgsql-16/bin/psql -d ${APP_DB} \\"
  echo "    -c \"EXPLAIN (VERBOSE) SELECT count(*) FROM orders WHERE tenant_id = 42;\""
fi

A couple of things to set correctly before production traffic. First, co-location matters: in the script above, orders is created with colocate_with => 'tenants', which means every shard of orders for a tenant lives on the same worker as that tenant’s row in tenants. Joins between distributed tables only stay single-node if they are co-located on the same distribution key. Get this wrong on day one and refactoring a 500 GB cluster to fix it is painful.

Second, monitor citus_stat_statements to find queries that fan out. Any query where the application omitted tenant_id is a query that hits every worker. The worst offenders are usually admin endpoints written without sharding in mind.

Third, this installer is the single-instance worker variant. Loss of one worker means loss of the shards on that worker. For production multi-tenant SaaS that can’t tolerate that exposure, layer streaming replication beneath each logical worker (each worker becomes a primary+replica pair) and use citus_update_node to point the coordinator at the standby after a failover. That’s a follow-up topology, not this article.

We design and operate Citus clusters under Managed Cloud Ops with co-location reviews, fan-out alerting, and a rehearsed worker-loss runbook — pair it with our cloud compute tier and book a sharding design session before you commit to a distribution column.