

# Configure game session placement
<a name="queues-intro"></a>

Game session placement is the process of finding available game servers to host new game sessions. Amazon GameLift Servers uses game session queues to intelligently place game sessions across your fleets, taking into account factors like player latency, fleet capacity, and cost optimization.

A well-configured game session queue ensures that players are connected to the best available game server, providing optimal performance while making efficient use of your hosting resources. Queues can span multiple fleets and AWS Regions to provide global coverage and redundancy.

A game session queue is the primary mechanism that Amazon GameLift Servers uses to search for available game servers and choose them to host new game sessions. Queues offers a far more efficient way to process large numbers of game session requests and find placements for them across multiple fleets of hosting resources. If your hosting solution uses more than one fleet, and you're processing high volumes of requests, you probably need a queue.

When your game wants to start a new game session for players, it sends a placement request to the Amazon GameLift Servers service, which funnels it to the queue. The queue's configuration determines when and how the requests are processed. When processing a placement request, Amazon GameLift Servers searches a set of fleets for a game server to host the game session. Placement succeeds when Amazon GameLift Servers finds an available game server and prompts it to start a game session. 

**Topics**
+ [Queue characteristics](#queues-intro-characteristics)
+ [Best practices for Amazon GameLift Servers game session queues](#queues-best-practices)
+ [Create a game session queue](queues-creating.md)
+ [Set up event notification for game session placement](queue-notification.md)

## Queue characteristics
<a name="queues-intro-characteristics"></a>

An Amazon GameLift Servers game session queue is an AWS cloud resource. You can create a queue in any AWS Region that Amazon GameLift Servers supports (see [Amazon GameLift Servers service locations](gamelift-regions.md)). Game session placement requests are sent to that location and processed there.

Automating game session placement with queues offers significant benefits for both game developers and players. These include:
+ **Queues deliver the "best possible" placement.** When processing game session placement requests, a queue uses the Amazon GameLift Servers FleetIQ algorithm to prioritize placements based on a set of defined preferences, including cost, location, and player latency.
+ **Queues support Spot fleets to help reduce game hosting costs.** You can configure your queues with AWS Spot fleets, which often offer significantly lower hosting costs, as well as On-Demand fleets. Because low cost is one of the key criteria for placements, queues can always take advantage of differences in cost.
+ **Queues can place new games faster during high demand.** By configuring a queue with multiple fleets, you're providing more flexible options for game session placement. But additional fleets also provide backup capacity as needed when demand increases. For any placement request, if Amazon GameLift Servers can't place a game session in the most preferred location, it automatically moves on to evaluate other locations. 
+ **Queues can make game server availability more resilient.** Outages can happen. With a multi-fleet queue, a slowdown or outage doesn't have to affect player access to your game. By configuring your queue with fleets that have capacity in different AWS Regions and availability zones, you can help make sure that players can always find a game session to join.
+ **Get metrics on game session placements and queue performance.** Amazon GameLift Servers emits queue metrics, including statistics on placement successes and failures, the number of requests in the queue, and average time that requests spend in the queue. You can view these metrics in the Amazon GameLift Servers console or in CloudWatch.

To get started by creating a basic starter queue, see [Create a game session queue](queues-creating.md).

**Topics**
+ [Queue characteristics](#queues-intro-characteristics)
+ [Best practices for Amazon GameLift Servers game session queues](#queues-best-practices)
+ [Create a game session queue](queues-creating.md)
+ [Set up event notification for game session placement](queue-notification.md)

## Best practices for Amazon GameLift Servers game session queues
<a name="queues-best-practices"></a>

A game session queue contains a list of fleets where Amazon GameLift Servers can place new game sessions. Each fleet can have hosting resources deployed in multiple geographic locations. When choosing a placement, the queue selects a fleet and a fleet location based on a set of priorities that you set for the fleet.

Consider the following guidelines and best practices:
+ **Add fleets in locations that cover your players.** You can add fleets and aliases in any available location. Location is important if you're making placements based on reported player latency.
+ **Use aliases for all fleets.** Assign an alias to each fleet in a queue, and use the alias names when setting destinations in your queue.
+ **Use the same or a similar game build or script for all fleets.** The queue might put players into game sessions on any fleet in the queue. Players must be able to play in any game session on any fleet. 
+ **Create fleets in at least two locations.** By having game servers hosted in at least one other location, you mitigate the impact of Regional outages on your players. You can keep your backup fleets scaled down, and use autoscaling to increase capacity if usage increases.
+ **Prioritize your game session placement.** A queue prioritizes placement choices based on several elements, including destination list order.
+ **Create your queue in the same location as your client service.** By putting your queue in a location near your client service, you can minimize communication latency.
+ **Use fleets with multiple locations.** Use the queue filter configuration to prevent the queue from placing game sessions in specified locations. You can use at least two multi-location fleets with different home locations to mitigate the impact of game placements during a Regional outage.
+ **Use the same TLS certificate setting for all fleets.** Game clients that connect to game sessions in your fleets must have compatible communication protocols. 

# Create a game session queue
<a name="queues-creating"></a>

Queues are used to place new game sessions across multiple fleets and locations. Your game starts new game sessions by submitting placement requests to a queue. A queue is configured with instructions for how to process requests. Learn more about initiating game session placement requests in [Create game sessions](gamelift-sdk-client-api.md#gamelift-sdk-client-api-create). 

**To create a game session queue**

These instructions illustrate how to create a simple working queue with minimal configuration settings and default settings. There are a number of options for customizing a queue configuration. These options help you make the best possible placements based on the needs of your game. To learn more about customizing queues for your game, see [Customize a game session queue](queues-design.md). You can update most queue configuration settings at any time.

You can create a game session queue using either the Amazon GameLift Servers console or the AWS CLI.

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

In the [Amazon GameLift Servers console](https://console.aws.amazon.com/gamelift/), select an AWS Region to work in. Open the console’s left navigation bar and choose **Queues**. 

1. On the **Queues** page, choose **Create queue** to start the workflow.

1. Under **Queue settings** enter the following settings:

   1. Enter a queue name. This name must be unique to the AWS Region that you're creating the queue in.

   1. Keep the default **Timeout** setting, which is 600 seconds (or 10 minutes). This value controls how long Amazon GameLift Servers tries to place a new game session before stopping. Amazon GameLift Servers searches for available resources until the request times out. You can update a queue's timeout setting at any time. 

   1. Skip the **Player latency policies** section. A queue uses latency policies only when it receives placement requests that include player latency data. You can add latency policies to a queue at any time. For more on creating latency policies, see [Create a player latency policy](queues-design-latency.md).

1. Skip the **Game session placement locations** section to use the default setting of **All locations**. This setting lets you create an allow list of locations where the queue can make placements (also called a filter configuration). For more about prioritizing by location and filter configurations, see [Prioritize placements by location](queues-design-priority.md#queues-design-priority-custom-location). 

1. Under **Destination order**, add one or more fleets to the queue. You can identify fleets by using fleet IDs or ARNs, or by using a fleet alias. When adding multiple fleets, keep in mind that they should all be running similar game builds and be compatible with any game client that uses this queue. In addition, all fleets in a queue must have the same certificate configuration.

   1. Select the **Region** where the fleet or alias was created. For a multi-location fleet, this is the "home" region.

   1. For destination **Type**, select either a fleet or an alias.

   1. Your region and type selections populate a dropdown list of existing fleets or aliases. Select one to designate as a queue destination.

   1. To specify another fleet or alias for the queue, choose **Add destination** and repeat the previous steps.

   1. After you've added a list of destinations, use the drag-and-drop feature to reorder the destinations. Amazon GameLift Servers uses this order when prioritizing placements by destination. 

1. Skip the **Game session placement priority** section to keep the default priority order. This setting lets you customize how Amazon GameLift Servers chooses where to look for available hosting resources for new game session placements. For more information about prioritizing placements, see [Prioritize game session placement](queues-design-priority.md). You can update a queue's placement priorities at any time.

1. Under **Location order**, keep the default values. This setting is used when prioritizing by fleet location. It provides location order to use. When using the default priority settings, location is used as a tiebreaker when the preferred destination is a fleet with multiple locations.

1. Skip the optional **Event notification settings** section. Event notifications are required for queues that process a high volume of placement requests. For queues that process low volumes, such as for development or testing purposes, you can track the status of placement requests by polling with[DescribeGameSessionPlacement](https://docs.aws.amazon.com/gameliftservers/latest/apireference/API_DescribeGameSessionPlacement.html). For more details, see [Set up event notification for game session placement](queue-notification.md). You can update a queue's event notification settings at any time. 

1. Choose **Create** to generate a new queue with minimal customization.

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

**Example Create a queue**  
The following example creates a game session queue with these configurations:  
+ A five minute timeout.
+ Two fleet destinations.
+ Filter to only allow placements in these locations: `us-east-1`, `us-east-2`. `us-west-2`, and `ca-central-1`.
+ Priority order based on cost and then locations in a specified order.

```
aws gamelift create-game-session-queue \
    --name "sample-test-queue" \
    --timeout-in-seconds 300 \
    --destinations DestinationArn="arn:aws:gamelift:us-east-1:111122223333:fleet/fleet-772266ba-8c82-4a6e-b620-a74a62a93ff8" DestinationArn="arn:aws:gamelift:us-east-1:111122223333:fleet/fleet-33f28fb6-aa8b-4867-85b4-ceb217bf5994" \
    --filter-configuration "AllowedLocations=us-east-1, ca-central-1, us-east-2, us-west-2" \
    --priority-configuration PriorityOrder="COST","LOCATION",LocationOrder="us-east-1","us-east-2","ca-central-1","us-west-2" \
    --notification-target "arn:aws:sns:us-east-1:111122223333:gamelift-test.fifo"
```

**Note**  
You can get fleet and alias ARN values by calling either [describe-fleet-attributes](https://docs.aws.amazon.com/cli/latest/reference/gamelift/describe-fleet-attributes.html) or [describe-alias](https://docs.aws.amazon.com/cli/latest/reference/gamelift/describe-alias.html) with the fleet or alias ID.

If the `create-game-session-queue` request is successful, Amazon GameLift Servers returns a [GameSessionQueue](https://docs.aws.amazon.com/gamelift/latest/apireference/API_GameSessionQueue.html) object with the new queue configuration. You can now submit requests to the queue using [StartGameSessionPlacement](https://docs.aws.amazon.com/gamelift/latest/apireference/API_StartGameSessionPlacement.html). 

**Example Create a queue with player latency policies**  
The following example creates a game session queue with these configurations:  
+ A ten minute timeout
+ Three fleet destinations
+ A set of player latency policies

```
aws gamelift create-game-session-queue \
    --name "matchmaker-queue" \
    --timeout-in-seconds 600 \
    --destinations DestinationArn=arn:aws:gamelift:us-east-1::alias/alias-a1234567-b8c9-0d1e-2fa3-b45c6d7e8910 \
               DestinationArn=arn:aws:gamelift:us-west-2::alias/alias-b0234567-c8d9-0e1f-2ab3-c45d6e7f8901 \
               DestinationArn=arn:aws:gamelift:us-west-2::fleet/fleet-f1234567-b8c9-0d1e-2fa3-b45c6d7e8912 \
    --player-latency-policies "MaximumIndividualPlayerLatencyMilliseconds=50,PolicyDurationSeconds=120" \
               "MaximumIndividualPlayerLatencyMilliseconds=100,PolicyDurationSeconds=120" \
               "MaximumIndividualPlayerLatencyMilliseconds=150" \
```

If the `create-game-session-queue` request is successful, Amazon GameLift Servers returns a [GameSessionQueue](https://docs.aws.amazon.com/gamelift/latest/apireference/API_GameSessionQueue.html) object with the new queue configuration. 

------

# Set up event notification for game session placement
<a name="queue-notification"></a>

You can use event notifications to monitor the status of individual placement requests. We recommend setting up event notifications for all games with high-volume placement activity.

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

For a list of game session placement events emitted by Amazon GameLift Servers, see [Game session placement events](queue-events.md).

**Important**  
For high-volume placement 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 queue placement notifications.

## Set up an SNS topic
<a name="queue-notification-sns"></a>

For Amazon GameLift Servers to publish all events generated by a game session queue to a topic, set the notification target field to a topic. 

**To set up an SNS topic for Amazon GameLift Servers event notification**

1. Sign in to the AWS Management Console and open the Amazon SNS console at [https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home).

1. From the SNS **Topics** page, choose **Create topic** and follow the instructions to create your topic.

1. Under **Access policy**, do the following:

   1. Choose the **Advanced** method.

   1. Add the following bolded section of the JSON object to the existing policy.

------
#### [ 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": "your_account"
              }
            }
          },
          {
            "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:gamesessionqueue/your_queue_name"
              }
            }
          }
        ]
      }
      ```

------

   1. (Optional) Add additional access control to the topic by adding conditions to the resource policy. 

1. Choose **Create topic**.

1. After you've created your SNS topic, add it to queues during queue creation, or edit an existing queue to add it.

## Set up an SNS topic with server-side encryption
<a name="queue-notification-sns-sse"></a>

With server-side encryption (SSE), you can store sensitive data in encrypted topics. SSE protects the contents of messages in Amazon SNS topics using keys that are 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:gamesessionqueue/your_queue_name" 
        },
        "StringEquals": { 
            "kms:EncryptionContext:aws:sns:topicArn": "arn:aws:sns:your_region:your_account:your_sns_topic_name" 
        }
    }
}
```

## Set up EventBridge
<a name="queue-notification-cwe"></a>

Amazon GameLift Servers automatically posts all game session placement events to EventBridge. With EventBridge you can set up rules to have events routed to targets for processing. For example, you can set a rule to route the event `PlacementFulfilled` to an AWS Lambda function that handles tasks that precede connecting to a game session. For more information about EventBridge, see [What is Amazon EventBridge?](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) in the *Amazon EventBridge User Guide*.

The following are some examples of EventBridge rules to use with Amazon GameLift Servers queues:

Matches events from all Amazon GameLift Servers queues

```
{
    "source": [
        "aws.gamelift"
    ],
    "detail-type": [
        "GameLift Queue Placement Event"
    ]
}
```

Matches events from a specific queue

```
{
    "source": [
        "aws.gamelift"
    ],
    "detail-type": [
        "GameLift Queue Placement Event"
    ],
    "resources": [
        "arn:aws:gamelift:your_region:your_account:gamesessionqueue/your_queue_name"
    ]
}
```

## Reference implementation with AWS CDK
<a name="queue-notification-toolkit"></a>

For a complete reference implementation of event-based game session placement using Amazon SNS, AWS Lambda, and Amazon DynamoDB, see the [ Event-based game session placement guidance](https://github.com/amazon-gamelift/amazon-gamelift-toolkit/tree/main/event-based-session-placement) in the Amazon GameLift Toolkit. This guidance includes an AWS CDK template for deploying a complete event-driven game session placement system with an AWS Lambda function for processing game session placement events, an Amazon DynamoDB table for tracking game session placement state, and best practices for Amazon GameLift Servers queue configuration.