Course
As more workloads move to the cloud, I have found that managing PostgreSQL efficiently and securely has become a core skill for data professionals.
PostgreSQL has long been one of my go-to relational databases. It is reliable, extensible, and backed by an open-source community.
But running it in the cloud - especially at scale - comes with its own set of challenges, which include: high availability, performance tuning, cost optimization, and meeting strict security requirements.
Azure Database for PostgreSQL solves many of these issues by offering a fully managed, scalable, and secure platform. In my experience, it simplifies deployment and operations while giving you the flexibility you need to build fast and adapt to evolving demands. That’s why, in this tutorial, I’ll cover everything you need to know about deploying an Azure PostgreSQL database.
> To get familiar with PostgreSQL fundamentals and how it works, check out What Is PostgreSQL? How It Works, Use Cases, and Resources.
Overview of Azure Database for PostgreSQL
Azure Database for PostgreSQL is a cloud-native, fully managed PostgreSQL service provided by Microsoft.
Designed for both small-scale and enterprise-grade workloads, it eliminates the need for manual provisioning, configuration, patching, and maintenance of database infrastructure.
Built on the trusted Azure platform, it supports three distinct deployment models, single server, flexible server, and Hyperscale (Citus), to accommodate different workloads and application architectures.
Some of the key benefits of Azure PostgreSQL include:
- Automatic patching and backups: Azure automates daily backups with customizable retention and applies security patches and updates without downtime.
- Enterprise-grade security and compliance: It supports features such as encryption at rest and in transit, role-based access control, private endpoints, and adheres to industry certifications (e.g., SOC, HIPAA, GDPR).
- Deep Azure ecosystem integration: Seamlessly connects with Azure Data Factory, Azure Monitor, Azure Active Directory, Power BI, and other services, accelerating development and enabling holistic observability.

Image showing the key benefits of Azure PostgreSQL. Created using Napkin AI.
Deployment Models and Architectural Frameworks
Azure Database for PostgreSQL supports multiple deployment models, which enables you to select the architecture that best fits your application's scalability, availability, and performance needs.
Flexible server deployment
The flexible server deployment model is the most versatile option, which offers granular control over resource configuration, availability, and performance tuning.
It is well-suited for mission-critical applications requiring high uptime and predictable performance.
High Availability (HA)
To ensure service continuity and minimize downtime, you should consider the following high availability configurations:
- Same-Zone HA: Deploys a standby replica in the same Availability Zone as the primary. It provides redundancy with faster failover times and minimal network latency.
- Zone-Redundant HA: Distributes primary and standby nodes across different Availability Zones, which offers resilience against zone-wide outages.
Scaling and optimization
To ensure performance and cost-efficiency, implement the following strategies for dynamic resource management and workload tuning:
- Vertical compute scaling: Adjust vCores and memory dynamically based on workload demand. Useful for seasonal spikes or cost savings during idle times.
- Auto stop/start: Schedule server shutdowns during off-peak hours to reduce costs.
- Storage auto-scaling: Automatically expands disk size as your data grows, eliminating the need for manual reallocation.
- IOPS tuning: Customize storage IOPS to align with workload demands, helping to reduce latency for read-heavy or write-intensive applications.
How to deploy a flexible server with HA enabled
To deploy a ‘flexible server’ with High Availability (HA) enabled, follow these steps:
01: Go to Azure Portal, then Azure Database for PostgreSQL flexible servers, and hit ‘create’.
The images below illustrate this step.
Image containing a screenshot of the Azure Portal interface showing the steps to create a new PostgreSQL flexible server (01).
Image containing a screenshot of the Azure Portal interface showing the steps to create a new PostgreSQL flexible server (02).
02: Under ‘High availability’, choose either ‘Same zone’ or ‘Zone redundant’.
The image below illustrates this step.
Image containing a screenshot of the flexible server creation, showing options for ‘Same zone’ and ‘Zone redundant’ selections.
03: Configure vCores, storage size, and IOPS settings.
04: Complete network configuration (e.g., VNet or public access) and deploy.
Image containing a screenshot of the ‘Networking’ configuration page.
Single server deployment
The single server model is designed for simplicity and quick setup.
It provides automatic backups, basic performance tuning, and minimal configuration overhead.
It is ideal for development, testing, or smaller production workloads.
Tiers available
Some of the tiers available include:
- Basic: Suitable for dev/test or lightweight applications.
- General purpose: Balanced compute and memory for standard workloads.
- Memory optimized: Enhanced memory-to-core ratio for cache-intensive workloads.
How to create a single server
01: In the Azure Portal, navigate to Azure Database for PostgreSQL servers, and hit ‘create’.
Image containing a screenshot of the Azure Portal interface showing the steps to create a new PostgreSQL single server.
02: Select a pricing tier based on workload requirements.
Refer to the Azure pricing page for the most up-to-date information on available tiers and pricing.
Image containing a screenshot of the Azure pricing page.
03: Set admin credentials, configure firewall rules, and deploy.
> If you are new to PostgreSQL, the Beginner's Guide to PostgreSQL is a great place to start working with databases before deploying them in the cloud.
Hyperscale (Citus) extension
The Hyperscale (Citus) deployment model is designed for distributed PostgreSQL use cases.
It transforms a single-node database into a horizontally scalable cluster by sharding data across worker nodes and coordinating queries efficiently.
Some of the key use cases include:
- Real-time analytics: Run concurrent queries across billions of rows with millisecond latencies.
- Multi-tenant SaaS applications: Distribute tenants across shards to isolate workloads and maintain performance.
How to create and distribute a table
01: Create a Hyperscale (Citus) server group in the Azure Portal. This sets up a distributed PostgreSQL cluster using the Citus extension.
02: Connect to the coordinator node using a tool like psql or Azure Data Studio.
Make sure you are connecting to the coordinator node (not a worker), since distributed table commands must be run from the coordinator.
03: Create the table in SQL (if it does not already exist):
CREATE TABLE your_table_name (
id SERIAL PRIMARY KEY,
distribution_column INT,
... other columns ...
);
04: Distribute the table using:
SELECT create_distributed_table('your_table_name', 'distribution_column');
Replace 'your_table_name' with your actual table name, and 'distribution_column' with a column that has good cardinality and is often used in queries.
Choosing the right deployment model
The table below outlines recommended deployment models based on common use cases.
| Use Case | Recommended Model |
|---|---|
| Low-cost development/testing | Single server |
| Large-scale, multi-tenant analytics | Hyperscale (Citus) |
| General-purpose apps with variable load | Flexible server |
Choosing the right deployment model depends on your application’s workload characteristics, high availability needs, and performance expectations.
> If you are not sure if PostgreSQL is the right choice for your project, check out PostgreSQL vs. MySQL: Choosing the Right Database for Your Project and SQLite vs PostgreSQL: A Detailed Comparison.
Become Azure AZ-900 Certified
Security and Compliance Architecture
Securing your Azure Database for PostgreSQL instance is crucial to protect sensitive data, ensure business continuity, and maintain regulatory compliance.
Azure provides robust, built-in capabilities that help enforce identity management, secure network access, and align with industry standards.
Authentication mechanisms
Authentication is the first line of defence in securing access to your PostgreSQL database.
Azure Active Directory (AAD) integration
Azure AD allows you to centrally manage users and their access to Azure resources, including PostgreSQL.
This is more secure than managing local server users and enables multi-factor authentication, conditional access, and user lifecycle management.
We can look at an example architecture:
You can integrate your on-premises Active Directory domain with Azure AD to extend your existing identity infrastructure to the cloud.
The image below illustrates a typical hybrid identity architecture:
Image illustrating a hybrid identity architecture integrating on-premises Active Directory with Azure Active Directory (Azure AD). Source: Microsoft Azure Architecture
To enable AAD authentication:
01: Register the PostgreSQL server with AAD:
- Open the Azure Portal.
- Navigate to your Azure Database for PostgreSQL flexible servers.
- Under Settings, click on ‘Active Directory admin’.
- Click ‘Set admin’, search for a user/group, then ‘Save’.
02: Set up AAD admin using Azure CLI (optional):
az postgres flexible-server ad-admin create \
--resource-group <your-resource-group> \
--server-name <your-server-name> \
--display-name <aad-user-name> \
--object-id <aad-user-object-id>
03: Connect using psql:
psql "host=<your-postgres-host> dbname=<your-db> user=<aad-user>@<tenant>.onmicrosoft.com sslmode=require"
SCRAM-SHA-256 authentication
Azure PostgreSQL supports SCRAM-SHA-256, a modern and secure password-based authentication mechanism that surpasses the outdated MD5.
Enable it in PostgreSQL server parameters:
- Navigate to the ‘server parameters’ section under flexible server in the Azure portal.
- Search for
password_encryptionand set it toscram-sha-256. - Save the changes and restart the server if required.
Row-Level Security (RLS)
Use RLS to define fine-grained access control policies, which allow only specific rows of a table to be visible or modifiable to certain users.
How to enable RLS:
01: Connect to your database and run:
ALTER TABLE employees ENABLE ROW LEVEL SECURITY;
02: Create a policy:
CREATE POLICY employee_policy
ON employees
USING (user_email = current_user);
Network protection
Protecting your Azure Database for PostgreSQL at the network level is essential to prevent unauthorized access and reduce the attack surface.
Azure provides several built-in networking features to isolate traffic and enforce access control.
01: Using private endpoints
Private endpoints allow your PostgreSQL server to be accessible only within your Azure Virtual Network, eliminating public exposure.
To configure a private endpoint:
01: Go to the Azure portal and select your PostgreSQL flexible server
02: Under ‘Settings’, click ‘Networking’.
03: Select ‘Private access (VNet integration)’.
04: Click ‘Add Private Endpoint’.
05: Provide a name and select your resource group and VNet/subnet.
06: Choose Private DNS Integration (recommended).
07: Review and create the private endpoint.
The images below show some of the main steps in the Azure portal for setting up a private endpoint.
Image showing a screenshot of the Azure portal steps for configuring a private endpoint (01).
Image showing a screenshot of the Azure portal steps for configuring a private endpoint (02).
02: Network Security Groups (NSGs)
NSGs control inbound and outbound traffic to network interfaces and subnets. Use them to allow only trusted IPs to connect.
To configure NSGs for your private endpoint:
01: Navigate to the subnet where your private endpoint resides.
02: Attach an NSG and define rules such as:
- Allow only IP ranges from your organization.
- Deny all other inbound connections.
03: Cross-Region Peering
For global applications, use VNet Peering between Azure regions to securely route traffic between virtual networks.
To set up cross-region peering in the Azure portal:
01: In the Azure portal, go to ‘Virtual networks’ and select ‘Peerings’.
02: Click ‘Add’ and select the remote virtual network (VNet).
03: Enable ‘Use remote gateways for cross-region connectivity’.
Compliance certifications
Azure Database for PostgreSQL complies with a broad range of industry and government standards, which ensures data protection and legal alignment:
Some of the certifications include:
- GDPR
- HIPAA
- SOC 1/2/3
- ISO/IEC 27001, 27018
- FedRAMP, PCI-DSS
You can view the compliance status on the Microsoft Trust Center and download compliance reports relevant to your region or industry.
Performance Optimization and Monitoring
Maximizing performance and reliability is critical for production workloads.
Azure provides tools for intelligent tuning, real-time monitoring, and alerting to ensure your PostgreSQL server runs optimally.
Intelligent tuning
Azure enables proactive performance improvement through built-in analytics and optimization tools.
Use cases include automatic scaling, workload distribution, and storage performance enhancement.
Use Azure Advisor for performance recommendations
Azure Advisor analyzes telemetry data and recommends best practices.
To apply performance recommendations:
01: Go to Azure Portal and select ‘Azure Advisor’.
02: Click on ‘Recommendations’, then ‘Performance’.
03: Look for your PostgreSQL flexible server.
04: Apply suggestions such as:
- Scaling vCores
- Increasing IOPS
- Using read replicas
Create a read replica
Offload read-heavy workloads by creating replicas. To do this:
01: In the Azure portal, select your PostgreSQL server.
02: Under ‘Settings’, choose ‘Replicas’.
03: Click ‘Add Replica’, select the region, and create it.
04: Use the read-only endpoints in your application.
Monitoring framework
Azure Monitor provides deep visibility into the health and usage of your PostgreSQL resources.
Key metrics to monitor
- CPU utilization
- Memory usage
- Disk I/O and IOPS
- Query execution time
- Active connections
- Connection failures
To view metrics:
Step 01: Go to the Azure portal and open Monitor.
Step 02: Click ‘Metrics’ and select your PostgreSQL flexible server.
Step 03: Choose a metric (e.g., CPU %).
Step 04: Apply filters and set aggregation (e.g., average, max).
Step 05: Create visual charts or pin them to dashboards.
Creating alert rules
Alerts help you act on performance anomalies before they impact users.
To create an alert:
Step 01: In the Azure portal, go to Monitor and select ‘Alerts’.
Step 02: Click ‘New Alert Rule’.
Step 03: Select your PostgreSQL resource.
Step 04: Choose a condition, e.g., CPU usage > 80%.
Step 05: Set the evaluation period and frequency.
Step 06: Define an action group (email, webhook, Logic App).
Step 07: Name and create the alert.
Key Performance Indicators (KPIs)
Monitoring KPIs ensures your system is healthy and meets SLAs:
|
KPI |
Description |
|
CPU Utilization |
Should stay below 75% for optimal performance |
|
Memory usage |
High usage can lead to slow queries or OOM kills |
|
Query duration |
Track slow queries using query performance logs |
|
Active connections |
Indicates concurrent user load |
|
Storage utilization |
Helps predict when auto-scaling may trigger |
You can view and analyze these KPIs in Azure Monitor Metrics.
Migration and Integration Patterns
Migrating databases to Azure Database for PostgreSQL can be seamless with the right tools and strategy.
Azure supports both online and offline migration, multiple source systems, and integration with AI and development tools.
> If you want a hands-on tutorial on working with PostgreSQL in real-world development environments, read through Using PostgreSQL in Python.
Database Migration Service (DMS)
Azure Database Migration Service (DMS) facilitates secure, guided migration from various database platforms (on-premises or cloud) to Azure PostgreSQL.
The image below illustrates supported migration scenarios and platforms:
Diagram showing Azure Database Migration Service (DMS). Source: Microsoft Products
Performing a migration using DMS
01: Create a DMS instance:
- Go to the Azure portal and search for ‘Database Migration Services’.
- Click ‘Create’, then choose your subscription, resource group, and region.
- Select ‘Integration Runtime (IR)’ and create or reuse an existing IR.
02: Create a migration project:
- Inside your DMS instance, click ‘Add New Migration Project’.
- Provide a name and set:
- Source server type: PostgreSQL
- Target server type: Azure Database for PostgreSQL
- Migration activity type: Online or Offline
03: Define source and target servers:
- Enter connection details for the source PostgreSQL server (on-prem, AWS RDS, etc.).
- Enter credentials for the target Azure PostgreSQL flexible server.
04: Run and monitor migration:
- Choose the databases/schemas to migrate.
- Configure table mapping and optional data transformation.
- Start migration and monitor progress in the Azure portal.
Migrating from on-premises or other clouds
For smaller or one-off migrations, you can use PostgreSQL native tools like pg_dump and pg_restore.
Offline migration via CLI
To perform an offline migration from an on-premises or other cloud PostgreSQL database to Azure, follow these steps:
01: Export the database from the source:
pg_dump -Fc --no-acl --no-owner -h <source-host> -U <source-user> dbname > db.dump
02: Import to Azure PostgreSQL:
pg_restore -h <azure-host> -U <azure-user> -d <target-db> db.dump
A tip would be to use --jobs flag with pg_restore for faster performance on large databases.
Migrating from Oracle to PostgreSQL
To migrate from Oracle to PostgreSQL, you can use Ora2Pg to convert Oracle schemas into PostgreSQL-compatible syntax. Follow these steps:
01: Install Ora2Pg.
02: Configure the ora2pg.conf file with your Oracle credentials.
03: Run the following commands:
ora2pg -c ora2pg.conf -o schema.sql
psql -h <azure-host> -U <user> -d <dbname> -f schema.sql
> To strengthen your ability to manage databases post-migration, have a look at Managing Databases in PostgreSQL.
AI Integration Capabilities
Azure PostgreSQL enables AI workloads using the pgvector extension, and can integrate with Azure Cognitive Services.
To enable and use pgvector:
CREATE EXTENSION IF NOT EXISTS vector;
02: Create and use vector columns:
CREATE TABLE embeddings (
id SERIAL PRIMARY KEY,
description TEXT,
embedding vector(1536)
);
03: Insert and search vectors:
INSERT INTO embeddings (description, embedding)
VALUES ('example', '[0.1, 0.2, 0.3, 0.4]');
SELECT * FROM embeddings
ORDER BY embedding <-> '[0.1, 0.2, 0.3, 0.4]'
LIMIT 5;
04: Integrate with AI services:
- Use Azure OpenAI, Cognitive Search, or Azure ML to generate embeddings.
- Store and query them using pgvector in PostgreSQL.
Cost Optimization Techniques
Azure offers multiple strategies to reduce PostgreSQL infrastructure and operational costs.
Flexible server pricing
To optimize costs with flexible server pricing options, you should follow these guidelines:
01: Use Burstable SKUs (e.g., B1ms) for development or low-CPU workloads.
- In the Azure portal, go to PostgreSQL and select ‘Pricing tier’.
- Choose ‘Burstable’.
02: Reserved capacity:
- Commit to 1 or 3 years of use to get up to 60% savings.
- Purchase via the Azure portal by going to ‘Reservations’, clicking ‘Add’, and selecting ‘PostgreSQL flexible server’.
Hyperscale (Citus) economics
Hyperscale uses horizontal sharding to improve throughput.
Benefits include:
- Load balancing across nodes
- Better resource isolation
- Storage efficiency via compression
Enable Hyperscale by going to the Azure portal, selecting ‘Create Resource’, and then choosing ‘Azure Database for PostgreSQL (Hyperscale, Citus)’.
Storage and backup cost management
To effectively manage storage and backup costs, you should consider the following steps:
Review snapshot retention:
- Azure keeps daily backups by default.
- Go to ‘Server settings’, then ‘Backups’, and adjust the ‘Retention Period’ (default is 7–35 days).
Estimate costs using Azure Pricing Calculator:
- Azure Pricing Calculator.
- Add PostgreSQL flexible server, choose region, SKU, backup retention, and IOPS.
Managing PostgreSQL Versions and Upgrades
Keep your environment secure and supported by regularly applying updates.
Supported versions and lifecycle policy
Understanding the supported PostgreSQL versions and their lifecycle policy is important for maintaining a secure and supported environment:
- Azure supports PostgreSQL versions 11–16.
- Version support is aligned with the PostgreSQL community EOL policy.
- Plan upgrades before EOL to maintain support and security.
Upgrading and patching
Upgrading and patching your PostgreSQL flexible server involves both automatic and manual processes, depending on the type of update:
- Minor version updates are applied automatically.
- Major upgrades require manual steps:
Steps to upgrade:
01: Backup current database:
pg_dumpall -h <current-host> -U <user> > backup.sql
02: Create a new server with the desired PostgreSQL version from the Azure Portal.
03: Restore backup to the new server:
psql -h <new-host> -U <user> -f backup.sql
04: Update connection strings in your application or environment variables.
Development Ecosystem
Azure PostgreSQL supports modern DevOps and geospatial workloads.
Infrastructure-as-Code (IaC)
Use Terraform for repeatable, automated provisioning. Here’s a sample Terraform script to create an Azure PostgreSQL flexible server:
resource "azurerm_postgresql_flexible_server" "example" {
name = "mypgflexserver"
resource_group_name = "myrg"
location = "East US"
administrator_login = "pgadmin"
administrator_password = "password123!"
sku_name = "Standard_B1ms"
version = "14"
}
To create the resource, run terraform init → terraform plan → terraform apply.
> To learn more, check out our comprehensive guide on using Terraform with Azure.
Geospatial capabilities with PostGIS
PostGIS extends PostgreSQL for spatial and geographic queries.
To enable PostGIS:
CREATE EXTENSION postgis;
Use for location-based apps, mapping, route optimization, and geofencing.
Popular extensions & integrations
Enable powerful PostgreSQL extensions to enhance observability and scheduling:
|
Extension |
Purpose |
|
pg_stat_statements |
Track and analyze query performance |
|
uuid-ossp |
Generate UUIDs |
|
postgis |
Geospatial queries |
|
pg_cron |
Schedule background jobs in SQL |
To enable the desired extensions, navigate to the Azure Portal and go to your PostgreSQL flexible server.
From there, access the Server Parameters section, locate the azure.extensions setting, add the required extensions as a comma-separated list, and save the changes.
Conclusion
Azure Database for PostgreSQL empowers you to deploy, scale, and manage PostgreSQL with enterprise-grade reliability, security, and performance in the cloud.
As cloud demands evolve, leveraging Azure’s robust ecosystem and PostgreSQL’s proven reliability will ensure your applications remain agile, compliant, and cost-efficient.
If you want to deepen your knowledge, I highly recommend checking out the Azure Fundamentals skill track. Happy learning!
