Choosing a routing key and routing function
A scaleout table in a database cluster group for Aurora needs a routing key that every statement on the table carries, and a routing function that turns the key into a collocation. The key decides both how evenly your data spreads and how many of your statements resolve to one member cluster. Choose both before you create the scaleout table. You can't update a routing key column, and a routing function has no ALTER statement. For how routing keys and routing functions work, see Scaleout tables and routing functions.
Properties of a good routing key
The following table compares good and bad candidates.
| Question | A good candidate | A bad candidate |
|---|---|---|
Do the busiest statements filter on it with = or IN? |
Every statement on the table already does | Some statements omit it |
| How many distinct values? | Many more than the collocations that you plan | A handful, such as a status, a Region, or a plan |
| How are rows and load spread over the values? | No value or narrow range dominates | A few values hold most rows or traffic |
| Does a row's value ever change? | Never | It's edited, such as an owner or an assignee |
| Is it a type that the routing function accepts? | An integer type, a character type (HASH, PREFIX, COLUMN), or a date and time type (HASH, COLUMN) |
Floating point, binary, JSON, or a column that can hold NULL |
When you choose and declare the key, follow these rules:
-
Choose a key that your statements already carry. The routing layer refuses a statement on a scaleout table that lacks its key as an equality or
INpredicate. It doesn't send the statement to every member cluster. -
Watch skew in rows and in load. A key with few distinct values, or with values that cluster, causes data skew, and only a data movement job corrects it. After you load data, compare the CloudWatch metrics of the member clusters, and separate data skew from query skew before you act, as described in Troubleshooting uneven load across member clusters.
-
Treat the key as immutable. The routing layer refuses a statement that changes a routing key column, even when the new value maps to the same member cluster. To change a value, delete the row and insert it again. When the new value can map to a different member cluster, run the
DELETEand theINSERTas two transactions. The routing layer rejects the second statement of a transaction when it targets another member cluster. On Aurora MySQL, that rejection leaves the transaction open, and a laterCOMMITcommits theDELETEwithout theINSERT. Roll back after a rejection, and then run the two statements as two transactions. Your application handles a failure between them. -
Choose a column that the application writes. A routed insert can't supply a generated column, and the routing layer refuses an insert that omits the key. Don't use a generated or auto-increment column as the routing key.
-
Declare one type everywhere. A routing function declares the type of each key parameter in its signature. Choose a type with one stable text representation, because the routing layer reads the key value from the statement text. The accepted types depend on the routing function, as Engine settings for the routing key shows.
The routing layer matches each
ROUTE BY KEYcolumn to the routing function parameter at the same position, and reads the key value with that parameter's type. The column doesn't need the parameter's name. The routing layer doesn't check the type of the key column in the member tables, so declare it with the parameter's type in every member table of every scaleout table that uses the function. For an integer key, declareBIGINT. You can't change a routing function in place, so widening anINTkey later takes anALTER TABLEon every member table, then a new routing function with aBIGINTparameter and the same collocations, and thenALTER SCALEOUT TABLE ... ROUTE BY KEY (...) USING ROUTING FUNCTIONon each scaleout table that uses it.NEW_FUNCTION -
Prefer a single-column key. Each key column is one more condition that every statement must meet.
MOD,PREFIX, andCOLUMNtake one key column.HASHsupports a multi-column key. AHASHrouting function on two key columns declares both columns in its signature. The routing layer hashes them in signature order, matched by position to the columns inROUTE BY KEY, so list them in the same order in both. The order insideHASH()doesn't matter, andSHOW CREATE SCALEOUT ROUTING FUNCTIONshows it in signature order. Every statement must carry every key column. -
Keep collation uniform, and use a fixed time zone offset. The routing layer reads a format-sensitive literal with your session's own settings. A character key needs one collation across member clusters. A
TIMESTAMPkey routes by its UTC instant, so sessions can use different time zones, but the sessiontime_zonemust be UTC or a fixed offset. For the key settings, see Engine settings for the routing key.
If the data already splits by database, consider database-level mappings instead, as Using database-level and table-level mappings describes.
Choosing a routing function
A routing function maps a routing key value to a collocation, not to a named member cluster. A data movement job can then move a collocation to another member cluster without a change to the routing function. You can use the MOD, HASH, PREFIX, and COLUMN functions that Aurora provides. The following table shows how each one places a key and when it fits. For the grammar and the full key type lists, see Routing function statements.
| Function | How it places a key | When it fits |
|---|---|---|
MOD |
The remainder of the routing key, key % n, which keeps the sign of the key, as the engine MOD() function does. A negative key gives a negative remainder, from -(n-1) to 0. Each collocation lists the remainders that it takes with VALUES IN, and it can list more than one, for example C1 VALUES IN (0, 1). List the negative remainders in a collocation if your keys can be negative. |
A high-cardinality integer key, such as IDs for point lookups, or an application that already routes by a key modulo the number of databases. The divisor is fixed for the life of the function. Use a divisor of 1 or more. |
HASH |
A hash of one or more key columns, as an integer from 0 to 9223372036854775807. Each collocation takes one range of that interval with VALUES IN RANGE. The ranges divide hash values, not routing key values. The routing layer computes the hash, and no statement returns the hash or the collocation of a key value. |
An integer or character key, a multi-column key, or a date and time key (DATE, DATETIME, TIMESTAMP) that should spread evenly. |
PREFIX |
The key up to the end of its depth-th segment, cut at a delimiter, for example PREFIX(path, '/', 1). A leading delimiter is kept. Each collocation lists the prefixes that it takes with VALUES IN, or takes one range of prefixes with VALUES IN RANGE. A key whose prefix no collocation covers is rejected. |
A string key with a leading segment that groups rows, such as a tenant or Region path ('/us/acme/42'). All rows that share a prefix stay together. |
COLUMN |
The key value itself. Each collocation lists exact values with VALUES IN, or takes one inclusive range with VALUES IN RANGE. The last range can end at MAXVALUE. |
Ranges or explicit lists that your application already assigns, time-based keys (DATE, DATETIME, TIMESTAMP), or statements that need range predicates on the key. |
No routing function reads a lookup table. A modulo-based, hash-based, prefix-based, or range-based scheme has a counterpart in MOD, HASH, PREFIX, or COLUMN. If your partitioning scheme uses a lookup table or direct placement, use one of the following: connect through session pinning, or map each database or schema to its member cluster with data mappings. You can also remap the keys to a routing function. The rows then belong to different collocations, and data movement doesn't move part of a table's rows, so you load the new member tables yourself, as Creating and loading a scaleout table describes. For the functions that you can use, see Routing functions.
HASH takes an algorithm name and the key columns. The following clause, from a CREATE SCALEOUT ROUTING FUNCTION statement, splits the hash interval into two collocations.
PARTITION BY HASH('cityhash', region, id) IN TARGET COLLOCATION ( C1 VALUES IN RANGE (0, 4611686018427387903), C2 VALUES IN RANGE (4611686018427387904, 9223372036854775807) )
Write the algorithm name in lowercase. The algorithms are cityhash, xxhash, md5, cityhash_normalized, xxhash_normalized, and md5_normalized. The *_normalized algorithms ignore the routing key's collation. They lowercase a string key, remove all whitespace, and remove accents that Unicode can separate from the base letter. They don't turn ß into ss, ø into o, or full-width letters into ASCII letters. Values that the collation compares as equal can then go to different member clusters. The other algorithms hash a string key under its collation, so values that the collation compares as equal get the same hash. Use cityhash, xxhash, or md5 for a string key, unless the key has a binary collation, such as utf8mb4_bin.
When you choose, consider the following:
-
Plan the number of collocations first. The rows of a scaleout table spread across no more member clusters than its routing function has collocations. Create more collocations than you have member clusters now. Two or more collocations can be on one member cluster, and a data movement job later moves one collocation to another member cluster. See Planning collocations and headroom.
-
Expect a heavy key to move with its collocation. Under any routing function, every key that maps to the same collocation stays together, so a heavy key or prefix moves with its collocation.
-
List every value up front. A routing function has no
ALTERstatement. UnderPREFIXorCOLUMNwith lists, a new prefix or value that no collocation lists is rejected. With ranges, end the last range atMAXVALUEso that new keys still route. -
Watch for a hot last range. Under
COLUMNwith ranges, increasing keys such as sequence IDs or the current date all go to the last range, so one member cluster takes every new write. UseHASHorMODif writes must spread. -
Range queries need
COLUMN. OnlyCOLUMNwith ranges routesBETWEEN,<, and>, only on an integer,DATE,DATETIME, orTIMESTAMPkey, and only when the whole range falls in one collocation. A range on aCHARorVARCHARkey is refused. -
Give collocated tables the identical routing function. Every scaleout table in one collocation uses the same function, named in
ROUTE BY KEYor inherited withUSING ROUTING FUNCTION OF. Mismatched functions send rows with the same key value to different member clusters. Give a table that needs a different rule its own collocations.
A routing function has no ALTER statement, and you can't drop a routing function while a scaleout table uses it. To change how a scaleout table routes, see Changing a routing function.
Measuring a candidate key
Before you create a scaleout table, measure each candidate key against the statements that your application sends and the data that it holds.
Check each candidate against the properties in Properties of a good routing key. For the queries that read a key's cardinality, the share of its top values, and the rows in each MOD bucket, see Identifying hot member clusters. Run them over a direct connection to an Aurora clone, not to a cluster that serves traffic.
Engine settings for the routing key
The key types, the character set, and the handling of some values are as follows. The group doesn't align the parameter groups of its member clusters. Through the routing endpoint, the routing layer sets sql_mode, time_zone, and the character set on every member session. Member cluster parameter group values for these settings don't apply to routed sessions. A routed session that doesn't set time_zone uses the time_zone routing endpoint parameter, +00:00 by default. Keep the other parameters that affect how the engine interprets a statement the same on every member cluster.
-
MODaccepts integer types.HASHaccepts integer types, the character typesCHAR,VARCHAR, andTEXT, and alsoDATE,DATETIME, andTIMESTAMPkeys.PREFIXacceptsCHAR,VARCHAR, andTEXT.COLUMNaccepts integer types,CHAR,VARCHAR,DATE,DATETIME, andTIMESTAMP, but notTEXT. -
Under a
*_normalizedHASHalgorithm, the routing layer normalizes a string key before it hashes it. It lowercases the value, removes whitespace, and removes accents that Unicode can separate from the base letter, whatever the key's collation. UnderPREFIX,COLUMN, and the otherHASHalgorithms, the routing layer compares a string key under the routing key's collation, whichROUTE BY KEY(... COLLATE ...)sets and which defaults toutf8mb4_0900_ai_ci. Under that default,'Alpha'and'alpha'go to the same collocation. UnderCOLLATE utf8mb4_binthey can go to different ones. -
PREFIXisn't supported on a key declared withutf8mb4_ja_0900_as_csorutf8mb4_ja_0900_as_cs_ks. -
The routing layer accepts the
utf8mb4character set family only. Connect every client with autf8mb4character set. -
The routing layer converts a
TIMESTAMPkey to UTC with the session'stime_zone, so the same instant routes to the same member cluster from sessions in different time zones. The sessiontime_zonemust be UTC or a fixed offset, such as+05:30. With a named time zone other thanUTC, or withSYSTEM, a statement on the key returns error 1235,Unsupported value for a temporal routing key: '<value>' (the session time_zone is not UTC or a fixed offset). Through the routing endpoint, every session starts with thetime_zonerouting endpoint parameter,+00:00by default. ADATETIMEkey routes as written. -
Aurora MySQL doesn't accept a
UUIDtype for a routing key. Store a UUID key in a character column and route it underHASH. -
The routing layer computes a key value from a literal and from a short list of functions over literals. For the list, see Routing keys in statements.
Related pages
For related tasks and concepts, see the following pages: