

# Monitoring with Performance Insights
<a name="performance-insights"></a>

Performance Insights adds to the existing Amazon DocumentDB monitoring features to illustrate your cluster performance and help you analyze any issues that affect it. With the Performance Insights dashboard, you can visualize the database load and filter the load by waits, query statements, hosts, or application.

**Note**  
Performance Insights is only available for Amazon DocumentDB 3.6, 4.0, 5.0, and 8.0 instance-based clusters.

**How is it useful?**
+ Visualize database performance — Visualize the load to determine when and where the load is on the database
+ Determine what is causing load on database — Determine which queries, hosts, and applications are contributing to the load on your instance
+ Determine when there is load on your database — Zoom in on the Performance Insights dashboard to focus on specific events or zoom out to look at trends across a larger time span
+ Alert on database load — Access new database load metrics automatically from CloudWatch where you can monitor the DB load metrics alongside other Amazon DocumentDB metrics and set alerts on them

**What are the limitations of Amazon DocumentDB Performance Insights?**
+ Performance Insights in the AWS GovCloud (US-East) and AWS GovCloud (US-West) regions are not available
+ Performance Insights for Amazon DocumentDB retains up to 7 days of performance data
+ Queries longer than 1,024 bytes are not aggregated in Performance Insights

**Topics**
+ [Performance Insights concepts](performance-insights-concepts.md)
+ [Enabling and disabling Performance Insights](performance-insights-enabling.md)
+ [Configuring access policies for Performance Insights](performance-insights-policies.md)
+ [Analyzing metrics with the Performance Insights dashboard](performance-insights-analyzing.md)
+ [Retrieving metrics with the Performance Insights API](performance-insights-metrics.md)
+ [Amazon CloudWatch metrics for Performance Insights](performance-insights-cloudwatch.md)
+ [Performance Insights for counter metrics](performance-insights-counter-metrics.md)

# Performance Insights concepts
<a name="performance-insights-concepts"></a>

**Topics**
+ [Average active sessions](#performance-insights-concepts-sessions)
+ [Dimensions](#performance-insights-concepts-dimensions)
+ [Max vCPU](#performance-insights-concepts-maxvcpu)

## Average active sessions
<a name="performance-insights-concepts-sessions"></a>

Database load (DB load) measures the level of activity in your database. The key metric in Performance Insights is `DB Load`, which is collected every second. The unit for the `DBLoad` metric is the *Average Active Sessions (AAS)* for an Amazon DocumentDB instance.

An *active* session is a connection that has submitted work to the Amazon DocumentDB instance and is waiting for a response. For example, if you submit a query to an Amazon DocumentDB instance, the database session is active while the instance is processing the query.

To obtain the average active sessions, Performance Insights samples the number of sessions concurrently running a query. The AAS is the total number of sessions divided by the total number of samples. The following table shows five consecutive samples of a running query.


| Sample | Number of sessions running query | AAS | Calculation | 
| --- | --- | --- | --- | 
|  1  |  2  |  2  |  2 sessions / 1 sample  | 
|  2  |  0  |  1  |  2 sessions / 2 samples  | 
|  3  |  4  |  2  |  6 sessions / 3 samples  | 
|  4  |  0  |  1.5  |  6 sessions / 4 samples  | 
|  5  |  4  |  2  |  10 sessions / 5 samples  | 

In the preceding example, the DB Load for the time interval from 1-5 is 2 AAS. An increase in DB load means that, on average, more sessions are running on the database.

## Dimensions
<a name="performance-insights-concepts-dimensions"></a>

The `DB Load` metric is different from the other time-series metrics because you can break it into subcomponents called dimensions. You can think of dimensions as categories for the different characteristics of the `DB Load` metric. When you are diagnosing performance issues, the most useful dimensions are **wait states** and **top query**.

**wait states**  
A *wait state *causes a query statement to wait for a specific event to happen before it can continue running. For example, a query statement might wait until a locked resource is unlocked. By combining `DB Load` with wait states, you can get a complete picture of the session state. Here are various Amazon DocumentDB wait states:


| Amazon DocumentDB wait state | Wait State Description | 
| --- | --- | 
|  Latch  |  The Latch wait state occurs when the session is waiting to page the buffer pool. Frequent paging in and out of the buffer pool can happen more often when there are frequent large queries being processed by the system, collection scans, or when the buffer pool is too small to handle the working set.  | 
| CPU |  The CPU wait state occurs when the session is waiting on CPU.  | 
|  CollectionLock  |  The CollectionLock wait state occurs when the session is waiting to acquire a lock on the collection. These events occur when there are DDL operations on the collection.  | 
| DocumentLock |  The DocumentLock wait state occurs when the session is waiting to acquire a lock on a document. High number of concurrent writes to the same document will contribute to more DocumentLock wait states on that document.   | 
|  SystemLock  |  The SystemLock wait state occurs when the session is waiting on the system. This can occur when there are frequent long running queries, long running transactions, or high concurrency on the system.  | 
|  IO  |  The IO wait state occurs when the session waiting on IO to complete.  | 
|  BufferLock  |  The BufferLock wait state occurs when the session is waiting to acquire a lock on a shared page in the buffer. BufferLock wait states can be prolonged if other processes are holding open cursors on the requested pages.   | 
|  LowMemThrottle  |  The LowMemThrottle wait state occurs when the session is waiting due to heavy memory pressure on the Amazon DocumentDB instance. If this state persists for a long time, consider scaling up the instance to provide additional memory. For more information, see [Resource Governor](https://docs.aws.amazon.com/documentdb/latest/developerguide/how-it-works.html).  | 
|  BackgroundActivity  |  The BackgroundActivity wait state occurs when the session is waiting on internal system processes.  | 
|  Other  |  The Other wait state is an internal wait state. If this state persists for a long time, consider terminating this query. For more information, see [How Do I Find and Terminate Long Running or Blocked Queries?](https://docs.aws.amazon.com/documentdb/latest/developerguide/user_diagnostics.html#user_diagnostics-query_terminating.html)  | 

**Top queries**  
Whereas wait states show bottlenecks, top queries show which queries are contributing the most to DB load. For example, many queries might be currently running on the database, but a single query might consume 99% of the DB load. In this case, the high load might indicate a problem with the query.

## Max vCPU
<a name="performance-insights-concepts-maxvcpu"></a>

In the dashboard, the **Database load** chart collects, aggregates, and displays session information. To see whether active sessions are exceeding the maximum CPU, look at their relationship to the **Max vCPU** line. The **Max vCPU** value is determined by the number of vCPU (virtual CPU) cores for your Amazon DocumentDB instance.

If the DB load is often above the **Max vCPU** line, and the primary wait state is CPU, the CPU is overloaded. In this case, you might want to throttle connections to the instance, tune any queries with a high CPU load, or consider a larger instance class. High and consistent instances of any wait state indicate that there might be bottlenecks or resource contention issues to resolve. This can be true even if the DB load doesn't cross the **Max vCPU** line.

# Enabling and disabling Performance Insights
<a name="performance-insights-enabling"></a>

To use Performance Insights, enable it on your DB instance. You can disable it later if necessary. Enabling and disabling Performance Insights doesn't cause downtime, a reboot, or a failover.

The Performance Insights agent consumes limited CPU and memory on the DB host. When the DB load is high, the agent limits the performance impact by collecting data less frequently.

## Enabling Performance Insights when creating a cluster
<a name="performance-insights-enabling-create-instance"></a>

In the console, you can enable or disable Performance Insights when you create or modify a new DB instance.

### Using the AWS Management Console
<a name="create-instance-console"></a>

In the console, you can enable Performance Insights when you create an Amazon DocumentDB cluster. When you create a new Amazon DocumentDB cluster, enable Performance Insights by choosing **Enable Performance Insights** in the **Performance Insights** section.

**Console instructions**

1. To create a cluster, follow the instructions for [Creating an Amazon DocumentDB cluster.](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-create.html)

1. Select **Enable Performance Insights** in the Performance Insights section.  
![\[The Performance Insights section with Enable Performance Insights selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/select-performance-insights.png)
**Note**  
The Performance Insights data retention period will be seven days.

   ** AWS KMS key** — Specify your AWS KMS key. Performance Insights encrypts all potentially sensitive data using your AWS KMS key. Data is encrypted in flight and at rest. For more information, see Configuring an AWS AWS KMS policy for Performance Insights.

## Enabling and disabling when modifying an instance
<a name="performance-insights-enabling-modify-instance"></a>

You can modify a DB instance to enable or disable Performance Insights using the console or AWS CLI.

------
#### [ Using the AWS Management Console ]

**Console instructions**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. Choose **Clusters**.

1. Choose a DB instance, and choose **Modify**.

1. In the Performance Insights section, choose either **Enable Performance Insights** or **Disable Performance Insights**.
**Note**  
If you choose **Enable Performance Insights**, you can specify your AWS AWS KMS key. Performance Insights encrypts all potentially sensitive data using your AWS KMS key. Data is encrypted in flight and at rest. For more information, see [Encrypting Amazon DocumentDB Data at Rest](https://docs.aws.amazon.com/documentdb/latest/developerguide/encryption-at-rest.html).

1. Choose **Continue**.

1. For **Scheduling of Modifications**, choose **Apply immediately**. If you choose **Apply during the next scheduled maintenance window**, your instance ignores this setting and enables Performance Insights immediately.

1. Choose **Modify instance**.

------
#### [ Using the AWS CLI ]

When you use the `create-db-instance` or `modify-db-instance` AWS AWS CLI commands, you can enable Performance Insights by specifying `--enable-performance-insights`, or disable it by specifying `--no-enable-performance-insights`.

The following procedure describes how to enable or disable Performance Insights for a DB instance using the AWS AWS CLI.



**AWS AWS CLI instructions**

Call the `modify-db-instance` AWS AWS CLI command and provide the following values:
+ `--db-instance-identifer` — The name of the DB instance
+ `--enable-performance-insights` to enable or `--no-enable-performance-insights` to disable

**Example**  
The following example enables Performance Insights for `sample-db-instance`:  

```
aws docdb modify-db-instance \
    --db-instance-identifier sample-db-instance \
    --enable-performance-insights
```

```
aws docdb modify-db-instance ^
    --db-instance-identifier sample-db-instance ^
    --enable-performance-insights
```

------

# Configuring access policies for Performance Insights
<a name="performance-insights-policies"></a>

To access Performance Insights, you must have the appropriate permissions from AWS Identity and Access Management (IAM). You have the following options for granting access:
+ Attach the `AmazonRDSPerformanceInsightsReadOnly` managed policy to a permission set or role.
+ Create a custom IAM policy and attach it to a permission set or role.

Also, if you specified a customer managed key when you turned on Performance Insights, make sure that users in your account have the `kms:Decrypt` and `kms:GenerateDataKey` permissions on the KMS key.

**Note**  
For encryption-at-rest with AWS KMS keys and security groups management, Amazon DocumentDB leverages operational technology that is shared with [Amazon RDS](https://aws.amazon.com/rds).

## Attaching the AmazonRDSPerformanceInsightsReadOnly policy to an IAM principal
<a name="USER_PerfInsights.access-control.IAM-principal"></a>

`AmazonRDSPerformanceInsightsReadOnly` is an AWS-managed policy that grants access to all read-only operations of the Amazon DocumentDB Performance Insights API. Currently, all operations in this API are read-only. If you attach `AmazonRDSPerformanceInsightsReadOnly` to a permission set or role, the recipient can use Performance Insights with other console features.

## Creating a custom IAM policy for Performance Insights
<a name="USER_PerfInsights.access-control.custom-policy"></a>

For users who don't have the `AmazonRDSPerformanceInsightsReadOnly` policy, you can grant access to Performance Insights by creating or modifying a user-managed IAM policy. When you attach the policy to a permission set or role, the recipient can use Performance Insights.

**To create a custom policy**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

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

1. Choose **Create policy**.

1. On the **Create Policy** page, choose the JSON tab. 

1. Copy and paste the following text, replacing *us-east-1* with the name of your AWS Region and *111122223333* with your customer account number.

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "rds:DescribeDBInstances",
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": "rds:DescribeDBClusters",
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": "pi:DescribeDimensionKeys",
               "Resource": "arn:aws:pi:us-east-1:111122223333:metrics/rds/*"
           },
           {
               "Effect": "Allow",
               "Action": "pi:GetDimensionKeyDetails",
               "Resource": "arn:aws:pi:us-east-1:111122223333:metrics/rds/*"
           },
           {
               "Effect": "Allow",
               "Action": "pi:GetResourceMetadata",
               "Resource": "arn:aws:pi:us-east-1:111122223333:metrics/rds/*"
           },
           {
               "Effect": "Allow",
               "Action": "pi:GetResourceMetrics",
               "Resource": "arn:aws:pi:us-east-1:111122223333:metrics/rds/*"
           },
           {
               "Effect": "Allow",
               "Action": "pi:ListAvailableResourceDimensions",
               "Resource": "arn:aws:pi:us-east-1:111122223333:metrics/rds/*"
           },
           {
               "Effect": "Allow",
               "Action": "pi:ListAvailableResourceMetrics",
               "Resource": "arn:aws:pi:us-east-1:111122223333:metrics/rds/*"
           }
       ]
   }
   ```

------

1. Choose **Review policy**.

1. Provide a name for the policy and optionally a description, and then choose **Create policy**.

You can now attach the policy to a permission set or role. The following procedure assumes that you already have a user available for this purpose.

**To attach the policy to a user**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

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

1. Choose an existing user from the list.
**Important**  
To use Performance Insights, make sure that you have access to Amazon DocumentDB in addition to the custom policy. For example, the **AmazonDocDBReadOnlyAccess** predefined policy provides read-only access to Amazon DocDB.For more information, see [Managing access using policies](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAM.html#security_iam_access-manage).

1. On the **Summary** page, choose **Add permissions**.

1. Choose **Attach existing policies directly**. For **Search**, type the first few characters of your policy name, as shown following.  
![\[Choose a Policy\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/pi-add-permissions.png)

1. Choose your policy, and then choose **Next: Review**.

1. Choose **Add permissions**.

## Configuring an AWS KMS policy for Performance Insights
<a name="USER_PerfInsights.access-control.cmk-policy"></a>

Performance Insights uses an AWS KMS key to encrypt sensitive data. When you enable Performance Insights through the API or the console, you have the following options:
+ Choose the default AWS managed key.

  Amazon DocumentDB uses the AWS managed key for your new DB instance. Amazon DocumentDB creates an AWS managed key for your AWS account. Your AWS account has a different AWS managed key for Amazon DocumentDB for each AWS Region.
+ Choose a customer managed key.

  If you specify a customer managed key, users in your account that call the Performance Insights API need the `kms:Decrypt` and `kms:GenerateDataKey` permissions on the KMS key. You can configure these permissions through IAM policies. However, we recommend that you manage these permissions through your KMS key policy. For more information, see [ Using key policies in AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html). 

**Example**  
The following sample key policy shows how to add statements to your KMS key policy. These statements allow access to Performance Insights. Depending on how you use the AWS KMS, you might want to change some restrictions. Before adding statements to your policy, remove all comments.

# Analyzing metrics with the Performance Insights dashboard
<a name="performance-insights-analyzing"></a>

The Performance Insights dashboard contains database performance information to help you analyze and troubleshoot performance issues. On the main dashboard page, you can view information about the database load (DB load). You can "slice" DB load by dimensions such as wait states or query. 

**Topics**
+ [Overview of the Performance Insights dashboard](performance-insights-dashboard-overview.md)
+ [Opening the Performance Insights dashboard](performance-insights-dashboard-opening.md)
+ [Analyzing database load by wait states](performance-insights-analyzing-db-load.md)
+ [Overview of the Top queries tab](performance-insights-top-queries.md)
+ [Zooming in on the database load chart](performance-insights-zoom-db-load.md)

# Overview of the Performance Insights dashboard
<a name="performance-insights-dashboard-overview"></a>

The dashboard is the easiest way to interact with Performance Insights. The following example shows the dashboard for an Amazon DocumentDB instance. By default, the Performance Insights dashboard shows data for the last hour.

![\[Performance Insights dashboard showing CPU utilization and database load over time for an Amazon DocumentDB instance.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/overview-dashboard.png)


The dashboard is divided into the following parts:

1. **Counter metrics** – Shows data for specific performance counter metrics.

1. **Database load** – Shows how the DB load compares to DB instance capacity as represented by the **Max vCPU** line.

1.  **Top dimensions** – Shows the top dimensions contributing to DB load. These dimensions include `waits`, `queries`, `hosts`, `databases`, and `applications`.

**Topics**
+ [Counter metrics chart](#performance-insights-overview-metrics)
+ [Database load chart](#performance-insights-overview-db-load-chart)
+ [Top dimensions table](#performance-insights-overview-top-dimensions)

## Counter metrics chart
<a name="performance-insights-overview-metrics"></a>

With counter metrics, you can customize the Performance Insights dashboard to include up to 10 additional graphs. These graphs show a selection of dozens of operating system metrics. You can correlate this information with DB load to help identify and analyze performance problems.

The **Counter metrics** chart displays data for performance counters.

![\[Counter metrics chart showing CPU utilization over time.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/counter-metrics.png)


To change the performance counters, choose **Manage metrics**. You can select multiple **OS metrics** as shown in the following screenshot. To see details for any metric, hover over the metric name.

![\[Performance Insights dashboard metric selection interface with OS metrics options.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/overview-os-metrics.png)


## Database load chart
<a name="performance-insights-overview-db-load-chart"></a>

The **Database load** chart shows how the database activity compares to instance capacity as represented by the **Max vCPU** line. By default, the stacked line chart represents DB load as average active sessions per unit of time. The DB load is sliced (grouped) by wait states.

![\[Database load chart showing average active sessions over time, with CPU usage spiking near the end.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/database-load.png)


**DB load sliced by dimensions**  
You can choose to display load as active sessions grouped by any supported dimensions. The following image shows the dimensions for the Amazon DocumentDB instance.

![\[Graph showing database load with various "Slice by" options displayed in a dropdown list.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/database-load-sliced.png)


**DB load details for a dimension item**  
To see details about a DB load item within a dimension, hover over the item name. The following image shows details for a query statement.

![\[Bar graph showing database load with additional details displayed upon hovering over an item name.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/database-load-details.png)


To see details for any item for the selected time period in the legend, hover over that item.

![\[Bar graph showing database load with additional details displayed upon hovering over a bar.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/database-load-hover.png)


## Top dimensions table
<a name="performance-insights-overview-top-dimensions"></a>

The **Top dimensions table** slices DB load by different dimensions. A dimension is a category or "slice by" for different characteristics of DB load. If the dimension is query, **Top queries **shows the query statements that contribute most to the DB load.

Choose any of the following dimension tabs.

![\[The Top queries dimensions tab showing the two top queries.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/top-dimensions.png)


The following table provides a brief description of each tab.


| Tab | Description | 
| --- | --- | 
|  Top waits  |   The event for which the database backend is waiting  | 
|  Top queries  |  The query statements that are currently running  | 
|  Top hosts  |  The host IP and port of the connected client  | 
|  Top databases  |  The name of the database to which the client is connected  | 
|  Top applications  |  The name of the application that is connected to the database  | 

To learn how to analyze queries by using the **Top queries** tab, see [Overview of the Top queries tab](performance-insights-top-queries.md).

# Opening the Performance Insights dashboard
<a name="performance-insights-dashboard-opening"></a>

**To view the Performance Insights dashboard in the AWS Management Console, use the following steps:**

1. Open the Performance Insights console at [https://console.aws.amazon.com/docdb/](https://console.aws.amazon.com/docdb/home#performance-insights).

1. Choose a DB instance. The Performance Insights dashboard is shown for that Amazon DocumentDB instance.

   For Amazon DocumentDB instances with Performance Insights enabled, you can also reach the dashboard by choosing the **Sessions** item in the list of instances. Under **Current activity**, the **Sessions** item shows the database load in average active sessions over the last five minutes. The bar graphically shows the load. When the bar is empty, the instance is idle. As the load increases, the bar fills with blue. When the load passes the number of virtual CPUs (vCPUs) on the instance class, the bar turns red, indicating a potential bottleneck.  
![\[The Clusters page showing an Amazon DocumentDB regional cluster and the CPU and current activity of each cluster instance.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/opening-clusters.png)

1. (Optional) Choose a different time interval by selecting a button in the upper right. For example, to change the interval to 1 hour, select **1h**.  
![\[Time interval buttons ranging from five minutes to one week.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/opening-time.png)

   In the following screenshot, the DB load interval is 1 hour.  
![\[Bar graph showing database load measured in average active sessions.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/opening-db-load.png)

1. To refresh your data automatically, enable **Auto refresh**.  
![\[The auto refresh button enabled, appearing next to the time interval buttons.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/opening-auto-refresh.png)

   The Performance Insight dashboard automatically refreshes with new data. The refresh rate depends on the amount of data displayed: 
   + 5 minutes refreshes every 5 seconds.
   + 1 hour refreshes every minute.
   + 5 hours refreshes every minute.
   + 24 hours refreshes every 5 minutes.
   + 1 week refreshes every hour.

# Analyzing database load by wait states
<a name="performance-insights-analyzing-db-load"></a>

If the **Database load (DB load)** chart shows a bottleneck, you can find out where the load is coming from. To do so, look at the top load items table below the **Database load** chart. Choose a particular item, like a query or an application, to drill down into that item and see details about it.

DB load grouped by waits and top queries typically provides the most insight into performance issues. DB load grouped by waits shows if there are any resource or concurrency bottlenecks in the database. In this case, the **Top queries** tab of the top load items table shows which queries are driving that load.

Your typical workflow for diagnosing performance issues is as follows:

1. Review the **Database load** chart and see if there are any incidents of database load exceeding the **Max CPU** line.

1. If there is, look at the **Database load** chart and identify which wait state or states are primarily responsible.

1. Identify the digest queries causing the load by seeing which of the queries the **Top queries** tab on the top load items table are contributing most to those wait states. You can identify these by the **Load by Wait (AAS)** column.

1. Choose one of these digest queries in the **Top queries** tab to expand it and see the child queries that it is composed of.

You can also see which hosts or applications are contributing the most load by selecting **Top hosts** or **Top applications**, respectively. Application names are specified in the connection string to the Amazon DocumentDB instance. `Unknown` indicates that the application field was not specified. 

For example, in the following dashboard, **CPU** waits account for most of the DB load. Selecting the top query under **Top queries** will scope the Database load chart to focus on the most load that is being contributed by the select query.

![\[Database load chart showing CPU usage spike. A corresponding Top queries tab shows queries contributing the most to wait states.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/db-load-1.png)


![\[Database load chart showing CPU usage spike for the query contributing the most to wait states. A corresponding Top queries tab shows that query's child queries.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/db-load-2.png)


# Overview of the Top queries tab
<a name="performance-insights-top-queries"></a>

By default, the **Top query** tab shows the queries that are contributing the most to DB load. You can analyze the query text to help tune your queries.

**Topics**
+ [Query digests](#performance-insights-top-queries-digests)
+ [Load by waits (AAS)](#performance-insights-top-queries-aas)
+ [Viewing detailed query information](#performance-insights-top-queries-query-info)
+ [Accessing statement query text](#performance-insights-top-queries-accessing-text)
+ [Viewing and downloading statement query text](#performance-insights-top-queries-viewing-downloading)

## Query digests
<a name="performance-insights-top-queries-digests"></a>

A *query digest* is a composite of multiple actual queries that are structurally similar but might have different literal values. The digest replaces hardcoded values with a question mark. For example, a query digest might look like this:

```
{"find":"customerscollection","filter":{"FirstName":"?"},"sort":{"key":{"$numberInt":"?"}},"limit":{"$numberInt":"?"}}
```

This digest might include the following child queries:

```
{"find":"customerscollection","filter":{"FirstName":"Karrie"},"sort":{"key":{"$numberInt":"1"}},"limit":{"$numberInt":"3"}}
{"find":"customerscollection","filter":{"FirstName":"Met"},"sort":{"key":{"$numberInt":"1"}},"limit":{"$numberInt":"3"}}
{"find":"customerscollection","filter":{"FirstName":"Rashin"},"sort":{"key":{"$numberInt":"1"}},"limit":{"$numberInt":"3"}}
```

To see the literal query statements in a digest, select the query, and then choose the plus symbol (`+`). In the following screenshot, the selected query is a digest.

![\[The Top queries table showing an expanded query digest with one child query selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/top-queries-literal.png)


**Note**  
A query digest groups similar query statements, but does not redact sensitive information. 

## Load by waits (AAS)
<a name="performance-insights-top-queries-aas"></a>

In **Top queries**, the **Load by waits (AAS)** column illustrates the percentage of the database load associated with each top load item. This column reflects the load for that item by whatever grouping is currently selected in the **DB load chart**. For example, you might group the **DB load chart** by wait states. In this case, the **DB Load by Waits** bar is sized, segmented, and color-coded to show how much of a given wait state that query is contributing to. It also shows which wait states are affecting the selected query.

![\[Bar chart showing database load grouped by CPU, IO, and latch wait states. The corresponding table shows the top queries based on load by wait.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/top-queries-aas.png)


## Viewing detailed query information
<a name="performance-insights-top-queries-query-info"></a>

In the **Top query** table, you can open a *digest statement* to view its information. The information appears in the bottom pane.

![\[The Top queries table showing a selected query statement and its query information below.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/top-queries-detailed.png)


The following types of identifiers (IDs) are associated with query statements:

1. **Support query ID** – A hash value of the query ID. This value is only for referencing a query ID when you are working with AWS Support. AWS Support doesn't have access to your actual query IDs and query text.

1. **Support digest ID** – A hash value of the digest ID. This value is only for referencing a digest ID when you are working with AWS Support. AWS Support doesn't have access to your actual digest IDs and query text.

## Accessing statement query text
<a name="performance-insights-top-queries-accessing-text"></a>

By default, each row in the **Top queries** table shows 500 bytes of query text for each query statement. When a digest statement exceeds 500 bytes, you can view more text by opening the statement in the Performance Insights dashboard. In this case, the maximum length for the displayed query is 1 KB. If you view a full query statement, you can also choose **Download**.

## Viewing and downloading statement query text
<a name="performance-insights-top-queries-viewing-downloading"></a>

In the Performance Insights dashboard, you can view or download query text.

**To view more query text in the Performance Insights dashboard**

1. Open the Amazon DocumentDB console at: [https://console.aws.amazon.com/docdb/](https://console.aws.amazon.com/docdb/) 

1. In the navigation pane, choose **Performance Insights**.

1. Choose a DB instance. The Performance Insights dashboard is displayed for that DB instance.

   Query statements with text larger than 500 bytes will look like the following image:  
![\[The Top queries table with a child query selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/top-queries-statement.png)

1. Examine the query information section to view more of the query text.  
![\[The Query information section showing the full text of the selected query.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/top-queries-query-text.png)

The Performance Insights dashboard can display up to 1 KB for each full query statement.

**Note**  
To copy or download the query statement, disable any pop-up blockers.

# Zooming in on the database load chart
<a name="performance-insights-zoom-db-load"></a>

You can use other features of the Performance Insights user interface to help analyze performance data.

**Click-and-Drag Zoom In**  
In the Performance Insights interface, you can choose a small portion of the load chart and zoom in on the detail.

![\[Bar chart showing database load, with a portion of it highlighted for zooming in.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/pi-zoom-1.png)


To zoom in on a portion of the load chart, choose the start time and drag to the end of the time period you want. When you do this, the selected area is highlighted. When you release the mouse, the load chart zooms in on the selected area, and the **Top *items*** table is recalculated.

![\[Database load bar chart showing zoomed-in portion, with corresponding Top waits table below.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/pi-zoom-2.png)


# Retrieving metrics with the Performance Insights API
<a name="performance-insights-metrics"></a>

When Performance Insights is enabled, the API provides visibility into instance performance. Amazon CloudWatch Logs provides the authoritative source for vended monitoring metrics for AWS services.

Performance Insights offers a domain-specific view of database load measured as average active sessions (AAS). This metric appears to API consumers as a two-dimensional time-series dataset. The time dimension of the data provides DB load data for each time point in the queried time range. Each time point decomposes overall load in relation to the requested dimensions, such as `Query`, `Wait-state`, `Application`, or `Host`, measured at that time point.

Amazon DocumentDB Performance Insights monitors your Amazon DocumentDB DB instance so that you can analyze and troubleshoot database performance. One way to view Performance Insights data is in the AWS Management Console. Performance Insights also provides a public API so that you can query your own data. You can use the API to do the following:
+ Offload data into a database
+ Add Performance Insights data to existing monitoring dashboards
+ Build monitoring tools

To use the Performance Insights API, enable Performance Insights on one of your Amazon DocumentDB instances. For information about enabling Performance Insights, see [Enabling and disabling Performance Insights](performance-insights-enabling.md). For more information about the Performance Insights API, see the [ Performance Insights API Reference](https://docs.aws.amazon.com/performance-insights/latest/APIReference/Welcome.html).

The Performance Insights API provides the following operations.


****  

|  Performance Insights action  |  AWS CLI command  |  Description  | 
| --- | --- | --- | 
|  [https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_DescribeDimensionKeys.html](https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_DescribeDimensionKeys.html)  |  [https://docs.aws.amazon.com/cli/latest/reference/pi/describe-dimension-keys.html](https://docs.aws.amazon.com/cli/latest/reference/pi/describe-dimension-keys.html)  |  Retrieves the top N dimension keys for a metric for a specific time period.  | 
|  [https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_GetDimensionKeyDetails.html](https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_GetDimensionKeyDetails.html)  |  [https://docs.aws.amazon.com/cli/latest/reference/pi/get-dimension-key-details.html](https://docs.aws.amazon.com/cli/latest/reference/pi/get-dimension-key-details.html)  |  Retrieves the attributes of the specified dimension group for a DB instance or data source. For example, if you specify a query ID, and if the dimension details are available, `GetDimensionKeyDetails` retrieves the full text of the dimension `db.query.statement` associated with this ID. This operation is useful because `GetResourceMetrics` and `DescribeDimensionKeys` don't support retrieval of large query statement text.   | 
| [GetResourceMetadata](https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_GetResourceMetadata.html) |  [https://docs.aws.amazon.com/cli/latest/reference/pi/get-resource-metadata.html](https://docs.aws.amazon.com/cli/latest/reference/pi/get-resource-metadata.html)  |  Retrieve the metadata for different features. For example, the metadata might indicate that a feature is turned on or off on a specific DB instance.   | 
|  [https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_GetResourceMetrics.html](https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_GetResourceMetrics.html)  |  [https://docs.aws.amazon.com/cli/latest/reference/pi/get-resource-metrics.html](https://docs.aws.amazon.com/cli/latest/reference/pi/get-resource-metrics.html)  |  Retrieves Performance Insights metrics for a set of data sources over a time period. You can provide specific dimension groups and dimensions, and provide aggregation and filtering criteria for each group.  | 
| [ListAvailableResourceDimensions](https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_ListAvailableResourceDimensions.html) |  [https://docs.aws.amazon.com/cli/latest/reference/pi/list-available-resource-dimensions.html](https://docs.aws.amazon.com/cli/latest/reference/pi/list-available-resource-dimensions.html)  |  Retrieve the dimensions that can be queried for each specified metric type on a specified instance.   | 
| [ListAvailableResourceMetrics](https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_ListAvailableResourceMetrics.html) |  [https://docs.aws.amazon.com/cli/latest/reference/pi/list-available-resource-metrics.html](https://docs.aws.amazon.com/cli/latest/reference/pi/list-available-resource-metrics.html)  |  Retrieve all available metrics of the specified metric types that can be queried for a specified DB instance.  | 

**Topics**
+ [AWS CLI for Performance Insights](#performance-insights-metrics-CLI)
+ [Retrieving time-series metrics](#performance-insights-metrics-time-series)
+ [AWS CLI examples for Performance Insights](#performance-insights-metrics-api-examples)

## AWS CLI for Performance Insights
<a name="performance-insights-metrics-CLI"></a>

You can view Performance Insights data using the AWS CLI. You can view help for the AWS CLI commands for Performance Insights by entering the following on the command line.

```
aws pi help
```

If you don't have the AWS CLI installed, see [Installing the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/installing.html) in the *AWS CLI User Guide *for information about installing it.

## Retrieving time-series metrics
<a name="performance-insights-metrics-time-series"></a>

The `GetResourceMetrics` operation retrieves one or more time-series metrics from the Performance Insights data. `GetResourceMetrics` requires a metric and time period, and returns a response with a list of data points. 

For example, the AWS Management Console uses `GetResourceMetrics` to populate the **Counter Metrics** chart and the **Database Load** chart, as seen in the following image.

![\[Counter Metrics and Database Load charts\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/perf-insights-api-charts.png)


All metrics returned by `GetResourceMetrics` are standard time-series metrics, with the exception of `db.load`. This metric is displayed in the **Database Load** chart. The `db.load` metric is different from the other time-series metrics because you can break it into subcomponents called *dimensions*. In the previous image, `db.load` is broken down and grouped by the waits states that make up the `db.load`.

**Note**  
`GetResourceMetrics` can also return the `db.sampleload` metric, but the `db.load` metric is appropriate in most cases.

For information about the counter metrics returned by `GetResourceMetrics`, see [Performance Insights for counter metrics](performance-insights-counter-metrics.md).

The following calculations are supported for the metrics:
+ Average – The average value for the metric over a period of time. Append `.avg` to the metric name.
+ Minimum – The minimum value for the metric over a period of time. Append `.min` to the metric name.
+ Maximum – The maximum value for the metric over a period of time. Append `.max` to the metric name.
+ Sum – The sum of the metric values over a period of time. Append `.sum` to the metric name.
+ Sample count – The number of times the metric was collected over a period of time. Append `.sample_count` to the metric name.

For example, assume that a metric is collected for 300 seconds (5 minutes), and that the metric is collected one time each minute. The values for each minute are 1, 2, 3, 4, and 5. In this case, the following calculations are returned:
+ Average – 3
+ Minimum – 1
+ Maximum – 5
+ Sum – 15
+ Sample count – 5

For information about using the `get-resource-metrics` AWS CLI command, see [https://docs.aws.amazon.com/cli/latest/reference/pi/get-resource-metrics.html](https://docs.aws.amazon.com/cli/latest/reference/pi/get-resource-metrics.html).

For the `--metric-queries` option, specify one or more queries that you want to get results for. Each query consists of a mandatory `Metric` and optional `GroupBy` and `Filter` parameters. The following is an example of a `--metric-queries` option specification.

```
{
   "Metric": "string",
   "GroupBy": {
     "Group": "string",
     "Dimensions": ["string", ...],
     "Limit": integer
   },
   "Filter": {"string": "string"
     ...}
```

## AWS CLI examples for Performance Insights
<a name="performance-insights-metrics-api-examples"></a>

The following examples show how to use the AWS CLI for Performance Insights.

**Topics**
+ [Retrieving counter metrics](#performance-insights-metrics-api-examples.CounterMetrics)
+ [Retrieving the DB load average for top wait states](#performance-insights-metrics-api-examples.DBLoadAverage)
+ [Retrieving the DB load average for top Query](#performance-insights-metrics-api-examples.topquery)
+ [Retrieving the DB load average filtered by Query](#performance-insights-metrics-api-examples.DBLoadAverageByQuery)

### Retrieving counter metrics
<a name="performance-insights-metrics-api-examples.CounterMetrics"></a>

The following screenshot shows two counter metrics charts in the AWS Management Console.

![\[Counter Metrics charts.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/performance-insights/perf-insights-api-counters-charts.png)


The following example shows how to gather the same data that the AWS Management Console uses to generate the two counter metric charts.

For Linux, macOS, or Unix:

```
aws pi get-resource-metrics \
   --service-type DOCDB \
   --identifier db-ID \
   --start-time 2022-03-13T8:00:00Z \
   --end-time   2022-03-13T9:00:00Z \
   --period-in-seconds 60 \
   --metric-queries '[{"Metric": "os.cpuUtilization.user.avg"  },
                      {"Metric": "os.cpuUtilization.idle.avg"}]'
```

For Windows:

```
aws pi get-resource-metrics ^
   --service-type DOCDB ^
   --identifier db-ID ^
   --start-time 2022-03-13T8:00:00Z ^
   --end-time   2022-03-13T9:00:00Z ^
   --period-in-seconds 60 ^
   --metric-queries '[{"Metric": "os.cpuUtilization.user.avg"  },
                      {"Metric": "os.cpuUtilization.idle.avg"}]'
```

You can also make a command easier to read by specifying a file for the `--metrics-query` option. The following example uses a file called query.json for the option. The file has the following contents.

```
[
    {
        "Metric": "os.cpuUtilization.user.avg"
    },
    {
        "Metric": "os.cpuUtilization.idle.avg"
    }
]
```

Run the following command to use the file.

For Linux, macOS, or Unix:

```
aws pi get-resource-metrics \
   --service-type DOCDB \
   --identifier db-ID \
   --start-time 2022-03-13T8:00:00Z \
   --end-time   2022-03-13T9:00:00Z \
   --period-in-seconds 60 \
   --metric-queries file://query.json
```

For Windows:

```
aws pi get-resource-metrics ^
   --service-type DOCDB ^
   --identifier db-ID ^
   --start-time 2022-03-13T8:00:00Z ^
   --end-time   2022-03-13T9:00:00Z ^
   --period-in-seconds 60 ^
   --metric-queries file://query.json
```

The preceding example specifies the following values for the options:
+ `--service-type` – `DOCDB` for Amazon DocumentDB
+ `--identifier` – The resource ID for the DB instance
+ `--start-time` and `--end-time` – The ISO 8601 `DateTime` values for the period to query, with multiple supported formats

It queries for a one-hour time range:
+ `--period-in-seconds` – `60` for a per-minute query
+ `--metric-queries` – An array of two queries, each just for one metric.

  The metric name uses dots to classify the metric in a useful category, with the final element being a function. In the example, the function is `avg` for each query. As with Amazon CloudWatch, the supported functions are `min`, `max`, `total`, and `avg`.

The response looks similar to the following.

```
{
    "AlignedStartTime": "2022-03-13T08:00:00+00:00",
    "AlignedEndTime": "2022-03-13T09:00:00+00:00",
    "Identifier": "db-NQF3TTMFQ3GTOKIMJODMC3KQQ4",
    "MetricList": [
        {
            "Key": {
                "Metric": "os.cpuUtilization.user.avg"
            },
            "DataPoints": [
                {
                    "Timestamp": "2022-03-13T08:01:00+00:00", //Minute1
                    "Value": 3.6
                },
                {
                    "Timestamp": "2022-03-13T08:02:00+00:00", //Minute2
                    "Value": 2.6
                },
                //.... 60 datapoints for the os.cpuUtilization.user.avg metric
        {
            "Key": {
                "Metric": "os.cpuUtilization.idle.avg"
            },
            "DataPoints": [
                {
                    "Timestamp": "2022-03-13T08:01:00+00:00",
                    "Value": 92.7
                },
                {
                    "Timestamp": "2022-03-13T08:02:00+00:00",
                    "Value": 93.7
                },
                //.... 60 datapoints for the os.cpuUtilization.user.avg metric 
            ]
        }
    ] //end of MetricList
} //end of response
```

The response has an `Identifier`, `AlignedStartTime`, and `AlignedEndTime`. B the `--period-in-seconds` value was `60`, the start and end times have been aligned to the minute. If the `--period-in-seconds` was `3600`, the start and end times would have been aligned to the hour.

The `MetricList` in the response has a number of entries, each with a `Key` and a `DataPoints` entry. Each `DataPoint` has a `Timestamp` and a `Value`. Each `Datapoints` list has 60 data points because the queries are for per-minute data over an hour, with `Timestamp1/Minute1`, `Timestamp2/Minute2`, and so on, up to `Timestamp60/Minute60`. 

Because the query is for two different counter metrics, there are two elements in the response `MetricList`.

### Retrieving the DB load average for top wait states
<a name="performance-insights-metrics-api-examples.DBLoadAverage"></a>

The following example is the same query that the AWS Management Console uses to generate a stacked area line graph. This example retrieves the `db.load.avg` for the last hour with load divided according to the top seven wait states. The command is the same as the command in [Retrieving counter metrics](#performance-insights-metrics-api-examples.CounterMetrics). However, the query.json file has the following contents.

```
[
    {
        "Metric": "db.load.avg",
        "GroupBy": { "Group": "db.wait_state", "Limit": 7 }
    }
]
```

Run the following command.

For Linux, macOS, or Unix:

```
aws pi get-resource-metrics \
   --service-type DOCDB \
   --identifier db-ID \
   --start-time 2022-03-13T8:00:00Z \
   --end-time   2022-03-13T9:00:00Z \
   --period-in-seconds 60 \
   --metric-queries file://query.json
```

For Windows:

```
aws pi get-resource-metrics ^
   --service-type DOCDB ^
   --identifier db-ID ^
   --start-time 2022-03-13T8:00:00Z ^
   --end-time   2022-03-13T9:00:00Z ^
   --period-in-seconds 60 ^
   --metric-queries file://query.json
```

The example specifies the metric of `db.load.avg` and a `GroupBy` of the top seven wait states. For details about valid values for this example, see [DimensionGroup](https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_DimensionGroup.html) in the *Performance Insights API Reference.*

The response looks similar to the following.

```
{
    "AlignedStartTime": "2022-04-04T06:00:00+00:00",
    "AlignedEndTime": "2022-04-04T06:15:00+00:00",
    "Identifier": "db-NQF3TTMFQ3GTOKIMJODMC3KQQ4",
    "MetricList": [
        {//A list of key/datapoints
            "Key": {
                //A Metric with no dimensions. This is the total db.load.avg
                "Metric": "db.load.avg"
            },
            "DataPoints": [
                //Each list of datapoints has the same timestamps and same number of items
                {
                    "Timestamp": "2022-04-04T06:01:00+00:00",//Minute1
                    "Value": 0.0
                },
                {
                    "Timestamp": "2022-04-04T06:02:00+00:00",//Minute2
                    "Value": 0.0
                },
                //... 60 datapoints for the total db.load.avg key
                ]
        },
        {
            "Key": {
                //Another key. This is db.load.avg broken down by CPU
                "Metric": "db.load.avg",
                "Dimensions": {
                    "db.wait_state.name": "CPU"
                }
            },
            "DataPoints": [
                {
                    "Timestamp": "2022-04-04T06:01:00+00:00",//Minute1
                    "Value": 0.0
                },
                {
                    "Timestamp": "2022-04-04T06:02:00+00:00",//Minute2
                    "Value": 0.0
                },
                //... 60 datapoints for the CPU key
            ]
        },//... In total we have 3 key/datapoints entries, 1) total, 2-3) Top Wait States
    ] //end of MetricList
} //end of response
```

In this response, there are three entries in the `MetricList`. There is one entry for the total `db.load.avg`, and three entries each for the `db.load.avg` divided according to one of the top three wait states. Since there was a grouping dimension (unlike the first example), there must be one key for each grouping of the metric. There can't be only one key for each metric, as in the basic counter metric use case.

### Retrieving the DB load average for top Query
<a name="performance-insights-metrics-api-examples.topquery"></a>

The following example groups `db.wait_state` by the top 10 query statements. There are two different groups for query statements:
+ `db.query` – The full query statement, such as `{"find":"customers","filter":{"FirstName":"Jesse"},"sort":{"key":{"$numberInt":"1"}}}`
+ `db.query_tokenized` – The tokenized query statement, such as `{"find":"customers","filter":{"FirstName":"?"},"sort":{"key":{"$numberInt":"?"}},"limit":{"$numberInt":"?"}}`

When analyzing database performance, it can be useful to consider query statements that only differ by their parameters as one logic item. So, you can use `db.query_tokenized` when querying. However, especially when you're interested in `explain()`, sometimes it's more useful to examine full query statements with parameters. There is a parent-child relationship between tokenized and full queries, with multiple full queries (children) grouped under the same tokenized query (parent).

The command in this example is the similar to the command in [Retrieving the DB load average for top wait states](#performance-insights-metrics-api-examples.DBLoadAverage). However, the query.json file has the following contents.

```
[
    {
        "Metric": "db.load.avg",
        "GroupBy": { "Group": "db.query_tokenized", "Limit": 10 }
    }
]
```

The following example uses `db.query_tokenized`.

For Linux, macOS, or Unix:

```
aws pi get-resource-metrics \
   --service-type DOCDB \
   --identifier db-ID \
   --start-time 2022-03-13T8:00:00Z \
   --end-time   2022-03-13T9:00:00Z \
   --period-in-seconds 3600 \
   --metric-queries file://query.json
```

For Windows:

```
aws pi get-resource-metrics ^
   --service-type DOCDB ^
   --identifier db-ID ^
   --start-time 2022-03-13T8:00:00Z ^
   --end-time   2022-03-13T9:00:00Z  ^
   --period-in-seconds 3600 ^
   --metric-queries file://query.json
```

This example queries over 1 hour, with a one minute period-in-seconds.

The example specifies the metric of `db.load.avg` and a `GroupBy` of the top seven wait states. For details about valid values for this example, see [DimensionGroup](https://docs.aws.amazon.com/performance-insights/latest/APIReference/API_DimensionGroup.html) in the *Performance Insights API Reference.*

The response looks similar to the following.

```
{
    "AlignedStartTime": "2022-04-04T06:00:00+00:00",
    "AlignedEndTime": "2022-04-04T06:15:00+00:00",
    "Identifier": "db-NQF3TTMFQ3GTOKIMJODMC3KQQ4",
    "MetricList": [
        {//A list of key/datapoints
            "Key": {
                "Metric": "db.load.avg"
            },
            "DataPoints": [
                //... 60 datapoints for the total db.load.avg key
                ]
        },
               {
            "Key": {//Next key are the top tokenized queries
                "Metric": "db.load.avg",
                "Dimensions": {
                    "db.query_tokenized.db_id": "pi-1064184600",
                    "db.query_tokenized.id": "77DE8364594EXAMPLE",
                    "db.query_tokenized.statement": "{\"find\":\"customers\",\"filter\":{\"FirstName\":\"?\"},\"sort\":{\"key\":{\"$numberInt\":\"?\"}},\"limit\"
:{\"$numberInt\":\"?\"},\"$db\":\"myDB\",\"$readPreference\":{\"mode\":\"primary\"}}"
                }
            },
            "DataPoints": [
            //... 60 datapoints 
            ]
        },
        // In total 11 entries, 10 Keys of top tokenized queries, 1 total key 
    ] //End of MetricList
} //End of response
```

This response has 11 entries in the `MetricList` (1 total, 10 top tokenized query), with each entry having 24 per-hour `DataPoints`.

For tokenized queries, there are three entries in each dimensions list:
+ `db.query_tokenized.statement` – The tokenized query statement.
+ `db.query_tokenized.db_id ` – The synthetic ID that Performance Insights generates for you. This example returns the `pi-1064184600` synthetic ID.
+ `db.query_tokenized.id` – The ID of the query inside Performance Insights.

  In the AWS Management Console, this ID is called the Support ID. It's named this because the ID is data that AWS Support can examine to help you troubleshoot an issue with your database. AWS takes the security and privacy of your data extremely seriously, and almost all data is stored encrypted with your AWS KMS key. Therefore, nobody inside AWS can look at this data. In the example preceding, both the `tokenized.statement` and the `tokenized.db_id` are stored encrypted. If you have an issue with your database, AWS Support can help you by referencing the Support ID.

When querying, it might be convenient to specify a `Group` in `GroupBy`. However, for finer-grained control over the data that's returned, specify the list of dimensions. For example, if all that is needed is the `db.query_tokenized.statement`, then a `Dimensions` attribute can be added to the query.json file.

```
[
    {
        "Metric": "db.load.avg",
        "GroupBy": {
            "Group": "db.query_tokenized",
            "Dimensions":["db.query_tokenized.statement"],
            "Limit": 10
        }
    }
]
```

### Retrieving the DB load average filtered by Query
<a name="performance-insights-metrics-api-examples.DBLoadAverageByQuery"></a>

The corresponding API query in this example is similar to the command in [Retrieving the DB load average for top Query](#performance-insights-metrics-api-examples.topquery). However, the query.json file has the following contents.

```
[
 {
        "Metric": "db.load.avg",
        "GroupBy": { "Group": "db.wait_state", "Limit": 5  }, 
        "Filter": { "db.query_tokenized.id": "AKIAIOSFODNN7EXAMPLE" }
    }
]
```

In this response, all values are filtered according to the contribution of tokenized query AKIAIOSFODNN7EXAMPLE specified in the query.json file. The keys also might follow a different order than a query without a filter, because it's the top five wait states that affected the filtered query.

# Amazon CloudWatch metrics for Performance Insights
<a name="performance-insights-cloudwatch"></a>

Performance Insights automatically publishes metrics to Amazon CloudWatch. The same data can be queried from Performance Insights, but having the metrics in CloudWatch makes it easy to add CloudWatch alarms. It also makes it easy to add the metrics to existing CloudWatch Dashboards.


| Metric | Description | 
| --- | --- | 
|  DBLoad  |  The number of active sessions for Amazon DocumentDB. Typically, you want the data for the average number of active sessions. In Performance Insights, this data is queried as `db.load.avg`.  | 
|  DBLoadCPU  |  The number of active sessions where the wait state type is CPU. In Performance Insights, this data is queried as `db.load.avg`, filtered by the wait state type `CPU`.  | 
|  DBLoadNonCPU  |  The number of active sessions where the wait state type is not CPU.  | 

**Note**  
These metrics are published to CloudWatch only if there is load on the DB instance.

You can examine these metrics using the CloudWatch console, the AWS CLI, or the CloudWatch API.

For example, you can get the statistics for the `DBLoad` metric by running the [get-metric-statistics](https://docs.aws.amazon.com/cli/latest/reference/cloudwatch/get-metric-statistics.html) command.

```
aws cloudwatch get-metric-statistics \
    --region ap-south-1 \
    --namespace AWS/DocDB \
    --metric-name DBLoad  \
    --period 360 \
    --statistics Average \
    --start-time 2022-03-14T8:00:00Z \
    --end-time 2022-03-14T9:00:00Z \
    --dimensions Name=DBInstanceIdentifier,Value=documentdbinstance
```

This example generates output similar to the following.

```
{
    "Datapoints": [
        {
            "Timestamp": "2022-03-14T08:42:00Z", 
            "Average": 1.0, 
            "Unit": "None"
        }, 
        {
            "Timestamp": "2022-03-14T08:24:00Z", 
            "Average": 2.0, 
            "Unit": "None"
        }, 
        {
            "Timestamp": "2022-03-14T08:54:00Z", 
            "Average": 6.0, 
            "Unit": "None"
        }, 
        {
            "Timestamp": "2022-03-14T08:36:00Z", 
            "Average": 5.7, 
            "Unit": "None"
        }, 
        {
            "Timestamp": "2022-03-14T08:06:00Z", 
            "Average": 4.0, 
            "Unit": "None"
        }, 
        {
            "Timestamp": "2022-03-14T08:00:00Z", 
            "Average": 5.2, 
            "Unit": "None"
        }
    ], 
    "Label": "DBLoad"
}
```

You can use the `DB_PERF_INSIGHTS` metric math function in the CloudWatch console to query Amazon DocumentDB Performance Insights counter metrics. The `DB_PERF_INSIGHTS` function also includes the `DBLoad` metric at sub-minute intervals. You can set CloudWatch alarms on these metrics. For more details on how to create an alarm, see [Create an alarm on Performance Insights counter metrics from an AWS database](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_alarm_database_performance_insights.html). 

For more information about CloudWatch, see [What is Amazon CloudWatch?](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) in the *Amazon CloudWatch User Guide*. 

# Performance Insights for counter metrics
<a name="performance-insights-counter-metrics"></a>

Counter metrics are operating system metrics in the Performance Insights dashboard. To help identify and analyze performance problems, you can correlate counter metrics with DB load.

## Performance Insights operating system counters
<a name="performance-insights-counter-metrics-counters"></a>

The following operating system counters are available with Amazon DocumentDB Performance Insights.


| Counter | Type | Metric | 
| --- | --- | --- | 
| active | memory | os.memory.active | 
| buffers | memory | os.memory.buffers | 
| cached | memory | os.memory.cached | 
| dirty | memory | os.memory.dirty | 
| free | memory | os.memory.free | 
| inactive | memory | os.memory.inactive | 
| mapped | memory | os.memory.mapped | 
| pageTables | memory | os.memory.pageTables | 
| slab | memory | os.memory.slab | 
| total | memory | os.memory.total | 
| writeback | memory | os.memory.writeback | 
| idle | cpuUtilization | os.cpuUtilization.idle | 
| system | cpuUtilization | os.cpuUtilization.system | 
| total | cpuUtilization | os.cpuUtilization.total | 
| user | cpuUtilization | os.cpuUtilization.user | 
| wait | cpuUtilization | os.cpuUtilization.wait | 
| one | loadAverageMinute | os.loadAverageMinute.one | 
| fifteen | loadAverageMinute | os.loadAverageMinute.fifteen | 
| five | loadAverageMinute | os.loadAverageMinute.five | 
| cached | swap | os.swap.cached | 
| free | swap | os.swap.free | 
| in | swap | os.swap.in | 
| out | swap | os.swap.out | 
| total | swap | os.swap.total | 
| rx | network | os.network.rx | 
| tx | network | os.network.tx | 
| numVCPUs | general | os.general.numVCPUs | 