View a markdown version of this page

Running queries and transactions through the routing layer - Amazon Aurora

Running queries and transactions through the routing layer

Through the routing endpoint of a database cluster group for Aurora, each statement and each transaction runs on one member cluster. A statement that resolves to one member cluster is the normal case and the only path for a write. Writing for a group mostly means giving the routing layer the routing key that it needs, and handling the errors when it can't resolve a statement. Work that must span member clusters runs in your application, one keyed statement at a time. For queries and transactions that span databases, Aurora DSQL is a complementary option. These rules apply to routed sessions. In a pinned session and on a direct connection, a statement runs as on a standalone Aurora DB cluster. For how the routing layer binds a transaction to a member cluster, see Transactions. For schema design that places related rows on the same member cluster, see Designing schemas and queries for one member cluster.

Writing keyed statements

A statement resolves to one member cluster when every object that it names resolves to the same member cluster. What resolves an object depends on how you placed it, as the following table shows. Name objects by their router names, not by their cluster names.

Placement What resolves the member cluster
A database placed on one member cluster The router database name in the data mapping
A table placed on one member cluster The router table name in the data mapping
A scaleout table The routing key value in the statement

On a scaleout table, the routing layer reads the routing key value from each statement and refuses a statement with no usable routing key before any member cluster runs it. Only equality and IN on literals resolve a key. Under a COLUMN routing function, a range or BETWEEN also resolves when one VALUES IN RANGE collocation holds the whole range. The key must be an integer, DATE, DATETIME, or TIMESTAMP column. Any other range, a pattern match, a null test, an inequality, and a function or arithmetic expression on the key column don't resolve. On a multi-column routing key, every key column must appear. On a table with a database-level or table-level mapping, any predicate routes. For the predicate forms, multi-row writes, and generated IDs, see Designing statements that route to one member cluster.

In application code, also do the following:

  • Carry the key in lookups, updates, deletes, and locking reads. Write WHERE tenant_id = ? AND order_id = ?, never WHERE order_id = ? alone.

  • Send key values as plain literals. The routing layer doesn't evaluate arithmetic or most functions on a key value. Compute values in your application, not in the predicate.

  • Write every insert with a column list. For an INSERT ... VALUES with no column list, the routing layer takes the key from the column position that ROUTE BY KEY declares.

  • Group the rows of a multi-row insert by member cluster. The routing layer rejects a multi-row INSERT whose rows resolve to more than one member cluster.

  • Change a row's routing key with a delete and an insert. The routing layer refuses an UPDATE of a routing key value, even when the new value maps to the same member cluster. Delete the row, and then insert it under the new key. Put both in one transaction only when both keys route to the same member cluster.

  • Run statements that name no table in a pinned session or on a member cluster endpoint. In query routing mode, the routing layer rejects a bare expression such as SELECT 1+1, and a stored procedure call under table-level placement, because neither names a table that resolves.

  • Configure ORMs for routing. Use an identifier that your application generates as the primary key, not a sequence-backed or AUTO_INCREMENT column. Check the statements that the ORM sends. For the connection to use for each ORM task, see Driver and ORM settings.

The following example shows a keyed read and write on the scaleout table app.orders, routed by tenant_id, and a read that the routing layer refuses.

-- Routes to the member cluster that holds tenant 42 SELECT * FROM app.orders WHERE tenant_id = 42 AND order_id = 7; INSERT INTO app.orders (tenant_id, order_id, status) VALUES (42, 8, 'new'); -- Refused: no routing key SELECT * FROM app.orders WHERE order_id = 7;

The routing layer refuses a statement that it can't resolve to one member cluster, whether the statement reads or writes. It returns error 1235 (SQLSTATE 42000) on Aurora MySQL. A refused DDL statement returns a different message, so you can tell whether to change the statement or the connection. For the message of each error, see Error codes for database cluster groups for Aurora.

Combining rows from several member clusters

The routing layer doesn't gather rows from more than one member cluster. To get a result that spans member clusters, do the following.

To combine rows from several member clusters
  1. In your application, write one query for each member cluster that holds rows that you need.

  2. Run each query at the routing endpoint with its routing key, or on that member cluster's own endpoint.

  3. In your application, combine the results.

Joins

A join resolves when every table that it names resolves to the same member cluster. A statement that names a scaleout table and a table with its own data mapping is refused, even when both are on the same member cluster. You meet this rule with placement, not with a rewrite of the query. Place the tables that you join on the same member cluster, or keep them in one collocation group. A collocation group stays together when a data movement job moves it. A join between two scaleout tables routes when the keys of both tables resolve to one member cluster, inside or outside a transaction. A literal routing key predicate on one of the tables is enough. When the keys are on different member clusters, the routing layer refuses the join. Each member cluster enforces foreign keys only between its own tables. For join designs, see Join patterns.

Statements to run on one member cluster

The routing layer refuses the following statements in a routed session. Run them in a pinned session or on a member cluster's own endpoint, with the cluster names on that member cluster. There they run as on a standalone Aurora DB cluster.

  • A view over a scaleout table

  • LOCK TABLES on a scaleout table

On Aurora MySQL, the advisory lock functions GET_LOCK, RELEASE_LOCK, and IS_FREE_LOCK in a statement that names a mapped table run on that table's member cluster, and the lock lives on that member cluster only. A lock taken through one member cluster doesn't block a session whose statement routes to another member cluster.

A subquery or a common table expression over a scaleout table routes when its routing key resolves the statement to one member cluster. You can't create a view on a scaleout table.

For the statements that each connection mode supports, see Statement compatibility.

Keeping transactions on one member cluster

A transaction runs on the member cluster of its first routable statement, and the routing layer refuses a later statement that needs another member cluster. For the order of session settings, transaction characteristics, and savepoints, and the state of a transaction after a refused statement, see Single-cluster transactions.

To keep a transaction on one member cluster
  1. At the routing endpoint, before BEGIN, set the session settings and transaction characteristics that the transaction needs, in the order that Transaction rules on Aurora MySQL requires.

  2. At the routing endpoint, start the transaction, and make its first routable statement carry the routing key. The transaction binds to that member cluster.

  3. At the routing endpoint, carry the same routing key, or name objects on the same member cluster, in every later statement of the transaction.

  4. At the routing endpoint, commit the transaction.

  5. If the routing layer refuses a statement in the transaction, send ROLLBACK, not COMMIT. Then fix the statement or split the transaction, and run it again from its first statement.

The following example keeps a transaction on the member cluster that holds tenant 42.

BEGIN; INSERT INTO app.orders (tenant_id, order_id, status) VALUES (42, 2, 'new'); INSERT INTO app.orders (tenant_id, order_id, status) VALUES (42, 7, 'new'); COMMIT;

Every isolation level of Aurora MySQL is available on every kind of connection, and the level applies on the member cluster that the transaction binds to. Set it before BEGIN.

Keep the following statements out of a routed transaction:

  • Data mapping changes. Data mapping changes aren't transactional, and the routing layer refuses one inside a transaction. Run each change on its own, outside a transaction.

  • DDL. In a routed session, the routing layer refuses DDL other than the scaleout statements and account management statements. Run other DDL in a pinned session or on a member cluster's own endpoint. For the rollout, see Rolling out schema changes.

  • Table locks across member clusters. The routing layer routes LOCK TABLES when every named table resolves to one member cluster. It refuses a lock on a scaleout table, or on tables on more than one member cluster.

Replacing a transaction that spans member clusters

To replace a transaction that would span member clusters, choose one of the following designs:

  • Keep the write on one member cluster. Choose a routing key and collocation groups so that rows that change together are on the same member cluster. Choose them before you load data. For more information, see Properties of a good routing key and Planning collocations and headroom.

  • Accept an outcome on each member cluster. Write to each member cluster in its own transaction, one after the other in the same session. A failure on one member cluster, such as a duplicate key, then leaves the member clusters in different states, so make your application detect and reconcile them.

  • A session with autocommit=0 counts as an open transaction, and some drivers, such as PyMySQL, turn autocommit off by default. Send SET autocommit = 1 or SET autocommit = 0 as a statement when the application needs a mode.

  • Run SET TRANSACTION ISOLATION LEVEL before BEGIN. After BEGIN, the routing layer refuses it with error 1568.

  • A statement that ends one transaction and starts the next keeps the next transaction on the same member cluster. These are COMMIT AND CHAIN, ROLLBACK AND CHAIN, and BEGIN or START TRANSACTION while a transaction is open. So is a plain COMMIT or ROLLBACK while completion_type is CHAIN. To let the next transaction bind to another member cluster, set completion_type to NO_CHAIN. Then end each transaction with a plain COMMIT or ROLLBACK, and run BEGIN.

  • The routing endpoint doesn't run XA transactions in a routed session. It rejects START TRANSACTION WITH CONSISTENT SNAPSHOT before the transaction binds to a member cluster. Run these forms on one member cluster, through a session pin or a direct connection, or run START TRANSACTION without WITH CONSISTENT SNAPSHOT.

Retrying after an error

When you change a data mapping or a routing function, or a data movement job cuts over, the routing layer routes on the change within a short time. A statement that the routing layer routed on an older mapping gets a retry error: error 1412 on Aurora MySQL. On Aurora MySQL, the routing layer resends a text-protocol statement up to 3 times first, and the error reaches you only when those resends are used up. The session stays open, and a retry routes on the new mapping. Inside a transaction, a statement that needs a mapping changed after the transaction's first routed statement fails with error 63928 (Aurora MySQL), and the routing layer has already rolled the whole transaction back. For how a change reaches each kind of session, see Applying data mapping changes. For the retry rule, see Transaction errors and retries.

Match errors by code or SQLSTATE, not by message text. The following table lists what the application does for each error.

Situation Aurora MySQL What the application does
The statement was routed on an older mapping 1412 Retry the statement. On Aurora MySQL, the routing layer first resends a text-protocol statement up to 3 times. After error 1412, the session and any open transaction stay open.
A statement in a transaction needed a mapping that changed after the transaction's first routed statement 63928 The routing layer has already rolled back the whole transaction. Start it again from the beginning; don't retry the single statement and don't send COMMIT.
A write arrived during a data movement cutover See Moving data between member clusters Retry the write. It reaches the new member cluster.
The routing layer refused the statement 1235 Don't retry, because no member cluster ran it. Inside a transaction, send ROLLBACK, not COMMIT. Then add the routing key, or split the statement or transaction.
A name isn't in the data mappings 1146 Inside a transaction, send ROLLBACK. Then check the name against the data mappings.
A deadlock on the member cluster 1213 Roll back if the transaction is still open, and retry the whole transaction, as on a standalone Aurora DB cluster.
The routing layer can't reach the member cluster 1429 (no healthy endpoint), 1105 (delivery failed), or 1053 (member session refused or timed out) Open a new connection, and retry with backoff.
The routing layer killed the connection 1927 Reconnect, and retry the transaction from its first statement.
The connection was lost 2013, 2006, or SQLSTATE 08S01 Reconnect, then retry the whole transaction, which was rolled back. An autocommit write might already be committed, so retry it only if it's safe to apply twice, or check for the row first. For a pinned session, pin again after you reconnect.

When the connection fails during COMMIT, the write might already be committed, so check for the transaction's writes before you run it again. For every error code and its message, see Error codes for database cluster groups for Aurora.

Compose a business operation that spans member clusters from separate transactions with idempotency keys, for example with an outbox or saga pattern, so that a retry doesn't apply it twice.

A failover or restart of a member cluster's writer, including a restart during an upgrade, closes the routed sessions that use that member cluster and rolls back any open transaction on it. Removing a member cluster from the group also closes the routed sessions whose last routed statement went to it. The routing layer returns error 1927 or 1053 on the next statement and then closes the connection. Write retry logic that reconnects after a connection closes with no error, and then retries the transaction from its first statement. Routed sessions that don't use that member cluster stay open.

Checking which member cluster a statement reaches

At the routing endpoint, EXPLAIN of a routable statement runs on the target member cluster. The routing layer builds no plan of its own. It returns the member cluster's plan in its native form and adds its routing decision. The routing decision names the member cluster that it chose and the cluster name behind each router name. The member cluster's plan names objects by their cluster names, not by their router names. Use the routing decision to relate a plan node to your query. The routing details are on by default. Where a tool needs only the native plan, turn them off with dbclustergroup_explain_routing_details. For the grammar, see EXPLAIN.

To check which member cluster a statement reaches
  1. At the routing endpoint, in a session that isn't pinned, read the data mappings for the database or schema that the statement names. This read changes nothing.

  2. At the routing endpoint, explain the statement with the routing key that the application uses. The statement doesn't run.

    EXPLAIN SELECT * FROM app.orders WHERE tenant_id = 42 AND order_id = 7;
  3. In the output of step 2, check that the routing layer's target names one member cluster, the one that the mapping or routing function names. In the member cluster's plan, check that the table is the member table, by its cluster name.

For step 1, read the mappings of one router database name.

SELECT * FROM dbclustergroup_sys.data_mappings WHERE router_db_name = 'ROUTER_DB';

The routing layer's row comes first, and the member cluster's plan follows in its native form. The routing row keeps the native column layout, so a client that reads the output by column position reads well-formed rows. However, a tool that reads a TRADITIONAL plan by row position also reads the routing row. In the member cluster's plan, the table column names the member table by its cluster name. To turn off the routing details, run SET SESSION dbclustergroup_explain_routing_details = OFF.

The routing row has id 0, select_type ROUTER, table router, and NULL in the optimizer columns. Its Extra cell holds the routing details as label value pairs separated by semicolons. Only the TRADITIONAL format carries it.

The Extra cell holds the following fields, in this order. The routing layer leaves out a field that doesn't apply to the statement.

  • Router Timing: the time that the routing layer used for the statement, in milliseconds.

  • Routing Classification: SINGLE_MEMBER_CLUSTER.

  • Routing Function: for a scaleout table, the routing function and its key columns, as function(key_column, ...).

  • Target Member Clusters: the alias of the member cluster that the statement reaches.

  • Alias Mapping: for a table with its own data mapping, the router name and the cluster name, as router_name -> cluster_name.

  • Object Resolution: DATA_MAPPING or SCALEOUT_TABLE.

  • Pushdown Query: the statement that the routing layer sends to the member cluster, on one line.

When a statement names more than one table, Routing Function and Object Resolution show each table's value as table: value, separated by commas. Apart from the Router Timing value, the cell holds at most 4,096 bytes. Over that size, the routing layer cuts Pushdown Query first and then the end of the cell, and the cut text ends in ....

EXPLAIN ANALYZE runs the statement on the member cluster. For a data change statement, it doesn't change any rows, and a single-table UPDATE or DELETE shows no plan. For details, see EXPLAIN. The timing covers the member cluster's execution only. EXPLAIN ANALYZE works on a scaleout table when a routing key predicate resolves the statement to one member cluster. A statement that doesn't resolve fails as the statement would without EXPLAIN.

The following also apply to EXPLAIN:

  • The plan comes from the member cluster's writer, which runs routed statements. To compare plans across a member cluster's instances, run EXPLAIN on each instance endpoint directly.

  • EXPLAIN produces no plan for a statement that spans member clusters, which returns an error instead of a partial plan, or for a query on a table in dbclustergroup_sys. On a scaleout table, it produces a plan only when a routing key predicate resolves the statement to one member cluster.

  • In a pinned session or on a member cluster's own endpoint, EXPLAIN, EXPLAIN ANALYZE, and ANALYZE behave as on a standalone Aurora DB cluster and add no routing details.

  • To check a data movement job before you start it, use EXPLAIN ALTER DBCLUSTERGROUP MOVE COLLOCATION, which is a different statement.

  • To match a client connection with its session on a member cluster, see Tracing a session or statement across the group.