

# Buiding a Amazon GameLift Servers FlexMatch matchmaker
Building a FlexMatch matchmaker

This section describes the key elements of a matchmaker and how to create and customize one for your game. This includes setting up a matchmaking configuration and a matchmaking rule set.

Creating your matchmaker is the first step in the FlexMatch roadmaps:
+ [Roadmap: Add matchmaking to a Amazon GameLift Servers hosting solution](match-tasks.md)
+ [Roadmap: Create a standalone matchmaking solution with FlexMatch](match-tasks-safm.md)

A FlexMatch matchmaker does the work of building a game match. It manages the pool of matchmaking requests received, processes and selects players to find the best possible player groups, and forms teams for a match. For games that use Amazon GameLift Servers for hosting, it also places and starts a game session for the match. 

FlexMatch pairs the matchmaking service with a customizable rules engine. This lets you design how to match players together based on player attributes and game modes that make sense for your game, and rely on FlexMatch to manage the nuts and bolts of forming player groups and placing them into games. See more details about custom matchmaking in [FlexMatch rule set examples](match-examples.md).

After forming a match, FlexMatch provides the match data for game session placement. For games that use Amazon GameLift Servers for hosting, FlexMatch sends a game session placement request with matched players to a game session queue. The queue searches for available hosting resources on your Amazon GameLift Servers fleets and starts a new game session for the match. For games that use another hosting solution, FlexMatch provides the match data for you to provide to your own game session placement component.

For a detailed description of how a FlexMatch matchmaker processes the matchmaking requests it receives, see [FlexMatch matchmaking process](gamelift-match-howitworks.md).

**Topics**
+ [

# Design a FlexMatch matchmaker
](match-configuration.md)
+ [

# Build a FlexMatch rule set
](match-rulesets.md)
+ [

# Create a matchmaking configuration
](match-create-configuration.md)
+ [

# Set up FlexMatch event notifications
](match-notification.md)

# Design a FlexMatch matchmaker
Design a matchmaker

This topic provides guidance on how to design a matchmaker that fits your game. 

**Topics**
+ [

## Configure a basic matchmaker
](#match-configuration-elements)
+ [

# Choose a location for the matchmaker
](match-configuration-regions.md)
+ [

# Add optional elements
](match-configuration-options.md)

## Configure a basic matchmaker


At a minimum, a matchmaker needs the following elements:
+ The **rule set **determines the size and scope of teams for a match and defines a set of rules to use when evaluating players for a match. Each matchmaker is configured to use one rule set. See [Build a FlexMatch rule set](match-rulesets.md) and [FlexMatch rule set examples](match-examples.md).
+ The **notification target** receives all matchmaking event notifications. You need to set up an Amazon Simple Notification Service (SNS) topic and then add the topic ID to the matchmaker. See more information on setting up notifications at [Set up FlexMatch event notifications](match-notification.md).
+ The **request timeout **determines how long matchmaking requests can remain in the request pool and be evaluated for potential matches. Once a request has timed out, it has failed to make a match and is removed from the pool. 
+ When using FlexMatch with Amazon GameLift Servers managed hosting, the **game session queue** finds the best available resources to host a game session for the match, and starts a new game session. Each queue is configured with a list of locations and resource types (including Spot or On-Demand Instances) that determine where game sessions can be placed. For more information on queues, see [ Using multi-location queues](https://docs.aws.amazon.com/gamelift/latest/developerguide/queues-intro.html).

# Choose a location for the matchmaker


Decide where you want matchmaking activity to take place and create your matchmaking configuration and rule set in that location. Amazon GameLift Servers maintains ticket pools for your game's match requests where they are sorted and evaluated for viable matches. After making a match, Amazon GameLift Servers sends the match details for game session placement. You can run the matched game sessions in any location that's supported by your hosting solution.

See [FlexMatch supported AWS Regions](match-regions.md) for the locations where you can create FlexMatch resources.

When choosing an AWS Region for your matchmaker, consider how location might impact performance and how it can optimize the match experience for players. We recommend the following best practices: 
+ Place a matchmaker in an location that is close to your players and your client service that sends FlexMatch matchmaking requests. This approach decreases the latency effect on your matchmaking request workflow and makes it more efficient. 
+ If your game reaches a global audience, consider creating matchmakers in multiple locations and routing match requests to the matchmaker that is closest to the player. In addition to boosting efficiency, this causes ticket pools to form with players who are geographically near each other, which improves the matchmaker's ability to match players based on latency requirements.
+ When using FlexMatch with Amazon GameLift Servers managed hosting, place your matchmaker and the game session queue that it uses in the same location. This helps to minimize communication latency between the matchmaker and queue.

# Add optional elements


In addition to these minimum requirements, you can configure your matchmaker with the following additional options. If you are using FlexMatch with an Amazon GameLift Servers hosting solution, many features are built in. If you're using FlexMatch as a standalone matchmaking service, you might want to build these features into your system.

**Player Acceptance**  
You can configure a matchmaker to require that all players who are selected for a match must accept participation. If your system requires acceptance, all players must be given the option to accept or reject a proposed match. A match must receive acceptances from all players in the proposed match before it can be completed. If any player rejects or fails to accept a match, the proposed match is discarded and the tickets are handled as follows. Tickets where all players in the ticket accepted the match are returned to the matchmaking pool for continued processing. Tickets where at least one player rejected the match or failed to respond are put into a failure status and are no longer processed. Player acceptance requires a time limit; all players must accept a proposed match within the time limit for the match to continue.

**Backfill Mode**  
Use FlexMatch backfill to keep your game sessions filled with well-matched new players throughout the life span of the game session. When handling backfill requests, FlexMatch uses the same matchmaker as was used to match the original players. You can customize how backfill tickets are prioritized with tickets for new matches, putting backfill tickets to either the front or end of the line. This means that, as new players enter the matchmaking pool, they are more or less likely to be placed in an existing game than in a newly formed game.

Manual backfill is available whether your game uses FlexMatch with managed Amazon GameLift Servers hosting or with other hosting solutions. Manual backfill gives you the flexibility to decide when to trigger a backfill request. For example, you may want to add new players only during certain phases of your game or only when certain conditions exist.

Automatic backfill is available only for games that use managed Amazon GameLift Servers hosting. With this feature enabled, if a game session starts with open player slots, Amazon GameLift Servers begins automatically generating backfill requests for it. This feature allows you to set up matchmaking so that new games are started with a minimum number of players and then quickly filled as new players enter the matchmaking pool. You can turn off automatic backfill at any time during the game session life span.

**Game Properties**  
For games that use FlexMatch with Amazon GameLift Servers managed hosting, you can provide additional information to be passed to a game server whenever a new game session is requested. This can be a useful way to pass game mode configurations that are needed to start a game session for the type of matches being created. All game sessions for matches that are created by a matchmaker receive the same set of game properties. You can vary game property information by creating different matchmaking configurations.

**Reserved Player Slots**  
You can designate that certain player slots in each match be reserved and filled at a later time. This is done by configuring the "additional player count" property of a matchmaking configuration. 

**Custom Event Data**  
Use this property to include a set of custom information in all matchmaking-related events for the matchmaker. This feature can be useful for tracking certain activity unique to your game, including tracking performance of your matchmakers. 

# Build a FlexMatch rule set
Build a rule set

Every FlexMatch matchmaker must have a rule set. The rule set determines the two key elements of a match: your game's team structure and size, and how to group players together for the best possible match. 

For example, a rule set might describe a match like this: Create a match with two teams of five players each, one team is the defenders and the other team the invaders. A team can have novice and experienced players, but the average skill of the two teams must be within 10 points of each other. If no match is made after 30 seconds, gradually relax the skill requirements.

The topics in this section describe how design and build a matchmaking rule set. When creating a rule set, you can use either the Amazon GameLift Servers console or the AWS CLI.

**Topics**
+ [

# Design a FlexMatch rule set
](match-design-ruleset.md)
+ [

# Design a FlexMatch large-match rule set
](match-design-rulesets-large.md)
+ [

# Tutorial: Create a matchmaking rule set
](match-create-ruleset.md)
+ [

# FlexMatch rule set examples
](match-examples.md)

# Design a FlexMatch rule set
Design a rule set

This topic covers the basic structure of a rule set and how to build a rule set for small matches up to 40 players. A matchmaking rule set does two things: lay out a match's team structure and size and tell the matchmaker how to choose players to form the best possible match. 

But your matchmaking rule set can do more. For example, you can:
+ Optimize the matchmaking algorithm for your game.
+ Set up minimum player latency requirements to protect the quality of gameplay.
+ Gradually relax team requirements and match rules over time so all active players can find an acceptable match when they want one.
+ Define handling for group matchmaking requests using party aggregation.
+ Process large matches of 40 or more players. For more information about building large matches, see [Design a FlexMatch large-match rule set](match-design-rulesets-large.md).

When building a matchmaking rule set, consider the following optional and required tasks: 
+ [Describe the rule set (required)](match-rulesets-components-set.md)
+ [Customize the match algorithm](match-rulesets-components-algorithm.md)
+ [Declare player attributes](match-rulesets-components-attributes.md)
+ [Define match teams](match-rulesets-components-teams.md)
+ [Set rules for player matching](match-rulesets-components-rules.md)
+ [Allow requirements to relax over time](match-rulesets-components-expansion.md)

You can build your rule set using the Amazon GameLift Servers console or the `[CreateMatchmakingRuleSet](https://docs.aws.amazon.com/gameliftservers/latest/apireference/API_CreateMatchmakingRuleSet.html)` operation.

# Describe the rule set (required)


Provide details for the rule set.
+ *name* (optional) – A descriptive label for your own use. This value isn't associated with the rule set name that you specify when creating the rule set with Amazon GameLift Servers.
+ *ruleLanguageVersion* – The version of the property expression language used to create FlexMatch rules. The value must be `1.0`.

# Customize the match algorithm


FlexMatch optimizes the default algorithm for most games to get players into acceptable matches with minimal wait time. You can customize the algorithm and adjust matchmaking for your game.

The following is the default FlexMatch matchmaking algorithm: 

1. FlexMatch places all open matchmaking tickets and backfill tickets in a ticket pool.

1. FlexMatch randomly groups tickets in the pool into one or more batches. As the ticket pool gets larger, FlexMatch forms additional batches to maintain optimal batch size.

1. FlexMatch sorts the tickets by age, within each batch.

1. FlexMatch builds a match based on the oldest ticket of each batch. 

To customize the match algorithm, add an `algorithm` component to your rule set schema. See [FlexMatch rule set schema](match-ruleset-schema.md) for the complete reference information. 

Use the following optional customizations to impact different stages of your matchmaking process. 
+ [Add pre-batch sorting](#match-rulesets-components-algorithm-presort)
+ [Form batches based on batchDistance attributes](https://docs.aws.amazon.com//gameliftservers/latest/flexmatchguide/match-rules-reference-ruletype.html#match-rules-reference-ruletype-batchdistance)
+ [Prioritize backfill tickets](#match-rulesets-components-algorithm-backfill)
+ [Favor older tickets with expansions](#match-rulesets-components-algorithm-expansion)

## Add pre-batch sorting


You can sort the ticket pool before forming batches. This type of customization is most effective with games with large tickets pools. Pre-batch sorting can help speed up the matchmaking process and increase player uniformity in defined characteristics.

Define Pre-batch sorting methods using the algorithm property `batchingPreference`. The default setting is `random`.

Options for customizing pre-batch sorting include:
+ **Sort by player attributes.** Provide a list of player attributes to pre-sort the ticket pool. 

  To sort by player attributes, set `batchingPreference` to `sorted`, and define your list of player attributes in `sortByAttributes`. To use an attribute, first declare the attribute in the `playerAttributes` component of the rule set. 

  In the following example, FlexMatch sorts the ticket pool based on players' preferred game map and then by player skill. The resulting batches are more likely to contain similarly skilled players who want to use the same map.

  ```
  "algorithm": {
      "batchingPreference": "sorted",
      "sortByAttributes": ["map", "player_skill"],
      "strategy": "exhaustiveSearch"
  },
  ```
+ **Sort by latency.** Create matches with the lowest available latency or quickly create matches with acceptable latency. This customization is useful for rule sets forming large matches of more than 40 players. 

  Set the algorithm property `strategy` to `balanced`. The balanced strategy limits the available types of rule statements. For more information, see [Design a FlexMatch large-match rule set](match-design-rulesets-large.md). 

  FlexMatch sorts tickets based on players' reported latency data in one of the following ways: 
  + *Lowest latency locations.* The ticket pool is pre-sorted by the locations where players report their lowest latency values. FlexMatch then batches tickets with low latency in the same locations, creating a better game play experience. It also reduces the number of tickets in each batch, so matchmaking can take longer. To use this customization, set `batchingPreference` to `fastestRegion`, as shown in the following example.

    ```
    "algorithm": {
        "batchingPreference": "fastestRegion",
        "strategy": "balanced"
    },
    ```
  + *Acceptable latency matches quickly.* The ticket pool is pre-sorted by locations where players report acceptable latency value. This forms fewer batches containing more tickets. With more tickets in each batch, finding acceptable matches is faster. To use this customization, set the property `batchingPreference` to` largestPopulation`, as shown in the following example.

    ```
    "algorithm": {
        "batchingPreference": "largestPopulation",
        "strategy": "balanced"
    },
    ```
**Note**  
The default value for the balanced strategy is `largestPopulation`.

## Prioritize backfill tickets


If your game implements auto-backfill or manual backfill, you can customize how FlexMatch processes matchmaking tickets based on request type. The request type can be a new match or backfill request. By default, FlexMatch treats both types of requests the same.

Backfill prioritization impacts how FlexMatch handles tickets after it batches them. Backfill prioritization requires rule sets to use the exhaustive search strategy. 

FlexMatch doesn't match multiple backfill tickets together.

To change prioritization for backfill tickets, set the property `backfillPriority`.
+ **Match backfill tickets first.** This option tries to match backfill tickets before creating new matches. This means that incoming players have a higher chance of joining an existing game. 

  It's best to use this if your game uses auto-backfill. Auto-backfill is often used in games with short game sessions and high player turnaround. Auto-backfill helps these games form minimum viable matches and get them started while FlexMatch searches for more players to fill open slots.

  Set the `backfillPriority` to `high`.

  ```
  "algorithm": {
      "backfillPriority": "high",
      "strategy": "exhaustiveSearch"
  },
  ```
+ **Match backfill tickets last.** This option ignores backfill tickets until it evaluates all other tickets. This means that FlexMatch backfills incoming players into existing games when it can't match them into new games. 

  This option is useful when you want to use backfill as a last-chance option to get players into a game, such as when there aren't enough players to form a new match. 

  Set `backfillPriority` to `low`. 

  ```
  "algorithm": {
      "backfillPriority": "low",
      "strategy": "exhaustiveSearch"
  },
  ```

## Favor older tickets with expansions


Expansion rules relax match criteria when matches are difficult to complete. Amazon GameLift Servers applies expansion rules when tickets in a partially completed match reach a certain age. The creation timestamps of the tickets determine when Amazon GameLift Servers applies the rules; by default, FlexMatch tracks the timestamp of the most recently matched ticket. 

To change when FlexMatch applies expansion rules, set the property `expansionAgeSelection` as follows: 
+ **Expand based on newest tickets.** This option applies expansion rules based on the newest ticket added to the potential match. Each time FlexMatch matches a new ticket, the time clock is reset. With this option, resulting matches tend to be higher quality but take longer to match; match requests might time out before completing if they take too long to match. Set `expansionAgeSelection` to `newest`. `newest` is default.
+ **Expand based on oldest tickets.** This option applies expansion rules based on the oldest ticket in the potential match. With this option, FlexMatch applies expansions faster, which improves wait times for the earliest matched players, but lowers the match quality for all players. Set `expansionAgeSelection` to `oldest`. 

```
"algorithm": {
    "expansionAgeSelection": "oldest",
    "strategy": "exhaustiveSearch"
},
```

# Declare player attributes


In this section, list individual player attributes to include in matchmaking requests. There are two reasons you might declare player attributes in a rule set: 
+ When the rule set contains rules that rely on player attributes.
+ When you want to pass a player attribute to the game session through the match request. For example, you might want to pass player character choices to the game session before each player connects. 

When declaring a player attribute, include the following information: 
+ *name* (required) – This value must be unique to the rule set.
+ *type* (required) – The data type of the attribute value. Valid data types are number, string, string list, or string map.
+ *default* (optional) – Enter a default value to use if a matchmaking request doesn't provide an attribute value. If no default is declared and a request doesn't include a value, FlexMatch can't fulfill the request.

# Define match teams


Describe the structure and size of the teams for a match. Each match must have at least one team, and you can define as many teams as you want. Your teams can have the same number of players or be asymmetric. For example, you might define a single-player monster team and a hunters team with 10 players.

FlexMatch processes match requests as either small match or large match, based on how the rule set defines team sizes. Potential matches of up to 40 players are small matches, matches with more than 40 players are large matches. To determine a rule set's potential match size, add up the *maxPlayer* settings for all teams defined in the rule set. 
+ *name* (required) – Assign each team a unique name. You use this name in rules and expansions, and FlexMatch references for the matchmaking data in a game session.
+ *maxPlayers* (required) – Specify the maximum number of players to assign to the team.
+ *minPlayers* (required) – Specify the minimum number of players to assign to the team. 
+ *quantity* (optional) – Specify the number of team to make with this definition. When FlexMatch creates a match, it gives these teams the provided name with an appended number. For example `Red-Team1`, `Red-Team2`, and `Red-Team3`. 

FlexMatch attempts to fill teams to the maximum player size but does create teams with fewer players. If you want all teams in the match to be equally sized, you can create a rule for that. See the [FlexMatch rule set examples](match-examples.md) topic for an example of an `EqualTeamSizes` rule.

# Set rules for player matching


Create a set of rule statements that evaluate players for acceptance in to a match. Rules might set requirements that apply to individual players, teams, or an entire match. When Amazon GameLift Servers processes a match request, it starts with the oldest player in the pool of available players and builds a match around that player. For detailed help on creating FlexMatch rules, see [FlexMatch rule types](match-rules-reference-ruletype.md).
+ *name* (required) – A meaningful name that uniquely identifies the rule within a rule set. Rule names are also referenced in event logs and metrics that track activity related to this rule. 
+ *description* (optional) – Use this element to attach a free-form text description.
+ *type* (required) – The type element identifies the operation to use when processing the rule. Each rule type requires a set of additional properties. See a list of valid rule types and properties in [FlexMatch rules language](match-rules-reference.md). 
+ Rule type property (may be required) – Depending on the type of rule defined, you may need to set certain rule properties. Learn more about properties and how to use the FlexMatch property expression language in [FlexMatch rules language](match-rules-reference.md).

# Allow requirements to relax over time


Expansions allow you to relax rule criteria over time when FlexMatch can't find a match. This feature ensures that FlexMatch makes a best available when it can't make a perfect match. By relaxing your rules with an expansion, you gradually expand the pool of players that are an acceptable match. 

Expansions start when the age of the newest ticket in the incomplete match matches an expansion wait time. When FlexMatch adds a new ticket to the match, the expansion wait time clock may be reset. You can customize how expansions start in the `algorithm` section of the rule set.

Here's an example of an expansion that gradually increases the minimum skill level required for the match. The rule set uses a distance rule statement, named *SkillDelta* to require that all players in a match be within 5 skill levels of each other. If no new matches are made for fifteen seconds, this expansion looks for a skill level difference of 10, and then ten seconds later looks for a difference of 20.

```
"expansions": [{
        "target": "rules[SkillDelta].maxDistance",
        "steps": [{
            "waitTimeSeconds": 15,
            "value": 10
        }, {
            "waitTimeSeconds": 25,
            "value": 20
        }]
    }]
```

With matchmakers that have automatic backfill enabled, don't relax your player count requirements too quickly. It takes a few seconds for the new game session to start up and begin automatic backfill. A better approach is to start your expansion after automatic backfill tends to kicks in for your games. Expansion timing varies depending on your team composition, so do testing to find the best expansion strategy for your game.

# Design a FlexMatch large-match rule set
Design a large-match rule set

If your rule set creates matches that allow 41 to 200 players, you need to make some adjustments to your rule set configuration. These adjustments optimize the match algorithm so that it can build viable large matches while also keeping player wait times short. As a result, large match rule sets replace time-consuming custom rules with standard solutions that are optimized for common matchmaking priorities. 

Here's how to determine if you need to optimize your rule set for large matches:

1. For each team defined in your rule set, get the value of *maxPlayer*,

1. Add up all the *maxPlayer* values. If the total exceeds 40, you've got a large match rule set. 

To optimize your rule set for large matches, make the adjustments described as follows. See the schema for a large match rule set in [Rule set schema for large matches](match-ruleset-schema-large.md) and rule set examples in [Example: Create a large match](match-examples-7.md).

# Customize match algorithm for large matches


Add an algorithm component to the rule set, if one doesn't already exist. Set the following properties. 
+ `strategy` (required) – Set the `strategy` property to “balanced”. This setting triggers FlexMatch to do additional post-match checks to find the optimal team balance based on a specified player attribute, which is defined in the `balancedAttribute` property. The balanced strategy replaces the need for custom rules to build evenly matched teams.
+ `balancedAttribute` (required) – Identify a player attribute to use when balancing the teams in a match. This attribute must have a numerical data type (double or integer). For example, if you choose to balance on player skill, FlexMatch tries to assign players so that all teams have aggregate skill levels that are as evenly matched as possible. The balancing attribute must be declared in the rule set's player attributes. 
+ `batchingPreference` (optional) – Choose how much emphasis you want to put on forming the lowest latency matches possible for your players. This setting affects how match tickets are sorted prior to building matches. Options include: 
  + Largest population. FlexMatch allows matches using all tickets in the pool that have acceptable latency values in at least one location in common. As a result, the potential ticket pool tends to be large, which makes it easier to fill matches more quickly. Players might be placed in games with acceptable, but not always optimal, latency. If the `batchingPreference` property isn't set, this is the default behavior when `strategy` is set to "balanced".
  + Fastest location. FlexMatch pre-sorts all tickets in the pool based on where they report the lowest latency values. As a result, matches tend to be formed with players that report low latency in the same locations. At the same time, the potential ticket pool for each match is smaller, which can increase the time needed to fill a match. In addition, because a higher priority is placed on latency, players in matches may vary more widely with regard to the balancing attribute.

The following example configures the match algorithm to behave as follows: (1) Pre-sort the ticket pool to group tickets by location where they have acceptable latency values; (2) Form batches of sorted tickets for matching; (3) Create matches with tickets in a batch and balance the teams to even out the average player skill.

```
"algorithm": {
    "strategy": "balanced",
    "balancedAttribute": "player_skill",
    "batchingPreference": "largestPopulation"
},
```

# Declare player attributes


Make sure that you declare the player attribute that is used as a balancing attribute in the rule set algorithm. This attribute should be included for each player in a matchmaking request. You can provide a default value for the player attribute, but attribute balancing works best when player-specific values are provided.

# Define teams


The process of defining team size and structure is the same as with small matches, but the way FlexMatch fills the teams is different. This affects how matches are likely to look like when only partially filled. You may want to adjust your minimum team sizes in response.

FlexMatch uses the following rules when assigning a player to a team. First: look for teams that haven't yet reached their minimum player requirement. Second: of those teams, find the one with the most open slots. 

For matches that define multiple equally sized teams, players are added sequentially to each team until full. As a result, teams in a match always have a nearly equal number of players, even when the match is not full. There is currently no way to force equally sized teams in large matches. For matches with asymmetrically sized teams, the process is a bit more complex. In this scenario, players are initially assigned to the largest teams that have the most open slots. As the number of open slots become more evenly distributed across all teams, players are slotted into the smaller teams.

For example, let's say you have a rule set with three teams. The Red and Blue teams are both set to `maxPlayers`=10, `minPlayers`=5. The Green team is set to `maxPlayers`=3, `minPlayers`=2. Here's the fill sequence: 

1. No team has reached `minPlayers`. Red and Blue teams have 10 open slots, while Green has 3. The first 10 players are assigned (5 each) to the Red and Blue teams. Both teams have now reached `minPlayers`.

1. Green team has not yet reached `minPlayers`. The next 2 players are assigned to the Green team. The Green team has now reached `minPlayers`.

1. With all teams at `minPlayers`, additional players are now assigned based on the number of open slots. The Red and Blue teams each have 5 open slots, while the Green team has 1. The next 8 players are assigned (4 each) to the Red and Blue teams. All teams now have 1 open slot.

1. The remaining 3 player slots are assigned (1 each) to teams in no particular order.

# Set rules for large matches


Matchmaking for large matches relies primarily on the balancing strategy and latency batching optimizations. Most custom rules are not available. However, you can incorporate the following types of rules: 
+ Rule that sets a hard limit on player latency. Use the `latency` rule type with the property `maxLatency`. See [Latency rule](match-rules-reference-ruletype.md#match-rules-reference-ruletype-latency) reference. Here's an example that sets maximum player latency to 200 milliseconds:

  ```
  "rules": [{
          "name": "player-latency",
          "type": "latency",
          "maxLatency": 200
      }],
  ```
+ Rule to batch players based on closeness in a specified player attribute. This is different than defining a balancing attribute as part of the large-match algorithm, which focuses on building evenly matched teams. This rule batches matchmaking tickets based on similarity in the specified attribute values, such as beginner or expert skill, which tends to lead to matches players who are closely aligned on the specified attribute. Use the `batchDistance` rule type, identify a numerically-based attribute, and specify the widest range to allow. See [Batch distance rule](match-rules-reference-ruletype.md#match-rules-reference-ruletype-batchdistance) reference. Here's an example that calls for a match's players to be within one skill level of each other:

  ```
  "rules": [{
          "name": "batch-skill",
          "type": "batchDistance",
          "batchAttribute": "skill",
          "maxDistance": 1
  ```

# Relax large match requirements


As with small matches, you can use expansions to relax match requirements over time when no valid matches are possible. With large matches, you have the option to relax either the latency rules or the team player counts. 

If you're using automatic match backfill for large matches, avoid relaxing your team player counts too quickly. FlexMatch starts generating backfill requests only after a game session starts, which may not happen for several seconds after a match is created. During that time, FlexMatch can create multiple partially filled new game sessions, especially when the player count rules are lowered. As a result, you end up with more game sessions than you need and players spread too thinly across them. Best practice is to give the first step in your player count expansion a longer wait time, long enough for your game session to start. Since backfill requests are given higher priority with large matches, incoming players will be slotted into existing games before new game are started. You may need to experiment to find the ideal wait time for your game.

Here's an example that gradually lowers the Yellow team's player count, with a longer initial wait time. Keep in mind that wait times in rule set expansions are absolute, not compounded. So the first expansion occurs at five seconds, and the second expansion occurs five seconds later, at ten seconds.

```
"expansions": [{
        "target": "teams[Yellow].minPlayers",
        "steps": [{
            "waitTimeSeconds": 5,
            "value": 8
        }, {
            "waitTimeSeconds": 10,
            "value": 5
        }]
    }]
```

# Tutorial: Create a matchmaking rule set
Tutorial: Create a rule set

Before you create a matchmaking rule set for your Amazon GameLift Servers FlexMatch matchmaker, we recommend checking the [rule set syntax](match-rules-reference.md). After you create a rule set using the Amazon GameLift Servers console or the AWS Command Line Interface (AWS CLI), you can't change it.

Note that there is a [service quota](https://console.aws.amazon.com/servicequotas/home/services/gamelift/quotas/) for the maximum number of rule sets that you can have in an AWS Region, so it's a good idea to delete unused rule sets.

**Topics**

------
#### [ Console ]

**Create a rule set**

1. Open the Amazon GameLift Servers console at [https://console.aws.amazon.com/gamelift/](https://console.aws.amazon.com/gamelift/).

1. Switch to the AWS Region where you want to create your rule set. Define rule sets in the same Region as the matchmaking configuration that uses them.

1. In the navigation pane, choose **FlexMatch**, **Matchmaking rule sets**.

1. On the **Matchmaking rule sets** page, choose **Create rule set**.

1. On the **Create matchmaking rule set** page, do the following:

   1. Under **Rule set settings**, for **Name**, enter a unique descriptive name that you can use to identify it in a list or in events and metrics tables.

   1. For **Rule set**, enter your rule set in JSON. For information about designing a rule set, see [Design a FlexMatch rule set](match-design-ruleset.md). You can also use one of the example rule sets from [FlexMatch rule set examples](match-examples.md).

   1. Choose **Validate** to verify that the syntax of your rule set is correct. You can't edit rule sets after they're created, so it's a good idea to validate them first.

   1. (Optional) Under **Tags**, add tags to help you manage and track your AWS resources.

1. Choose **Create**. If creation is successful, you can use the rule set with a matchmaker.

------
#### [ AWS CLI ]

**Create a rule set**

Open a command line window and use the command [create-matchmaking-rule-set](https://docs.aws.amazon.com/cli/latest/reference/gamelift/create-matchmaking-rule-set.html).

This example command creates a simple matchmaking rule set that sets up a single team. Be sure to create the rule set in the same AWS Region as the matchmaking configurations that uses it.

```
aws gamelift create-matchmaking-rule-set \
    --name "SampleRuleSet123" \
    --rule-set-body '{"name": "aliens_vs_cowboys", "ruleLanguageVersion": "1.0", "teams": [{"name": "cowboys", "maxPlayers": 8, "minPlayers":  4}]}'
```

If the creation request is successful, Amazon GameLift Servers returns a [MatchmakingRuleSet](https://docs.aws.amazon.com/gameliftservers/latest/apireference/API_MatchmakingRuleSet.html) object that includes the settings that you specified. A matchmaker can now use the new rule set.

------<a name="match-delete-ruleset"></a><a name="match-delete-ruleset-cli"></a>

------
#### [ Console ]

**Delete a rule set**

1. Open the Amazon GameLift Servers console at [https://console.aws.amazon.com/gamelift/](https://console.aws.amazon.com/gamelift/).

1. Switch to the Region that you created the rule set in.

1. In the navigation pane, choose **FlexMatch**, **Matchmaking rule sets**.

1. On the **Matchmaking rule sets** page, select the rule set that you want to delete, and then choose **Delete**.

1. In the **Delete rule set** dialog box, choose **Delete** to confirm deletion.
**Note**  
If a matchmaking configuration is using the rule set, Amazon GameLift Servers displays an error message (**Can't delete rule set**). If this occurs, change the matchmaking configuration to use a different rule set, then try again. To find out which matchmaking configurations are using a rule set, choose the name of a rule set to view its details page.

------
#### [ AWS CLI ]

**Delete a rule set**

Open a command line window and use the command [delete-matchmaking-rule-set](https://docs.aws.amazon.com/cli/latest/reference/gamelift/delete-matchmaking-rule-set.html) to delete a matchmaking rule set.

If a matchmaking configuration is using the rule set, Amazon GameLift Servers returns an error message. If this occurs, change the matchmaking configuration to use a different rule set, then try again. To get a list of which matchmaking configurations are using a rule set, use the command [describe-matchmaking-configurations](https://docs.aws.amazon.com/cli/latest/reference/gamelift/describe-matchmaking-configurations.html) and specify the rule set name.

This example command checks for the matchmaking rule set's usage and then deletes the rule set.

```
aws gamelift describe-matchmaking-rule-sets \
    --rule-set-name "SampleRuleSet123" \
    --limit 10

aws gamelift delete-matchmaking-rule-set \
    --name  "SampleRuleSet123"
```

------

# FlexMatch rule set examples
Rule set examples

FlexMatch rule sets can cover a variety of matchmaking scenarios. The following examples conform to the FlexMatch configuration structure and property expression language. Copy these rule sets in their entirety or choose components as needed.

For more information on using FlexMatch rules and rule sets, see the following topics:

**Note**  
When evaluating a matchmaking ticket that includes multiple players, all players in the request must meet the match requirements.

**Topics**
+ [

# Example: Create two teams with evenly matched players
](match-examples-1.md)
+ [

# Example: Create uneven teams (Hunters vs Monster)
](match-examples-2.md)
+ [

# Example: Set team-level requirements and latency limits
](match-examples-3.md)
+ [

# Example: Use explicit sorting to find best matches
](match-examples-4.md)
+ [

# Example: Find intersections across multiple player attributes
](match-examples-5.md)
+ [

# Example: Compare attributes across all players
](match-examples-6.md)
+ [

# Example: Create a large match
](match-examples-7.md)
+ [

# Example: Create a multi-team large match
](match-examples-8.md)
+ [

# Example: Create a large match with players with similar attributes
](match-examples-9.md)
+ [

# Example: Use a compound rule to create a match with players with similar attributes or similar selections
](match-examples-10.md)
+ [

# Example: Create a rule that uses a player's block list
](match-examples-11.md)

# Example: Create two teams with evenly matched players


This example illustrates how to set up two equally matched teams of players with the following instructions. 
+ Create two teams of players.
  + Include between four and eight players in each team.
  + Final teams must have the same number of players.
+ Include a player’s skill level (if not provided, default to 10).
+ Choose players based on whether their skill level is similar to other players. Ensure that both teams have an average player skill within 10 points of each other.
+ If the match is not filled quickly, relax the player skill requirement to complete a match in reasonable time. 
  + After 5 seconds, expand the search to allow teams with average player skills within 50 points. 
  + After 15 seconds, expand the search to allow teams with average player skills within 100 points. 

Notes on using this rule set: 
+ This example allows for teams to be any size between four and eight players (although they must be the same size). For teams with a range of valid sizes, the matchmaker makes a best-effort attempt to match the maximum number of allowed players.
+ The `FairTeamSkill` rule ensures that teams are evenly matched based on player skill. To evaluate this rule for each new prospective player, FlexMatch tentatively adds the player to a team and calculates the averages. If rule fails, the prospective player is not added to the match.
+ Since both teams have identical structures, you could opt to create just one team definition and set the team quantity to "2". In this scenario, if you named the team "aliens", then your teams would be assigned the names "aliens\$11" and "aliens\$12".

```
{
    "name": "aliens_vs_cowboys",
    "ruleLanguageVersion": "1.0",
    "playerAttributes": [{
        "name": "skill",
        "type": "number",
        "default": 10
    }],
    "teams": [{
        "name": "cowboys",
        "maxPlayers": 8,
        "minPlayers": 4
    }, {
        "name": "aliens",
        "maxPlayers": 8,
        "minPlayers": 4
    }],
    "rules": [{
        "name": "FairTeamSkill",
        "description": "The average skill of players in each team is within 10 points from the average skill of all players in the match",
        "type": "distance",
        // get skill values for players in each team and average separately to produce list of two numbers
        "measurements": [ "avg(teams[*].players.attributes[skill])" ],
        // get skill values for players in each team, flatten into a single list, and average to produce an overall average
        "referenceValue": "avg(flatten(teams[*].players.attributes[skill]))",
        "maxDistance": 10 // minDistance would achieve the opposite result
    }, {
        "name": "EqualTeamSizes",
        "description": "Only launch a game when the number of players in each team matches, e.g. 4v4, 5v5, 6v6, 7v7, 8v8",
        "type": "comparison",
        "measurements": [ "count(teams[cowboys].players)" ],
        "referenceValue": "count(teams[aliens].players)",
        "operation": "=" // other operations: !=, <, <=, >, >=
    }],
    "expansions": [{
        "target": "rules[FairTeamSkill].maxDistance",
        "steps": [{
            "waitTimeSeconds": 5,
            "value": 50
        }, {
            "waitTimeSeconds": 15,
            "value": 100
        }]
    }]
}
```

# Example: Create uneven teams (Hunters vs Monster)


This example describes a game mode in which a group of players hunt a single monster. People choose either a hunter or a monster role. Hunters specify the minimum skill level for the monster that they want to face. The minimum size of the hunter team can be relaxed over time to complete the match. This scenario sets out the following instructions: 
+ Create one team of exactly five hunters. 
+ Create a separate team of exactly one monster. 
+ Include the following player attributes:
  + A player’s skill level (if not provided, default to 10).
  + A player’s preferred monster skill level (if not provided, default to 10).
  + Whether the player wants to be the monster (if not provided, default to 0 or false).
+ Choose a player to be the monster based on the following criteria:
  + Player must request the monster role.
  + Player must meet or exceed the highest skill level preferred by the players who are already added to the hunter team. 
+ Choose players for the hunter team based on the following criteria:
  + Players who request a monster role cannot join the hunter team.
  + If the monster role is already filled, player must want a monster skill level that is lower than the skill of the proposed monster. 
+ If a match is not filled quickly, relax the hunter team's minimum size as follows:
  + After 30 seconds, allow a game to start with only four players in the hunter team.
  + After 60 seconds, allow a game to start with only three people in the hunter team.

Notes on using this rule set: 
+ By using two separate teams for hunters and monster, you can evaluate membership based on different sets of criteria.

```
{
    "name": "players_vs_monster_5_vs_1",
    "ruleLanguageVersion": "1.0",
    "playerAttributes": [{
        "name": "skill",
        "type": "number",
        "default": 10
    },{
        "name": "desiredSkillOfMonster",
        "type": "number",
        "default": 10
    },{
        "name": "wantsToBeMonster",
        "type": "number",
        "default": 0
    }],
    "teams": [{
        "name": "players",
        "maxPlayers": 5,
        "minPlayers": 5
    }, {
        "name": "monster",
        "maxPlayers": 1,
        "minPlayers": 1 
    }],
    "rules": [{
        "name": "MonsterSelection",
        "description": "Only users that request playing as monster are assigned to the monster team",
        "type": "comparison",
        "measurements": ["teams[monster].players.attributes[wantsToBeMonster]"],
        "referenceValue": 1, 
        "operation": "="
    },{
        "name": "PlayerSelection",
        "description": "Do not place people who want to be monsters in the players team",
        "type": "comparison",
        "measurements": ["teams[players].players.attributes[wantsToBeMonster]"],
        "referenceValue": 0,
        "operation": "="
    },{
        "name": "MonsterSkill",
        "description": "Monsters must meet the skill requested by all players",
        "type": "comparison",
        "measurements": ["avg(teams[monster].players.attributes[skill])"],
        "referenceValue": "max(teams[players].players.attributes[desiredSkillOfMonster])",
        "operation": ">="
    }],
    "expansions": [{
        "target": "teams[players].minPlayers",
        "steps": [{
            "waitTimeSeconds": 30,
            "value": 4 
        },{
            "waitTimeSeconds": 60,
            "value": 3 
        }]
    }]
}
```

# Example: Set team-level requirements and latency limits


This example illustrates how to set up player teams and apply a set of rules to each team instead of each individual player. It uses a single definition to create three equally matched teams. It also establishes a maximum latency for all players. Latency maximums can be relaxed over time to complete the match. This example sets out the following instructions:
+ Create three teams of players.
  + Include between three and five players in each team.
  + Final teams must contain the same or nearly the same number of players (within one).
+ Include the following player attributes:
  + A player’s skill level (if not provided, default to 10).
  + A player’s character role (if not provided, default to “peasant”).
+ Choose players based on whether their skill level is similar to other players in the match.
  + Ensure that each team has an average player skill within 10 points of each other. 
+ Limit teams to the following number of “medic” characters:
  + An entire match can have a maximum of five medics.
+ Only match players who report latency of 50 milliseconds or less.
+ If a match is not filled quickly, relax the player latency requirement as follows: 
  + After 10 seconds, allow player latency values up to 100 ms.
  + After 20 seconds, allow player latency values up to 150 ms. 

Notes on using this rule set: 
+ The rule set ensures that teams are evenly matched based on player skill. To evaluate the `FairTeamSkill` rule, FlexMatch tentatively adds the prospective player to a team and calculates the average skill of players in the team. It then compares it against the average skill of players in both teams. If rule fails, the prospective player is not added to the match.
+ The team- and match-level requirements (total number of medics) are achieved through a collection rule. This rule type takes a list of character attributes for all players and checks against the maximum counts. Use `flatten` to create a list for all players in all teams.
+ When evaluating based on latency, note the following: 
  + Latency data is provided in the matchmaking request as part of the Player object. It is not a player attribute, so it does not need to be listed as one. To obtain accurate latency measurements, use Amazon GameLift Servers's UDP ping beacons. These endpoints enable you to measure actual UDP network latency between player devices and each of the potential hosting locations, resulting in more accurate placement decisions than using ICMP pings. For more information on using UDP ping beacons to measure latency, refer to [UDP ping beacons](https://docs.aws.amazon.com/gameliftservers/latest/developerguide/reference-udp-ping-beacons.html).
  + The matchmaker evaluates latency by region. Any region with a latency higher than the maximum is ignored. To be accepted for a match, a player must have at least one region with a latency below the maximum.
  + If a matchmaking request omits latency data one or more players, the request is rejected for all matches.

```
{
    "name": "three_team_game",
    "ruleLanguageVersion": "1.0",
    "playerAttributes": [{
        "name": "skill",
        "type": "number",
        "default": 10
    },{
        "name": "character",
        "type": "string_list",
        "default": [ "peasant" ]
    }],
    "teams": [{
        "name": "trio",
        "minPlayers": 3,
        "maxPlayers": 5,
        "quantity": 3
    }],
    "rules": [{
        "name": "FairTeamSkill",
        "description": "The average skill of players in each team is within 10 points from the average skill of players in the match",
        "type": "distance",
        // get players for each team, and average separately to produce list of 3
        "measurements": [ "avg(teams[*].players.attributes[skill])" ],
        // get players for each team, flatten into a single list, and average to produce overall average
        "referenceValue": "avg(flatten(teams[*].players.attributes[skill]))",
        "maxDistance": 10 // minDistance would achieve the opposite result
    }, {
        "name": "CloseTeamSizes",
        "description": "Only launch a game when the team sizes are within 1 of each other.  e.g. 3 v 3 v 4 is okay, but not 3 v 5 v 5",
        "type": "distance",
        "measurements": [ "max(count(teams[*].players))"],
        "referenceValue": "min(count(teams[*].players))",
        "maxDistance": 1
    }, {
        "name": "OverallMedicLimit",
        "description": "Don't allow more than 5 medics in the game",
        "type": "collection",
        // This is similar to above, but the flatten flattens everything into a single
        // list of characters in the game.
        "measurements": [ "flatten(teams[*].players.attributes[character])"],
        "operation": "contains",
        "referenceValue": "medic",
        "maxCount": 5
    }, {
        "name": "FastConnection",
        "description": "Prefer matches with fast player connections first",
        "type": "latency",
        "maxLatency": 50
    }],
    "expansions": [{
        "target": "rules[FastConnection].maxLatency",
        "steps": [{
            "waitTimeSeconds": 10,
            "value": 100
        }, {
            "waitTimeSeconds": 20,
            "value": 150
        }]
    }]
}
```

# Example: Use explicit sorting to find best matches


This example sets up a simple match with two teams of three players. It illustrates how to use explicit sorting rules to help find the best possible matches as quickly as possible. These rules sort all active matchmaking tickets to create the best matches based on certain key requirements. This example is implemented with the following instructions:
+ Create two teams of players.
+ Include exactly three players in each team.
+ Include the following player attributes:
  + Experience level (if not provided, default to 50).
  + Preferred game modes (can list multiple values) (if not provided, default to “coop” and “deathmatch”).
  + Preferred game maps, including map name and preference weighting (if not provided, default to `"defaultMap"` with a weight of 100).
+ Set up presorting:
  + Sort players based on their preference for the same game map as the anchor player. Players can have multiple favorite game maps, so this example uses a preference value. 
  + Sort players based on how closely their experience level matches the anchor player. With this sort, all players in all teams will have experience levels that are as close as possible. 
+ All players across all teams must have selected at least one game mode in common.
+ All players across all teams must have selected at least one game map in common. 

Notes on using this rule set: 
+ The game map sort uses an absolute sort that compares the mapPreference attribute value. Because it is first in the rule set, this sort is performed first. 
+ The experience sort uses a distance sort to compare a prospective player's skill level with the anchor player's skill. 
+ Sorts are performed in the order they are listed in a rule set. In this scenario, players are sorted by game map preference, and then by experience level. 

```
{
    "name": "multi_map_game",
    "ruleLanguageVersion": "1.0",
    "playerAttributes": [{
        "name": "experience",
        "type": "number",
        "default": 50
    }, {
        "name": "gameMode",
        "type": "string_list",
        "default": [ "deathmatch", "coop" ]
    }, {
        "name": "mapPreference",
        "type": "string_number_map",
        "default": { "defaultMap": 100 }
    }, {
        "name": "acceptableMaps",
        "type": "string_list",
        "default": [ "defaultMap" ]
    }],
    "teams": [{
        "name": "red",
        "maxPlayers": 3,
        "minPlayers": 3
    }, {
        "name": "blue",
        "maxPlayers": 3,
        "minPlayers": 3
    }],
    "rules": [{
        // We placed this rule first since we want to prioritize players preferring the same map
        "name": "MapPreference",
        "description": "Favor grouping players that have the highest map preference aligned with the anchor's favorite",
        // This rule is just for sorting potential matches.  We sort by the absolute value of a field.
        "type": "absoluteSort",
        // Highest values go first
        "sortDirection": "descending",
        // Sort is based on the mapPreference attribute.
        "sortAttribute": "mapPreference",
        // We find the key in the anchor's mapPreference attribute that has the highest value.
        // That's the key that we use for all players when sorting.
        "mapKey": "maxValue"
    }, {
        // This rule is second because any tie-breakers should be ordered by similar experience values
        "name": "ExperienceAffinity",
        "description": "Favor players with similar experience",
        // This rule is just for sorting potential matches.  We sort by the distance from the anchor.
        "type": "distanceSort",
        // Lowest distance goes first
        "sortDirection": "ascending",
        "sortAttribute": "experience"
    }, {
        "name": "SharedMode",
        "description": "The players must have at least one game mode in common",
        "type": "collection",
        "operation": "intersection",
        "measurements": [ "flatten(teams[*].players.attributes[gameMode])"],
        "minCount": 1
    }, {
        "name": "MapOverlap",
        "description": "The players must have at least one map in common",
        "type": "collection",
        "operation": "intersection",
        "measurements": [ "flatten(teams[*].players.attributes[acceptableMaps])"],
        "minCount": 1
    }]
}
```

# Example: Find intersections across multiple player attributes


This example illustrates how to use a collection rule to find intersections in two or more player attributes. When working with collections, you can use the `intersection` operation for a single attribute, and the `reference_intersection_count` operation for multiple attributes. 

To illustrate this approach, this example evaluates players in a match based on their character preferences. The example game is a "free-for-all" style in which all players in a match are opponents. Each player is asked to (1) choose a character for themselves, and (2) choose characters they want to play against. We need a rule that ensures that every player in a match is using a character that is on all other players' preferred opponents list. 

The example rule set describes a match with the following characteristics: 
+ Team structure: One team of five players
+ Player attributes: 
  + *myCharacter*: The player's chosen character.
  + *preferredOpponents*: List of characters that the player wants to play against.
+ Match rules: A potential match is acceptable if each character in use is on every player's preferred opponents list. 

To implement the match rule, this example uses a collection rule with the following property values:
+ Operation – Uses `reference_intersection_count` operation to evaluate how each string list in the measurement value intersects with the string list in the reference value. 
+ Measurement – Uses the `flatten` property expression to create a list of string lists, with each string list containing one player's *myCharacter* attribute value. 
+ Reference value – Uses the `set_intersection` property expression to create a string list of all *preferredOpponents* attribute values that are common to every player in the match.
+ Restrictions – `minCount` is set to 1 to ensure that each player's chosen character (a string list in the measurement) matches at least one of the preferred opponents common to all players. (a string in the reference value). 
+ Expansion – If a match is not filled within 15 seconds, relax the minimum intersection requirement.

The process flow for this rule is as follows:

1. A player is added to the prospective match. The reference value (a string list) is recalculated to include intersections with the new player's preferred opponents list. The measurement value (a list of string lists) is recalculated to add the new player's chosen character as a new string list.

1. Amazon GameLift Servers verifies that each string list in the measurement value (the players' chosen characters) intersects with at least one string in the reference value (the players' preferred opponents). Since in this example each string list in the measurement contains only one value, the intersection is either 0 or 1.

1. If any string list in the measurement does not intersect with the reference value string list, the rule fails and the new player is removed from the prospective match.

1. If a match is not filled within 15 seconds, drop the opponent match requirement to fill the remaining player slots in the match.

```
{
    "name": "preferred_characters",
    "ruleLanguageVersion": "1.0",

    "playerAttributes": [{
        "name": "myCharacter",
        "type": "string_list"
    }, {
        "name": "preferredOpponents",
        "type": "string_list"
    }],

    "teams": [{
        "name": "red",
        "minPlayers": 5,
        "maxPlayers": 5
    }],

    "rules": [{
        "description": "Make sure that all players in the match are using a character that is on all other players' preferred opponents list.",
        "name": "OpponentMatch",
        "type": "collection",
        "operation": "reference_intersection_count",
        "measurements": ["flatten(teams[*].players.attributes[myCharacter])"],
        "referenceValue": "set_intersection(flatten(teams[*].players.attributes[preferredOpponents]))",
        "minCount":1
    }],
    "expansions": [{
        "target": "rules[OpponentMatch].minCount",
        "steps": [{
            "waitTimeSeconds": 15,
            "value": 0
        }]
    }]
}
```

# Example: Compare attributes across all players


This example illustrates how to compare player attributes across a group of players. 

The example rule set describes a match with the following characteristics: 
+ Team structure: Two single-player teams
+ Player attributes: 
  + *gameMode*: Type of game chosen by the player (if not provided, default to "turn-based").
  + *gameMap*: Game world chosen by the player (if not provided, default to 1).
  + *character*: Character chosen by the player (no default value means that players must specify a character).
+ Match rules: Matched players must meet the following requirements: 
  + Players must choose the same game mode.
  + Players must choose the same game map.
  + Players much choose different characters.

Notes on using this rule set: 
+ To implement the match rule, this example uses comparison rules to check all players' attribute values. For game mode and map, the rule verifies that the values are the same. For character, the rule verifies that the values are different. 
+ This example uses one player definition with a quantity property to create both player teams. The team are assigned the following names: "player\$11" and "player\$12".

```
{
    "name": "",
    "ruleLanguageVersion": "1.0",

    "playerAttributes": [{
        "name": "gameMode",
        "type": "string",
        "default": "turn-based"
    }, {
        "name": "gameMap",
        "type": "number",
        "default": 1
    }, {
        "name": "character",
        "type": "number"
    }],

    "teams": [{
        "name": "player",
        "minPlayers": 1,
        "maxPlayers": 1,
        "quantity": 2
    }],

    "rules": [{
        "name": "SameGameMode",
        "description": "Only match players when they choose the same game type",
        "type": "comparison",
        "operation": "=",
        "measurements": ["flatten(teams[*].players.attributes[gameMode])"]
    }, {
        "name": "SameGameMap",
        "description": "Only match players when they're in the same map",
        "type": "comparison",
        "operation": "=",
        "measurements": ["flatten(teams[*].players.attributes[gameMap])"]
    }, {
        "name": "DifferentCharacter",
        "description": "Only match players when they're using different characters",
        "type": "comparison",
        "operation": "!=",
        "measurements": ["flatten(teams[*].players.attributes[character])"]
    }]
}
```

# Example: Create a large match


This example illustrates how to set up a rule set for matches that can exceed 40 players. When a rule set describes teams with a total maxPlayer count greater than 40, it is processed as a large match. Learn more in [Design a FlexMatch large-match rule set](match-design-rulesets-large.md). 

The example rule set creates a match using the following instructions: 
+ Create one team with up to 200 players, with a minimum requirement of 175 players. 
+ Balancing criteria: Select players based on similar skill level. All players must report their skill level to be matched.
+ Batching preference: Group players by similar balancing criteria when creating matches. 
+ Latency rules: Set the maximum acceptable player latency of 150 milliseconds.
+ If the match is not filled quickly, relax the requirements to complete a match in reasonable time. 
  + After 10 seconds, accept a team with 150 players. 
  + After 12 seconds, raise the maximum acceptable latency to 200 milliseconds. 
  + After 15 seconds, accept a team with 100 players.

Notes on using this rule set: 
+ Because the algorithm uses the "largest population" batching preference, players are first sorted based on the balancing criteria. As a result, matches tend to be fuller and contain players that are more similar in skill. All players meet acceptable latency requirements, but they may not get the best possible latency for their location.
+ The algorithm strategy used in this rule set, "largest population", is the default setting. To use the default, you can opt to omit the setting.
+ If you've enabled match backfill, do not relax player count requirements too quickly, or you may end up with too many partially filled game sessions. Learn more in [Relax large match requirements](match-design-rulesets-large-relax.md).

```
{
    "name": "free-for-all",
    "ruleLanguageVersion": "1.0",
    "playerAttributes": [{
        "name": "skill",
        "type": "number"
    }],
    "algorithm": {
        "balancedAttribute": "skill",
        "strategy": "balanced",
        "batchingPreference": "largestPopulation"
    },
    "teams": [{
        "name": "Marauders",
        "maxPlayers": 200,
        "minPlayers": 175
    }],
    "rules": [{
        "name": "low-latency",
        "description": "Sets maximum acceptable latency",
        "type": "latency",
        "maxLatency": 150
    }],
    "expansions": [{
        "target": "rules[low-latency].maxLatency",
        "steps": [{
            "waitTimeSeconds": 12,
            "value": 200
        }],
    }, {
        "target": "teams[Marauders].minPlayers",
        "steps": [{
            "waitTimeSeconds": 10,
            "value": 150
        }, {
            "waitTimeSeconds": 15,
            "value": 100
        }]
    }]
}
```

# Example: Create a multi-team large match


This example illustrates how to set up a rule set for matches with multiple teams that can exceed 40 players. This example illustrates how to create multiple identical teams with one definition and how asymmetrically sized teams are filled during match creation.

The example rule set creates a match using the following instructions: 
+ Create ten identical "hunter" teams with up to 15 players, and one "monster" team with exactly 5 players. 
+ Balancing criteria: Select players based on number of monster kills. If players don't report their kill count, use a default value of 5.
+ Batching preference: Group players based on the regions where they report the fastest player latency. 
+ Latency rule: Sets a maximum acceptable player latency of 200 milliseconds. 
+ If the match is not filled quickly, relax the requirements to complete a match in reasonable time. 
  + After 15 seconds, accept teams with 10 players. 
  + After 20 seconds, accept teams with 8 players. 

Notes on using this rule set: 
+ This rule set defines teams that can potentially hold up to 155 players, which makes it a large match. (10 x 15 hunters \$1 5 monsters = 155)
+ Because the algorithm uses the "fastest region" batching preference, players tend to be placed in regions where they report faster latency and not in regions where they report high (but acceptable) latency. At the same time, matches are likely to have fewer players, and the balancing criteria (number of monster skills) may vary more widely.
+ When an expansion is defined for a multi-team definition (quantity > 1), the expansion applies to all teams created with that definition. So by relaxing the hunter team minimum players setting, all ten hunter teams are affected equally.
+ Since this rule set is optimized to minimize player latency, the latency rule acts as a catch-all to exclude players who have no acceptable connection options. We don't need to relax this requirement.
+ Here's how FlexMatch fills matches for this rule set before any expansions take effect:
  + No teams have reached minPlayers count yet. Hunter teams have 15 open slots, while Monster team has 5 open slots. 
    + The first 100 players are assigned (10 each) to the ten hunter teams.
    + The next 22 players are assigned sequentially (2 each) to hunter teams and monster team.
  + Hunter teams have reached minPlayers count of 12 players each. Monster team has 2 players and has not reached minPlayers count.
    + The next three players are assigned to the monster team.
  + All teams have reached minPlayers count. Hunter teams each have three open slots. Monster team is full.
    + The final 30 players are assigned sequentially to the hunter teams, ensuring that all hunter teams have nearly the same size (plus or minus one player).
+ If you've enabled backfill for matches created with this rule set, do not relax player count requirements too quickly, or you may end up with too many partially filled game sessions. Learn more in [Relax large match requirements](match-design-rulesets-large-relax.md).

```
{
    "name": "monster-hunters",
    "ruleLanguageVersion": "1.0",
    "playerAttributes": [{
        "name": "monster-kills",
        "type": "number",
        "default": 5
    }],
    "algorithm": {
        "balancedAttribute": "monster-kills",
        "strategy": "balanced",
        "batchingPreference": "fastestRegion"
    },
    "teams": [{
        "name": "Monsters",
        "maxPlayers": 5,
        "minPlayers": 5
    }, {
        "name": "Hunters",
        "maxPlayers": 15,
        "minPlayers": 12,
        "quantity": 10
    }],
    "rules": [{
        "name": "latency-catchall",
        "description": "Sets maximum acceptable latency",
        "type": "latency",
        "maxLatency": 150
    }],
    "expansions": [{
        "target": "teams[Hunters].minPlayers",
        "steps": [{
            "waitTimeSeconds": 15,
            "value": 10
        }, {
            "waitTimeSeconds": 20,
            "value": 8
        }]
    }]
}
```

# Example: Create a large match with players with similar attributes


This example illustrates how to set up a rule set for matches with two teams using `batchDistance`. In the example: 
+ The `SimilarLeague` rule ensures all players in a match have a `league` within 2 of other players. 
+ The `SimilarSkill` rule ensures all players in a match have a `skill` within 10 of other players. If a player has been waiting 10 seconds, the distance is expanded to 20. If a player has been waiting 20 seconds, the distance is expanded to 40. 
+ The `SameMap` rule ensures all players in a match have requested the same `map`. 
+ The `SameMode` rule ensures all players in a match have requested the same `mode`. 

```
{
    "ruleLanguageVersion": "1.0",
    "teams": [{
        "name": "red",
        "minPlayers": 100,
        "maxPlayers": 100
    }, {
        "name": "blue",
        "minPlayers": 100,
        "maxPlayers": 100
    }],
    "algorithm": {
        "strategy":"balanced",
        "balancedAttribute": "skill",
        "batchingPreference":"fastestRegion"
    },
    "playerAttributes": [{
        "name": "league",
        "type": "number"
    },{
        "name": "skill",
        "type": "number"
    },{
        "name": "map",
        "type": "string"
    },{
        "name": "mode",
        "type": "string"
    }],
    "rules": [{
        "name": "SimilarLeague",
        "type": "batchDistance",
        "batchAttribute": "league",
        "maxDistance": 2
    }, {
        "name": "SimilarSkill",
        "type": "batchDistance",
        "batchAttribute": "skill",
        "maxDistance": 10
    }, {
        "name": "SameMap",
        "type": "batchDistance",
        "batchAttribute": "map"
    }, {
        "name": "SameMode",
        "type": "batchDistance",
        "batchAttribute": "mode"
    }],
    "expansions": [{
        "target": "rules[SimilarSkill].maxDistance",
        "steps": [{
            "waitTimeSeconds": 10,
            "value": 20
        }, {
            "waitTimeSeconds": 20,
            "value": 40
        }]
    }]
}
```

# Example: Use a compound rule to create a match with players with similar attributes or similar selections


This example illustrates how to set up a rule set for matches with two teams using `compound`. In the example: 
+ The `SimilarLeagueDistance` rule ensures all players in a match have a `league` within 2 of other players. 
+ The `SimilarSkillDistance` rule ensures all players in a match have a `skill` within 10 of other players. If a player has been waiting 10 seconds, the distance is expanded to 20. If a player has been waiting 20 seconds, the distance is expanded to 40. 
+ The `SameMapComparison` rule ensures all players in a match have requested the same `map`. 
+ The `SameModeComparison` rule ensures all players in a match have requested the same `mode`. 
+ The `CompoundRuleMatchmaker` rule ensures a match if at least one of the following conditions is true: 
  + Players in a match have requested the same `map` and the same `mode`.
  + Players in a match have comparable `skill` and `league` attributes.

```
{
    "ruleLanguageVersion": "1.0",
    "teams": [{
        "name": "red",
        "minPlayers": 10,
        "maxPlayers": 20
    }, {
        "name": "blue",
        "minPlayers": 10,
        "maxPlayers": 20
    }],
    "algorithm": {
        "strategy":"balanced",
        "balancedAttribute": "skill",
        "batchingPreference":"fastestRegion"
    },
    "playerAttributes": [{
        "name": "league",
        "type": "number"
    },{
        "name": "skill",
        "type": "number"
    },{
        "name": "map",
        "type": "string"
    },{
        "name": "mode",
        "type": "string"
    }],
    "rules": [{
        "name": "SimilarLeagueDistance",
        "type": "distance",
        "measurements": ["max(flatten(teams[*].players.attributes[league]))"],
        "referenceValue": "min(flatten(teams[*].players.attributes[league]))",
        "maxDistance": 2
    }, {
        "name": "SimilarSkillDistance",
        "type": "distance",
        "measurements": ["max(flatten(teams[*].players.attributes[skill]))"],
        "referenceValue": "min(flatten(teams[*].players.attributes[skill]))",
        "maxDistance": 10
    }, {
        "name": "SameMapComparison",
        "type": "comparison",
        "operation": "=",
        "measurements": ["flatten(teams[*].players.attributes[map])"]
    }, {
        "name": "SameModeComparison",
        "type": "comparison",
        "operation": "=",
        "measurements": ["flatten(teams[*].players.attributes[mode])"]
    }, {
        "name": "CompoundRuleMatchmaker",
        "type": "compound",
        "statement": "or(and(SameMapComparison, SameModeComparison), and(SimilarSkillDistance, SimilarLeagueDistance))"
    }],
    "expansions": [{
        "target": "rules[SimilarSkillDistance].maxDistance",
        "steps": [{
            "waitTimeSeconds": 10,
            "value": 20
        }, {
            "waitTimeSeconds": 20,
            "value": 40
        }]
    }]
}
```

# Example: Create a rule that uses a player's block list


This example illustrates a rule set that lets players avoid being matched with certain other players. Players can create a block list, which the matchmaker evaluates during player selection for a match. For more guidance on adding a block list or avoid list feature, see [AWS for Games Blog](https://aws.amazon.com/blogs/gametech/category/game-development/amazon-gamelift/).

This example sets out the following instructions:
+ Create two teams of exactly five players.
+ Pass in a player's block list, which is a list of player IDs (up to 100).
+ Compare all players against each player's block list and reject a proposed match if any blocked player IDs are found.

Notes on using this rule set: 
+ When evaluating a new player to add to a proposed match (or to backfill a spot in an existing match), the player might be rejected for either of the following reasons: 
  + If the new player is on a block list for any players that are already selected for the match. 
  + If any players that are already selected for the match are on the new player's block list.
+ As shown, this rule set prevents matching a player with any player on their block list. You can change this requirement to a preference (also called an "avoid" list) by adding a rule expansion and increasing the `maxCount` value.

```
{
    "name": "Player Block List",
    "ruleLanguageVersion": "1.0",
    "teams": [{
        "maxPlayers": 5,
        "minPlayers": 5,
        "name": "red"
    }, {
        "maxPlayers": 5,
        "minPlayers": 5,
        "name": "blue"
    }],
    "playerAttributes": [{
        "name": "BlockList",
        "type": "string_list",
        "default": []
    }],
    "rules": [{
        "name": "PlayerIdNotInBlockList",
        "type": "collection",
        "operation": "reference_intersection_count",
        "measurements": "flatten(teams[*].players.attributes[BlockList])",
        "referenceValue": "flatten(teams[*].players[playerId])",
        "maxCount": 0
    }]
}
```

# Create a matchmaking configuration
Create a matchmaking configuration

To set up an Amazon GameLift Servers FlexMatch matchmaker to process matchmaking requests, create a matchmaking configuration. Use either the Amazon GameLift Servers console or the AWS Command Line Interface (AWS CLI). For more information about creating a matchmaker, see [Design a FlexMatch matchmaker](match-configuration.md).

**Topics**
+ [

# Tutorial: Create a matchmaker for Amazon GameLift Servers hosting
](match-create-configuration-withqueue.md)
+ [

# Tutorial: Create a matchmaker for standalone FlexMatch
](match-create-configuration-standalone.md)
+ [

# Tutorial: Edit a matchmaking configuration
](match-create-configuration-edit.md)

# Tutorial: Create a matchmaker for Amazon GameLift Servers hosting
Tutorial: Create a matchmaker for hosting

Before creating a matchmaking configuration, [create a rule set](match-create-ruleset.md) and an Amazon GameLift Servers [game session queue](https://docs.aws.amazon.com/gameliftservers/latest/developerguide/queues-creating.html) to use with the matchmaker.

------
#### [ Console ]

1. In the [Amazon GameLift Servers console](https://console.aws.amazon.com/gamelift/), in the navigation pane, choose **Matchmaking configurations**.

1. Switch to the AWS Region where you want to create your matchmaker.

1. On the **Matchmaking configurations** page, choose **Create matchmaking configuration**.

1. On the **Define configuration details** page, under **Matchmaking configuration details**, do the following:

   1. For **Name**, enter a matchmaker name that can help you identify it in a list and in metrics. The matchmaker name must be unique within the Region. Matchmaking requests identify which matchmaker to use by its name and Region.

   1. (Optional) For **Description**, add a description to help identify the matchmaker.

   1. For **Rule set**, choose a rule set from the list to use with the matchmaker. The list contains all rule sets that you've created in the current Region.

   1. For **FlexMatch mode**, choose **Managed** for Amazon GameLift Servers managed hosting. This mode prompts FlexMatch to pass successful matches to the specified game session queue.

   1. For **AWS Region**, choose the Region where you configured the game session queue that you want to use with the matchmaker.

   1. For **Queue**, choose the game session queue that you want to use with the matchmaker.

1. Choose **Next**.

1. On the **Configure settings** page, under **Matchmaking settings**, do the following:

   1. For **Request timeout**, set the maximum amount of time, in seconds, for the matchmaker to complete a match for each request. FlexMatch cancels matchmaking requests that exceed this time.

   1. For **Backfill mode**, choose a mode for handling match backfills. 
      + To turn on the automatic backfill feature, choose **Automatic**.
      + To create your own backfill request management or to not use the backfill feature, choose **Manual**.

   1. (Optional) For **Additional player count**, set the number of player slots to keep open in a match. FlexMatch can fill these slots with players in the future.

   1. (Optional) Under **Match acceptance options**, for **Acceptance required**, if you want to require each player in a proposed match to actively accept participation in the match, select **Required**. If you select this option, then for **Acceptance timeout**, set how long, in seconds, you want the matchmaker to wait for player acceptances before canceling the match.

1. (Optional) Under **Event notification settings**, do the following:

   1. (Optional) For **SNS topic**, choose an Amazon Simple Notification Service (Amazon SNS) topic for receiving matchmaking event notifications. If you haven't yet set up an SNS topic, you can choose this later by editing the matchmaking configuration. For more information, see [Set up FlexMatch event notifications](match-notification.md).

   1. (Optional) For **Custom event data**, enter any custom data that you want to associate with this matchmaker in event messaging. FlexMatch includes this data in every event associated with the matchmaker.

1. (Optional) Expand **Additional game data**, and then do the following:

   1. (Optional) For **Game session data**, enter any additional game-related information that you want FlexMatch to deliver to new game sessions started with matches made using this matchmaking configuration.

   1. (Optional) For **Game properties**, add key-value pair properties that contain information about a new game session.

1. (Optional) Under **Tags**, add tags to help you manage and track your AWS resources.

1. Choose **Next**.

1. On the **Review and create** page, review your choices, and then choose **Create**. Upon successful creation, the matchmaker is ready to accept matchmaking requests.

------
#### [ AWS CLI ]

To create a matchmaking configuration with the AWS CLI, open a command line window and use the [create-matchmaking-configuration](https://docs.aws.amazon.com/cli/latest/reference/gamelift/create-matchmaking-configuration.html) command to define a new matchmaker.

This example command creates a new matchmaking configuration that requires player acceptance and enables automatic backfill. It also reserves two player slots for FlexMatch to add players later, and it provides some game session data.

```
aws gamelift create-matchmaking-configuration \
    --name "SampleMatchamker123" \
    --description "The sample test matchmaker with acceptance" \
    --flex-match-mode WITH_QUEUE \
    --game-session-queue-arns "arn:aws:gamelift:us-west-2:111122223333:gamesessionqueue/MyGameSessionQueue" \
    --rule-set-name "MyRuleSet" \
    --request-timeout-seconds 120 \
    --acceptance-required \
    --acceptance-timeout-seconds 30 \
    --backfill-mode AUTOMATIC \
    --notification-target "arn:aws:sns:us-west-2:111122223333:My_Matchmaking_SNS_Topic" \
    --additional-player-count 2 \
    --game-session-data "key=map,value=winter444"
```

If the matchmaking configuration creation request is successful, Amazon GameLift Servers returns a [MatchmakingConfiguration](https://docs.aws.amazon.com/gameliftservers/latest/apireference/API_MatchmakingConfiguration.html) object with the settings that you requested for the matchmaker. The new matchmaker is ready to accept matchmaking requests.

------

# Tutorial: Create a matchmaker for standalone FlexMatch


Before creating a matchmaking configuration, [create a rule set](match-create-ruleset.md) to use with the matchmaker.

------
#### [ Console ]

1. Open the Amazon GameLift Servers console at [https://console.aws.amazon.com/gamelift/home](https://console.aws.amazon.com/gamelift/).

1. Switch to the AWS Region where you want to create your matchmaker. For a list of Regions that support FlexMatch matchmaking configurations, see [Choose a location for the matchmaker](match-configuration-regions.md).

1. In the navigation pane, choose **FlexMatch**, **Matchmaking configurations**.

1. On the **Matchmaking configurations** page, choose **Create matchmaking configuration**.

1. On the **Define configuration details** page, under **Matchmaking configuration details**, do the following:

   1. For **Name**, enter a matchmaker name that can help you identify it in a list and in metrics. The matchmaker name must be unique within the Region. Matchmaking requests identify which matchmaker to use by its name and Region.

   1. (Optional) For **Description**, add a description to help identify the matchmaker.

   1. For **Rule set**, choose a rule set from the list to use with the matchmaker. The list contains all rule sets that you've created in the current Region.

   1. For **FlexMatch mode**, choose **Standalone**. This indicates that you have a custom mechanism for starting new game sessions on a hosting solution outside of Amazon GameLift Servers.

1. Choose **Next**.

1. On the **Configure settings** page, under **Matchmaking settings**, do the following:

   1. For **Request timeout**, set the maximum amount of time, in seconds, for the matchmaker to complete a match for each request. Matchmaking requests that exceed this time are rejected.

   1. (Optional) Under **Match acceptance options**, for **Acceptance required**, if you want to require each player in a proposed match to actively accept participation in the match, select **Required**. If you select this option, then for **Acceptance timeout**, set how long, in seconds, you want the matchmaker to wait for player acceptances before canceling the match.

1. (Optional) Under **Event notification settings**, do the following:

   1. (Optional) For **SNS topic**, choose an Amazon SNS topic for receiving matchmaking event notifications. If you haven't yet set up an SNS topic, you can choose this later by editing the matchmaking configuration. For more information, see [Set up FlexMatch event notifications](match-notification.md).

   1. (Optional) For **Custom event data**, enter any custom data that you want to associate with this matchmaker in event messaging. FlexMatch includes this data in every event associated with the matchmaker.

1. (Optional) Under **Tags**, add tags to help you manage and track your AWS resources.

1. Choose **Next**.

1. On the **Review and create** page, review your choices, and then choose **Create**. Upon successful creation, the matchmaker is ready to accept matchmaking requests.

------
#### [ AWS CLI ]

To create a matchmaking configuration with the AWS CLI, open a command line window and use the [create-matchmaking-configuration](https://docs.aws.amazon.com/cli/latest/reference/gamelift/create-matchmaking-configuration.html) command to define a new matchmaker.

This example command creates a new matchmaking configuration for a standalone matchmaker that requires player acceptance.

```
aws gamelift create-matchmaking-configuration \
    --name "SampleMatchamker123" \
    --description "The sample test matchmaker with acceptance" \
    --flex-match-mode STANDALONE \
    --rule-set-name "MyRuleSetOne" \
    --request-timeout-seconds 120 \
    --acceptance-required \
    --acceptance-timeout-seconds 30 \
    --notification-target "arn:aws:sns:us-west-2:111122223333:My_Matchmaking_SNS_Topic"
```

If the matchmaking configuration creation request is successful, Amazon GameLift Servers returns a [MatchmakingConfiguration](https://docs.aws.amazon.com/gameliftservers/latest/apireference/API_MatchmakingConfiguration.html) object with the settings that you requested for the matchmaker. The new matchmaker is ready to accept matchmaking requests.

------

# Tutorial: Edit a matchmaking configuration


To edit a matchmaking configuration, choose **Matchmaking configurations** from the navigation bar and choose the configuration you want to edit. You can update any field in an existing configuration except for it's name. 

When updating a configurations rule set, a new rule set can be incompatible if there are existing active matchmaking tickets for the following reasons:
+ New or different team names or number of teams
+ New player attributes
+ Changes to existing player attribute types

To make any of the these changes to your rule set, create a new matchmaking configuration with the updated rule set.

# Set up FlexMatch event notifications
Set up event notifications

You can use event notifications to track the status of individual matchmaking requests. All games in production, or in pre-production with high-volume matchmaking activity should use event notifications.

There are two options for setting up event notifications. 
+ Have your matchmaker publish event notifications to an Amazon Simple Notification Service (Amazon SNS) topic.
+ Use automatically published Amazon EventBridge events and its suite of tools for managing events.

For a list of the FlexMatch events that Amazon GameLift Servers emits, see [FlexMatch matchmaking events](match-events.md).

**Important**  
For high-volume matchmaking systems, we recommend using standard (non-FIFO) Amazon SNS topics rather than FIFO topics. FIFO topics have lower publishing limits than standard topics, which can lead to throttling exceptions during high load. If you experience throttling with FIFO topics, you may lose FlexMatch notifications.

**Note**  
 Amazon GameLift Servers automatically handles Amazon SNS delivery failures and throttling with built-in retry logic. When Amazon SNS returns throttling errors or temporary failures, Amazon GameLift Servers retries the notification delivery with progressive delays between attempts. This helps ensure event notifications are delivered reliably. However, notifications may be lost if failures persist after all retry attempts, or for non-retryable errors such as authorization failures or missing topics. 

**Topics**
+ [

## Set up EventBridge events
](#match-notification-cwe)
+ [

# Tutorial: Set up an Amazon SNS topic
](match-notification-sns.md)
+ [

# Set up an SNS topic with server-side encryption
](queue-notification-sns-sse.md)
+ [

# Configure a topic subscription to invoke a Lambda function
](match-notification-lambda.md)

## Set up EventBridge events


Amazon GameLift Servers automatically posts all matchmaking events to Amazon EventBridge. With EventBridge, you can set up rules to have matchmaking events routed to targets for processing. For example, you can set a rule to route the event "PotentialMatchCreated" to an AWS Lambda function that handles player acceptances. For more information, see [What is Amazon EventBridge?](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html)

**Note**  
When you configure your matchmakers, keep the notification target field empty or reference an SNS topic if you want to use both EventBridge and Amazon SNS.

# Tutorial: Set up an Amazon SNS topic


You can have Amazon GameLift Servers publish all events that a FlexMatch matchmaker generates to an Amazon SNS topic.

**To create an SNS topic for Amazon GameLift Servers event notifications**

1. Open the [Amazon SNS console](https://console.aws.amazon.com/sns).

1. In the navigation pane, choose **Topics**.

1. On the **Topics** page, choose **Create topic**.

1. Create a topic in the console. For more information, see [To create a topic using the AWS Management Console](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html#create-topic-aws-console) in the *Amazon Simple Notification Service Developer Guide*.

1. On the **Details** page for your topic, choose **Edit**.

1. (Optional) On the **Edit** page for your topic, expand **Access policy**, then add the bold syntax from the following AWS Identity and Access Management (IAM) policy statement to the end of your existing policy. (The entire policy is shown here for clarity.) Be sure to use the Amazon Resource Name (ARN) details for your own SNS topic and Amazon GameLift Servers matchmaking configuration.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Id": "__default_policy_ID",
     "Statement": [
       {
         "Sid": "__default_statement_ID",
         "Effect": "Allow",
         "Principal": {
           "AWS": "*"
         },
         "Action": [
           "SNS:GetTopicAttributes",
           "SNS:SetTopicAttributes",
           "SNS:AddPermission",
           "SNS:RemovePermission",
           "SNS:DeleteTopic",
           "SNS:Subscribe",
           "SNS:ListSubscriptionsByTopic",
           "SNS:Publish"
         ],
         "Resource": "arn:aws:sns:us-east-1:111122223333:your_topic_name",
         "Condition": {
           "StringEquals": {
           "AWS:SourceAccount": "111122223333"
           }
         }
       },
       {
         "Sid": "__console_pub_0",
         "Effect": "Allow",
         "Principal": {
           "Service": "gamelift.amazonaws.com"
         },
         "Action": "SNS:Publish",
         "Resource": "arn:aws:sns:us-east-1:111122223333:your_topic_name",
         "Condition": {
           "ArnLike": {
           "aws:SourceArn": "arn:aws:gamelift:us-east-1:111122223333:matchmakingconfiguration/your_configuration_name"
           }
         }
       }
     ]
   }
   ```

------

1. Choose **Save changes**.

# Set up an SNS topic with server-side encryption


You can use server-side encryption (SSE) to store sensitive data in encrypted topics. SSE protects the contents of messages in Amazon SNS topics using keys managed in AWS Key Management Service (AWS KMS). For more information about server-side encryption with Amazon SNS, see [Encryption at rest](https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html) in the *Amazon Simple Notification Service Developer Guide*.

To set up an SNS topic with server-side encryption, review the following topics:
+ [Creating key](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html) in the *AWS Key Management Service Developer Guide*
+ [Enabling SSE for a topic](https://docs.aws.amazon.com/sns/latest/dg/sns-enable-encryption-for-topic.html) in the *Amazon Simple Notification Service Developer Guide*

When creating your KMS key, use the following KMS key policy:

```
{ 
  "Effect": "Allow", 
  "Principal": { 
    "Service": "gamelift.amazonaws.com" 
  },
  "Action": [
      "kms:Decrypt",
      "kms:GenerateDataKey"
  ],
  "Resource": "*",
  "Condition": {
      "ArnLike": { 
        "aws:SourceArn": "arn:aws:gamelift:your_region:your_account:matchmakingconfiguration/your_configuration_name" 
      },
      "StringEquals": { 
        "kms:EncryptionContext:aws:sns:topicArn": "arn:aws:sns:your_region:your_account:your_sns_topic_name" 
      }
  }
}
```

# Configure a topic subscription to invoke a Lambda function


You can invoke a Lambda function using event notifications published to your Amazon SNS topic. When configuring the matchmaker, be sure to set the notification target to your SNS topic's ARN.

The following AWS CloudFormation template configures a subscription to an SNS topic named `MyFlexMatchEventTopic` to invoke a Lambda function named `FlexMatchEventHandlerLambdaFunction`. The template creates an IAM permissions policy that allows Amazon GameLift Servers to write to the SNS topic. The template then adds permissions for the SNS topic to invoke the Lambda function.

```
FlexMatchEventTopic:
  Type: "AWS::SNS::Topic"
  Properties:
    KmsMasterKeyId: alias/aws/sns #Enables server-side encryption on the topic using an AWS managed key 
    Subscription:
      - Endpoint: !GetAtt FlexMatchEventHandlerLambdaFunction.Arn
        Protocol: lambda
    TopicName: MyFlexMatchEventTopic

FlexMatchEventTopicPolicy:
  Type: "AWS::SNS::TopicPolicy"
  DependsOn: FlexMatchEventTopic
  Properties:
    PolicyDocument:
      Version: "2012-10-17"
      Statement:
        - Effect: Allow
          Principal:
            Service: gamelift.amazonaws.com
          Action:
            - "sns:Publish"
          Resource: !Ref FlexMatchEventTopic
    Topics:
      - Ref: FlexMatchEventTopic

FlexMatchEventHandlerLambdaPermission:
  Type: "AWS::Lambda::Permission"
  Properties:
    Action: "lambda:InvokeFunction"
    FunctionName: !Ref FlexMatchEventHandlerLambdaFunction
    Principal: sns.amazonaws.com
    SourceArn: !Ref FlexMatchEventTopic
```