Deploy Postgres HA Django

Django on a Patroni cluster with primary and replica routing

Deploy Postgres HA Django

/var/lib/postgresql/data

/var/lib/postgresql/data

/var/lib/postgresql/data

Deploy and Host self hosted Postgres HA Django (Highly Available Postgres for Django) on Railway

This template gives Django a three-node Patroni Postgres cluster behind a router, with the primary on port 5432 and a replica on 5433.

About Hosting Postgres HA Django open-source software on Railway (self hosted a Patroni-backed Postgres HA setup with a router, replicas and Django read routing template)

This template runs a three-node Patroni cluster with etcd, Postgres 18.6 nodes (pg-1, pg-2, pg-3) with pgvector, PostGIS, and pg_cron, and a HAProxy router.

Railway handles containers, private networking, and redeploys, while Patroni handles leader election and failover.

Why Deploy Postgres HA Django, the Amazon RDS alternative on Railway (Railway Free Trial)

Amazon RDS Multi-AZ keeps a standby in another Availability Zone, but you pay for it and see little of the cluster.

Railway is a singular platform to deploy your infrastructure stack. Railway will host your infrastructure so you don't have to deal with configuration, while allowing you to vertically and horizontally scale it.

By deploying Postgres HA Django on Railway, you are one step closer to supporting a complete full-stack application with minimal burden. Host your servers, databases, AI agents, and more on Railway.

Railway vs Other Hosting Providers and VPS for Postgres HA Django self hosting

On Railway, the three Postgres nodes, the router, and your Django app share one project with private networking.

ProviderWhat You Get with RailwayWhat You Get with the Other Provider
DigitalOceanpg-1, pg-2, pg-3 and the router deployed with private domains already wired.Cheap Droplets, but you install and maintain Patroni, etcd, and HAProxy.
AWSThe cluster with RW 5432, RO 5433, and health on 8080 ready for Django.Fine-grained network and AZ control, with RDS Multi-AZ as a pricier managed option.
HetznerThe full HA stack deployed without server admin work.Low-cost servers with generous bandwidth, but all failover setup is on you.

Common Use Cases for hosted Postgres HA Django

  • Splitting read-heavy views onto the replica: Route list and report querysets to the read-only alias on port 5433 with a small router class. Admin dashboards and exports stop competing with checkout writes on the primary.
  • Keeping writes and migrations on the primary: The router sends every write to "default" on port 5432, and ./manage.py migrate runs against that alias. Schema changes land on the node that owns the data.
  • Surviving a primary restart: Set CONN_MAX_AGE and CONN_HEALTH_CHECKS on the default alias so Django tests reused connections. Workers reconnect cleanly after a failover instead of hitting closed sockets.
  • Running a self-hosted HA stack for about $25-60/mo: Three nodes plus the router cost far less than a managed multi-AZ tier at light use.
  • Keeping credentials and TLS in your project: Database secrets stay inside your own Railway project. The template certificate is self-signed, so use sslmode=require, not verify-full.

Dependencies for Postgres HA Django Docker hosted on Railway

This template runs a small Patroni cluster: three Postgres nodes (pg-1, pg-2, pg-3) plus an HAProxy router.

Deployment Dependencies for Managed Postgres HA Django Service (Database)

  • Node image: ghcr.io/onepush-dev/postgres-ha-node:18.6, used by pg-1, pg-2 and pg-3.
  • Router image: ghcr.io/onepush-dev/postgres-ha-router:18.6, exposing RW 5432, RO 5433 and health HTTP 8080.
  • Patroni plus etcd handle leader election, so a failed primary is replaced automatically.
  • Persistent volumes on each node keep the data directory across redeploys.
  • Shared secrets PATRONI_SUPERUSER_PASSWORD, PATRONI_REPLICATION_PASSWORD and PATRONI_RESTAPI_PASSWORD, generated on pg-1 and referenced by the other nodes.

Implementation Details for Postgres HA Django (Using Postgres HA official docker image)

Point the default alias at Postgres.PGHOST on Postgres.PGPORT (5432) and the replica alias at the same host on Postgres.PGPORT_READONLY (5433), using Postgres.PGUSER, Postgres.PGPASSWORD and Postgres.PGDATABASE.

How does Postgres HA Django compare against other ways to run highly available Postgres for Django apps

Postgres HA Django vs Amazon RDS Multi-AZ (Managed AWS Alternative)

  • Routing control: You wire the default alias to port 5432 and a replica alias to port 5433 yourself, so reads and writes split where your router says. RDS Multi-AZ gives you a standby for failover but no read endpoint for your app to target.
  • Cost shape: This template runs three Postgres nodes plus the router at roughly $25-60/mo at light use. RDS wins if you need AWS-native IAM and tight VPC integration.

Postgres HA Django vs Supabase (Hosted Postgres Platform Alternative)

  • Scope: This is a database cluster and nothing more. Supabase bundles auth, storage, and realtime APIs, which helps if you want those pieces without building them.
  • Django fit: Supabase works as a Postgres endpoint, but you do not get Patroni node control or explicit primary and replica ports.

Postgres HA Django vs Crunchy Bridge (Managed Postgres Alternative)

  • Ownership model: Crunchy Bridge runs standard Postgres as a managed service, so operations are handed off. Here you own upgrades, backups, and the Patroni config.
  • Where it wins: If you want a vendor to answer the pager for your Postgres, Crunchy Bridge is the safer pick.

Postgres HA Django vs Neon (Serverless Postgres Alternative)

  • Architecture: Neon separates compute from storage and supports branching, which suits preview environments and scale-to-zero workloads. This template is a fixed Patroni cluster with a primary and two replicas that does not scale to zero.
  • Best fit: Choose Neon for branching and bursty traffic. Choose this template for a classic primary and replica layout.

How to use Postgres HA Django (the OSS database cluster)?

  1. In your Django project, add a "default" alias in DATABASES pointing at Postgres.PGHOST on port 5432 with OPTIONS sslmode=require, and a "replica" alias on port 5433.

  2. Create a router with db_for_read returning "replica" and db_for_write returning "default", and register it with DATABASE_ROUTERS.

  3. Run ./manage.py migrate, which targets the default alias on the primary.

  4. Check GET /health (expect "Service ready") and GET /status (expect primary_up=1 and replicas_up=2).

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "HOST": os.environ["PGHOST"], "PORT": "5432",
        "NAME": os.environ["PGDATABASE"], "USER": os.environ["PGUSER"],
        "PASSWORD": os.environ["PGPASSWORD"],
        "CONN_MAX_AGE": 60, "CONN_HEALTH_CHECKS": True,
        "OPTIONS": {"sslmode": "require"},
    },
    "replica": {
        "ENGINE": "django.db.backends.postgresql",
        "HOST": os.environ["PGHOST"], "PORT": "5433",
        "NAME": os.environ["PGDATABASE"], "USER": os.environ["PGUSER"],
        "PASSWORD": os.environ["PGPASSWORD"],
        "OPTIONS": {"sslmode": "require"},
    },
}
DATABASE_ROUTERS = ["myproject.routers.PrimaryReplicaRouter"]

class PrimaryReplicaRouter:
    def db_for_read(self, model, **hints):
        return "replica"
    def db_for_write(self, model, **hints):
        return "default"

How to self host Postgres HA Django on other VPS Services (Postgres HA self hosting guide)

Running the cluster on your own VPS works the same way, as long as the router, the three Patroni nodes, and your Django app can reach each other.

Clone the Repository

Clone the template repo and move into it.

git clone https://github.com/onepush-dev/postgres-ha.git
cd postgres-ha

Install Dependencies

Create a virtual environment and install Django and the Postgres driver.

python3 -m venv .venv
source .venv/bin/activate
pip install django psycopg[binary]

Configure Environment Variables

Point PGHOST at the router, not at a single node.

export PGHOST=router.your-domain.internal
export PGPORT=5432
export PGPORT_READONLY=5433
export PGUSER=postgres
export PGPASSWORD=your-password
export PGDATABASE=railway

Start the Postgres HA Django Application

Run migrations against the primary, then start Django.

./manage.py migrate
./manage.py runserver 0.0.0.0:8000

On Railway, the platform handles the VPS networking, DNS, and TLS for you.

Official Pricing of Postgres HA Django (Postgres HA pricing)

Postgres HA Django is free and open source, so there is no license fee to pay.

Postgres HA Django cloud vs self hosted comparison (Pricing, features, costs, and more)

Self hosting this Patroni cluster trades a managed bill for hands-on upkeep.

Monthly cost of self hosting Postgres HA Django on Railway

Railway's range for this template is about $25-60/mo for three Postgres nodes plus the router at light use, rising as data and RAM grow.

System Requirements for Hosting Postgres HA Django on a VPS

On a VPS you run three Postgres nodes, etcd, and the router yourself, so plan for enough RAM to cover shared_buffers plus your working set.

Frequently Asked Questions (FAQs)

Do I need to run migrations against the replica?

No, migrate runs on the primary alias.

How do I avoid stale reads after a write?

Replication lag means a replica may not have your latest row yet, so the router alone won't prevent it.

Why do I get errors after a primary restart?

Django keeps persistent connections open, and a restarted or failed-over primary closes them.

Can I join models across the default and replica aliases?

No, Django doesn't support cross-database relations.

How many connections does each worker thread need?

Each thread holds its own connection, so the database must allow at least as many simultaneous connections as you have worker threads.


Template Content

More templates in this category

View Template
RustFS | (Just Updated) S3 Object Store, Public URL and Keys Set
S3-compatible object store, keys and public URL preset, volume kept

SuperSlowSloth
0
View Template
TimescaleDB
A PostgreSQL-based time-series database for analytics on Railway.

Rakit
1
View Template
Garage S3 Storage
Ultra-light S3 server: fast, open-source, plug-and-play.

PROJETOS
8