Azure Database for PostgreSQL and MySQL: The Complete Advanced Guide

Azure Database for PostgreSQL and MySQL: The Complete Advanced Guide

A book-quality walkthrough of Microsoft's managed open-source relational databases, from the first idea of a managed database to storage internals, high availability, security, performance tuning, migration, and cost control.

Imagine you own a busy restaurant. You could grow your own vegetables, raise your own chickens, repair the freezer when it breaks at midnight, and still try to cook dinner for two hundred guests. Or you could buy fresh ingredients from a trusted supplier who also keeps the freezer running, replaces broken equipment, and guards the pantry door. Running a database yourself is like the first option. Using Azure Database for PostgreSQL or MySQL is like the second. You keep the cooking, which means your tables, queries, and business logic, and Microsoft handles the kitchen plumbing.

This guide teaches you everything about these two services in plain language. We start from the very beginning, explaining every new word the first time it appears, and we build slowly toward advanced topics such as failover internals, replication topologies, key management, and capacity planning. You do not need to be a database expert to begin, and by the end you will think like one.

1Databases, Relational Thinking, and the Case for Managed Services

Before we meet the Azure services, we need a shared understanding of what a relational database is and why running one is harder than it looks.

What a database actually is

A database is an organized place to store information so that programs can find it again quickly and safely. A relational database keeps that information in tables, which look like spreadsheets. Each table has columns that describe the kind of data, such as a name or a price, and rows that hold individual records, such as one customer or one order. Tables are connected to each other through shared values called keys. An order row might hold a customer number, and that number points to a row in the customer table. This connection is the “relation” in the word relational.

Simple Analogy

Think of a school. One notebook lists all students, another lists all classes, and a third lists which student attends which class. Nothing is repeated, yet you can answer questions like “Who is in Mathematics on Monday?” by following the links between notebooks. A relational database is that school office, but it answers in milliseconds and never loses a notebook.

The language of relational databases

Programs talk to relational databases using a language called SQL, short for Structured Query Language. SQL lets an application ask for data, add new data, change existing data, or remove it. Both PostgreSQL and MySQL understand SQL, although each adds its own dialect and special features. They are both open source, which means their source code is public and a worldwide community improves them.

ACID: the promise that protects your data

Serious databases follow a set of guarantees called ACID. Atomicity means a group of changes either all happen or none happen, like a bank transfer that must both remove money from one account and add it to another. Consistency means the data always obeys the rules you defined. Isolation means two people working at the same time do not see each other’s half-finished work. Durability means that once the database says “saved”, the data survives a power cut. Every feature you will read about in this guide, from write-ahead logs to zone-redundant standby servers, exists to protect these four promises at scale.

Why running your own database is hard

Installing a database on a virtual machine takes an afternoon. Keeping it healthy for ten years takes a team. Someone must apply security patches, plan upgrades, schedule backups, test that those backups can really be restored, watch disk space, tune memory, set up a standby server, practice failover, rotate certificates, and answer the phone at three in the morning. Each task is small, but together they form a permanent job known as database administration.

i
Key Idea

A managed database service does not remove the need to understand databases. It removes the repetitive operational chores so your people can spend their time on schema design, query quality, and application behavior, which are the parts that make your product different.

What “managed” means in practice

In a managed service the cloud provider operates the machines, the operating system, the database engine installation, the backup system, the monitoring plumbing, and the failover machinery. You receive a connection address, a login, and a set of settings that you can adjust. You are still responsible for what lives inside the database: the tables, indexes, users, queries, and data quality. This split of duties is called the shared responsibility model, and we will return to it when we discuss security.

Term 1

Table

A grid of rows and columns that stores one kind of thing, such as customers or invoices.

Term 2

Index

A sorted shortcut that helps the database find rows fast, like the index at the back of a book.

Term 3

Transaction

A bundle of changes treated as one unit, which either fully succeeds or fully rolls back.

Term 4

Query

A question or command written in SQL that asks the database to read or change data.

Term 5

Schema

The blueprint that describes which tables, columns, and relationships exist.

Term 6

Engine

The core software, such as PostgreSQL or MySQL, that stores data and answers queries.

2Meet Azure Database for PostgreSQL and MySQL

Two engines, one family of managed services, and one deployment model that you should use for every new project.

The two services

Azure Database for PostgreSQL is Microsoft’s managed service for the PostgreSQL engine. Azure Database for MySQL is its managed service for the MySQL engine. Both are built around the same operating philosophy: Microsoft runs the infrastructure, you choose the size and settings, and the service provides automatic backups, built-in security, monitoring hooks, and optional high availability. Because they share a philosophy, many concepts you learn for one transfer directly to the other.

Flexible Server: the deployment model that matters

Older material you may find online mentions “Single Server”, an earlier deployment option. Single Server has been retired for both engines, and Flexible Server is now the model you use for all new work. Flexible Server gives you more control than the older design. You can pick your availability zone, choose between same-zone and zone-redundant high availability, stop the server to save money during quiet periods, schedule your own maintenance window, and connect through private networking. When this guide says “the service” it always means Flexible Server.

!
Common Mistake

Reading an old tutorial and following Single Server instructions. Features, limits, and even connection formats differ. Always check that a page you are reading talks about Flexible Server and check its publication date.

Where the services fit among Azure data options

Azure offers many data services. Azure SQL targets the Microsoft SQL Server engine. Azure Cosmos DB targets globally distributed document and key-value workloads. Azure Database for PostgreSQL and MySQL target teams that want the open-source engines, the huge ecosystem of drivers, frameworks, and extensions, and freedom from vendor-specific SQL. If your application already runs on PostgreSQL or MySQL somewhere else, moving to the Azure services is typically the smallest change possible, since your code continues to speak the same protocol.

2
Open-source engines supported
1
Current deployment model: Flexible Server
3
Compute tiers for each engine

The current landscape

The services evolve monthly. As of late 2026, the PostgreSQL service supports versions from 13 through 18, with PostgreSQL 18 having reached general availability in November 2025. The MySQL service supports the community versions 5.7, 8.0, and 8.4, with 5.7 only in extended support. Microsoft ships a new service release roughly every month; new servers receive it first, and existing servers receive it during their next scheduled maintenance window. Because details change fast, treat this guide as a map of concepts and confirm exact limits in the official documentation before making a purchase or architecture decision.

Web and mobile application backends

A shopping app stores customers, products, carts, and orders in PostgreSQL or MySQL on Azure and lets the platform handle backups and failover while developers ship features.

Content management and e-commerce platforms

Popular platforms such as WordPress, Drupal, and Magento were designed around MySQL, so the MySQL service is a natural, low-friction home for them.

Analytics-flavored and AI-flavored applications

Teams building search, recommendations, or retrieval-augmented generation use PostgreSQL extensions that store and compare vector embeddings right next to their business data.

3PostgreSQL or MySQL: Choosing the Right Engine

The managed wrapper is similar, but the engines underneath have different personalities. Picking the one that fits your workload saves years of friction.

Two engines, two personalities

PostgreSQL is often described as the feature-rich, standards-focused engine. It supports advanced data types such as arrays, ranges, geometric shapes, and rich JSON storage, plus powerful indexing choices, sophisticated query planning, and an extension system that lets the community add whole new capabilities. MySQL is often described as the simple, fast, widely deployed engine. It has a long track record in web workloads, an enormous base of tutorials and hosting support, and a straightforward replication model that many teams already understand.

Simple Analogy

PostgreSQL is like a professional workshop with every tool on the wall, including some you will use once a year. MySQL is like a well-organized toolbox that fits in your car and handles ninety percent of daily jobs. Neither is better in the abstract. The right choice depends on which jobs you actually have.

TopicPostgreSQLMySQL
StrengthsComplex queries, rich data types, extensions, strict standards behaviorSimple read-heavy web workloads, broad hosting and tooling support
JSON handlingBinary JSON type with powerful indexing and query operatorsNative JSON type with functions, less index flexibility
ExtensionsLarge ecosystem including vector search, geospatial, scheduling, graph, and morePlugin model is narrower on the managed service
Scale-out option on AzureElastic clusters spread data across multiple nodesRead replicas for read scale-out; sharding handled by the application
Replication stylePhysical streaming replicas, logical replicationBinary-log based replication, with data-in and data-out patterns
Typical fitLine-of-business systems, analytics-adjacent, geospatial, AI searchWeb apps, content platforms, legacy PHP and similar stacks

How to decide

Start from your existing assets. If a vendor product requires MySQL, or your team has ten years of MySQL experience and tooling, stay with MySQL. If you are building a new system that will need advanced querying, strict data integrity features, geospatial data, or vector search for AI, PostgreSQL is usually the more comfortable home. If you are unsure, choose the engine your team can operate and debug confidently, because a well-understood database always beats a theoretically better one that nobody can troubleshoot.

i
Practical Tip

Do not pick an engine from a feature list alone. Build a one-week prototype with a realistic slice of your data and your hardest three queries, then measure. Real numbers settle debates faster than opinions.

“A database you understand beats a database you merely admire.”

4Architecture and Core Components

Understanding the moving parts turns the service from a magic box into a system you can reason about.

The big picture

Every Flexible Server deployment has a few essential parts. There is a compute layer, which is the virtual machine running the database engine. There is a storage layer, which holds the data files, the transaction logs, and the temporary files. There is a networking layer, which controls who can reach the server. There is a control plane, which is the Azure management system that creates, scales, patches, and repairs servers on your behalf. Finally, when high availability is enabled, there is a standby copy of the compute and storage ready to take over.

flowchart LR
  APP["Application"] --> NET["Networking Layer: public access or private access"]
  NET --> GW["Gateway and Connection Routing"]
  GW --> CMP["Compute: Database Engine"]
  CMP --> STO["Storage: Data Files and Logs"]
  CP["Azure Control Plane"] -.manages.-> CMP
  CP -. manages .-> STO
  CMP -. replicates .-> SBY["Standby Compute and Storage"]
        
FIG 1 — Main building blocks of a Flexible Server deployment

Control plane versus data plane

The control plane is where management actions happen: creating a server, changing its size, turning on high availability, restoring a backup. These actions go through Azure Resource Manager, the same front door used by every Azure resource. The data plane is where your application talks to the database engine using the normal PostgreSQL or MySQL protocol. The two planes are deliberately separate. If the control plane has a hiccup, your running database keeps serving queries, and if your application floods the data plane with traffic, you can still scale the server through the control plane.

Resource hierarchy

Inside Azure, a server lives in a resource group, which lives in a subscription, which belongs to a tenant. A single server can host many databases, and each database holds many tables. Permissions, policies, tags, and cost reports can be applied at any of these levels, which makes governance easier in large organizations.

Component

Compute

Provides virtual CPUs and memory to run the engine and handle connections.

Component

Storage

Durable disks holding data, indexes, and transaction logs, replicated for safety.

Component

Gateway

Routes incoming connections to the right server, even after failover changes the underlying machine.

Component

Built-in Pooler

On PostgreSQL, a managed PgBouncer option shares a small number of real connections among many clients.

Component

Standby

A second copy of the server that is kept in sync and promoted if the primary fails.

Component

Backup Service

Takes snapshots and archives logs automatically so you can restore to a chosen moment.

Simple Analogy

Picture an airport. Passengers are your application requests. The control tower is the control plane, deciding where planes park and which runway to use. The runway and aircraft are the compute and storage that do the real work. When the tower closes for a short break, planes already in the air still land safely, which is why the two are separated.

5Compute Tiers and Sizing

Choosing the right size is a balance between performance, resilience, and cost, and it can be changed later.

The three tier families

Compute is sold in tiers that describe the ratio of CPU to memory and the intended workload. The Burstable tier is designed for development, testing, and light workloads that are idle most of the time and need short bursts of power. It accumulates credits while quiet and spends them when busy. The General Purpose tier offers a balanced ratio of CPU to memory and suits most production applications. The memory-heavy tier, called Memory Optimized on PostgreSQL and Business Critical on MySQL, offers more memory per virtual core for workloads that cache large working sets, run heavy joins, or serve many concurrent sessions.

TierBest forWatch out for
BurstableDevelopment, test, small internal tools, low-traffic sitesSustained high CPU exhausts burst credits and slows the server
General PurposeMost production web and business applicationsMemory may become the limit before CPU for large working sets
Memory Optimized or Business CriticalLarge caches, heavy reporting, high concurrencyHigher price per core, so confirm the need with real metrics

Scaling up and down

You change compute size through the control plane. The service provisions the new size and restarts the database, which causes a short interruption. On servers with high availability, recent platform improvements allow the switch to use the standby first, which reduces how long clients are disconnected. In mid-2026 the PostgreSQL service reduced its gateway switch time during failover and scaling from several minutes at worst to under one minute, which is a good example of why you should read the monthly release notes.

!
Common Mistake

Scaling compute to fix a slow query. If one query reads a million rows because an index is missing, doubling the CPU only makes the slow query slightly less slow while doubling your bill. Fix the query first, then right-size.

How to size sensibly

Begin with your current workload numbers. Measure peak concurrent connections, typical CPU use, memory pressure, and the size of the frequently read data, which is called the working set. If the working set fits in memory, queries are fast because the engine rarely touches disk. If it does not, input and output pressure rises and latency becomes unpredictable. Choose a size that keeps typical CPU under about sixty percent so spikes have room, then revisit monthly using the platform metrics.

1

Measure the baseline

Capture CPU, memory, connections, and storage input and output for at least one full business cycle.

2

Pick a starting tier

Use General Purpose unless data clearly shows a memory-heavy need or a tiny, spiky workload.

3

Load test

Replay realistic traffic and watch for saturation in CPU, memory, connection counts, and storage limits.

4

Set alerts and review

Create alerts at warning thresholds and review sizing every month or after any major release.

6Storage, IOPS, and Premium SSD v2

Storage is where durability meets performance, and the newest storage option changes how you plan capacity.

What storage holds

The storage layer holds your data files, your indexes, and the transaction logs that record every change. Temporary files used for sorting large results also use space. All data is encrypted at rest by default using strong encryption keys managed by Azure, and you can choose to bring your own keys, which we cover in the security chapter.

Three measurements of storage

Storage is described by three numbers. Capacity is how many gigabytes or terabytes you can store. IOPS, short for input and output operations per second, is how many separate reads and writes the disk can perform each second. Throughput is how many megabytes per second can flow through. A database full of tiny random lookups cares most about IOPS, while a nightly report scanning huge tables cares most about throughput. In traditional disk designs these numbers were tied together: to get more IOPS you had to buy more capacity, even if you did not need the space.

Simple Analogy

Storage is like a highway. Capacity is the length of the road, IOPS is how many cars can enter per second, and throughput is how much total cargo flows past a point. In older designs you could only widen the road by also making it longer, which wasted land.

Premium SSD v2: independent scaling

Premium SSD v2 separates the three numbers so you can set capacity, IOPS, and throughput independently. On the PostgreSQL service, Premium SSD v2 reached general availability in April 2026, including support for customer-managed keys and online storage expansion. On the MySQL service, Premium SSD v2 entered private preview in July 2026, and it also brings support for newer compute families. Availability varies by region and compute size, so always check current documentation before planning around it.

Advantages

  • Pay for the IOPS and throughput you need without over-buying capacity
  • Change performance settings as workloads grow or shrink
  • Better fit for databases with small data but heavy transaction rates
  • Online expansion reduces planned downtime for growth

Disadvantages / Trade-offs

  • More knobs to understand and monitor
  • Regional and size availability may be limited at first
  • Some features can be restricted during preview stages

Storage autogrow and limits

Storage can be configured to grow automatically as data increases, which protects against the nightmare of a database that stops accepting writes because the disk is full. Growth is usually one-way: you can add storage but cannot shrink it later without migrating to a new server. For that reason, set alerts on storage percentage and plan growth deliberately rather than relying on autogrow as a permanent safety net.

i
Practical Tip

Treat a full disk as an outage. Create an alert that fires well before eighty percent usage, because large maintenance operations such as index rebuilds temporarily need extra space.

7Internal Working: How a Write Travels Through the System

Following one change from application to durable storage reveals why logs, buffers, and replication matter.

Step one: the connection arrives

Your application opens a connection using the server name. The gateway receives it, checks which physical machine currently hosts the server, and forwards the traffic. This indirection matters: after a failover the underlying machine changes but the name stays the same, so your application does not need a new address.

Step two: the engine plans and executes

The engine parses your SQL, plans the cheapest way to answer it, and executes the plan. Changes are first applied to pages held in memory, in an area called the buffer pool in MySQL and shared buffers in PostgreSQL. These in-memory pages are fast but vulnerable to power loss, so the engine cannot rely on them alone for durability.

Step three: the log makes it durable

Before the engine tells your application “committed”, it writes a description of the change to a transaction log. PostgreSQL calls this the write-ahead log, and MySQL’s InnoDB engine uses a redo log. Writing a small sequential log entry is much faster than rewriting a scattered data page, so databases write the log immediately and flush the data pages to disk later in the background. If the server crashes, it replays the log on restart and recovers every committed change. This is the technical heart of the durability promise.

sequenceDiagram
  participant A as Application
  participant G as Gateway
  participant E as Engine
  participant L as Transaction Log
  participant S as Standby
  A->>G: Send change request
  G->>E: Route to primary
  E->>E: Update page in memory
  E->>L: Write log entry to storage
  E->>S: Ship log to standby when HA is on
  S-->>E: Acknowledge receipt
  E-->>A: Report commit success
        
FIG 2 — Life of a committed write with high availability enabled

Step four: replication and archiving

With high availability, the log is also shipped to a standby so it holds the same committed changes. With read replicas, the same log stream feeds additional servers that answer read queries. The log is also archived to backup storage continuously, and this archive is what makes point-in-time restore possible, because a base snapshot plus the log can rebuild the database at any moment you choose.

ANTI-PATTERN-01 Avoid
Problem

Teams disable or weaken durability settings to chase benchmark speed, accepting that a crash could lose recent commits.

Why It’s Harmful

A faster benchmark is worthless if a power event or failover silently erases orders that customers already paid for. Managed services protect against hardware loss, but they cannot recover changes the engine was told not to persist.

Correct Approach

Keep the default durability behavior for business data, and gain speed through better indexes, batching, connection pooling, and right-sized storage performance instead.

8High Availability and Failover

Hardware fails, zones lose power, and software restarts. High availability is the design that keeps your application running through all of it.

What high availability means

High availability, often shortened to HA, is the ability of a system to keep working when one of its parts breaks. For a database this means that if the machine running your server fails, another machine takes over quickly, with no committed data lost. Without HA, a hardware failure means waiting for the platform to rebuild a server, which can take minutes or longer. With HA, a ready-made standby is waiting and takes over in a short, predictable time.

Simple Analogy

A hospital keeps a backup generator beside the main power line. The generator is switched on and warm, and a switch moves the load automatically when the grid fails. Nobody in the operating room notices more than a flicker. A standby database server plays the same role.

Two HA modes

Flexible Server offers two ways to place the standby. In same-zone HA, the primary and the standby live in the same availability zone, which is one physical data center building within a region. This protects against server-level failures and planned maintenance, but not against loss of the whole building. In zone-redundant HA, the standby sits in a different availability zone, so even the loss of a complete data center does not take your database offline. Zone-redundant HA costs the same compute and storage again for the standby, plus a small latency cost because commits must be acknowledged across zones, but it gives the strongest protection available inside a region.

AspectWithout HASame-Zone HAZone-Redundant HA
Standby copyNoneYes, same buildingYes, different building
Survives server failureAfter rebuildYes, fastYes, fast
Survives zone outageNoNoYes
CostBaselineRoughly double compute and storageRoughly double compute and storage
Write latencyLowestSlightly higherSlightly higher still due to cross-zone trips

How failover happens

The service continuously monitors the primary. If it detects a failure, it promotes the standby, which already holds every committed transaction, and redirects traffic. Your application keeps using the same server name. Connections that were open are dropped, so a well-written application must retry. You can also trigger a planned failover yourself to test your application or to move the primary to a different zone. On the MySQL service, newer HA configurations use a dedicated Standard Load Balancer in front of the pair so traffic can be redirected without waiting for DNS changes, which noticeably shortens failover time. On the PostgreSQL service, the gateway switch time during failover and scaling was reduced to under a minute in 2026.

flowchart TD
  A["Primary server fails"] --> B["Platform detects failure"]
  B --> C["Standby is promoted to primary"]
  C --> D["Traffic is redirected to the new primary"]
  D --> E["Application reconnects with retry logic"]
  C --> F["A new standby is built in the background"]
        
FIG 3 — Failover sequence in a high availability deployment

Planned versus unplanned events

Unplanned failover is triggered by failures. Planned failover happens during maintenance or when you ask for it. Both result in the same short connection interruption, but planned events let you choose a quiet moment. With HA enabled, maintenance such as minor version upgrades is applied first to the standby, which then takes over, reducing visible downtime.

!
Common Mistake

Believing HA replaces backups. HA protects against infrastructure failure. It faithfully copies your mistakes too: if someone deletes a table, the standby deletes it a moment later. Backups and point-in-time restore protect against human error and data corruption.

i
Practical Tip

Rehearse failover before you need it. Trigger a planned failover in a test environment while a load generator runs, and watch how long your application takes to recover. The result usually reveals missing retry logic, overly long connection timeouts, or stale connection pools.

9Backup, Restore, and Disaster Recovery

A backup you have never restored is only a hope. This chapter explains how the service protects your data and how to plan for the worst day.

Automatic backups

Both services take backups automatically with no work from you. A snapshot of the storage is taken regularly, and the transaction logs are archived continuously in between. Together they allow point-in-time restore, which means you can rebuild the database as it was at any second inside your retention window. The retention window is configurable, and the default is seven days with the option to extend to about thirty-five days. Restoring always creates a new server, so your original server is not overwritten, which is a safety feature that lets you compare the old and restored data side by side.

Simple Analogy

Think of a security camera that stores one clear photo every day and also records a continuous video in between. To see exactly what the room looked like at 2:13 on Tuesday, you take the nearest photo and play the video forward to that exact moment. Base snapshot plus log is that photo plus video.

Backup redundancy

Backup storage can be kept redundant inside the region, with copies spread across zones where the region supports it, or it can be geo-redundant, with a copy asynchronously stored in the paired region hundreds of miles away. Geo-redundant backup lets you perform a geo-restore after a regional disaster. The trade-off is that the remote copy is slightly behind, so the amount of recent data you could lose, known as the recovery point, is larger than with in-region protection.

Long-term retention

Some industries must keep backups for years. The PostgreSQL service offers long-term retention backups that can be kept far beyond the normal window, and in 2026 the platform improved the reliability and failure visibility of these backups. Check current documentation for retention limits and region availability, because this area is evolving.

Recovery vocabulary

Metric

RPO

Recovery Point Objective: the most data loss your business can accept, measured in time, such as five minutes.

Metric

RTO

Recovery Time Objective: how long your business can wait for the system to return, such as one hour.

Action

Point-in-time restore

Rebuilds a server to a chosen second within the retention window.

Action

Geo-restore

Rebuilds a server in the paired region from geo-redundant backup after a regional disaster.

Safety Net

Restore a dropped server

Lets you recover a server that was deleted by mistake, within a limited window.

Protection

Resource locks

Azure locks stop accidental deletion of servers and resource groups.

Designing a recovery strategy

Start from RPO and RTO, not from features. An internal reporting database might accept a day of data loss and a day of recovery time, so default backups are plenty. A payments database might need near-zero data loss and a recovery within minutes, which calls for zone-redundant HA, a cross-region read replica ready for promotion, and regularly rehearsed runbooks. Write the plan down, assign owners, and test it at least twice a year, because configurations drift and people forget.

1

Define RPO and RTO per system

Agree on the loss and downtime the business can tolerate for each database and write them down.

2

Match features to targets

Select backup redundancy, HA mode, and cross-region replicas to meet those targets.

3

Document runbooks

Record who does what, in which order, including application configuration changes.

4

Rehearse

Practice restores and region failovers on a schedule and measure the actual time taken.

“Backups are a promise. Restore tests are the proof.”

10Networking and Connectivity

Who can reach your database, and by which road, is one of the most important decisions you will make.

Two connectivity models

A Flexible Server can be reachable in two main ways. With public access, the server has an address on the public internet, protected by firewall rules that list which client addresses may connect. With private access, the server is injected into a virtual network, which is your own private network space in Azure, and receives only a private address that is unreachable from the internet. Alongside these, private endpoints let you attach a private address from your network to a server through Azure Private Link, which suits organizations that already use private endpoints for other services. In 2026 the services continued to improve migration paths from virtual network integration to private endpoints, including for servers that already have high availability enabled.

Simple Analogy

Public access with firewall rules is a shop on the main street with a guard checking an approved visitor list. Private access is an office inside a gated campus. Visitors cannot even see the building from the street, so there is nothing to knock on.

OptionHow it worksGood forConsider
Public access with firewallInternet address, allowed client listQuick starts, remote developers, simple setupsKeep lists small and review often
Private access with VNet integrationServer placed in a delegated subnetStrict isolation inside Azure networksSubnet planning, DNS zone setup, mode chosen at creation time on some paths
Private endpointPrivate address attached via Private LinkHub and spoke networks, on-premises accessDNS configuration and per-endpoint cost

DNS: the quiet troublemaker

Private networking depends on private DNS, the naming system that turns a server name into a private address. Many outages in private deployments are not database problems at all. They happen because a client resolves the name to the public address, or to nothing, because the private DNS zone is not linked to the correct network. When connection problems appear in a private setup, check name resolution before anything else.

Encryption in transit

Connections to both services are encrypted using TLS, the same technology that protects websites. Modern versions of TLS are supported, and the MySQL service added TLS 1.3 support even for the older 5.7 version in early 2026. You can require encrypted connections and set a minimum TLS version. Certificates are renewed automatically by the platform, and in 2026 the MySQL service began renewing them earlier in their lifetime to reduce the risk of expiry-related connection failures. Your client applications should trust the current root certificates, and your team should track announcements about certificate authority changes.

Connection pooling

Each connection to a PostgreSQL server consumes memory because the engine dedicates a separate process to it. Applications that open thousands of connections, for example many small microservices or serverless functions, can exhaust memory long before CPU runs out. A connection pooler sits between the application and the database, keeping a small number of real connections and sharing them among many clients. The PostgreSQL service includes a built-in PgBouncer option that you can switch on with a setting, which removes the need to run your own pooler. MySQL uses threads rather than processes, so it tolerates more connections, but a pooling layer in the application or an intermediate proxy is still valuable for bursty workloads.

!
Common Mistake

Allowing every Azure service or a very wide address range through the firewall “just to get it working”. This quietly exposes the database to far more traffic than intended. Use narrow rules, or move to private connectivity.

flowchart LR
  subgraph VNET["Your Virtual Network"]
    APP["Application Subnet"] --> PE["Private Endpoint or Delegated Subnet"]
  end
  PE --> DB["Flexible Server"]
  DNS["Private DNS Zone"] -.resolves name.-> APP
  INTERNET["Public Internet"] -. blocked .-> DB
        
FIG 4 — Private connectivity keeps the database off the public internet

11Security: Identity, Encryption, and Governance

Security is built in layers, so that a failure in one layer is caught by the next.

The shared responsibility model

Microsoft secures the physical data centers, the host machines, the platform software, and the default encryption of data. You secure your identities, your network exposure choices, your database permissions, and your data classification decisions. A common source of incidents is assuming the provider handles something that is actually the customer’s job, such as removing an old firewall rule or rotating a shared password.

Authentication: proving who you are

Both services support traditional database users with passwords. The PostgreSQL service now defaults to SCRAM, a modern password-exchange method that never sends the password itself, for new servers on recent versions. Both services also support Microsoft Entra ID, Azure’s identity system, so people and applications sign in with their organizational identity or a managed identity instead of a stored password. Managed identities are especially valuable because an Azure application can authenticate without any secret in its configuration, and access disappears the moment the identity is removed. Entra group login, introduced in preview in 2025, lets you grant database access to a group so that membership changes flow automatically.

Simple Analogy

A database password is a physical key that anyone can copy and keep forever. Entra ID sign-in is a company badge that the security desk can deactivate in one click, that expires automatically, and that records every door it opens.

Authorization: deciding what each identity can do

Once a user is identified, the database decides what they may read or change. Follow the principle of least privilege: give each application account only the rights it needs, keep administrator accounts for administrators, and separate accounts for read-only reporting from those that write data. Roles in the database group permissions so you can manage them by job function rather than person by person.

Encryption at rest and customer-managed keys

By default, data, backups, and temporary files are encrypted on disk with keys managed by the platform. For organizations with compliance requirements, customer-managed keys allow you to hold the master key in Azure Key Vault or a hardware-backed managed module, and to revoke access by disabling the key. Recent improvements include automatic key version updates, support for hardware-backed key vaults at higher protection levels on the MySQL service, and a preview of cross-tenant customer-managed keys on the PostgreSQL service. The cost of this control is operational: if your key is deleted or access is lost, the database becomes unreadable, so protect keys with soft-delete, purge protection, backups, and tight access policies.

!
Common Mistake

Turning on customer-managed keys without a key recovery plan. Losing the key is equivalent to losing the data, and no support case can reverse it.

Threat protection, auditing, and governance

Detect

Microsoft Defender for Cloud

Flags suspicious activity such as unusual login patterns or potential brute-force attempts against open-source databases.

Record

Audit logging

Records who connected and which statements ran, so investigators can reconstruct events.

Enforce

Azure Policy

Applies rules at scale, such as requiring private access or specific TLS versions on every server.

Protect

Key Vault

Stores encryption keys and secrets with access control, rotation, and logging.

ANTI-PATTERN-02 Avoid
Problem

One shared administrator login is embedded in every application and used by every developer.

Why It’s Harmful

Nobody can tell who did what, a single leaked secret exposes everything, and rotating the password requires coordinated changes across every system, so it never gets done.

Correct Approach

Use managed identities or Entra ID accounts, give each application its own least-privilege role, keep the administrator account for emergencies, and send audit logs to a central place.

12Scaling Out: Read Replicas and Elastic Clusters

Scaling up means a bigger server. Scaling out means more servers sharing the work. Both services offer ways to scale out reads, and PostgreSQL adds a way to scale writes too.

Read replicas

A read replica is a copy of your server that receives every change from the primary and serves read-only queries. Most applications read far more than they write, so sending reports, search pages, and dashboards to replicas frees the primary for writes. Replication is asynchronous, which means a replica can lag slightly behind the primary. Your application must accept that a user who just saved data might not see it immediately on a replica, and should read from the primary when freshness matters. Replicas can be placed in the same region or a different region, which also helps users who are far from the primary and doubles as a disaster recovery option because a replica can be promoted to become an independent server.

Simple Analogy

A library has one master catalog that librarians update, plus several photocopies placed in different reading rooms. Readers consult the nearby copy, which is fast and avoids queues at the main desk, but a book added a minute ago might not appear on the copy yet.

Modern replica features on PostgreSQL

The PostgreSQL service supports virtual endpoints, which give your application a stable name that always points to the current primary or to the replica set, so promoting a replica does not require changing application configuration. Cascading replicas, which are replicas fed by other replicas rather than the primary, reached general availability in 2026, reducing load on the primary when you need many copies or a chain across regions. Logical replication and logical decoding are also available for streaming individual table changes to other systems.

Replication on MySQL

The MySQL service supports read replicas built on the engine’s binary log replication. It also supports data-in replication, which lets a Flexible Server act as a replica of a MySQL server running elsewhere, which is a powerful migration technique, and data-out patterns to send changes to other systems. A recent improvement allows self-service configuration of binary log row metadata, which unblocked several change data capture tools that previously needed support tickets.

Elastic clusters for PostgreSQL

A single server has an upper limit on how much write traffic and data it can handle. Elastic clusters in Azure Database for PostgreSQL address this by spreading data across several nodes, a technique called sharding. Tables are split into pieces based on a chosen key, such as a tenant identifier, and each node stores a share. Queries that include the key go directly to the right node, so adding nodes adds capacity. Elastic clusters reached general availability in early 2026 and gained Terraform support shortly after. They suit multi-tenant software-as-a-service products and high-volume transactional systems, but they require thoughtful data modeling, because the choice of distribution key is difficult to change later.

Advantages

  • Capacity grows by adding nodes instead of buying an ever larger single server
  • Tenant data can be isolated naturally by distribution key
  • Queries on one tenant stay fast as the total data grows
  • Keeps familiar PostgreSQL tools and drivers

Disadvantages / Trade-offs

  • Data modeling becomes more demanding
  • Queries that span all shards cost more than single-shard queries
  • Some features and extensions may behave differently across nodes
  • Operational complexity and cost are higher than a single server
i
Practical Tip

Exhaust the simple options first. A well-indexed single server with a connection pooler and a couple of read replicas serves a surprising number of businesses. Move to elastic clusters when measurements show that a single primary cannot keep up with writes or data volume.

13Extensions, AI Features, and Analytics Integration

PostgreSQL’s extension system turns the database into a platform. This chapter shows what the managed service offers and what to be careful about.

What an extension is

An extension is an add-on package that gives the database new abilities, such as new data types, new index methods, or new functions. You allow an extension on the server and then enable it inside a database. The Azure service curates the list of supported extensions, which is why you cannot install an arbitrary one, but the list is long and grows each month.

Vectors

pgvector

Stores numeric embeddings and finds the most similar items, the foundation of semantic search and recommendation features.

Vectors

DiskANN index

An index method designed to search very large embedding collections efficiently without holding everything in memory.

AI

azure_ai

Lets the database call Azure AI services to create embeddings or analyze text directly from queries.

Geospatial

PostGIS

Adds maps, locations, distances, and shapes, powering delivery, mapping, and logistics applications.

Scheduling

pg_cron

Runs recurring jobs inside the database, such as nightly cleanups.

Graph

Apache AGE

Adds graph-style queries for relationships such as social networks or fraud rings.

Analytics

pg_duckdb

Brings a fast analytical engine closer to PostgreSQL data, with support for reading and writing files in object storage.

Time

temporal_tables

Keeps a history of how rows change over time for auditing and reporting.

AI-ready databases

Modern applications often combine ordinary business data with unstructured knowledge such as documents or product descriptions. An embedding turns a piece of text into a list of numbers that captures its meaning, so similar meanings land close together. Storing embeddings in the same PostgreSQL database as your orders and customers lets you filter by business rules and rank by similarity in one query, and it keeps security, backups, and transactions in one place. The platform also publishes a Model Context Protocol server for PostgreSQL, in preview since 2025, to help AI agents interact with the database in a controlled way. Because these features move fast, verify their status before depending on them in production.

Simple Analogy

Keyword search is like looking for a book by exact title. Vector search is like asking a librarian for “something similar to the book I loved last month”. The librarian understands meaning, not just spelling, and the library of meanings sits on the same shelf as the rest of your records.

Mirroring into analytics platforms

Heavy analytical queries compete with transactions for the same resources. Mirroring in Microsoft Fabric replicates data from the PostgreSQL service into an analytics lakehouse automatically, so analysts can run large aggregations without touching the production server. This pattern separates operational and analytical workloads while avoiding hand-built extraction pipelines.

MySQL extension story

MySQL’s managed service has a smaller plugin surface. Its strengths lie elsewhere: wide compatibility with web platforms, simple replication patterns, and performance features such as Accelerated Logs on higher tiers, which speeds up write commits by using faster storage for transaction logs. If advanced extension features are central to your design, that tilts the choice toward PostgreSQL.

!
Common Mistake

Enabling many extensions “just in case”. Each extension increases the surface for bugs, resource use, and upgrade complications. Enable only what you use and review the list at every major upgrade.

14Monitoring, Logging, and Metrics

You cannot fix what you cannot see. Observability turns a mysterious slowdown into a clear, answerable question.

Three kinds of signals

Observability uses metrics, logs, and traces. Metrics are numbers sampled over time, such as CPU percentage or active connections. Logs are text records of events, such as slow queries, errors, or logins. Traces follow a single request through several systems. For managed databases, metrics and logs matter most, and you route them through Azure Monitor, which can show charts, send alerts, and forward data to a central logging workspace.

The metrics that matter

MetricWhat it tells youWhen to worry
CPU percentageHow busy the compute isSustained above about eighty percent
Memory percentagePressure on caches and sessionsSteadily climbing with swapping or cache misses
Storage percentageHow full the disk isAbove about seventy to eighty percent
IOPS and throughput consumptionDisk limits being approachedNear the provisioned maximum for long periods
Active and failed connectionsConnection behaviorRapid growth or growing failures
Replication lagHow far behind replicas areLag that exceeds what your application can tolerate
Deadlocks and long transactionsContention inside the engineAny repeated pattern

Logs and query insight

Slow query logs record statements that exceed a time threshold. The PostgreSQL service offers Query Store, which keeps statistics about queries over time, and Query Performance Insight, a portal view that ranks queries by time consumed and shows how they change. The MySQL service provides slow query logs, audit logs, and performance insight style features as well. Built-in Grafana dashboards arrived in the portal for PostgreSQL in 2026, giving teams ready-made views without building their own. Send logs to a Log Analytics workspace if you want to search across many servers, keep history longer, and correlate database events with application events.

Alerting that people actually respect

An alert that fires constantly gets ignored. Create a small number of meaningful alerts: storage above a safe level, CPU sustained high, failed connections spiking, replication lag, and failover events. Route them to the people who can act, and write a one-page response guide for each. Review alerts quarterly and remove those that never lead to action.

i
Practical Tip

Record a baseline during a calm week. When something feels slow, compare current numbers with the baseline. Without a baseline, every number looks either alarming or fine with no way to tell which.

15Performance Tuning

Most performance problems are not about the size of the server. They are about the shape of the queries and the design of the data.

Start with the questions, not the knobs

Performance work follows a loop: find the most expensive queries, understand why they are expensive, change one thing, and measure again. The Query Store and slow query logs from the previous chapter tell you where time goes. Typically a handful of queries account for most of the load, so fixing three or four statements can reduce CPU more than doubling the server would.

Indexes: the biggest lever

Without an index, the engine must read every row of a table to find the ones you asked for, which is called a full scan. With the right index, it jumps directly to the matching rows. Indexes are not free: each one uses storage and slows down writes slightly, because every insert or update must also update the index. Create indexes for the columns that appear often in filters, joins, and sort orders, remove the ones that are never used, and prefer a few well-chosen indexes over many speculative ones. PostgreSQL offers several index types for different shapes of data, such as text search, ranges, and geometry, while MySQL focuses on its well-tuned tree-based indexes.

Simple Analogy

Finding a name in a phone book is quick because it is sorted. Finding a phone number from a name that is not sorted requires reading every line. An index is another sorted view of your data, built so a particular kind of question becomes quick.

Reading the query plan

Both engines can explain how they intend to execute a query, listing which tables are scanned, which indexes are used, and how results are joined. Learning to read these plans is the single most valuable database skill. Look for full scans on large tables, estimates that are wildly different from actual row counts, and expensive sorts. Bad estimates usually mean the statistics that the planner relies on are stale, which a routine statistics refresh can fix.

PostgreSQL housekeeping: vacuum

PostgreSQL keeps old row versions around so that readers and writers do not block each other. A background process called autovacuum cleans up the dead versions and refreshes statistics. If autovacuum cannot keep up, tables bloat, queries slow down, and in extreme cases the database must stop accepting writes to protect itself from transaction identifier wraparound. The platform exposes autovacuum metrics and advisor recommendations so you can see tables where vacuum is behind. Tune autovacuum settings for large, heavily updated tables rather than disabling it, and avoid very long-running transactions, which prevent cleanup.

MySQL housekeeping: the buffer pool and purge

In MySQL’s InnoDB engine, performance relies heavily on the buffer pool, the memory cache for data and index pages. A pool too small for the working set causes constant disk reads. InnoDB also purges old row versions in the background, and long-running transactions can delay this cleanup, leading to growth in history. As with PostgreSQL, keep transactions short and review slow queries regularly.

1

Find the top consumers

Rank queries by total time, not just by single slow runs, using Query Store or slow logs.

2

Study the plan

Check for full scans, missing indexes, and poor row estimates.

3

Change one thing

Add an index, rewrite the query, or refresh statistics, but not all at once.

4

Measure and keep notes

Compare before and after, and record the lesson so the team does not repeat it.

Application-side causes

Many slowdowns originate in the application. A common one is the N+1 pattern, where code fetches a list of one hundred items and then issues one hundred separate queries for the details, instead of one query that joins them. Another is fetching far more columns and rows than the screen displays. Fixing these at the source often yields larger gains than any database setting.

ANTI-PATTERN-03 Avoid
Problem

When the application becomes slow, the team repeatedly scales the server to a larger size without investigating queries.

Why It’s Harmful

Costs rise every time while the underlying inefficiency stays. Eventually the biggest size is reached and the real problem must be fixed anyway, now under pressure.

Correct Approach

Investigate the top queries first, fix indexes and access patterns, and scale only when measurements show that the workload is efficient but simply large.

16Maintenance, Versions, and Upgrades

A managed service still needs to be updated. Understanding the update model lets you plan changes instead of being surprised by them.

Monthly service releases

Both services publish a new release roughly each month. A release can include engine minor versions with security and bug fixes, new features, extension updates, and fixes for known issues. New servers receive the release first. Existing servers receive it during their next scheduled maintenance window, which you can customize by choosing a preferred day and hour. Maintenance can sometimes be rescheduled within a limited period, but postponing indefinitely is not an option because security patches must reach every server.

i
Practical Tip

Set your custom maintenance window to the quietest period of your week and use the service’s early-access canary option on a non-production server so you can test the next release before it reaches production.

Minor versus major versions

A minor version, such as moving from one patch level to the next, contains fixes and is backward compatible. The platform applies these for you. A major version, such as moving from PostgreSQL 16 to 17 or from MySQL 5.7 to 8.0, changes internal behavior and may remove old features. You choose when to move. The PostgreSQL service supports in-place major version upgrade, and during 2026 it improved reliability for databases with many large objects and extended support to upgrades involving temporary tablespaces, with in-place upgrade to PostgreSQL 18 available globally. For safe upgrades, restore a recent backup into a test server, perform the upgrade there, run your application tests, and measure how long the upgrade takes before touching production.

End of life and extended support

Open-source engine versions eventually stop receiving community fixes. The Azure services handle this by announcing retirement dates and sometimes offering paid extended support for a limited time. MySQL 5.7, for example, is in extended support, and PostgreSQL versions 11 to 13 have received security patches under extended support arrangements. Treat extended support as a bridge to buy time for migration, not as a destination. Track the version support policy page and put retirement dates on your team calendar.

SituationRecommended action
Engine version near end of lifePlan a major upgrade to a current supported version well ahead of the date
New major version releasedTest on a copy, wait for the first few minor releases for production
Extensions in useCheck compatibility lists before upgrading and update the extension versions
Applications with old driversUpgrade client libraries first, since new engines may change authentication or defaults

Stop and start for savings

Development and test servers do not need to run at night. Flexible Server lets you stop a server so that compute charges pause while storage and backups continue. A stopped server is automatically restarted after a limited period, so do not rely on this for long-term parking. Automation using scheduled tasks can stop non-production servers every evening and start them each morning.

17Migrating to Azure

Moving a live database is like changing the engine of a plane while it flies. Good planning makes it routine.

Know your source and your tolerance for downtime

Migrations fall into two broad styles. Offline migration copies data while the application is stopped, then switches to the new database. It is simple and safe but requires downtime proportional to the data size. Online migration copies the bulk of the data while the source keeps running, then continuously applies new changes until the two are in sync, and only a brief cutover pause is needed. Online migration is more complex but is the choice for systems that cannot be offline for hours.

Simple Analogy

Offline migration is closing the old shop, moving all the shelves overnight, and reopening in the new building. Online migration is slowly moving stock to the new shop while the old shop keeps selling, then handing over the keys when the last small items are copied.

Tools and approaches

Service

Azure Database Migration Service

Guided online and offline migrations; it added support for targeting MySQL 8.4 in mid-2026.

Native

Dump and restore

Export with engine tools and import into Azure; simple and reliable for small and medium databases.

MySQL

Data-in replication

Makes the Azure server a replica of the source, then promotes it at cutover.

PostgreSQL

Logical replication

Streams table changes from the source so that cutover pauses are short.

The migration journey

1

Assess

Inventory databases, sizes, versions, extensions, users, and dependent applications. Identify unsupported features early.

2

Design the target

Choose version, compute, storage, networking, HA mode, and security settings before any data moves.

3

Rehearse with a copy

Run a full trial migration, time it, and test the application against the result.

4

Cut over

Stop writes at the source, wait for the target to catch up, validate row counts and key checks, and switch application settings.

5

Stabilize and keep a fallback

Monitor closely, keep the source untouched for a defined period, and decommission only after confidence is established.

!
Common Mistake

Migrating the data but forgetting the surroundings: users and permissions, scheduled jobs, connection strings, firewall rules, certificates, monitoring, and backup expectations. The database is only one piece of the system.

Compatibility checks

Because the services run community engines, compatibility is generally high, but details matter. Check for unsupported extensions, features that require superuser rights that the managed service restricts, storage engines that are not offered, and settings that the platform controls on your behalf. Confirm that your client drivers support the encryption and authentication modes the server requires.

18Cost Management

Cloud databases are billed by what you provision, so careful choices pay off every month.

What you are billed for

Charges come from four main places. Compute is billed for the size you provision for each hour the server runs. Storage is billed for the provisioned amount, plus separate charges for extra performance when you use storage options with adjustable IOPS and throughput. Backup storage beyond the free allowance is billed. Network data leaving Azure or crossing regions is billed, which matters for cross-region replicas. A high availability deployment bills for the standby as well, and each read replica is billed as a full server.

Savings levers

Reserved capacity

Committing to one or three years of compute usage gives a substantial discount for steady production workloads. Reservations apply to a size family, so confirm your sizing is stable before committing.

Right-sizing

Review CPU, memory, and storage metrics monthly. Servers that run at ten percent CPU for months are candidates for a smaller size.

Burstable tier for non-production

Development and test environments rarely need continuous full performance and can use the cheaper burstable tier, combined with nightly stop schedules.

Independent storage performance

With storage that scales IOPS and throughput separately, avoid buying large capacity just to reach a performance target.

Tags and budgets

Tag every server with owner, environment, and cost center, and set budget alerts so surprises are caught in days rather than at month end.

x2
Compute cost when HA standby is enabled
1-3 yrs
Typical reservation commitment terms
Monthly
Recommended cadence for sizing review
i
Practical Tip

Prices and discounts change, and they differ by region and size. Use the official Azure pricing calculator for current numbers rather than relying on a tutorial, including this one.

19Design Patterns and Anti-Patterns

Patterns are solutions that many teams have already tested. Anti-patterns are the traps that many teams have already fallen into.

Helpful patterns

Primary with read replicas and a read/write split

Writes go to the primary, tolerant reads go to replicas. Use virtual endpoints or a routing layer so applications do not hard-code server names.

Connection pooling at the edge of the database

Use the built-in PgBouncer for PostgreSQL or a pooling layer in application frameworks to protect the database from connection storms.

Tenant-keyed design for software-as-a-service

Include a tenant identifier in every table so that data can later be sharded across an elastic cluster and so that isolation rules are easy to enforce.

Outbox pattern for reliable messaging

Write business changes and an outgoing message record in the same transaction, then publish messages from that table, so the database and message system never disagree.

Separate operational and analytical workloads

Mirror or replicate data into an analytics platform so reporting never competes with checkout traffic.

Retry with backoff in every client

Assume that connections will occasionally drop during failover or maintenance, and make clients reconnect gracefully with increasing delays.

flowchart LR
  U["Users"] --> APP["Application Tier"]
  APP -->|writes and fresh reads| PRI["Primary Server with HA"]
  APP -->|tolerant reads| RR["Read Replicas"]
  PRI -->|log stream| RR
  PRI -->|mirroring| LAKE["Analytics Platform"]
  PRI -->|backups| BK["Backup Storage"]
        
FIG 5 — A common production topology for scale, protection, and analytics

Frequent anti-patterns

ANTI-PATTERN-04 Avoid
Problem

Using the database as a message queue or as a place for large binary files such as videos and high-resolution images.

Why It’s Harmful

Constant polling creates load, large objects bloat storage and backups, and restore times grow. The database becomes slow and expensive.

Correct Approach

Store large files in object storage and keep only references in the database. Use a proper queue or event service for messaging.

ANTI-PATTERN-05 Avoid
Problem

Production and test workloads share one server, and developers run experiments directly on it.

Why It’s Harmful

A single heavy test query can slow every customer, and an accidental change in the wrong environment can destroy real data.

Correct Approach

Keep separate servers per environment, restrict production access, and refresh test data from masked copies.

20Real-World and Industry Scenarios

Concepts become clearer when you see how they combine in realistic situations. These scenarios are illustrative composites rather than descriptions of specific named customers.

Retail platform with seasonal peaks

An online store runs on MySQL. During normal weeks, a General Purpose server with zone-redundant HA is sufficient. Before a festival sale, the team scales up compute in a planned window, adds read replicas for browsing traffic, and uses pooling so that the surge of shoppers does not exhaust connections. After the sale they scale back and remove extra replicas to control cost.

Multi-tenant software-as-a-service product

A business software company stores thousands of customer accounts in PostgreSQL. Every table carries a tenant identifier. As the largest customers grow, the team moves to an elastic cluster so that data and write traffic spread across nodes, while each tenant’s queries remain fast because they touch a single shard.

Financial services with strict compliance

A lending application stores sensitive records in PostgreSQL with private connectivity only, Entra ID sign-in, customer-managed keys in a hardware-backed vault, audit logs sent to a central workspace, and policy rules that block any server without these settings. Backups are geo-redundant, and a cross-region replica is rehearsed for disaster recovery twice a year.

Healthcare analytics

Operational patient scheduling data lives on PostgreSQL. Mirroring feeds an analytics platform where researchers explore trends without touching the production server, and strict role design ensures only authorized staff see identifiable information.

AI-powered knowledge search

A support portal stores articles and their embeddings in PostgreSQL with a vector index. A query filters by product and language and then ranks by meaning similarity, returning relevant answers while keeping the data under the same security controls as the rest of the application.

Content website with a legacy stack

A media company runs a PHP-based publishing platform that expects MySQL. Moving to the managed MySQL service with data-in replication allows a near-seamless cutover, and the team gains automatic backups and HA without changing application code.

21Best Practices and Common Mistakes

If you remember only one chapter, make it this one. These habits separate calm operations from constant firefighting.

Best Practices

  • Use Flexible Server for every new deployment and keep engine versions current
  • Choose zone-redundant HA for production systems that cannot tolerate zone loss
  • Prefer private connectivity and Entra ID or managed identity sign-in
  • Practice restores and failovers on a schedule
  • Create alerts for storage, CPU, connections, and replication lag
  • Review top queries and unused indexes every month
  • Tag resources and set budgets from day one

Common Mistakes

  • Treating HA as a substitute for backups
  • Opening firewalls widely to solve connection issues
  • Scaling hardware instead of fixing queries
  • Ignoring monthly release notes and retirement dates
  • Running without retry logic in applications
  • Sharing one administrator credential everywhere
  • Never testing a restore until a real emergency
i
A Simple Launch Checklist

Before going live, confirm: version supported, HA mode chosen, backups and retention set, private access or tight firewall, sign-in method decided, alerts created, maintenance window selected, pooling configured, restore rehearsed, and costs tagged.

22A Troubleshooting Playbook

When something goes wrong at an awkward hour, a calm, ordered method beats guesswork. This chapter gives you that method.

The golden rule: narrow the problem first

Every incident belongs to one of four zones: the application, the network path, the database engine, or the platform underneath. Asking “which zone is this in?” before changing anything saves hours. A symptom such as “the app is slow” could come from any zone, so gather evidence that proves or eliminates each one. Start with the cheapest checks: is the service healthy according to the Azure status information, did anything change recently, and are other applications affected too?

flowchart TD
  S["Symptom reported"] --> Q1{"Can clients reach the server name?"}
  Q1 -->|No| N["Check DNS, firewall rules, private endpoint, and network routes"]
  Q1 -->|Yes| Q2{"Do connections succeed?"}
  Q2 -->|No| C["Check sign-in method, TLS settings, connection limits, and server state"]
  Q2 -->|Yes| Q3{"Is the server resource-starved?"}
  Q3 -->|Yes| R["Check CPU, memory, storage, IOPS, and long transactions"]
  Q3 -->|No| Q4{"Are specific queries slow?"}
  Q4 -->|Yes| P["Study plans, indexes, statistics, and locking"]
  Q4 -->|No| A["Investigate the application and recent releases"]
        
FIG 6 — A decision path for narrowing down database problems

Common symptoms and their usual causes

SymptomLikely causesFirst things to check
Cannot connect at allFirewall rule missing, private DNS misconfigured, wrong server name, server stoppedServer state, name resolution from the client, allowed address list
Intermittent connection errorsFailover or maintenance, connection pool exhaustion, expired certificate trustMaintenance and failover events, connection metrics, client trust stores
Too many connectionsApplication leak, no pooling, sudden traffic surgeConnection counts by user, pooler status, application behavior
Sudden slownessA new query, a missing index after a release, stale statistics, a lockTop queries by time, blocking sessions, recent deployments
High storage growthBloated tables, large logs, long transactions holding old versions, runaway temporary filesTable sizes, autovacuum progress, log retention, open transactions
Replica lag growingHeavy write bursts, under-sized replica, long queries on replica, network distanceReplica CPU and IOPS, query activity on replica, write rate on primary
Writes suddenly failDisk full, read-only mode triggered by storage, wraparound protectionStorage percentage, server messages, vacuum health

Locks and blocking

Databases use locks to keep concurrent work consistent. Usually locks last milliseconds, but one forgotten transaction that holds a lock while waiting for a person or a slow external call can make dozens of other requests queue behind it. The symptom looks like a sudden freeze with low CPU. Look for sessions that are waiting and identify the session at the head of the queue. The fix is usually in the application: keep transactions short, avoid user interaction or network calls while a transaction is open, and always release connections back to the pool.

Simple Analogy

Imagine a single-lane road where one car stops to ask for directions. Every car behind it waits, even though the road itself is empty ahead. Finding the stopped car at the front is the only way to clear the jam. Blocking sessions work the same way.

Deadlocks

A deadlock happens when two transactions each hold something the other needs, so neither can proceed. The engine detects this and cancels one of them with an error. Occasional deadlocks are normal in busy systems, and applications should retry the failed transaction. Frequent deadlocks signal a design problem, most often two code paths updating the same rows in different orders. Make all code paths touch shared rows in the same order and keep transactions small.

When to open a support case

Contact Azure support when evidence points to the platform itself: failovers that did not complete, storage or networking behavior that contradicts documentation, or maintenance that left a server in an unexpected state. Include the server name, region, exact timestamps in a single time zone, error messages, and what you have already ruled out. Good evidence shortens resolution time dramatically.

i
Practical Tip

Keep an incident log. After each event, write three lines: what happened, what fixed it, and what will prevent it next time. A year of these notes becomes your team’s most valuable operations guide.

Prevent rather than cure

Most incidents repeat. Convert each lesson into a permanent safeguard: a new alert, a test in your release pipeline, a policy rule, or a documented runbook step. Run game days, which are planned exercises where the team deliberately triggers a failover, revokes a credential in a test environment, or fills a test disk, and watches how systems and people respond. Teams that practice failure handle real failure with far less stress.

23Frequently Asked Questions

Q1Is Azure Database for PostgreSQL the same as PostgreSQL running on a virtual machine?

No. It uses the same community engine, but Microsoft operates the machines, patching, backups, and failover. In exchange, you give up operating system access and some superuser-level control, and you can only use the supported extensions and settings.

Q2What happened to Single Server?

Single Server was the earlier deployment model for both engines and has been retired. Flexible Server is the current model and the one to use for all new work and for migrations of old servers.

Q3Which versions are supported?

The PostgreSQL service supports recent community versions up to 18, and the MySQL service supports 5.7 in extended support, 8.0, and 8.4. Support lists change, so check the official version support policy before choosing.

Q4Will my application notice a failover?

Open connections are dropped and then re-established, typically within a short period. Applications with retry logic and healthy connection pools usually recover without user-visible errors, while applications without retry logic may show errors until restarted.

Q5Can I shrink storage after growing it?

Generally no. Storage can be increased but not decreased on an existing server. To reduce it, you migrate to a new server with a smaller size, which is why growth should be planned rather than automatic only.

Q6Do read replicas give me high availability?

They provide read scale and a manual disaster recovery option, since a replica can be promoted. They are not an automatic failover mechanism within a region. Use zone-redundant HA for automatic failover.

Q7How do I connect securely from my on-premises network?

Use private connectivity through a VPN or dedicated circuit into an Azure network, combined with private access or a private endpoint, and ensure private DNS resolves the server name for your on-premises clients.

Q8Is my data encrypted?

Yes. Data at rest is encrypted by default and connections can be required to use TLS. You can additionally bring your own encryption keys if your compliance rules demand it.

Q9When should I choose elastic clusters?

When a single PostgreSQL server cannot handle your write rate or data volume even after tuning, and when your data can be naturally partitioned by a key such as a tenant. For most applications, a single well-tuned server is enough.

Q10How do I reduce costs for development environments?

Use the burstable tier, stop servers outside working hours, avoid HA and replicas in non-production, and delete environments that are no longer needed.

Q11How far back can I restore?

Within your configured backup retention window, which starts at about seven days by default and can be extended to about thirty-five days. Long-term retention options exist for longer needs on supported configurations.

Q12Can I use both PostgreSQL and MySQL in the same project?

Yes, they are independent services. Many organizations use each where it fits best, though operating two engines requires skills and tooling for both, so avoid mixing without a clear reason.

24Summary and Key Takeaways

Azure Database for PostgreSQL and MySQL give you the open-source engines you already know, wrapped in a platform that handles patching, backups, monitoring, and failover. Flexible Server is the single deployment model to learn. Everything else in this guide, from storage that scales performance independently to elastic clusters, private networking, and vector search, is a tool you add as your needs grow. The most durable skills are not product trivia but engineering habits: design for failure, protect identity and network paths, test your recoveries, read your query plans, and measure before you scale. Because the services change every month, keep the official release notes close and treat any tutorial, including this one, as a map rather than a contract.

Key Takeaways

  • Use Flexible Server — it is the current deployment model for both engines, and Single Server is retired.
  • Pick the engine your team can operate — PostgreSQL shines for rich features and extensions, MySQL for web-platform compatibility and simplicity.
  • High availability is not backup — use zone-redundant HA for infrastructure failures and tested point-in-time restore for human error.
  • Secure in layers — private connectivity, Entra ID or managed identities, TLS, encryption keys, auditing, and least-privilege roles work together.
  • Scale the cheap way first — fix queries and indexes, add pooling and read replicas, and only then consider larger sizes or elastic clusters.
  • Plan upgrades and migrations — track monthly releases and retirement dates, rehearse on copies, and keep a fallback.
  • Measure continuously — baselines, meaningful alerts, and monthly cost and sizing reviews keep systems healthy and affordable.