Azure Database for PostgreSQL and MySQL
A friendly, deep walk through Azure's managed services for two of the world's most loved open-source databases: how they are built, how they stay available and safe, and how to size, connect, tune, and pay for them wisely.
Imagine you own a busy shop. Every sale, every customer name, every delivery address is written in one big ledger. As long as that ledger is safe, your shop runs smoothly. But what if the ledger is lost in a fire? What if two clerks write in it at the same moment and spoil a page? What if the shop becomes so popular that one ledger cannot keep up?
Smart shop owners hire a professional record-keeping firm. The firm keeps duplicate ledgers in separate buildings, makes a copy every night, hires extra clerks on busy days, and fixes problems before the owner even notices. The owner simply says what to write and what to look up.
Azure Database for PostgreSQL and Azure Database for MySQL are exactly that firm for your application’s data. They run the real PostgreSQL and MySQL engines, but Microsoft takes care of the buildings, the machines, the patches, the backups, and the failovers. In this guide you will learn what these services are, how they work inside, how to choose between the two engines, how to keep them fast and safe, and how to avoid the mistakes that catch most beginners. No earlier database knowledge is required.
1What Are Azure Database for PostgreSQL and MySQL?
They are fully managed database services in Azure that run the real open-source PostgreSQL and MySQL engines, so you can use familiar tools and skills without running the servers yourself.
First, what is a database?
A database is an organized place to keep information so that programs can store it, find it, and change it quickly and safely. Most business applications use a relational database. In this kind of database, information lives in tables, which look like spreadsheets. Each row is one record, such as one customer, and each column is one detail, such as a name or an email address. Programs talk to the database using a language called SQL, which lets them ask questions like, “Show me all orders from last week.”
Two famous engines
PostgreSQL, often called Postgres, is known for correctness, rich features, and the ability to be extended with add-ons. MySQL is known for speed, simplicity, and its huge popularity with websites and web applications. Both are open source, which means anyone can use them without paying a license fee. Both have been trusted by large companies for decades.
What “managed” means
If you install PostgreSQL or MySQL on your own server, you must also look after that server. You install the operating system, keep it patched, set up backups, build a standby copy for emergencies, watch the disk space, and wake up at night when something fails. A managed service moves most of that work to Microsoft. You still design your tables, write your queries, and manage your users. Azure handles the machines, the operating system, the database software updates, the backups, and the machinery for high availability.
Think of the difference between buying a house and staying in a serviced apartment. In your own house, you fix the roof, change the bulbs, and pay the plumber. In a serviced apartment, the building takes care of the roof, the lifts, and the security, while you still decorate your own rooms and live your own life. Azure Database is the serviced apartment for your data.
One name, one model: Flexible Server
Both services today use a deployment style called Flexible Server. It gives you more control over the maintenance schedule, the high availability setup, the network, and the cost than the older Single Server style, which Microsoft has retired for both engines. When you read documentation or create a new database in Azure, you will be working with Flexible Server.
What you get
- The real engines. Your existing drivers, tools, and skills keep working.
- Automatic backups and the ability to restore to any moment within your retention period.
- High availability with a standby server in another zone that takes over automatically.
- Read replicas to share heavy reading traffic and to prepare for disasters.
- Security built in, with encryption, private networking, and Microsoft Entra ID sign-in.
- Scaling choices for compute and storage, with stop and start options for saving money.
Managed does not mean “no work”. It means the heavy, repeating infrastructure work is handled for you, so your time goes to the schema, the queries, the access rules, and the design of your application.
2Why Managed Databases Exist
To see why these services matter, picture a small team trying to run their own database server for the first time.
The long list of jobs nobody sees
A database server sounds like one program, but running it well involves dozens of quiet jobs. Someone must install and patch the operating system. Someone must update the database software when security fixes arrive. Someone must schedule backups, copy them to a safe place, and, more importantly, test that they can be restored. Someone must build a second server and write the steps to switch to it if the first one dies. Someone must watch disk space, memory, and slow queries. Someone must be on call.
Each of these jobs is simple on its own. Together, they are a full-time responsibility, and mistakes are expensive. A missed backup is discovered only on the day it is needed. A full disk stops the whole application at the worst moment.
Running your own database server is like running your own power plant for your factory. It can be done, and some giants do it. But most factories happily buy electricity from the grid, because generating power is not their business. A managed database is the grid for your data.
What Azure took over
Hardware and operating system
Microsoft owns the machines, replaces failed parts, and keeps the operating system secure and patched. You never log in to the server itself.
Backups and recovery
Backups run automatically, and logs are archived continuously so you can restore to a chosen second inside your retention window.
High availability
A standby copy runs in a separate zone, and Azure detects trouble and switches to the standby without you writing any scripts.
Monitoring plumbing
Metrics, logs, and alerts flow into Azure Monitor from the first minute, with no agents for you to install.
Security foundations
Encryption at rest, encrypted connections, and integration with Azure identity and networking come ready to use.
Who benefits most
Small teams gain because they get professional-grade reliability without hiring a database administrator on day one. Large companies gain because they can run hundreds of databases with a small operations team and consistent standards. Teams moving from their own data centers gain because their applications keep working with the same open-source engines, with very little rewriting.
3Core Concepts and Vocabulary
Every technology has its own small language. Learn these words once, and the rest of this guide, and the Azure documentation, will read easily.
Server
The Azure resource that runs the database engine. It has a name, a size, a network setting, and an address that applications connect to.
Database
A named container for related tables. One server can hold several databases, like one building holding several offices.
Table, row, column
A table is a grid. Each row is one record and each column is one kind of detail about it.
SQL
The Structured Query Language used to create tables, add data, and ask questions.
Transaction
A group of changes that either all succeed together or all fail together, like a bank transfer that must both remove and add money.
Index
A separate lookup structure that lets the database find rows fast, like the index at the back of a book.
Transaction log
A running record of every change. PostgreSQL calls it the write-ahead log, and MySQL uses redo and binary logs. It protects data and feeds replication.
Standby server
A second server, in another zone, that mirrors the first and takes over if the first fails.
Read replica
An extra copy of the server that serves read-only questions, taking pressure off the main server.
Failover
The act of moving work from a failed server to its standby.
Point-in-time restore
Rebuilding a database as it looked at a chosen moment, by combining a backup with the saved log.
Connection
An open conversation between an application and the database. Each one uses memory, so there is a limit on how many can be open.
vCore
A virtual processor core. Compute size is described by how many vCores and how much memory a server has.
IOPS
Input and output operations per second, a measure of how many small reads and writes the storage can handle.
Server parameter
A tunable setting of the engine, such as how much memory to use for sorting. Azure lets you change many of them.
Extension
An optional add-on module, mostly known in PostgreSQL, that adds features such as maps or vector search.
The ACID promise
Relational databases are famous for a promise called ACID. Atomic means a transaction is all or nothing. Consistent means the data always follows your rules. Isolated means several people working at once do not see each other’s half-finished work. Durable means once the database says “saved”, the data survives even a sudden power loss. Both PostgreSQL and MySQL, with the standard storage engine, keep this promise, which is why banks and shops trust them.
Think of paying for groceries. Either the cashier scans everything, you pay, and you leave with your bags, or none of it happens. You never leave having paid for nothing, or with bags you did not pay for. A transaction in a database works like that single, complete checkout.
4Architecture and Components
A flexible server is more than one machine. It is a small system of cooperating parts, with services around it that protect, copy, and secure the data.
flowchart TD
APP["Applications and services"] --> POOL["Connection pooler"]
POOL --> EP["Server endpoint with public or private access"]
subgraph SRV["Flexible Server"]
PRI["Primary server running the database engine"]
STB["Standby server in another zone"]
DSK["Premium SSD storage"]
end
EP --> PRI
PRI -->|"synchronous log shipping"| STB
PRI --> DSK
PRI -->|"asynchronous replication"| RR["Read replicas"]
PRI --> BKP["Automated backups and log archive"]
BKP --> GEO["Geo-redundant backup copy"]
KV["Key Vault"] -.->|"customer managed keys"| SRV
ENTRA["Microsoft Entra ID"] -.->|"sign in"| EP
MON["Azure Monitor and Log Analytics"] -.->|"metrics and logs"| SRV
Read the diagram from the top. Applications reach the server through its endpoint, often through a connection pooler that keeps the number of open connections healthy. Behind the endpoint is the primary server, which runs the database engine and keeps its data on fast Premium SSD storage. If high availability is turned on, a standby server in another zone receives every change as it happens. Read replicas receive changes a little later and serve read-only traffic. Backups and the continuous log archive are stored separately, optionally with a copy in another region. Key Vault, Microsoft Entra ID, and Azure Monitor sit around the server and add keys, identity, and visibility.
The compute side
The primary server is a virtual machine managed by Azure that runs only the database engine. You choose its size by picking a compute tier and a number of vCores. You cannot log in to the operating system, but you can adjust many engine settings through server parameters.
The storage side
The data and the transaction logs live on managed Premium SSD storage that you size and that can grow over time. The storage service itself keeps several copies of every block, which protects against drive failure. The amount of storage you choose also decides how many IOPS you get, so storage size is both a capacity decision and a performance decision.
The availability side
High availability adds a second, hidden server called the standby. It is not for your queries. It exists only to take over. Read replicas are different: they are visible servers that you can query, designed to share reading work and to help with recovery planning.
The protection side
Azure takes regular backups of the data and archives the transaction log continuously. Together they make point-in-time restore possible. You can choose where backups are stored: in one zone, spread across zones, or copied to another region.
The management side
Everything you create goes through Azure Resource Manager, the same front door used by all Azure services. The server, its settings, its firewall rules, and its tags appear as normal Azure resources that you can control through the portal, command line, or templates.
Imagine a courtroom stenographer. The main stenographer types everything that is said. A second stenographer in another room listens through a speaker and types the same words, ready to take over if the first collapses. The archive room stores copies of the transcript at the end of every day. The clerk at the door decides who may enter. The database server, standby, backups, and firewall play the same roles.
5PostgreSQL or MySQL: Which One to Choose?
Both are excellent. The best choice usually depends on your application, your team’s experience, and the features you need.
| Question | PostgreSQL | MySQL |
|---|---|---|
| Known for | Rich features, strict correctness, extensibility | Simplicity, speed, huge web ecosystem |
| Complex queries and analytics | Very strong, with advanced SQL features and good planning | Good for common workloads, with fewer advanced features |
| Special data types | JSON binary storage, arrays, ranges, maps through extensions, vector search | JSON support and standard types |
| Add-on modules | A large extension system, including PostGIS and pgvector | More limited, with plug-in storage engines |
| Typical applications | Business systems, SaaS platforms, geographic and AI applications | Websites, content systems, shops, and LAMP-style stacks |
| Maximum read replicas in Azure | Up to five | Up to ten |
| Built-in connection pooler in Azure | Yes, PgBouncer | No, use application pools or a proxy |
| Maintenance task to remember | Vacuum keeps tables tidy and prevents bloat | Monitor replication lag and the buffer pool |
When PostgreSQL is a natural fit
- Your application needs advanced queries, window functions, or strong data rules.
- You need maps and location queries, using the PostGIS extension.
- You are building AI features that store and search embeddings, using the pgvector extension.
- Your team wants a database that can be shaped with extensions for special needs.
When MySQL is a natural fit
- You run a popular web platform or content system that was built for MySQL, such as many shop and blog platforms.
- Your team already knows MySQL well and your application uses its syntax and tools.
- Your workload is mostly simple reads and writes at high volume, and you want many read replicas.
- You are migrating an existing MySQL system and want the smallest possible change.
PostgreSQL is like a well-equipped professional workshop with every tool on the wall, and room to bring in special machines. MySQL is like a fast, tidy kitchen that does the most common jobs very well. Both can make you a great meal, and the better choice depends on what you need to cook.
The honest rule
If your application already uses one of the two engines, stay with it. Changing engines means rewriting queries, testing behavior differences, and moving data, which is costly. If you are starting a brand new project with no strong preference, PostgreSQL’s wider feature set and extension system make it a popular default, while MySQL remains a smart choice for web workloads with strong existing tooling.
The engine is chosen when you create the server and cannot be switched in place. Treat the choice as a design decision, not a default click.
6Compute Tiers, Storage, and Sizing
Choosing the right size is the most important cost and performance decision you will make for a database server.
Three compute tiers
| Tier | Idea | Good for |
|---|---|---|
| Burstable | Low baseline CPU with the ability to burst higher using saved credits | Development, testing, small websites, and light workloads |
| General Purpose | A balanced mix of CPU and memory | Most production applications |
| Memory Optimized | More memory for each vCore | Large datasets that benefit from caching, heavy analytics, and busy databases |
The Burstable tier works like a savings account for CPU. When the database is quiet, it collects credits. When a busy moment arrives, it spends them to run faster. If the credits run out, the server slows to its baseline. That is why Burstable is excellent for test systems and unpredictable light loads, but a poor choice for a database that is busy all day.
Memory is the secret to speed
Databases are fastest when the data they use often can be kept in memory. This memory area is called the buffer cache or buffer pool. If the most-used data fits in memory, queries return quickly without waiting for the disk. When the working set grows larger than memory, the server reads from disk much more often and speed falls. This is why a server with more memory per vCore, the Memory Optimized tier, can help heavy workloads more than adding more CPU.
Storage
Data and logs are kept on managed Premium SSD storage. You choose the size, and you can increase it later, but you cannot shrink it. Optional storage auto-grow can enlarge the storage automatically as it fills, which protects you from the nightmare of a database stopping because the disk is full. The storage size also sets the baseline IOPS, so a bigger disk gives you more speed. Some setups also let you pay for extra IOPS on their own, separate from size.
Think of a restaurant. The vCores are the cooks, the memory is the size of the preparation table where ingredients are laid out within reach, and the storage is the pantry in the back. Many cooks with a tiny table spend their time walking to the pantry. A big table keeps everyone productive. You can always rent a bigger pantry, but you cannot give back the walls once you have built them.
How to size a new server
Estimate the data size and growth
Count the data you have now and how fast it will grow in a year. Add room for indexes, which can be as large as the data.
Estimate the busy-time load
Find the peak number of connections and queries per second. Averages hide the moments that cause trouble.
Pick a tier and size with spare room
Start from General Purpose for production, Burstable for tests, and Memory Optimized for large cached datasets. Leave headroom so normal spikes do not hit limits.
Load test with realistic data
Test with a copy of real data and realistic traffic, then watch CPU, memory, IOPS, and connections.
Adjust and keep measuring
Change the size when numbers show a limit. Scaling compute causes a short restart, so plan it for a quiet period.
Compute can be scaled up when needed, and storage can grow but not shrink. That means it is cheaper to start with a smaller storage size and grow, than to oversize storage on day one and pay for it forever.
Available sizes, maximum storage, IOPS limits, and supported regions change as Azure improves. Always confirm the latest numbers on the official pricing and documentation pages before sizing a production system.
7How a Managed Database Works Inside
Let us follow one small change, saving a new order, from the application to safe storage.
sequenceDiagram
participant App as Application
participant Eng as Database Engine
participant Log as Transaction Log
participant Stb as Standby Server
participant Dsk as Data Files on Disk
App->>Eng: Save a new order and commit
Eng->>Eng: Change the page in memory
Eng->>Log: Write the change to the log
Log->>Stb: Ship the log record to the standby
Stb-->>Log: Confirm the log is safe
Log-->>Eng: The log is durable
Eng-->>App: Commit succeeded
Eng->>Dsk: Write changed pages later in the background
Step by step
The application sends the change
The program sends a SQL statement and asks to commit. The engine checks that the statement is valid and that the rules, such as unique keys, still hold.
The change happens in memory first
The engine loads the needed data page into its memory cache if it is not already there, and changes it there. Memory is far faster than disk.
The change is written to the log
Before telling the application “done”, the engine writes a short record of the change to the transaction log on durable storage. This log is small and written in order, so it is fast.
With high availability, the standby confirms too
When zone-redundant high availability is on, the log record also reaches the standby in another zone, and the commit is acknowledged only after it is safe in both places.
The data files are updated later
The changed pages are written to the main data files in the background in large, efficient batches, at moments called checkpoints. If the server crashes before this, the log is replayed on restart and nothing is lost.
A shopkeeper first jots every sale into a small notebook at the counter, then later, in a quiet hour, copies the notes neatly into the big ledger. If the lights go out in the middle of copying, the notebook still has everything. The transaction log is that counter notebook, and the data files are the big ledger.
PostgreSQL: versions and vacuum
PostgreSQL uses a design called multi-version concurrency control. When a row is changed, it does not overwrite the old row. It writes a new version and keeps the old one until no running transaction needs it. This lets many people read and write at the same time without blocking each other. The old versions, called dead rows, must be cleaned up. A background process named autovacuum does this cleaning. If it falls behind, tables grow with wasted space, called bloat, and queries slow down. In very long-running systems, a cleanup task also protects against a rare but serious problem called transaction ID wraparound. Watching autovacuum is a basic part of caring for PostgreSQL.
MySQL: InnoDB, redo logs, and binary logs
MySQL’s standard storage engine is called InnoDB. It keeps a redo log to guarantee that committed changes survive a crash, and undo logs to roll back unfinished work and to show readers older versions of rows. Separately, the binary log records every change in order, and this log is what feeds read replicas and point-in-time restore. The memory area that caches data is called the InnoDB buffer pool, and sizing it well is the main tuning lever for speed.
Checkpoints and recovery
Both engines periodically make sure that enough changed pages have been written to disk, so that crash recovery has only a small amount of log to replay. If you ever see a short pause or a burst of disk activity at regular intervals, a checkpoint is often the cause. Azure sets sensible defaults, but heavy write workloads may benefit from tuning.
Because the log must be safely written before a commit finishes, slow log storage makes every write slow. Fast storage for the log, and the extra wait for the standby in high availability mode, are why commit time is a little longer on a highly available server than on a single server.
8Connections, Pooling, and Client Behavior
Many database problems are not about the database at all. They are about how applications connect to it.
What a connection costs
A connection is an open conversation between an application and the database. In PostgreSQL, each connection is served by its own operating system process, which uses a noticeable amount of memory. In MySQL, each connection uses a thread with smaller, but still real, memory use. Both engines have a maximum number of connections, which depends on the size of the server. If too many applications or too many copies of one application open connections, the server can run out of memory or hit the limit, and new connections are refused.
Imagine a restaurant with twenty waiters and a hundred customers. If every customer demands a personal waiter standing next to them all evening, the restaurant collapses. A smart restaurant lets waiters serve many tables in turn. A connection pool lets a few database connections serve many application requests in turn.
Connection pooling
A connection pool keeps a modest number of open connections ready and lends them to the application when needed. This avoids the cost of opening a new connection for every request, and it keeps the total number of connections safely below the limit. Azure Database for PostgreSQL has a built-in pooler called PgBouncer that you can switch on and reach on its own port. For MySQL there is no built-in pooler, so applications use their own libraries’ pools or a proxy placed in front of the server.
Good habits for applications
- Reuse connections. Open them once and keep them, rather than opening and closing for each request.
- Limit pool sizes so that the total across all application instances stays below the server’s maximum.
- Retry on failure. During a failover, maintenance restart, or scaling event, connections drop for a short time. Applications should reconnect automatically after a brief wait.
- Set sensible timeouts so a stuck request does not hold a connection forever.
- Close transactions quickly. A transaction left open and idle holds resources and, in PostgreSQL, stops cleanup.
- Use encrypted connections, which Azure enforces by default.
The server name stays the same
When a failover happens, the standby becomes the primary, but the server’s name does not change. The same name now points to the new primary. This is why applications should connect by name, never by a remembered address, and why reconnecting is usually all they need to do.
Scaling out applications multiplies connections
A common surprise is that adding more application servers, or autoscaling a web tier from five instances to fifty, multiplies the number of database connections by ten. A database that was perfectly happy can suddenly fail because it is flooded with connections. Plan connection totals together with application scaling, and put a pooler in the middle where possible.
When a database feels slow, teams often raise the maximum connections. This usually makes the problem worse, because more active connections compete for the same CPU and memory. Pool and queue the requests instead.
9Networking and Connectivity
A database holds your most valuable data, so deciding who can reach it is one of the first and most important choices you make.
Two ways to be reachable
Public access with firewall rules
The server has a public name on the internet, but a firewall blocks everyone except the address ranges you list. It is simple to start, and suits small projects, but needs careful rules.
Private access in your virtual network
The server is placed in a dedicated subnet of your virtual network and has only private addresses. Nothing on the open internet can even see it. This is the usual choice for production systems.
How private access works
With private access, you set aside a subnet and delegate it to the database service, which tells Azure that only this service may place servers there. Your applications in the same virtual network, or in networks connected to it through peering, a VPN, or ExpressRoute, reach the database through its private name. A private DNS zone makes sure the server’s name resolves to the right private address. Azure also offers private endpoints for some situations, which give the server a private address inside a subnet of your choosing, so you can combine private connectivity with other layouts.
Public access with firewall rules is a shop with a front door on the main street and a guard checking a list. Private access is a vault inside a locked building where only staff with badges can even find the corridor. For valuables, most people prefer the vault.
Choose carefully at creation
The basic network style of a server, public access or private access through a delegated subnet, is decided when you create the server, and switching between them later is limited or not possible. Plan this with your network team before you build. Moving a database from one style to another usually means creating a new server and migrating the data.
Encrypted connections
Azure requires encrypted connections by default, using TLS with modern versions. Your applications should be configured to use encryption and to verify the server’s certificate. This protects passwords and data on their journey, even inside a private network.
| Question | What to decide |
|---|---|
| Public or private? | Private for production unless there is a strong reason; public with strict rules for small or temporary projects |
| Which subnet and how big? | A dedicated delegated subnet with room for growth, replicas, and standby servers |
| How do people reach it? | Through a jump host, VPN, or private connectivity, not by opening the server to the internet |
| Which DNS setup? | A private DNS zone linked to every network that must reach the server |
| Which TLS settings? | Require encryption, use current TLS versions, and verify certificates in the application |
| Which Azure services need access? | Prefer private paths; avoid broad “allow all Azure services” rules |
Never open a database firewall to every address “just for testing”. Automated scanners find open databases within minutes, and weak passwords on exposed servers are the cause of many real data breaches.
10Data Flow and the Life of a Server
A database server has a life story: planning, creation, daily work, change, and retirement. Knowing the steps prevents surprises.
flowchart LR
A["Plan: engine, version, region, size"] --> B["Create the server"] --> C["Set up network and security"] --> D["Create databases and users"] --> E["Applications connect and work"]
E --> F["Automated backups and monitoring"] --> E
E --> G["Scale compute or storage"] --> E
E --> H["Add read replicas"] --> E
E --> I["Minor patches in maintenance windows"] --> E
E --> J["Major version upgrade"] --> E
E --> K["Stop, restore, or delete"]
Planning
Before creating anything, decide the engine, the major version, the region, the network style, the size, the availability level, and the backup settings. Choose a region close to your application servers, because distance adds delay to every query. Choose the version carefully: a newer major version gives more features and a longer support life, while an older version may be needed for application compatibility.
Creation and setup
Create the server
Pick the compute tier, storage, high availability, backup retention and redundancy, and network style. Azure builds the server in minutes.
Secure the doors
Set firewall rules or private networking, turn on identity options, and check that encryption is required.
Create databases and roles
Create your databases and separate users for each application, with only the rights each one needs.
Load data and test
Import the schema and data, and test your application against the server, including a trial failover and a trial restore.
Daily work and change
Once running, the server serves queries, takes backups, and sends metrics to Azure Monitor. Over time you will adjust parameters, add indexes, scale the compute size, add read replicas, and accept monthly maintenance. Most of these actions can be done while the server stays online, though some, such as changing compute size or certain parameters, cause a short restart.
Retirement
When a server is no longer needed, you delete it. This is serious: the automatic backups of a deleted server are removed along with it, so you cannot restore it afterward. Before deleting anything important, take an export of the data or a copy you can keep, and confirm that nothing still depends on it.
Think of opening a new branch of a bank. First you plan the location and size, then build the branch, install the locks and cameras, hire staff and open accounts, and finally welcome customers. Over the years you add counters, change the opening hours, and eventually, if the branch is closed, you carefully move every account to another branch before turning off the lights.
Describe your servers as code using templates or infrastructure tools. You can then recreate the same server for testing, review every change like application code, and avoid unrepeatable clicking in a portal.
11High Availability and Maintenance
Machines fail, buildings lose power, and software needs updating. High availability is how your database keeps answering through all of it.
Failure comes in layers
Process crash or disk problem
Handled inside the service by automatic restart and by the redundancy of the storage layer.
Loss of the host machine
Handled by moving the server to healthy hardware, or by switching to the standby when high availability is on.
Loss of an availability zone
Handled by zone-redundant high availability, where the standby in another zone becomes the primary.
Loss of a whole region
Handled by cross-region read replicas or geo-restore, which need a plan and some manual steps.
Zone-redundant and same-zone high availability
When you turn on high availability, Azure creates a standby server that continuously receives every change from the primary. With zone-redundant high availability, the standby sits in a different availability zone, so even the loss of a whole building does not stop your database. With same-zone high availability, the standby is in the same zone, which protects against server failures but not zone failures, and is useful in regions without zones. The standby is not for queries. It waits.
Picture a pilot and a co-pilot. The co-pilot watches every control the pilot touches, but does not fly. If the pilot cannot continue, the co-pilot takes over at once, and the passengers stay in the same plane. Zone-redundant high availability places the co-pilot in a separate cockpit so even an accident in the first cockpit cannot take out both.
What a failover looks like
Azure detects the problem
Health checks notice that the primary is no longer responding properly.
The standby is promoted
The standby finishes applying the last log records it received and becomes the new primary. Because replication is synchronous, no committed transaction is lost.
The name points to the new primary
The server name now leads to the new primary. Existing connections drop, and applications reconnect.
A new standby is built
Azure creates a fresh standby in the background to restore full protection.
A typical failover takes roughly one to two minutes, though this depends on the workload and how much recovery work remains. Applications that retry their connections recover on their own. Applications that crash on the first error need a human to restart them. You can also trigger a planned failover yourself to test your application, which is a good habit before going to production.
Availability promise
Microsoft publishes a service level agreement for these services, with the highest availability offered for servers with zone-redundant high availability, and lower figures for servers without it. These numbers cover the service itself, not your application or network. Read the current agreement for exact terms before quoting it in a contract.
Maintenance
Azure regularly patches the operating system and applies minor engine updates, usually once a month. You can choose a custom maintenance window, such as Sunday at three in the morning, so that disruption lands in a quiet period. With high availability on, Azure updates the standby first, then switches over, so the interruption is short. Major version upgrades are different: they move to a new engine version with new features and removed old behavior, and you start them yourself after testing. Never upgrade production without a trial on a restored copy.
High availability protects against infrastructure failure, not against mistakes. A wrong command that deletes data is copied to the standby instantly. You still need backups and tested restores.
12Backups, Point-in-Time Restore, and Disaster Recovery
A good backup plan is the difference between a bad afternoon and the loss of a business. The service handles the mechanics, but you decide the rules.
How automatic backups work
Azure takes regular backups of the server’s data and continuously archives the transaction log. A backup alone shows the data as it was at one moment. The archived log lets Azure replay changes forward from that moment. Together they allow point-in-time restore: you pick any second within your retention period, and Azure builds the database as it was at that second.
Imagine a photograph of a whiteboard taken every night, plus a video of everything written on it throughout the day. To see the board at 3:15 in the afternoon, you take the morning photo and play the video forward until 3:15. Backups are the photos, and the log is the video.
Retention and redundancy
- Retention period. You can keep point-in-time history for seven to thirty-five days. A longer period gives more time to discover a mistake, and costs more backup storage over the free allowance.
- Backup redundancy. Backups can be stored in one location, across availability zones, or copied to another region with geo-redundancy. Geo-redundant backups are usually chosen when the server is created, so decide early.
- Long-term retention. For audit rules that need monthly or yearly copies for years, check the current long-term backup options for your engine, or schedule your own exports into storage.
Restoring creates a new server
A restore never overwrites your existing server. It creates a brand-new server from the chosen moment. You can then check the data, copy back what you need, or switch the application to the new server. Remember that a restored server needs its network settings, firewall rules, alerts, and permissions set up again, because these live in the resource, not in the backup. Practice a restore, time it, and write down the steps before you ever need them.
| Situation | Best tool | Notes |
|---|---|---|
| Someone deleted a table an hour ago | Point-in-time restore to a new server | Copy the table back, or switch applications to the restored server |
| A bad release corrupted data | Point-in-time restore to just before the release | Choose a time carefully; later data is lost unless it is merged by hand |
| An availability zone is down | Zone-redundant high availability | Automatic failover to the standby |
| A whole region is down | Cross-region read replica promotion or geo-restore | Needs planning, network readiness, and some manual steps |
| You need a copy for testing | Restore to a new server | Mask or remove sensitive data before sharing |
| You must keep monthly copies for years | Long-term retention options or scheduled exports | Check the current feature set for your engine |
Disaster recovery across regions
If a whole region is lost, zone-redundant high availability cannot help, because all the zones are in that region. You have two main choices. A cross-region read replica keeps a continuously updated copy in another region; in a disaster you promote it to become an independent writable server. Geo-restore uses geo-redundant backups to rebuild the server in another region. The replica gives a much shorter recovery time and less data loss, while geo-restore costs less and is slower.
Two numbers every plan needs
The recovery point objective is how much recent data you can afford to lose. The recovery time objective is how long you can afford to be down. Write both down for each database. A shop’s product catalogue may tolerate an hour of loss, while a payment ledger may tolerate none. These two numbers decide which of the tools above you need.
The automatic backups of a server are tied to that server. If the server is deleted, they disappear. Protect important servers with resource locks and limited delete permissions, and keep an independent export of anything you cannot lose.
13Read Replicas and Scaling
When one server is no longer enough, you can make it stronger, or you can share its work. Each approach has its place.
Scaling up: a bigger server
Vertical scaling means moving to a larger compute size, with more vCores and memory. It is the simplest fix, because the application does not change. Changing compute size restarts the server, so the database is briefly unavailable. Storage can also be increased, but not decreased. There is a ceiling to how large a single server can be, and the largest sizes cost a great deal, so scaling up is not a forever answer.
Scaling out reads: read replicas
Many applications read far more than they write. A read replica is an additional server that receives all changes from the primary and answers read-only queries. PostgreSQL supports up to five replicas and MySQL supports up to ten. Replication to replicas is asynchronous, which means a replica can be a little behind the primary. This delay is called replica lag.
A busy library has one master catalogue where librarians add new books. To save readers from queuing at one desk, the library prints copies of the catalogue and puts them at other desks. The copies are updated a short time after the master changes, so a reader may not see a book that was added just a minute ago. Read replicas are those printed copies.
Using replicas wisely
- Send reporting and search queries to replicas so heavy reads do not slow the main system.
- Route reads in the application or through a proxy. The database does not choose for you.
- Expect lag. Do not read a replica right after writing and expect to see the change. For such cases, read from the primary.
- Watch the lag metric and alert if it grows, because a replica far behind is serving old data.
- Remember cost. Each replica is a full server with its own compute and storage charges.
- Use cross-region replicas for disaster recovery as well as for bringing reads closer to distant users.
Promoting a replica
A replica can be promoted to a standalone server. This stops replication and makes the server writable. The step is one-way: the promoted server does not rejoin as a replica. It is used in disasters and in planned moves, such as migrating to a new region.
Other ways to relieve the database
Caching
Keep frequent answers in a fast cache, such as Azure Cache for Redis, so the database is asked less often.
Better indexes and queries
One missing index can make a query hundreds of times slower. Fixing queries often beats buying hardware.
Table partitioning
Split a huge table into smaller pieces, often by date, so queries and maintenance touch only what they need.
Queues for writes
Absorb sudden bursts of writes in a message queue and apply them at a steady pace.
When one server is truly not enough
A few systems outgrow the largest single server for writes. Options include splitting data across several databases by customer or region in your own application, or using a distributed database product designed for that purpose. These choices add complexity, so exhaust simpler options first.
First fix slow queries and indexes. Then add caching. Then add read replicas. Then scale up. Only at the end consider splitting the data. This order is cheaper and safer than jumping straight to the biggest server.
14Security, Identity, and Encryption
Databases hold customer records, orders, and secrets. Azure offers layers of protection, and the best designs use several of them together.
Layer one: the network
Keep the server off the open internet with private access, or with a strict firewall if you must use public access. Allow only the application subnets and administrator addresses that truly need to connect.
Layer two: encrypted connections
All connections use TLS encryption by default, which stops eavesdroppers from reading passwords or data in transit. Keep this requirement on, and have applications verify the server’s certificate.
Layer three: encryption at rest
Data files, backups, and logs are encrypted on disk automatically with strong encryption and keys that Microsoft manages. If your rules require control of the keys, you can use customer-managed keys stored in Azure Key Vault. Then you decide when keys rotate and who may use them, but you also carry the duty to protect them, since a lost key means unreadable data.
Layer four: who is allowed to sign in
- Database users and passwords are the classic method. Use strong, unique passwords and a separate user for each application.
- Microsoft Entra ID authentication lets people and applications sign in with their organization identity, using short-lived tokens instead of stored passwords. Applications running in Azure can use managed identities, so no password is written in any configuration file.
- Least privilege. Give each user only the rights it needs. An application that reads data should not be able to drop tables.
Think of a hospital. The building has guarded gates (network), sealed ambulances for moving patients (encrypted connections), locked records rooms (encryption at rest), badges that open only the doors a person needs (identity and permissions), and cameras that record who went where (auditing). A thief must defeat every layer.
Layer five: watching and recording
Turn on audit logging so you know who ran which statements. In PostgreSQL the pgAudit extension records detailed activity, and in MySQL the audit log feature does a similar job. Send the logs to Log Analytics for search and alerts. Microsoft Defender for Cloud offers protection for open-source relational databases, which can flag suspicious sign-in patterns and risky settings.
Protecting the management plane
Use Azure role-based access control so that only a few trusted people can delete servers or change security settings. Add resource locks on important servers. Use Azure Policy to require private networking, backups, and encryption settings across all your databases.
Protecting secrets
Never keep passwords inside application code or images. Store them in Azure Key Vault, or avoid them altogether with managed identities and Entra ID sign-in. Rotate passwords on a schedule, and remove access promptly when people leave a team.
Do not use one shared administrator login for every application and every person. A leak of that single password gives the attacker everything, and you can never tell who did what.
15Monitoring, Logging, and Performance Tuning
A slow database makes the whole application feel slow. Good measurements tell you where to look before users start complaining.
Key metrics to watch
| What to watch | What it tells you | Worry when |
|---|---|---|
| CPU percent | How hard the processors are working | Sustained high values, near the limit for long periods |
| Memory percent | How much memory is in use | Very high, which may force heavy disk reading |
| Storage percent | How full the disk is | Above about eighty percent without auto-grow or a plan |
| IOPS and throughput | How busy the storage is | Close to the limit for the chosen storage size |
| Active connections | How many sessions are open | Approaching the server’s maximum |
| Failed connections | Whether applications are being refused | Any sudden growth |
| Replica lag | How far behind replicas are | Growing steadily or well beyond normal |
| Deadlocks and lock waits | Whether transactions block each other | Frequent occurrences |
| Transaction log and backup storage | How much log or backup data is held | Unexpected growth, often from a long-running transaction |
| Oldest transaction age (PostgreSQL) | Whether cleanup keeps pace | Climbing toward the safety limit |
Logs that explain why
Metrics tell you that something is wrong. Logs help you learn why. Enable the slow query log, which records statements that take longer than a threshold you choose. In PostgreSQL, the pg_stat_statements extension collects statistics for every kind of query, such as how often each runs and how long it takes in total. Send logs to Log Analytics so you can search and graph them, and keep them long enough to compare this week with last month.
A calm method for slow queries
Find the worst offenders
List the queries that use the most total time, not only the slowest single run. A modest query that runs a million times may hurt more than a heavy one that runs twice.
Look at the query plan
Use the EXPLAIN command to see how the engine finds the data. A plan that reads an entire large table to return a few rows usually signals a missing index.
Fix the cause
Add an index, rewrite the query to ask for fewer columns or rows, refresh the table statistics, or change how the application calls the database.
Measure again
Check that the change really helped. Remove indexes that turn out unused, because each index slows writes and takes space.
Common tuning wins
- Add the right indexes on columns used for filtering, joining, and sorting.
- Avoid asking for everything. Select only the columns you need and limit the number of rows.
- Avoid the “N plus one” pattern, where an application sends one query to get a list and then one more query for each item in the list. Fetch related data in one request instead.
- Batch writes instead of sending thousands of tiny single-row writes.
- Keep statistics fresh so the engine’s planner makes good choices.
- In PostgreSQL, watch autovacuum and fix long-running idle transactions that block cleanup.
Alerts that matter
Set alerts for high CPU over several minutes, storage nearing full, connections near the limit, replication lag, failed backups, and unusual numbers of failed sign-ins. Send them to the people who can act, and attach a short runbook that says what to check first.
A doctor measures your temperature and pulse, but also asks where it hurts. Metrics are the thermometer, slow query logs are the question “where does it hurt?”, and query plans are the scan that shows what is really wrong inside.
Record what normal looks like when the system is healthy: typical CPU, connections, IOPS, and query times. When trouble comes, you will see at once what has changed, instead of guessing.
16Cost Optimization
Databases are often among the largest items in a cloud bill. A little care brings large savings.
How you are billed
You pay for compute by the hour, based on the tier and number of vCores. You pay for provisioned storage by the gigabyte each month, whether or not it is full. Backup storage beyond the free allowance, which is tied to your provisioned storage size, is billed separately. Extra provisioned IOPS, network data leaving Azure, and each read replica add their own charges. High availability roughly doubles the compute and storage cost, because a second server runs alongside the first.
| Cost lever | How it saves money | Watch out for |
|---|---|---|
| Right-size compute | Match vCores and memory to real use | Too small causes slow responses and restarts when scaling |
| Use Burstable for dev and test | Low cost for light and occasional loads | Credits run out under steady load |
| Stop non-production servers | Stopped servers do not bill for compute, though storage still costs | Servers restart automatically after a limit; some setups, like high availability, cannot be stopped |
| Reserved capacity | Discounts for committing to one or three years of compute | Committing to more than you will use |
| High availability only where needed | Avoids paying for a standby on unimportant systems | Under-protecting critical systems |
| Limit read replicas | Each replica is a full server | Leaving forgotten replicas running |
| Tune queries and indexes | Often avoids buying a bigger server | Unused indexes still cost storage and slow writes |
| Sensible backup retention | Prevents large backup storage bills | Too short a retention for your recovery needs |
| Keep storage lean | Storage cannot shrink once grown | Careless auto-grow after a one-time data spike |
Common sources of waste
Production sizes in test environments
A test server copies the production size and high availability setting, and runs around the clock for months with almost no use.
Forgotten servers and replicas
A project ends but its server and replicas keep running and billing quietly every hour.
Buying hardware for a query problem
A server is upgraded twice because of slowness caused by a single missing index. A five-minute fix would have saved thousands.
Oversized storage from the start
Large storage is provisioned for data that may never arrive. Because it cannot shrink, the bill stays high until the server is rebuilt.
Think of renting office space. You pay for the floor whether or not every desk is used, and you pay double if you keep an identical backup office ready across town. A wise tenant rents what the team needs now, keeps the backup office only for the most critical work, and gives back rooms that are no longer needed.
Tag every server with its owner and project, set budgets and alerts in Azure Cost Management, review sizes quarterly against real CPU and memory use, and check the Azure Advisor recommendations for underused databases.
17Compared with Other Database Options
Azure offers many ways to store data. These managed open-source services are the right choice for some jobs and the wrong choice for others.
| Option | What it is | Choose it when |
|---|---|---|
| Azure Database for PostgreSQL | Managed open-source PostgreSQL | You want a rich relational database, extensions, geospatial or vector features, and no vendor-specific SQL |
| Azure Database for MySQL | Managed open-source MySQL | Your application or platform was built for MySQL, or you need a simple fast web database with many replicas |
| Azure SQL Database and Managed Instance | Managed Microsoft SQL Server engine | Your applications use SQL Server features and tools |
| Azure Cosmos DB | Globally distributed NoSQL database | You need flexible schemas, huge scale, and multi-region writes with low latency |
| PostgreSQL or MySQL on virtual machines | Self-managed installation | You need full control of the operating system, unusual extensions, or settings the managed service does not allow |
| Database operators on Kubernetes | Self-run databases inside containers | You have a strong platform team and want a uniform Kubernetes-based setup |
| Distributed PostgreSQL offerings | PostgreSQL spread across many nodes | One server cannot hold your write load; check the current Azure offerings, as they have changed over time |
Managed service versus a database on a virtual machine
Installing PostgreSQL or MySQL on a virtual machine gives you total control. You choose every setting, every extension, and every patch time. In return, you take on every task described earlier: backups, failover, security patches, and monitoring. A managed service restricts a few things, such as access to the operating system and some rarely used extensions, and gives back a large amount of free time and reliability. Most teams are better off with the managed service unless they have a specific need that it cannot meet.
Cooking at home gives you total control of the recipe, but you shop, wash, and clean up. A good restaurant serves a very similar meal, with the shopping and washing done by others. A database on a VM is the home kitchen, and a managed service is the restaurant.
Relational or NoSQL?
Relational databases like PostgreSQL and MySQL suit data with clear structure and relationships, such as customers, orders, and invoices, where correctness matters. NoSQL databases like Cosmos DB suit data with flexible shapes and extreme scale or global distribution needs. PostgreSQL’s strong JSON support also lets it handle semi-structured data well, so you can mix both styles in one system for many applications.
A simple way to decide
- Application built for MySQL or a MySQL-based platform: Azure Database for MySQL.
- New application with rich queries, maps, or AI search: Azure Database for PostgreSQL.
- Application built for SQL Server: Azure SQL.
- Massive global scale with simple access patterns: Cosmos DB.
- Need unusual control: a database on virtual machines, with your own operations team.
Choosing a database because it is fashionable, not because it fits the data and the team’s skills. A well-run relational database handles far more than most people expect.
18Design Patterns and Anti-Patterns
Patterns are recipes that have worked for many teams. Anti-patterns are recipes that look fine until the day they fail.
Patterns worth copying
Pool in the middle
Put a connection pool between application instances and the database so the number of connections stays steady, even when the application scales out.
Primary for writes, replicas for reads
Send writes and reads that need the freshest data to the primary. Send reports, searches, and dashboards to replicas.
Retry with patience
Build applications that reconnect after short interruptions, using increasing waits between attempts, so failovers and maintenance pass unnoticed.
One database user per application
Give each application its own login with only the rights it needs. If one is compromised, the damage stays small.
Cache the hot reads
Keep the answers to repeated questions in a fast cache and let the database handle only what is new.
Migrations as code
Change the schema using versioned scripts, applied automatically and reviewed like application code, never by hand in production.
The pool-in-the-middle pattern is like a receptionist who sends visitors to the few available meeting rooms in turn, instead of letting a hundred people crowd into the director’s office all at once.
Anti-patterns to avoid
What it looks like
The firewall allows every address, protected only by a simple administrator password.
Why it hurts
Automated attackers scan the internet constantly. A weak password on an exposed server is a leading cause of data theft.
Do this instead
Use private access, or a strict firewall limited to known addresses. Prefer Entra ID sign-in and strong, unique passwords stored in Key Vault.
What it looks like
Every request opens a brand-new database connection, and the application autoscales to many instances.
Why it hurts
The server spends its memory and CPU on connection setup and runs into its connection limit, so new requests fail during exactly the busiest moments.
Do this instead
Use pooling in the application and, for PostgreSQL, the built-in PgBouncer. Plan total connections together with application scaling.
What it looks like
A team enables zone-redundant high availability and decides backups are not a priority.
Why it hurts
The standby receives every change, including accidental deletes and corrupted data. High availability does not take you back in time.
Do this instead
Keep sensible backup retention, test point-in-time restores, and add cross-region protection for the most important data.
What it looks like
An application opens a transaction, then waits for a user or another service while the transaction stays open.
Why it hurts
Locks are held, other work is blocked, and in PostgreSQL cleanup stops, causing bloat and slowdowns that spread.
Do this instead
Keep transactions short, do slow work outside them, and set timeouts for idle sessions.
What it looks like
Major version upgrades go straight to production, and nobody has ever practiced a restore.
Why it hurts
Behavior changes between versions break queries, and in an emergency nobody knows how long recovery takes.
Do this instead
Test upgrades on a restored copy, rehearse restores and failovers, and write down the steps and the timings.
19Best Practices and Common Mistakes
A short list of habits prevents most database problems. A short list of mistakes causes most of them.
Best practices checklist
- Choose the engine and version on purpose, and plan upgrades before a version reaches the end of its support life.
- Use private networking for production, with a delegated subnet and private DNS.
- Turn on zone-redundant high availability for important databases and test a failover before launch.
- Set backup retention to match your needs, choose redundancy that fits, and practice point-in-time restores.
- Use connection pooling and keep total connections within limits.
- Build retry logic into every application that talks to the database.
- Sign in with Entra ID and managed identities where possible, and give each application the least privilege it needs.
- Enable auditing and send logs to Log Analytics, and use Defender for Cloud for threat detection.
- Monitor the key numbers and alert on CPU, storage, connections, replica lag, and backup failures.
- Tune queries first, then add caching, replicas, and bigger sizes in that order.
- Schedule maintenance in a quiet window and read the notifications that Azure sends in advance.
- Describe servers and schema changes as code, reviewed and repeatable.
- Tag, budget, and review every server on a regular schedule.
Mistakes beginners make
Using the administrator account for the application
The application logs in with the all-powerful account. A single mistake or injection attack can drop tables or steal everything. Create a limited user instead.
Forgetting about time zones and character sets
Dates shift by hours, or accented names turn into question marks, because the database, application, and client disagree on settings. Decide on UTC for stored times and a modern character encoding at the start.
No indexes, then a bigger server
A query scans millions of rows because no index supports it. The team doubles the server size instead of adding a small index that would fix the problem for free.
Running out of storage
A growing log or a large import fills the disk, and the database becomes read-only or stops. Use alerts, auto-grow where suitable, and watch for sudden growth.
Skipping retry logic
A routine maintenance restart takes the application down for hours because it crashes on the first dropped connection and nobody notices.
Ignoring replica lag
A page reads from a replica immediately after a write and shows old data, so users think their changes were lost. Read from the primary for that case, or tolerate the delay in the design.
Production data in test environments
A restored copy of production, with real customer data, is handed to developers with weak controls. Mask or remove sensitive data first.
Imagine that your database server vanished this minute. Do you know how to restore it, how long it will take, how much data would be lost, and which applications must be reconfigured? If you cannot answer, you have found your next task.
20Real-World Usage
PostgreSQL and MySQL sit underneath a huge share of the web. Here are the kinds of systems where these managed services shine.
Common workloads
Content websites and online shops
Many popular content and shop platforms are built for MySQL. Running them on Azure Database for MySQL gives site owners backups, failover, and scaling without managing database servers, with read replicas absorbing traffic during sales.
Software-as-a-service platforms
Business applications that serve many customers often use PostgreSQL for its strong data rules and rich queries. Each customer may have their own schema or a shared schema with a tenant column, with row-level security keeping their data apart.
Maps and location services
Delivery, travel, and property applications use the PostGIS extension in PostgreSQL to answer questions like “Which depots are within ten kilometers of this address?” quickly and accurately.
AI applications with search by meaning
Applications that retrieve documents by meaning store numeric embeddings in PostgreSQL using the pgvector extension. Azure also offers an extension that connects the database with Azure AI services, so data and AI features can work together.
Microservices with their own databases
Teams give each small service its own database server or database, so a change or failure in one does not spread to the rest. Managed services make running many small databases practical.
Reporting without hurting the main system
Dashboards and heavy reports run on a read replica, so the business can analyze last hour’s sales without slowing the shop’s checkout.
Company scenarios
The scenarios below describe typical situations rather than named companies, because real designs are private. They show how teams combine the ideas of this guide.
A regional online retailer
A retailer runs its shop on MySQL with zone-redundant high availability and four read replicas. Product pages read from replicas and a cache, while orders go to the primary. Before each festival sale, the team scales the compute up in a quiet window and scales it down afterward.
A logistics startup
A startup tracks vehicles and deliveries in PostgreSQL with PostGIS. It uses private networking, Entra ID sign-in for staff, and a cross-region replica that can be promoted if the main region is lost.
A bank’s internal tools
A bank runs internal applications on PostgreSQL with customer-managed keys, auditing sent to a central log workspace, strict least-privilege roles, and resource locks. Backups are tested monthly, and restores are timed and recorded for auditors.
A school results portal
An education board’s results site is quiet for months and extremely busy on result day. The team caches results pages, uses replicas for reads, and scales the primary before the announcement, then returns to a smaller size.
21Migrating to Azure Database
Most teams do not start from nothing. They move an existing database from their own servers, another cloud, or an older Azure service. A calm plan keeps this safe.
Two broad styles
Dump and restore
Stop writes, export the data with the engine’s standard tools, and import it into the new server. Simple and reliable, but needs downtime that grows with the size of the data.
Continuous replication
Copy the data once, then keep the target updated with ongoing changes from the source until the moment you switch. Downtime shrinks to minutes, but setup is more careful.
Tools you can use
- Native tools such as the standard dump and restore utilities of each engine.
- The migration service in the Azure portal for supported sources, which can do offline and online moves and guides you through checks.
- Azure Database Migration Service for broader and larger projects.
- Logical replication in PostgreSQL and binary log replication in MySQL for near-zero-downtime moves, when the source and target support it.
Tool names and capabilities change, so confirm the current options in the Azure documentation before you decide.
A calm migration plan
Assess
List versions, sizes, extensions, special settings, character sets, and the applications that connect. Look for features the managed service does not allow.
Design the target
Choose the engine version, size, network, high availability, and security settings. Prepare the private network, DNS, and identity.
Move the schema first
Create the structures, users, and extensions on the target. Fix any incompatibilities early, when they are cheap to fix.
Copy the data and keep it in sync
Do the bulk copy, then apply ongoing changes if you are doing an online move.
Test with the real application
Run functional and performance tests against the target. Compare query results and speed with the source.
Cut over with a rollback plan
Pause writes, let the last changes arrive, switch the application to the new server, and keep the old one untouched for a safe period in case you must go back.
Migrating a database is like moving a family to a new house without missing a single meal. You pack boxes in advance, move the heavy furniture over several days, keep the kitchen working at the old place until the new kitchen is ready, and only then hand over the old keys. Online migration is moving while the family keeps eating dinner at the old house until the last evening.
Moving from the retired Single Server
The older Single Server deployment style has been retired for both engines. If you still have databases or documents that refer to it, move them to Flexible Server using the migration tools and guidance Microsoft provides, and take the chance to review network, backup, and security settings, which are different in the newer model.
Check extensions, collations, and engine versions before the move. A missing extension or a different sorting rule can silently change query results, and these differences are far cheaper to find on a test copy than after the cutover.
22Troubleshooting Common Problems
When something goes wrong, a calm, ordered checklist beats panic every time.
| Symptom | Likely causes | First things to check |
|---|---|---|
| Cannot connect at all | Firewall or network rules, wrong name, DNS, TLS settings | Firewall or subnet access, private DNS link, server name, and certificate settings |
| Too many connections | No pooling, application scaled out, leaked connections | Active connections metric, pool sizes, idle sessions, and use of PgBouncer for PostgreSQL |
| Everything is slow | CPU or memory pressure, missing indexes, storage limits | CPU, memory, IOPS metrics and the slowest queries by total time |
| Server out of storage | Data growth, large transaction log, long transactions, many temporary files | Storage percent, log size, old transactions, and auto-grow settings |
| Brief outage at night | Planned maintenance or failover | Maintenance window and Service Health notices; check retry logic |
| Replica shows old data | Replica lag, heavy writes on the primary, undersized replica | Replica lag metric and replica size |
| PostgreSQL tables keep growing | Autovacuum behind, long-running transactions | Dead row counts, autovacuum activity, oldest transaction age |
| Restore finished but app cannot connect | Network and firewall settings not copied, name changed | New server name, firewall rules, private DNS, and application settings |
| Deadlocks and timeouts | Transactions locking each other, long transactions | Deadlock metrics, lock waits, and the order in which code touches tables |
A calm method for a slow database
Confirm it is the database
Check the application and network first. A slow web tier or distant client can look like a slow database.
Read the four signals
Look at latency, traffic, errors, and saturation. Is CPU, memory, storage, or the connection count near its limit?
Find the expensive queries
Use the slow query log and statistics to list the statements that use the most total time, and inspect their plans.
Make the smallest change that fits
Add an index, fix a query, adjust a pool, or resize. Change one thing, measure again, and then decide on the next.
When a restaurant’s service slows down, a wise manager does not buy a bigger kitchen at once. First they check whether the oven, the waiters, or the delivery is the problem. Finding the true cause before spending is the same discipline you need with databases.
23Frequently Asked Questions
Short, direct answers to the questions beginners ask most.
24Summary and Key Takeaways
You began with a shop owner who hired a record-keeping firm. You now know how Azure plays that role for your application’s data.
Azure Database for PostgreSQL and Azure Database for MySQL are managed services that run the real open-source engines on Flexible Server. Azure handles the machines, patches, backups, and failovers, while you design the data, the queries, and the access rules. With good choices about engine, size, network, availability, security, and monitoring, they give you a database that is fast, safe, and affordable, and that your team can run with confidence.
Key Takeaways
- Managed does not mean no work. Azure runs the infrastructure, and you own the schema, queries, indexes, users, and the design of your application.
- Choose the engine on purpose. Stay with the engine your application already uses; for new projects, PostgreSQL offers a rich feature set and extensions, while MySQL is a strong choice for web workloads and existing MySQL platforms.
- Size by measurement. Pick Burstable for tests, General Purpose for most production, and Memory Optimized for large cached datasets. Compute can scale, but storage cannot shrink.
- Plan for failure in layers. Use zone-redundant high availability for important servers, practice failovers, and make every application reconnect and retry.
- High availability is not backup. Keep sensible retention, test point-in-time restores, and add cross-region replicas or geo-restore for disaster recovery.
- Protect in layers: private networking, required TLS, encryption at rest, Entra ID sign-in, least-privilege roles, auditing, and resource locks.
- Tune before you buy. Pool connections, fix slow queries and indexes, then add caching and read replicas, and only then move to bigger servers. Watch the metrics and the bill every month.