

# 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](databaseclustergroups-scaleout-tables.md).

## Properties of a good routing key
<a name="databaseclustergroups-cr-choosing-a-routing-key"></a>

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 `IN` predicate. 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](databaseclustergroups-ts-uneven-load.md).
+ **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 `DELETE` and the `INSERT` as 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 later `COMMIT` commits the `DELETE` without the `INSERT`. 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](#databaseclustergroups-routing-key-engines) shows.

  The routing layer matches each `ROUTE BY KEY` column 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, declare `BIGINT`. You can't change a routing function in place, so widening an `INT` key later takes an `ALTER TABLE` on every member table, then a new routing function with a `BIGINT` parameter and the same collocations, and then `ALTER SCALEOUT TABLE ... ROUTE BY KEY (...) USING ROUTING FUNCTION {{NEW_FUNCTION}}` on each scaleout table that uses it.
+ **Prefer a single-column key.** Each key column is one more condition that every statement must meet. `MOD`, `PREFIX`, and `COLUMN` take one key column. `HASH` supports a multi-column key. A `HASH` routing 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 in `ROUTE BY KEY`, so list them in the same order in both. The order inside `HASH()` doesn't matter, and `SHOW CREATE SCALEOUT ROUTING FUNCTION` shows 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 `TIMESTAMP` key routes by its UTC instant, so sessions can use different time zones, but the session `time_zone` must be UTC or a fixed offset. For the key settings, see [Engine settings for the routing key](#databaseclustergroups-routing-key-engines).

If the data already splits by database, consider database-level mappings instead, as [Using database-level and table-level mappings](databaseclustergroups-mapping-levels.md) describes.

## Choosing a routing function
<a name="databaseclustergroups-routing-key-functions"></a>

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](databaseclustergroups-sql-routing-functions.md).


| 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](databaseclustergroups-create-scaleout-table.md) describes. For the functions that you can use, see [Routing functions](databaseclustergroups-scaleout-tables.md#databaseclustergroups-routing-function-availability).

`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.

```sql
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](databaseclustergroups-collocation-planning.md).
+ **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 `ALTER` statement. Under `PREFIX` or `COLUMN` with lists, a new prefix or value that no collocation lists is rejected. With ranges, end the last range at `MAXVALUE` so that new keys still route.
+ **Watch for a hot last range.** Under `COLUMN` with 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. Use `HASH` or `MOD` if writes must spread.
+ **Range queries need `COLUMN`.** Only `COLUMN` with ranges routes `BETWEEN`, `<`, and `>`, only on an integer, `DATE`, `DATETIME`, or `TIMESTAMP` key, and only when the whole range falls in one collocation. A range on a `CHAR` or `VARCHAR` key is refused.
+ **Give collocated tables the identical routing function.** Every scaleout table in one collocation uses the same function, named in `ROUTE BY KEY` or inherited with `USING 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](databaseclustergroups-changing-routing-function.md).

## Measuring a candidate key
<a name="databaseclustergroups-routing-key-measuring"></a>

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](#databaseclustergroups-cr-choosing-a-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](databaseclustergroups-ts-uneven-load.md#databaseclustergroups-identify-heat). Run them over a direct connection to an Aurora clone, not to a cluster that serves traffic.

## Engine settings for the routing key
<a name="databaseclustergroups-routing-key-engines"></a>

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.
+ `MOD` accepts integer types. `HASH` accepts integer types, the character types `CHAR`, `VARCHAR`, and `TEXT`, and also `DATE`, `DATETIME`, and `TIMESTAMP` keys. `PREFIX` accepts `CHAR`, `VARCHAR`, and `TEXT`. `COLUMN` accepts integer types, `CHAR`, `VARCHAR`, `DATE`, `DATETIME`, and `TIMESTAMP`, but not `TEXT`.
+ Under a `*_normalized` `HASH` algorithm, 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. Under `PREFIX`, `COLUMN`, and the other `HASH` algorithms, the routing layer compares a string key under the routing key's collation, which `ROUTE BY KEY(... COLLATE ...)` sets and which defaults to `utf8mb4_0900_ai_ci`. Under that default, `'Alpha'` and `'alpha'` go to the same collocation. Under `COLLATE utf8mb4_bin` they can go to different ones.
+ `PREFIX` isn't supported on a key declared with `utf8mb4_ja_0900_as_cs` or `utf8mb4_ja_0900_as_cs_ks`.
+ The routing layer accepts the `utf8mb4` character set family only. Connect every client with a `utf8mb4` character set.
+ The routing layer converts a `TIMESTAMP` key to UTC with the session's `time_zone`, so the same instant routes to the same member cluster from sessions in different time zones. The session `time_zone` must be UTC or a fixed offset, such as `+05:30`. With a named time zone other than `UTC`, or with `SYSTEM`, 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 the `time_zone` routing endpoint parameter, `+00:00` by default. A `DATETIME` key routes as written.
+ Aurora MySQL doesn't accept a `UUID` type for a routing key. Store a UUID key in a character column and route it under `HASH`.
+ 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](databaseclustergroups-scaleout-tables.md#databaseclustergroups-routing-keys-inside-a-scaleout-table).

## Related pages
<a name="databaseclustergroups-routing-key-related"></a>

For related tasks and concepts, see the following pages:
+ [Scaleout tables and routing functions](databaseclustergroups-scaleout-tables.md)
+ [Planning collocations and headroom](databaseclustergroups-collocation-planning.md)
+ [Creating and loading a scaleout table](databaseclustergroups-create-scaleout-table.md)