Managing connections
In a database cluster group for Aurora with routing enabled, the routing layer sits between the member clusters and the applications that connect through the routing endpoint. AWS manages the routing layer, which is serverless and scales automatically with your workload. You control how your application pools and retires connections, and how much capacity each member cluster has. Applications that connect to a member cluster directly don't use the routing layer.
Connection best practices at a glance
The following practices matter most for applications that use the routing endpoint:
-
Set the pool acquisition timeout to the wait that your application accepts.
-
Retire connections before the routing layer closes them, with a maximum lifetime that has jitter, an idle timeout, and validation on borrow.
-
Bound each pool and how fast it grows, and drain pools gradually when you restart or deploy.
-
Set session variables once, when the connection opens, not with each request.
-
Require TLS in the client, and read the negotiated TLS version from the client.
-
Pin a session to reach one member cluster, on a dedicated connection that isn't part of an application pool.
Using routed connections efficiently
The routing layer opens a session on a member cluster when a client connection sends its first statement to that member cluster, not when the client connects. It keeps that session while the client connection stays open, idle or not, and uses it for every later statement to that member cluster. A client connection that has reached several member clusters holds one session on each of them. You can also pin a session to one member cluster yourself. Use routed connections as follows:
-
Set a maximum connection lifetime in each pool so that the pool replaces its connections before the routing layer ends them. Recycled connections pick up changes in the routing layer and in the member clusters. For the limits, see Idle close and connection lifetime.
-
Set session variables once, when the connection opens, in the driver's connection options or the pool's initialization statement. The routing layer applies the session settings on each member cluster that the session reaches, so a
SETbefore every request adds work to every request. -
Check routing with a routed statement. The routing layer itself answers a table-less
SELECT 1, version reads, the sessionSETstatements that it holds, and the group's system tables. These prove the connection to the routing layer, not routing.
The routing layer doesn't share a member cluster session between client connections. It ends a connection's member cluster sessions when the connection closes, including at the idle close and the maximum lifetime, after KILL CONNECTION, and after a connection reset or a user change. If one of those member cluster sessions ends on its own, for example after a failover or a KILL on the member cluster, what happens next depends on the session's state. If that member cluster session had an open transaction, a statement running, or prepared statements on it, the routing layer doesn't open a replacement and ends the client connection with error 1927. A member cluster session that was idle, with none of those, can be replaced at the session's next statement on that member cluster, and the routing layer applies the session's settings again on the new member cluster session. Session state that only the member cluster held, such as temporary tables and locks from GET_LOCK and LOCK TABLES, is gone. A pinned session runs on its own member cluster session on the pinned member cluster, apart from the sessions that routed statements use, and unpinning ends that session.
Configuring connection pools
A connection pool that works with an Aurora DB cluster works with the routing endpoint. Configure each pool that connects to the routing endpoint as follows:
-
Set the pool acquisition timeout to the wait that your application accepts. The routing layer has no shared pool of member cluster connections. When a member cluster refuses a new session or doesn't open it in time, the statement fails with error
1053(08S01), and the connection closes. When the routing layer's wait for a member cluster connection runs out, the statement fails with error9501, and the connection stays open. Reconnect or retry with backoff. A pool acquisition timeout comes from the application's own pool. -
Open connections at a steady rate. The routing layer adds capacity as your workload grows. When it can't accept a new connection, it rejects the connection before it authenticates the client, with error
1040on Aurora MySQL. Open connections gradually instead of in large bursts, and retry a rejected connection after a short wait. On Aurora MySQL,@@max_connectionsat the routing endpoint returns a fixed value of 35000, which isn't the connection limit of your group or of a member cluster. -
Bound the pool and its growth rate. Set a maximum pool size, and allow the pool to shrink back to its minimum after a burst. A burst of thousands of new connections, or of disconnects during an application restart or deploy, stalls routed traffic, including queries that are already running. Drain pools gradually, and restart application hosts one at a time.
-
Spread the first statements of new connections. Because the routing layer opens member cluster sessions at a connection's first statement, many connections that send their first statement together open many sessions on each member cluster at once. This is most likely when every client reconnects at the same time. A pool that is open but idle holds no member cluster sessions, so a large burst arrives when its connections first run statements. A large burst of new sessions can delay the statements on that member cluster, including those on its direct connections, until the burst passes. After a reconnect, start the first statements of new connections over a period of time, not all at once.
-
Validate connections on borrow with a routed statement. A pool's health check, such as
SELECT 1, checks only the connection to the routing layer. To check a member cluster too, validate with a statement on a mapped table, such asSELECT 1 FROM. On Aurora MySQL, a health check that names no table and isn't one that the routing layer answers, such asa_mapped_tableLIMIT 1DO 1, fails with error1235. -
Connection reset and user switching work through the routing endpoint. On Aurora MySQL, a connection reset (
COM_RESET_CONNECTION) returns the session to its defaults and keeps its user, its connection ID, and its current database. It rolls back an open transaction, releasesLOCK TABLESlocks, drops prepared statements and user variables, clears a session pin, and ends the session's member cluster sessions, so the connection's next statement opens new ones. A user change (COM_CHANGE_USER) resets the session in the same way, except that the current database becomes the database that the request names, or none if the request names none, and then signs in as the router user that it names. If that sign-in fails, for example with a wrong password (error1045), the routing layer closes the connection. You can use one pool for each router user, or switch the router user on a returned connection. -
Don't depend on an error cause to retry. The routing layer usually ends a connection gracefully and sends no SQL error. For retries, see Retrying after an error.
Idle close and connection lifetime
The routing layer ends client connections as follows:
-
Idle close. The routing layer closes a client connection 30 minutes (1,800 seconds) after its last traffic, including when the session is idle inside an open transaction. The member cluster session ends with it, and the member cluster rolls back an open transaction. The routing layer sends no SQL error, so the next statement on that connection fails as a lost connection, with error
2013on Aurora MySQL. Any statement, or a protocol ping such asCOM_PING, restarts the period. TCP keepalive doesn't. The member cluster'swait_timeoutdoesn't control this close. -
Maximum lifetime. The routing layer ends every client connection 12 hours (43,200 seconds) after it opened, even a connection in steady use. On Aurora MySQL, an idle connection that reaches the limit gets error 4031,
Connection closed: maximum connection lifetime reached, and then closes. A connection that has a statement running closes with no error, and the statement keeps running on the member cluster. Treat an autocommit write that was running then as possibly committed.
Neither limit is a setting that you change. To retire connections before the routing layer closes them, configure each pool as follows:
-
Set the maximum connection lifetime well below 12 hours, and add jitter to it, so that the pool doesn't reconnect all its connections at the same time. The routing layer adds and removes routers as your workload changes. A client connection stays on the router that it opened on, so only new connections reach a router that the routing layer adds. A shorter lifetime, for example 30 minutes, spreads connections across the routers sooner after the routing layer scales.
-
Set the idle timeout below 1,800 seconds, so that the pool, not the routing layer, closes idle connections.
-
Turn on validation on borrow, so that the pool replaces a connection that closed while it was idle.
Connection pools and session pins
A session pin is the way to reach one member cluster from the routing endpoint without a new connection. A pinned session passes its statements through, so anything that the member cluster accepts runs there, such as DDL, administrative statements, and catalog reads. For what a pin carries, see Session pinning.
Pinning needs no privilege, so every router user can pin a session. A pin stays on its session until you unpin it or the connection closes. A pin left on a pooled connection sends the next borrower's statements to one member cluster without routing. Use pins as follows:
-
For pinned work, open a dedicated connection that isn't part of an application pool. For a pool that does only work on one member cluster, such as the pool of a schema change tool, put the pin statement in the pool's connection initialization statement.
-
After you pin, name objects by their cluster names on that member cluster, and set the database to a cluster name. A pin first runs
USEof the pin's database part, or of the session's current database, on the member cluster. If that name isn't a database there, the pin is refused and the session stays as it was. Name the cluster database in the pin, as in'alias@cluster_db'. -
If you must pin a pooled connection, unpin it before you return it to the pool. You can't pin or unpin inside a transaction.
-
If the member cluster connection of a pinned session fails, the routing layer doesn't reconnect it or restore the session state. Reconnect, and then pin the session again.
At the routing endpoint, pin the session to a member cluster by its alias, and unpin it before you return the connection to a pool.
SET SESSION router_cluster_pin = 'MEMBER_CLUSTER_ALIAS'; -- Work on that member cluster, under its cluster names. SET SESSION router_cluster_pin = DEFAULT;
A pin, an unpin, or a change of pin target inside an open transaction returns error 1179 (SQLSTATE 25000), and the open transaction stays as it was. With autocommit = 0, commit or roll back after the first statement before you pin or unpin. Use the SET SESSION router_cluster_pin or SET router_cluster_pin form. Unpinning ends the member cluster session that the pin used, so temporary tables, locks from GET_LOCK and LOCK TABLES end with it, and session variables carry over. For the statement, see SET router_cluster_pin.
Setting timeouts
Set connect and statement timeouts as you do for any Aurora DB cluster. Also set a statement timeout that the member cluster enforces, at the start of the session, so that the member cluster stops a statement that runs longer. Through the routing endpoint, the routing layer sets the session timeouts wait_timeout, interactive_timeout, and net_write_timeout on every member session. Member cluster parameter group values for these settings don't apply to routed sessions. Keep other timeout parameters, such as innodb_lock_wait_timeout and max_execution_time, the same on every member cluster. For parameter groups, see Parameter groups for Amazon Aurora.
Set max_execution_time at the start of the session. The routing layer applies each member cluster session variable that you set, including timeout settings such as innodb_lock_wait_timeout and lock_wait_timeout. It applies them on each member cluster that the session reaches, and the member cluster enforces them. The optimizer hints MAX_EXECUTION_TIME and SET_VAR also reach the member cluster. To stop a running statement and keep the session, run KILL QUERY with the connection ID at the routing endpoint. KILL CONNECTION ends the session and its member cluster sessions. You can send either statement through any connection to the routing endpoint. For the connection IDs, see Tracing a session or statement across the group. For the Aurora MySQL parameters, see Aurora MySQL configuration parameters.
Sizing pools and member clusters
Each member cluster keeps its own connection limit, as an Aurora DB cluster does. Each routed client connection holds one session on every member cluster that it has reached, for as long as it stays open. Each of those sessions counts toward that member cluster's max_connections. Size each pool against the connection limit of every member cluster that the pool reaches, and add the direct connections to that member cluster. Idle connections that a pool keeps after a burst also keep their member cluster sessions. For Aurora Serverless v2, see Maximum connections for Aurora serverless and Performance and scaling for Aurora serverless.
To keep the number of member cluster sessions down, keep each pool's traffic on the member clusters that its application needs.
A member cluster can also refuse a new session from the routing layer. On Aurora MySQL, when the member cluster doesn't accept a new session from the routing layer, the statement that needed it gets error 1053 (SQLSTATE 08S01) Member cluster is not accepting new sessions; reconnect and retry the statement, and the routing layer closes the client connection. A member cluster that refuses at its own connection limit returns its own error instead, for example 1040 (max_connections), or 1203 or 1226 for a per-user limit. A pin to that member cluster gets error 3170, The member cluster is not accepting new sessions. Retry later., and the session stays as it was. Reconnect and retry with backoff. For the messages, see Routing and data mapping errors.
Running a test workload
Before your application uses the routing endpoint, run a test workload that sends traffic the way your application does. For load generator settings and examples, see Running your first workload through the routing endpoint.
Driver and ORM settings
Most drivers and ORMs work through the routing layer with a few settings. An ORM's runtime statements route like any other statement, while its schema changes and catalog introspection run on one member cluster. Give each kind of work its own connection, as the following table shows. Most ORMs already run schema changes apart from runtime work.
| Task | Connection |
|---|---|
| Runtime reads and writes | The routing endpoint |
Schema changes (CREATE, ALTER, DROP) |
A pinned session or a direct connection, on each member cluster |
| Schema introspection and validation | A pinned session or a direct connection |
In the ORM's models, use an identifier that your application generates as the primary key. Don't compute the keys of a bulk insert from the last insert ID plus an offset. Turn off foreign key generation in the ORM's schema changes where it supports that, or keep related tables on one member cluster. For the setting in each driver, pool, and framework, see Drivers and connection pools and ORMs. For keyed statements, see Running queries and transactions through the routing layer.
-
Use text or binary-protocol prepared statements on scaleout tables. SQL
PREPAREandEXECUTEroute like the statement that they prepare. On a scaleout table, a binary-protocolCOM_STMT_EXECUTEroutes by the routing key value bound for that execute. The routing layer prepares the statement on a new member cluster first. You don't need to turn off server-side prepared statements. In a session without a pin, the routing layer refuses server-side cursors, long data, and a reset (COM_STMT_RESET) of a statement that it forwarded to a member cluster. For more information, see Statement compatibility. A textPREPAREfrom before the pin keeps working when its tables are on the pinned member cluster and none is a scaleout table. Any other textPREPAREfrom before the pin returns error4163(User-level lock name 'Prepared statement cannot run in the current pin state. …' should not exceed 64 characters) when you run it. A binary-protocol prepared statement from before the pin returns error1235(Prepared statement cannot run in the current pin state.). Prepare either kind again after the pin. -
Send one statement in each request, or turn on multi-statements in the driver. With the client's multi-statement option on (
CLIENT_MULTI_STATEMENTS, for exampleallowMultiQueries=truein MySQL Connector/J), the routing layer runs the statements of a request one at a time, and each statement routes on its own. Without that option, a request with more than one statement fails with error1064, as on an Aurora DB cluster. -
Connect with a utf8mb4 handshake, for example with
--default-character-set=utf8mb4. The routing layer refusesSET NAMESand driver character set options outside the utf8mb4 family with error1115. For collations, see Character sets and collations. -
Set the transaction isolation level for the session or for one transaction. A
SET SESSION TRANSACTION ISOLATION LEVELapplies on every member cluster that the session reaches. ASET TRANSACTIONbeforeBEGINsets the level for the next transaction only. -
Turn off protocol compression in the client. Depending on the driver, a client that forces compression either loses the connection after it signs in or runs uncompressed.
-
Set driver-read settings at the routing endpoint. Some drivers read a value once and reuse it, such as MySQL Connector/J with
@@auto_increment_increment. On Aurora MySQL, routed sessions start withauto_increment_incrementset to1and withsql_modefrom thesql_moderouting endpoint parameter, regardless of the member clusters' DB cluster parameter groups. ASET SESSION auto_increment_incrementstatement in the session applies on every member cluster that the session uses. To changesql_modefor routed sessions, set thesql_moderouting endpoint parameter. Also setsql_modeto the same value on every member cluster, so that direct connections behave the same on each one. -
Read warnings right away. Send
SHOW WARNINGSorSHOW ERRORSimmediately after the statement that it reports on. -
Expect member-table values in schema validation. An ORM that validates the schema at startup, such as Hibernate
validate, TypeORMsynchronize, or GORMAutoMigrate, can readinformation_schemawithout a schema or table filter. That read lists each scaleout table under its own name, with the values of one member table.TABLE_ROWS,DATA_LENGTH, and the other statistics are that member table's values, not sums or averages. If a member cluster doesn't answer, the read fails with an error and returns no rows.