href="/docs/intro/distro">
Just use PostgreSQL for Everything! \
Build data infra with assembled superpowers!
This is the multi-page printable view of this section. .
Key Features
- 1: PG Extensions
- 2: PG Kernel Forks
- 3: Observability Infra
- 4: High Availability
- 5: Disaster Recovery
- 6: Infra as Code
- 7: No Containers
- 8: App Templates
- 9: Local First
- 10: Supabase
Self-hosting PostgreSQL like a Pro! \
Operate production grade Service without expertise
Get the superpower of **437** PG extensions out of the box
Self-healing architecture and hassle-free service access
Simulating MySQL, Mongo, Oracle, SQL Server upon PGSQL
Auto configured backups and PITR made simple
Describe and materialize everything with Code / Data
Pre-configured Dashboards with Grafana & Prometheus stack
Turn Postgres into a full-featured backend as a service
Harden software with HA PG: Gitlab, Odoo, Dify, and more
1 - PG Extensions
Pigsty allows you to harness the synergistic superpower of the PostgreSQL extensions ecosystem with three things:
- Catalog : Find the extension you need, with unparalleled 437 extensions included
- Repository : Get pre-made RPM/DEB packages for 10 mainstream Linux OS
- Package Manager : Install everything with a single command -
pig
Also check our blog post: PostgreSQL is eating the Database World
Extensions
TIME
GIS
RAG
FTS
OLAP
FEAT
LANG
TYPE
UTIL
FUNC
ADMIN
STAT
SEC
FDW
SIM
ETL
| Category | Count | Description |
|---|---|---|
| TIME | 11 | TimescaleDB, Versioning & Temporal Table, Crontab, Async & Background Job Scheduler |
| GIS | 20 | GeoSpatial Data Types, Operators, and Indexes, Hexagonal Indexing, OGR Data FDW, GeoIP & MobilityDB |
| RAG | 10 | Vector Database with IVFFLAT, HNSW, DiskANN Indexes, AI & ML in SQL interface, Similarity Funcs |
| FTS | 20 | ElasticSearch Alternative with BM25, 2-gram/3-gram Fuzzy Search, Zhparser & Hunspell Segregation Dicts |
| OLAP | 13 | DuckDB Integration with FDW & PG Lakehouse, Access Parquet from File/S3, Sharding with Citus/Partman/PlProxy |
| FEAT | 56 | OpenCypher with AGE, GraphQL, JsonSchema, Hints & Hypo Index, HLL, Rum, IVM, ChemRDKit, and Message Queues |
| LANG | 31 | Develop, Test, Package, and Deliver Stored Procedures written in various PL/Languages: Java, Js, Lua, R, Sh, PRQL |
| TYPE | 37 | Dedicate New Data Types Like: prefix, sember, uint, SIUnit, RoaringBitmap, Rational, Sphere, Hash, RRule |
| UTIL | 31 | Utilities such as send http request, perform gzip/zstd compress, send mails, Regex, ICU, encoding, docs, Encryption |
| FUNC | 43 | Function such as id generator, aggregations, sketches, vector functions, mathematical functions and digest functions |
| ADMIN | 36 | Utilities for Bloat Control, DirtyRead, BufferInspect, DDL Generate, ChecksumVerify, Permission, Priority, Catalog |
| STAT | 34 | Observability Catalogs, Monitoring Metrics & Views, Statistics, Query Plans, WaitSampling, SlowLogs |
| SEC | 26 | Auditing Logs, Enforce Passwords, Keep Secrets, TDE, SM Algorithm, Login Hooks, Log Erros, Extension White List |
| FDW | 22 | Wrappers & Multicorn for FDW Development, Access other DBMS: MySQL, Mongo, SQLite, MSSQL, Oracle, HDFS, DB2 |
| SIM | 16 | Protocol Simulation & heterogeneous DBMS Compatibility: Oracle, MSSQL, DB2, MySQL, Memcached, and Babelfish |
| ETL | 17 | Logical Replication, Decoding, CDC in protobuf/JSON/Mongo format, Copy & Load & Compare Postgres Databases |
Repository
Pigsty has a repository that provides 200+ extra PostgreSQL extensions on 10 mainstream Linux Distros. It is designed to work together with the official PostgreSQL Global Development Group (PGDG) repo.
You can enable the pigsty infra & pgsql repo with the pig CLI tool, or add them manually to your system:
All the RPM / DEB packages are signed with GPG Key fingerprint (B9BD8B20) in Pigsty repository.
Package Manager
“Postgres Install Genius, the missing extension package manager for PostgreSQL ecosystem”
Get started with PIG in seconds:
Then it’s ready to use, assume you want to install the pg_duckdb extension:
2 - PG Kernel Forks
Pigsty supports various PostgreSQL kernels and compatible forks, enabling you to simulate different database systems while leveraging PostgreSQL’s ecosystem. Each kernel provides unique capabilities and compatibility layers.
Database Kernels
Vanilla Postgres with 437 Extensions
Native Distributive Extension
SQL Server wire-compatible
Oracle grammar & PL/SQL compatible
MySQL wire-compatibility
Transparent Data Encryption
OLTP-optimized cloud-native storage engine
Aurora-like RAC with china domestic compliance
Backend as a Service, self-hosting Firebase
Mongo Wire-Compatibility over PostgreSQL
Choose the Right Kernel
Flexible Kernel: Choose the right kernel for your specific use case - whether you need MSSQL compatibility, Oracle features, or horizontal scaling capabilities.
| Kernel | Key Feature | Description |
|---|---|---|
| PostgreSQL | Original Flavor | Vanilla PostgreSQL with 437 extensions |
| Citus | Horizontal Scaling | Distributive PostgreSQL via native extension |
| WiltonDB | SQL Server Migration | SQL Server wire-compatibility |
| IvorySQL | Oracle Migration | Oracle Grammar and PL/SQL compatible |
| OpenHalo | MySQL Migration | MySQL wire-protocol compatibility |
| Percona | Transparent Data Encryption | Percona Distribution with pg_tde |
| FerretDB | MongoDB Migration | MongoDB wire-protocol compatibility |
| OrioleDB | OLTP Optimization | Zheap, No bloat, S3 Storage |
| PolarDB | Aurora flavor RAC | RAC, China domestic compliance |
| Supabase | Backend as Service | BaaS based on PostgreSQL, Firebase alternative |
| Cloudberry (WIP) | MPP DW & Analytics | Massively parallel processing database warehouse |
Citus (Distributive)
Citus Native Distributive
Citus transforms PostgreSQL into a distributed database system, enabling horizontal scaling across multiple nodes. Deploy native HA Citus clusters with Pigsty for better throughput and performance.
Key Features
- Distributed Tables: Automatically shard tables across worker nodes
- Distributed Queries: Execute queries across the entire cluster
- High Availability: Built-in replication and failover capabilities
- Real-time Analytics: Handle both transactional and analytical workloads
- Postgres Compatibility: Maintain full PostgreSQL feature compatibility
Use Cases
- Multi-tenant SaaS applications requiring horizontal scaling
- Real-time analytics on large datasets
- High-throughput OLTP workloads
- Applications need to scale beyond single-node limitations
Planning Required: Proper shard key selection is crucial for optimal performance and avoiding cross-shard queries.
Babelfish (MSSQL)
Babelfish SQL Server Wire Compatible
SQL Server Compatible
Beta
Create SQL Server-compatible PostgreSQL clusters with WiltonDB and Babelfish, providing wire protocol-level compatibility with Microsoft SQL Server.
Key Features
- T-SQL Support: Execute T-SQL queries natively
- Wire Protocol Compatibility: Connect using SQL Server drivers and tools
- Stored Procedures: Support for T-SQL stored procedures and functions
- Data Types: Compatible with SQL Server data types and behaviors
- Migration Tools: Simplified migration from SQL Server environments
Use Cases
- Migrating legacy SQL Server applications to PostgreSQL
- Multi-database environments requiring SQL Server compatibility
- Cost reduction while maintaining application compatibility
- Cloud migration from SQL Server to open-source alternatives
Migration Path: Ideal for organizations looking to reduce licensing costs while maintaining existing SQL Server application compatibility.
IvorySQL (Oracle)
Babelfish Oracle Grammar Compatible
Run Oracle-compatible PostgreSQL clusters with the IvorySQL kernel, open-sourced by HighGo, providing Oracle syntax and feature compatibility.
Key Features
- PL/SQL Support: Execute PL/SQL code with minimal modifications
- Oracle Syntax: Support for Oracle-specific SQL syntax and functions
- Package Support: Oracle-style package and procedure definitions
- Data Types: Oracle-compatible data types and behaviors
- Migration Tools: Utilities for Oracle to PostgreSQL migration
Use Cases
- Oracle database migration projects
- Organizations seeking Oracle feature compatibility
- Cost optimization while preserving Oracle functionality
- Development environments requiring Oracle compatibility
Enterprise Focus: Particularly valuable for enterprises with significant Oracle investments looking for migration paths.
OpenHalo (MySQL)
OpenHalo MySQL Wire-Compatible
The OpenHalo kernel provides MySQL-compatible PostgreSQL functionality, accessible using standard MySQL clients and protocols.
Key Features
- MySQL Protocol: Wire-level compatibility with MySQL protocol
- Client Compatibility: Use existing MySQL drivers and tools
- SQL Dialect: Support for MySQL-specific SQL syntax
- Migration Support: Simplified migration from MySQL environments
- Ecosystem Integration: Leverage PostgreSQL’s advanced features with MySQL compatibility
Use Cases
- MySQL application migration to PostgreSQL
- Multi-database environments requiring MySQL compatibility
- Leveraging PostgreSQL features while maintaining MySQL interface
- Gradual migration strategies from MySQL to PostgreSQL
Early Stage: Currently experimental - evaluate thoroughly before production use.
OrioleDB (OLTP)
OrioleDB OLTP Optimized Cloud Native
A PostgreSQL storage engine optimized for OLTP workloads, eliminating transaction ID wraparound issues and table bloat while supporting cloud storage.
Compatible with PostgreSQL 17, Available on all support platforms.
Key Features
- No XID Wraparound: Eliminates transaction ID wraparound maintenance
- No Table Bloat: Advanced storage management prevents table bloat
- Cloud Storage: Native support for S3-compatible object storage
- OLTP Optimization: Specifically designed for transactional workloads
- Improved Performance: Better space utilization and query performance
Use Cases
- High-frequency transactional applications
- Cloud-native deployments requiring object storage
- Applications suffering from PostgreSQL maintenance overhead
- Systems requiring consistent performance without vacuum cycles
Early Stage: Currently in Beta - evaluate thoroughly before production use.
PolarDB PG (RAC)
PolarDB Aurora Flavor RAC
Replace vanilla PostgreSQL with PolarDB PG, an open-source Aurora-like solution similar to Oracle RAC with shared storage architecture.
Key Features
- Shared Storage: Multiple compute nodes sharing the same storage layer
- Read Scaling: Add read replicas without storage duplication
- Fast Recovery: Rapid recovery through shared storage architecture
- Cost Efficiency: Reduced storage costs through sharing
- High Availability: Built-in failover and disaster recovery
Use Cases
- Applications requiring extreme read scalability
- Cost-sensitive deployments need high availability
- Cloud environments with shared storage infrastructure
- Workloads with variable read/write patterns
Cloud Architecture: Designed for cloud environments with disaggregated compute and storage.
Supabase (Firebase)
Supabase Backend as a Service
Self-host Supabase with existing managed HA PostgreSQL clusters, launching the stateless components with docker-compose for a complete Firebase alternative.
Key Features
- Real-time APIs: Auto-generated REST and GraphQL APIs
- Real-time Subscriptions: WebSocket-based real-time data sync
- Authentication: Built-in user authentication and authorization
- Storage: File storage with CDN capabilities
- Edge Functions: Serverless functions for custom logic
Use Cases
- Rapid application development with backend-as-a-service
- Real-time applications requiring instant data sync
- JAMstack applications needing serverless backend
- Mobile and web apps require authentication and storage
Full Stack: Provides a complete backend solution with PostgreSQL as the foundation.
Cloudberry (MPP)
Cloudberry MPP Data Warehouse
Install and monitor Greenplum / Cloudberry / YMatrix MPP clusters with Pigsty for large-scale analytical processing and data warehousing.
Key Features
- Massively Parallel Processing: Distribute queries across multiple nodes
- Columnar Storage: Optimized storage for analytical workloads
- Advanced Analytics: Built-in machine learning and statistical functions
- Petabyte Scale: Handle massive datasets with linear scalability
- Standard SQL: Full SQL compliance with PostgreSQL compatibility
Use Cases
- Data warehousing and business intelligence
- Large-scale analytics and reporting
- Machine learning on big datasets
- ETL processing for enterprise data platforms
Enterprise Analytics: Designed for enterprise-scale analytical workloads requiring massive parallel processing capabilities.
3 - Observability Infra
Pigsty delivers unparalleled observability with a modern monitoring stack built on industry best practices. Automatically monitor every component with 3000+ metrics, 30+ dashboards.

Complete Insight: Monitor everything from high-level cluster health to individual table statistics. Get complete insight into the past, present, and future of your infrastructure.
Architecture Overview

Pigsty’s observability infrastructure leverages battle-tested open-source components in a cohesive, production-ready stack:
Dashboards with advanced interactive visualizations
Time-series storage with powerful query language
Centralized logging with label-based indexing
Alert aggregate, management and escalation
Service Architecture
graph TB
subgraph "Observability Stack"
Grafana[Grafana :3000]
Prometheus[Prometheus :9058]
Loki[Loki :3100]
AlertManager[AlertManager :9059]
Pushgateway[Pushgateway :9091]
Blackbox[Blackbox :9115]
end
subgraph "Data Sources"
PG[(PostgreSQL)]
Node[Node Metrics]
Redis[(Redis)]
MinIO[(MinIO)]
end
subgraph "Exporters"
PGExp[pg_exporter]
NodeExp[node_exporter]
RedisExp[redis_exporter]
MinIOExp[minio_exporter]
end
PG --> PGExp
Node --> NodeExp
Redis --> RedisExp
MinIO --> MinIOExp
PGExp --> Prometheus
NodeExp --> Prometheus
RedisExp --> Prometheus
MinIOExp --> Prometheus
Prometheus --> Grafana
Prometheus --> AlertManager
Loki --> GrafanaMonitoring Dashboards
Multi-Level Dashboard Hierarchy
Pigsty provides 26+ PostgreSQL dashboards organized in a logical drill-down hierarchy:
Purpose: High-level operational visibility across entire environment Audience: Operations teams, management dashboards
Purpose: Cluster-wide PostgreSQL performance and health Audience: Database administrators, SRE teams
Purpose: Deep-dive into individual PostgreSQL instances Audience: Database developers, performance engineers
Purpose: Application-level database performance analysis Audience: Application developers, database analysts
Dashboard Features
Seamless exploration from overview to granular details with contextual linking
Flexible time windows from real-time to historical analysis over months
Dynamic filtering by cluster, instance, database, or custom labels
Visual alert correlation with metrics and direct links to alert details
Grafana Deployment
Enhanced Grafana Stack
Pigsty extends Grafana with powerful plugins and data sources for advanced analytics:
Purpose: Essential visualization capabilities for monitoring dashboards
Purpose: Rich, interactive visualizations for complex data analysis
Purpose: Connect to diverse data sources beyond traditional metrics
Purpose: Tailored user experience optimized for PostgreSQL environments
Configuration & Customization
Prometheus Stack
Complete Monitoring Ecosystem
Pigsty deploys the full Prometheus ecosystem for comprehensive observability:
Step 1
Prometheus Server
Core metrics database with advanced querying and storage capabilities
Step 2
AlertManager
Intelligent alert routing with suppression, grouping, and escalation
Step 3
Pushgateway
Batch job metrics collection for ephemeral workloads and cron jobs
Step 4
Blackbox Exporter
Network connectivity monitoring with HTTP, TCP, and ICMP probes
Pre-configured Alert Rules
pg_exporter: Advanced PostgreSQL Monitoring
Custom Metrics Engine
Pigsty’s pg_exporter is a highly customizable PostgreSQL metrics collector supporting all PostgreSQL versions with fine-grained metric control:
Advantages: Flexible, lightweight, and highly configurable
Benefit: Single exporter for heterogeneous PostgreSQL environments
Metrics Configuration
Host & Infrastructure Monitoring
Pigsty v3.7 installs node_exporter on managed nodes and registers Node,
HAProxy, Keepalived, Nginx, Etcd, MinIO, Redis, PostgreSQL, PgBouncer, and
pgBackRest targets with Prometheus when the corresponding modules are
enabled. Component ports and switches are defined by the tagged role
defaults and documented on each module’s parameter page.
External Database Monitoring
Existing PostgreSQL instances and cloud RDS can be registered with
pgsql-monitor.yml. Supply a monitor connection URL with only the required
pg_monitor privileges; Pigsty registers pg_exporter and the Grafana
datasource without provisioning or changing that database.
Data Analytics & Visualization Platform
Grafana can query both Prometheus metrics and PostgreSQL data. The bundled dashboards use variables and URL links for drill-down navigation; ECharts and other packaged plugins can visualize application or business data.
Low-Code Application Development
Grafana panels may be combined with PostgreSQL queries to build internal operational views. This is a visualization capability, not a separate Pigsty deployment module or application API.
Reusable Infrastructure
infra.yml can deploy INFRA independently from PGSQL. Nginx, DNSMasq,
Prometheus, AlertManager, Grafana, and Loki are controlled by their
documented *_enabled parameters, allowing Pigsty to reuse or coexist with
existing infrastructure.
Best Practices
- Control metric cardinality and set retention according to available disk.
- Back up Grafana configuration and keep alert notification channels tested.
- Protect monitoring endpoints with access controls and HTTPS when exposed outside the trusted network.
- Monitor the monitoring stack itself and review storage growth regularly.
Limitations & Considerations
Prometheus and Loki in v3.7 are single-node services by default. Very large metric cardinality, long retention, or complex dashboards require capacity planning. External long-term storage and HA monitoring architectures are manual integrations rather than built-in v3.7 modules.
4 - High Availability
Pigsty uses Patroni to achieve high availability for PostgreSQL, ensuring automatic failover.

Primary Failure RTO ≈ 30s, RPO < 1MB, Replica Failure RTO≈0 (reset current conn)
Overview
Pigsty’s PostgreSQL cluster has battery-included high-availability powered by Patroni, Etcd, and HAProxy.
When you have two or more instances in the PostgreSQL cluster, you have the ability to self-heal from hardware failures without any further configuration — as long as any instance within the cluster survives, the cluster can serve its services. Clients simply need to connect to any node in the cluster to obtain full services without worrying about replication topology changes.
By default, the recovery time objective (RTO) for primary failure is approximately 30s ~ 60s, and the data recovery point objective (RPO) is < 1MB; for standby failure, RPO = 0, RTO ≈ 0 (instantaneous). In consistency-first mode, zero data loss during failover is guaranteed: RPO = 0. These metrics can be configured as needed based on your actual hardware conditions and reliability requirements.
Pigsty incorporates an HAProxy load balancer for automatic traffic switching, offering multiple access methods for clients such as DNS/VIP/LVS. Failovers and switchover are almost imperceptible to the business side except for sporadic interruptions, meaning applications do not need connection string modifications or restarts.
Key Metrics
What High Availability Solves
High availability addresses critical operational challenges:
Elevates availability: RPO ≈ 0, RTO < 30s for enhanced data protection
Seamless maintenance: Minimize maintenance windows for operational convenience
Self-healing: Automatic recovery from hardware failures without human intervention
Read scaling: Distribute read-only queries across standby instances
Specific Benefits
- Enhanced data safety: Improves the availability aspect of data safety CIA to a new height
- Rolling maintenance capabilities: Enables seamless maintenance with minimal downtime
- Hardware failure recovery: Self-healing from hardware failures without human intervention
- Load sharing: Read-only requests can be distributed across standby instances
Costs of High Availability
Implementing HA introduces certain trade-offs and requirements:
Infrastructure Requirements: HA requires at least 3 nodes and additional infrastructure dependencies.
Resource Requirements
- Minimum cluster size: At least 3 nodes for proper consensus
- Additional infrastructure: Requires consensus store (Etcd) and load balancer
- Resource overhead: Additional CPU, memory, and network resources
- Operational complexity: Increased monitoring and management requirements
Limitations
High availability cannot prevent:
- Human errors and operational mistakes
- Software defects causing data corruption
- Logical data deletion or corruption
For these scenarios, additional recovery strategies are needed:
- Delayed clusters for protection against logical corruption
- Point-in-time recovery for fine-grained data restoration
- Regular backups for disaster recovery scenarios
Architecture
Pigsty’s HA architecture leverages a multi-component design that eliminates single points of failure:
Cluster Management: Orchestrates PostgreSQL processes and handles automatic failover
Consensus Store: Provides distributed configuration and leader election
Load Balancer: Routes traffic and provides service discovery
Virtual IP: Optional Layer 2 VIP binding for seamless connectivity
Component Roles
Cluster Orchestrator
- Manages PostgreSQL server processes
- Handles automatic failover and switchover
- Monitors cluster health and topology
- Configures streaming replication
- Provides REST API for cluster management
Distributed Configuration Store
- Stores cluster configuration and state
- Provides leader election mechanism
- Ensures consistent view across all nodes
- Handles network partitions gracefully
- Maintains cluster membership information
Traffic Router and Load Balancer
- Routes read/write traffic to appropriate nodes
- Provides health checking for database instances
- Offers multiple service endpoints
- Handles connection pooling and load distribution
- Supports SSL termination and connection limits
Virtual IP Management
- Manages Layer 2 Virtual IP addresses
- Provides seamless client connectivity
- Handles VIP migration during failover
- Supports multiple VIP interfaces
- Optional component for simplified client access
Implementation
Pigsty’s HA implementation follows proven patterns for PostgreSQL clustering:
Replication Architecture
Step 1
Streaming Replication
PostgreSQL uses built-in streaming replication for data synchronization between primary and standby nodes.
Step 2
Consensus-Based Leadership
Patroni uses Etcd for distributed consensus to elect cluster leader and manage topology changes.
Step 3
Automatic Failover
When primary fails, Patroni automatically promotes the most up-to-date standby to become the new primary.
Step 4
Traffic Rerouting
HAProxy detects topology changes and automatically routes traffic to the new primary instance.
Failure Scenarios
Primary Node Failure Process
- Detection: Patroni detects primary node failure (15-30 seconds)
- Leader Election: Etcd coordinates new leader selection
- Promotion: Most up-to-date standby is promoted to primary
- Reconfiguration: Remaining standbys reconfigure to new primary
- Traffic Switch: HAProxy redirects traffic to new primary
Write Service Interruption: 15-30 seconds during failover process
Standby Node Failure Process
- Detection: Immediate detection of standby failure
- Traffic Rerouting: HAProxy removes failed node from pool
- Service Continuity: Read queries continue on remaining standbys
- Automatic Recovery: Node rejoins cluster when restored
Minimal Impact: Read-only queries experience brief interruption only
Network Partition Handling
- Split-Brain Prevention: Etcd consensus prevents multiple primaries
- Quorum Requirements: Majority of nodes required for operations
- Graceful Degradation: Read-only mode in minority partitions
- Automatic Recovery: Normal operations resume when partition heals
Quorum Dependency: Requires majority of consensus nodes to remain operational
Trade-Offs
Pigsty provides configurable parameters to balance between recovery speed and data consistency:
Recovery Time Objective (RTO)
The pg_rto parameter controls failover timing and sensitivity:
Lower RTO values:
- ✅ Faster failover response
- ✅ Reduced service interruption
- ❌ Higher risk of false positives
- ❌ May cause unnecessary failovers
Higher RTO values:
- ✅ More stable, fewer false alarms
- ✅ Better tolerance for network hiccups
- ❌ Longer service interruption
- ❌ Delayed response to real failures
Recovery Point Objective (RPO)
The pg_rpo parameter limits potential data loss during failover:
Lower RPO values:
- ✅ Better data consistency
- ✅ Minimal data loss risk
- ❌ May delay failover
- ❌ Could impact availability
Higher RPO values:
- ✅ Faster failover process
- ✅ Better availability
- ❌ Potential for more data loss
- ❌ Consistency trade-offs
Configuration Examples
Use Case: Financial systems, critical transactional data
Use Case: High-traffic applications, read-heavy workloads
Use Case: Most production environments
Network Quality Impact
Network conditions significantly affect HA behavior:
- High-quality networks: Can use lower RTO values safely
- Unstable networks: Require higher RTO to prevent false positives
- WAN deployments: Need careful tuning of timeout parameters
- Local networks: Can optimize for faster failover
Monitoring and Observability
Pigsty provides comprehensive monitoring for HA cluster health:
Key Metrics
Monitor cluster topology, leader status, and member health
Track replication lag and sync status across all replicas
Log and analyze failover events and their impact
Monitor query performance and connection health
Dashboard Integration
Pigsty includes pre-built Grafana dashboards for HA monitoring:
- Cluster Overview: Real-time cluster topology and health
- Replication Monitoring: Lag metrics and sync status
- Failover Analysis: Historical failover events and timing
- Performance Metrics: Query performance during normal and failover scenarios
Best Practices
Deployment Recommendations
Anti-Affinity: Deploy cluster nodes across different physical hosts, racks, or availability zones.
- Hardware diversity: Use different hardware configurations to avoid common failure modes
- Network redundancy: Ensure multiple network paths between cluster nodes
- Storage considerations: Use local storage for best performance, shared storage for specific use cases
- Monitoring setup: Implement comprehensive monitoring before going to production
Operational Guidelines
- Regular testing: Perform controlled failover tests in non-production environments
- Capacity planning: Size cluster nodes appropriately for failover scenarios
- Backup strategy: Maintain regular backups independent of HA setup
- Documentation: Keep runbooks updated for emergency procedures
Common Pitfalls
Avoid These Common Mistakes:
- Insufficient network bandwidth between nodes
- Inadequate monitoring of replication lag
- Not testing failover procedures regularly
- Incorrect firewall configurations
Summary
Pigsty’s high availability solution provides:
- Automatic failover with sub-minute RTO
- Configurable consistency with RPO control
- Self-healing capabilities for hardware failures
- Load balancing for read scaling
- Minimal operational overhead with automated management
The combination of Patroni, Etcd, and HAProxy creates a robust, production-ready HA solution that handles the majority of failure scenarios automatically while providing the flexibility to tune behavior based on specific requirements.
High availability is not just about technology—it’s about building resilient systems that your business can depend on.
5 - Disaster Recovery
Point-in-Time Recovery (PITR) allows rolling back a PostgreSQL cluster to any specific moment in the past, preventing data loss from software defects or human errors. Pigsty uses pgBackRest for PITR, with configurable backup strategies using local filesystems or object storage like MinIO.

Time Travel for Databases: Roll back your cluster to any point in time, protecting against software defects, human errors, and data corruption scenarios that high availability cannot address.
Overview
Pigsty provides enterprise-grade Point-in-Time Recovery with zero-configuration setup, automated backups, and flexible restore options. Built on pgBackRest with MinIO/S3 support, it protects against data corruption, human errors, and logical disasters.
Minimize Recovery Point Objective with continuous WAL archiving
Enhanced data integrity protection against corruption
Improved disaster recovery capabilities with flexible restore options
How PITR Works
PITR requires two key components working together to enable point-in-time recovery:
Base Backups
Uses pgBackRest to create database cluster snapshots with multiple backup types:
- **Full backups**: Complete database cluster snapshots
- **Incremental backups**: Only changes since the last backup
- **Differential backups**: Changes since the last full backup
- **Scheduled backups**: Periodic backups configured via Crontab
WAL Archiving
Continuously archives Write-Ahead Log (WAL) segment files:
- **Continuous archiving**: Real-time WAL file preservation
- **Automatic management**: WAL files and cleanup handled automatically
- **Optional feature**: Can be disabled if PITR is not needed
Implementation
Pigsty provides two default backup strategies with flexible configuration options:
Local Filesystem Strategy
- **Frequency**: Daily full backups
- **Storage**: Local filesystem storage
- **Use case**: Single-node or local development environments
MinIO/S3 Strategy
- **Frequency**: Weekly full backup with daily incremental backups
- **Storage**: Object storage (MinIO, S3)
- **Use case**: Production environments with distributed storage
Configuration Options
Backup configuration is highly flexible with options to specify:
- Repository type: Local, S3, or other supported backends
- Retention policies: How long to keep backups
- Encryption: Secure backup storage
- Storage locations: Multiple backup destinations
Recovery Options
Recovery operations should be performed carefully as they will replace the current database state.
Recovery commands allow restoring to various points in time:
Step 1
### Latest WAL Archive
Restore to the most recent point available in WAL archives:
```bash
pg-pitr
```
Step 2
### Specific Timestamp
Restore to an exact moment in time:
```bash
pg-pitr --time="2022-12-30 14:44:44+08"
```
Step 3
### Named Restore Point
Restore to a previously created named point:
```bash
pg-pitr --name="my-restore-point"
```
Step 4
### Specific LSN or Transaction ID
Restore to a particular Log Sequence Number or transaction:
```bash
pg-pitr --lsn="0/1234567"
pg-pitr --xid="12345"
```
While PITR is powerful for data recovery, it should ideally be combined with High Availability solutions for comprehensive data protection against both logical and physical failures.
6 - Infra as Code
Pigsty provides a declarative interface: Describe everything in a config file, and Pigsty operates it to the desired state with idempotent playbooks. It works like Kubernetes CRDs & Operators but for databases and infrastructures on any nodes: bare metal or virtual machines.
Infra as Code, Database as Code: Declarative API & Idempotent Playbooks, GitOPS works like a charm.
Declare Module
You can declare modules on a single node:
And apply with playbooks:
Declare Cluster
To create a three-node HA postgres cluster with streaming replication:
And apply with:
Declare Cluster Internal
You can deep customize a database cluster:
Declare Access Control
Define advanced access control rules:
Citus Distributive Cluster
Declare a horizontally distributed Citus cluster:
Redis Clusters
Declare different types of Redis clusters:
Etcd Cluster
Declare a 3-node etcd consensus cluster:
MinIO Cluster
Declare a 3-node MinIO object storage cluster:
Pigsty enables you to describe your entire infrastructure declaratively and manage it through code, providing consistency, repeatability, and scalability for your database and infrastructure operations.
7 - No Containers
Pigsty runs on bare Linux, We support mainstream Linux distributions like EL / Debian / Ubuntu, and compatible Linux distributions like Rocky Linux, AlmaLinux, etc…
We do this on purpose. It is hard to compile and package all the postgres related packages and hundreds of extensions into RPM/DEB for each Major version x PG version x OS Arch…
But I believe this is the right thing to do. So we don’t take shortcuts like Docker, Podman, or Kubernetes.
8 - App Templates
Self-Hosting Supabase
Run Odoo the OSS ERP
Run Dify the AI workflow
Run official Admin GUI Tool
