Managed MySQL databases
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's database runs in a container on your laptop. If the server crashes at night, who restores the data? A cloud provider can run MySQL for you, but your app must still connect to it safely.
What a managed database gives you
A managed database is a database server that a cloud provider runs for you: it patches, backs up and monitors it. You get a host name, a port and an admin login, and you still own the schema, the users and the queries.
Running MySQL in a container on a VM works, but backups, upgrades, disk space and crash recovery are then all yours. A managed service such as Amazon RDS or Cloud SQL takes that work over.
Example 1 · Failover: the app reconnects to the new main server
import java.util.List;
public class FailoverDemo { static String primary = "zone-a";
static String query(int attempt) { if (attempt == 3) { primary = "zone-b"; // the provider promotes the standby throw new IllegalStateException("Communications link failure"); } return "orders read from " + primary; }
public static void main(String[] args) { List<Integer> requests = List.of(1, 2, 3, 4, 5); for (int r : requests) { try { System.out.println("Request " + r + ": " + query(r)); } catch (IllegalStateException e) { System.out.println("Request " + r + ": failed (" + e.getMessage() + "), pool drops the broken connection"); } } System.out.println("Same host name throughout; only request 3 saw the switch."); }}Request 1: orders read from zone-a Request 2: orders read from zone-a Request 3: failed (Communications link failure), pool drops the broken connection Request 4: orders read from zone-b Request 5: orders read from zone-b Same host name throughout; only request 3 saw the switch.
What this code does
- This is a simplified model: the third request hits the moment the main server dies, and the provider promotes the standby in zone b.
- The app keeps using the same host name. The request in flight fails, the pool replaces its connection, and the next requests work again.
A managed service gives you:
- Automated backups: a daily snapshot plus change logs, kept for a set number of days.
- Patches: minor version updates in a maintenance window you choose.
- Monitoring: graphs of CPU, connections, storage and slow queries.
- Failover (on higher plans): a standby copy in another zone takes over when the main server dies. The host name stays the same; open connections break and the app must reconnect.
A slow query is just as slow on a managed server, so the work on your SQL and indexes stays yours.
An app user with least privilege, not root
Least privilege means every login can do only what its job needs. The admin user can create users and drop every database, so it never goes into the app's configuration.
Create the schema, then two logins: one for the running app and one for Flyway. Each gets only the rights its job needs.
Example 2 · Creating the schema and two least-privilege users
Runs in: the mysql client, connected as the managed database's admin user
CREATE DATABASE shoplite CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
-- Flyway only: may change tables in shoplite, nothing elseCREATE USER 'shoplite_migrator'@'%' IDENTIFIED BY '<long random password 1>' REQUIRE SSL;GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX, REFERENCES ON shoplite.* TO 'shoplite_migrator'@'%';
-- The running app: rows onlyCREATE USER 'shoplite_app'@'%' IDENTIFIED BY '<long random password 2>' REQUIRE SSL;GRANT SELECT, INSERT, UPDATE, DELETE ON shoplite.* TO 'shoplite_app'@'%';
SHOW GRANTS FOR 'shoplite_app'@'%';Query OK, 1 row affected (0.03 sec) Query OK, 0 rows affected (0.02 sec) Query OK, 0 rows affected (0.01 sec) Query OK, 0 rows affected (0.02 sec) Query OK, 0 rows affected (0.01 sec) +--------------------------------------------------------------------------------+ | Grants for shoplite_app@% | +--------------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO `shoplite_app`@`%` | | GRANT SELECT, INSERT, UPDATE, DELETE ON `shoplite`.* TO `shoplite_app`@`%` | +--------------------------------------------------------------------------------+ 2 rows in set (0.00 sec)
What this code does
GRANT USAGE ON *.*means "may log in, nothing else"; the second line is the only real permission the app has.'%'allows any client address at the MySQL level; the provider's allowed-IP list is what limits the network. Generate the passwords (for exampleopenssl rand -base64 24) and store them only in the platform's secret settings.
shoplite_app can only read and change rows in the shoplite schema. shoplite_migrator can also change tables and is used only by Flyway at start-up. If an attacker finds a SQL injection bug, the app user cannot drop a table or read other schemas.
REQUIRE SSL on each user makes the server refuse any connection from that user that is not encrypted, even if someone forgets the setting in the URL. A single user limited to shoplite.* is the minimum; the two-user split is the stricter version.
Find the bug
Find the unsafe database line
Tap the risky line in each snippet, then check the fix.
The running app must only read and change shop rows.
Round 1 of 3Connection strings with SSL and allowed IPs
sslMode=REQUIRED is a MySQL Connector/J setting in the JDBC URL that makes the driver refuse to connect unless the traffic is encrypted with TLS, so the password and the data cannot be read on the network.
A JDBC URL holds the host, port and database name, and driver options after ?. The program below builds one and checks that it is safe for production.
Example 3 · Building and checking a JDBC URL
import java.util.LinkedHashMap;import java.util.Map;
public class JdbcUrlDemo { static String url(String host, int port, String db) { return "jdbc:mysql://" + host + ":" + port + "/" + db + "?sslMode=REQUIRED&connectTimeout=10000"; }
static Map<String, String> params(String url) { Map<String, String> map = new LinkedHashMap<>(); int q = url.indexOf('?'); if (q < 0) { return map; } for (String pair : url.substring(q + 1).split("&")) { String[] kv = pair.split("=", 2); map.put(kv[0], kv.length > 1 ? kv[1] : ""); } return map; }
static String verdict(String url) { String mode = params(url).getOrDefault("sslMode", "PREFERRED (default)"); boolean safe = mode.equals("REQUIRED") || mode.startsWith("VERIFY"); return "sslMode=" + mode + " -> " + (safe ? "encrypted or refused" : "may fall back to plain text"); }
public static void main(String[] args) { String good = url("shoplite-db.mumbai.example.net", 3306, "shoplite"); System.out.println(good); System.out.println(verdict(good)); System.out.println(verdict("jdbc:mysql://shoplite-db.mumbai.example.net:3306/shoplite")); System.out.println(verdict("jdbc:mysql://localhost:3307/shoplite?sslMode=DISABLED")); }}jdbc:mysql://shoplite-db.mumbai.example.net:3306/shoplite?sslMode=REQUIRED&connectTimeout=10000 sslMode=REQUIRED -> encrypted or refused sslMode=PREFERRED (default) -> may fall back to plain text sslMode=DISABLED -> may fall back to plain text
What this code does
- The URL keeps the host, port and database name in the usual places; driver options go after
?, joined with&. - A URL with no
sslModeusesPREFERRED, which is why the check treats a missing value as unsafe for production.
TLS (often still called SSL) is the encryption itself. The sslMode choices:
PREFERRED(the default) uses TLS if the server offers it, but silently falls back to plain text.REQUIREDrefuses to connect without TLS. Use it at least.VERIFY_CAandVERIFY_IDENTITYalso check the server's certificate (and host name) against the provider's CA certificate, which stops a fake server in the middle.
The provider also has a list of allowed IPs (authorized networks, trusted sources or a security group, depending on the cloud). Only listed addresses can open a connection. Add your app server's address, never 0.0.0.0/0 (everyone). If both live in the same cloud, private networking keeps the database off the public internet.
Predict the output
Does the connection stay encrypted?
The database server has TLS switched off. What happens?
Round 1 of 2
What does the driver do with this URL?
Flyway on the first start
Flyway is a tool that builds and updates a database schema from numbered SQL scripts (V1__..., V2__...) when the app starts, and records each script it has run in the flyway_schema_history table.
On a brand-new managed database, the first start of ShopLite runs every migration script. Watch the start-up log:
Example 4 · First start on the managed database: Flyway builds the schema
Runs in: the shoplite-api container started with SPRING_PROFILES_ACTIVE=prod
# Platform environment variables (values hidden in the platform's settings)SPRING_PROFILES_ACTIVE=prodDB_URL=jdbc:mysql://shoplite-db.mumbai.example.net:3306/shoplite?sslMode=REQUIRED&connectTimeout=10000DB_USER=shoplite_appDB_PASSWORD=********FLYWAY_USER=shoplite_migratorFLYWAY_PASSWORD=********# application-prod.yml uses them like this:# spring.datasource.username: ${DB_USER}# spring.flyway.user: ${FLYWAY_USER}INFO o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table `shoplite`.`flyway_schema_history` ... INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite`: << Empty Schema >> INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "1 - create schema" INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "2 - add order history index" INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "3 - add product search index" INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "4 - create users and roles" INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "5 - create refresh token" INFO o.f.core.internal.command.DbMigrate : Successfully applied 5 migrations to schema `shoplite`, now at version v5 (execution time 00:01.214s) INFO com.zaxxer.hikari.HikariDataSource : ShopLitePool - Start completed. INFO c.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 9.87 seconds
What this code does
- Five migrations run on an empty schema, exactly the V1 to V5 scripts from Sections 16 and 17. The dev-data scripts do not run because the prod profile does not list
db/dev-data. - Flyway connects as
shoplite_migrator; the HikariCP pool that serves requests connects asshoplite_app. The next start printsSchema shoplite is up to date. No migration necessary.
Later starts find flyway_schema_history, see nothing new and continue in under a second.
With two users, Spring Boot connects Flyway with spring.flyway.user and spring.flyway.password, and the app with spring.datasource.username and password. Sample data stays out: the db/dev-data folder is listed in spring.flyway.locations only in the dev profile, so production starts with empty tables.
Order of execution
The first start on an empty database
Put the steps of the first ShopLite start in order.
Errors: timeouts and too many connections
max_connections is the MySQL setting for the most connections the server accepts at once. Small plans allow 30 to 100, and each app instance opens a whole pool, so instances x pool size must stay below it.
Two errors cause most failed first connections. Start with the pool sizes, which are easy to add up:
Example 5 · Sizing the pool for a small plan
public class PoolBudgetDemo { static void check(String plan, int maxConnections, int instances, int poolSize) { int flyway = 1; // one connection while migrating at start-up int spare = 5; // you in a SQL client, monitoring, backups int needed = instances * poolSize + flyway + spare; String result = needed <= maxConnections ? "OK" : "TOO MANY CONNECTIONS"; System.out.printf("%-6s max %3d | %d x pool %2d + %d + %d = %3d -> %s%n", plan, maxConnections, instances, poolSize, flyway, spare, needed, result); }
public static void main(String[] args) { check("tiny", 30, 2, 20); check("tiny", 30, 2, 10); check("tiny", 30, 2, 5); check("small", 100, 3, 20); }}tiny max 30 | 2 x pool 20 + 1 + 5 = 46 -> TOO MANY CONNECTIONS tiny max 30 | 2 x pool 10 + 1 + 5 = 26 -> OK tiny max 30 | 2 x pool 5 + 1 + 5 = 16 -> OK small max 100 | 3 x pool 20 + 1 + 5 = 66 -> OK
What this code does
- Each app instance opens its whole pool, so the total grows with the number of instances, not with the number of users.
- ShopLite's prod profile used a pool of 20; on a tiny plan with two instances that alone breaks the limit. A pool of 5 to 10 is plenty for a small API.
Example 6 · Reading a connection timeout in the start-up log
Runs in: the platform's log viewer for the shoplite-api service
# The VM's public IP is 203.0.113.25; the database allows only 198.51.100.0/24.# Fix: add 203.0.113.25/32 to the database's allowed IPs (or use private networking).ERROR com.zaxxer.hikari.pool.HikariPool : ShopLitePool - Exception during pool initialization. com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:...) ... Caused by: java.net.SocketTimeoutException: Connect timed out ... APPLICATION FAILED TO START
What this code does
- "Has not received any packets" plus
Connect timed outmeans no reply at all: a network rule dropped the connection before MySQL could see it. - Compare:
Access denied for user 'shoplite_app'means MySQL answered and rejected the password, andUnknown databasemeans the login worked but the schema name is wrong.
Connection timeout. The log shows Communications link failure caused by Connect timed out. Nothing answered at all, which almost always means a network rule: the app server's IP is not on the allowed list, or you used the private host name from outside the private network. A wrong password gives Access denied instead. Add connectTimeout=10000 to the URL so the failure appears after 10 seconds instead of hanging.
Too many connections. HikariCP's default maximum-pool-size is 10, and Flyway and your SQL client need connections too. Instances x pool size + a few spare must stay below the plan's max_connections. For a small API, a pool of 5 is plenty.
Fix the error
Read the error, pick the fix
Each error points at one line. Choose what to put there.
Round 1 of 3
The first deploy cannot reach the database.
Error
Communications link failure Caused by: java.net.SocketTimeoutException: Connect timed out
Next step
Check your understanding
11 quick questions