API Reference: Usage Reporting Plugin
Sending metrics from Apollo Server to GraphOS requires an Enterprise plan. If your organization doesn't have an Enterprise plan, you can test out this functionality by signing up for a free GraphOS trial.
Apollo Server's built-in usage reporting plugin gathers data on how your clients use the operations and fields in your GraphQL schema. The plugin also handles pushing this usage data to GraphOS, as described in Metrics and logging.
This plugin is designed to be used in an Apollo Gateway or in a monolithic server; it is not designed to be used from a subgraph. In a supergraph running Apollo Federation, the Apollo Gateway or GraphOS Router will send usage reports to Apollo's cloud. Subgraphs don't need to also send usage reports to Apollo's cloud; instead, they send it to the Router via inline traces and the Router combines execution information across all subgraphs and sends summarized reports to the cloud.
Default installation
📣 New in Apollo Server 4: error details are not included in traces by default. For more details, see Error Handling.
Apollo Server automatically installs and enables this plugin with default settings if you provide a graph API key and a graph ref to Apollo Server and your server is not a federated subgraph. You usually do this by setting the APOLLO_KEY
and APOLLO_GRAPH_REF
(or APOLLO_GRAPH_ID
and APOLLO_GRAPH_VARIANT
) environment variables. No other action is required.
If you don't provide an API key and graph ref, or if your server is a federated subgraph, this plugin is not automatically installed.
If you provide an API key but don't provide a graph ref, a warning is logged. You can disable the plugin to hide the warning.
If you provide an API key and graph ref but your server is a federated subgraph, a warning is logged. You can disable the plugin to hide the warning.
Custom installation
If you want to configure the usage reporting plugin, import it and pass it to your ApolloServer
constructor's plugins
array:
1import { ApolloServer } from '@apollo/server';
2import { ApolloServerPluginUsageReporting } from '@apollo/server/plugin/usageReporting';
3
4const server = new ApolloServer({
5 typeDefs,
6 resolvers,
7 plugins: [
8 ApolloServerPluginUsageReporting({
9 fieldLevelInstrumentation: 0.5,
10 })
11 ],
12});
While you can install the usage reporting plugin in a server that is a federated subgraph, this is not recommended, and a warning will be logged.
Supported configuration options are listed below.
Options
Name / Type |
Description |
---|---|
Configuring which data is sent to Apollo Studio | |
| Provide this object to configure which GraphQL variable values are included in trace data that's sent to Apollo Studio. Valid options are described in Valid sendVariableValues object signatures.The default value is { none: true } , which means no variable values are sent to Studio. This is a security measure to prevent sensitive data from potentially reaching Apollo servers. |
| Provide this object to configure which request header names and values are included in trace data that's sent to Apollo Studio. Valid options are described in Valid sendHeaders object signatures.The default value is { none: true } , which means no header names or values are sent to Studio. This is a security measure to prevent sensitive data from potentially reaching Apollo servers. |
| Provide this object to modify GraphQL operation errors before Apollo Server reports those errors to Apollo Studio. Valid options are described in Valid sendErrors object signatures.The default value is { masked: true } , which means error messages are masked and extensions are omitted in the traces that Apollo Server sends to Apollo Studio. This is a security measure to prevent sensitive data from potentially reaching Apollo servers.Note: If this ApolloServer instance is acting as the gateway in an Apollo Federation architecture, this option does not modify errors that originate in subgraphs. To modify those errors, instead configure the includeErrors option in the inline trace plugin, which you install in the subgraph's ApolloServer instance. |
| This option enables you to configure whether Apollo Server calculates detailed per-field statistics for each operation. It is used only for operations that reach execution without encountering an error (such as during parsing, validation, or resolving the operation name). It is not used if you provide an includeRequest hook that returns false .You can provide either a number or an an async function.If you provide a number, that number must be between 0 and 1 , inclusive. This number specifies the probability that Apollo Server calculates per-field statistics for each incoming operation.For example, if you pass 0.01 , then Apollo Server calculates statistics for approximately 1% of operations. When Apollo Server reports these statistics to Apollo Studio, it also provides an "estimation multiplier" of each field's actual number of executions (for example, with a probability of 0.01 , the estimation multiplier is 100 ).Providing a number x is equivalent to passing this function:async () => Math.random() < x ? 1/x : 0 If you pass a function, the function is called once for each operation, and it's passed a corresponding GraphQLRequestContext object. The function can return either a boolean or a number. Returning false is equivalent to returning 0 , and returning true is equivalent to returning 1 .If the function returns false (or 0 ):
false (or 0 ) for some or all operations can improve your server's performance, because calculating complete traces can introduce significant overhead. This is especially true for a federated graph, because traces are transmitted from the subgraph to the Gateway in-band inside the actual GraphQL response.If the function returns a positive number:
10 . Your function can use different logic for different operations, such as to more frequently report rare operations than common operations.Note that returning true here does not mean that the data derived from field-level instrumentation must be transmitted to Apollo Studio's servers in the form of a trace. The data can still be aggregated locally to statistics. Either way, this operation contributes to the "field executions" statistic in Studio, along with timing hints.The default value is a function that always returns true . |
| Specify this asynchronous function to configure which requests are included in usage reports sent to Apollo Studio. For example, you can omit requests that execute a particular operation or requests that include a particular HTTP header.Note that returning false here means that the operation is completely ignored by all Apollo Studio features. If you want to improve performance by skipping the field-level execution trace, set the fieldLevelInstrumentation option instead of this one.This function is called for each received request. It takes a GraphQLRequestContext object and must return a Promise<Boolean> that indicates whether to include the request. It's called either after the operation is successfully resolved (via the didResolveOperation event), or when sending the final error response if the operation was not successfully resolved (via the willSendResponse event).If you don't want any usage reporting at all, don't use this option: instead, either avoid specifying an Apollo API key or explicitly disable the plugin.By default, all requests are included in usage reports. |
| Specify this function to provide Apollo Studio with client details for each processed request. Apollo Studio uses this information to segment metrics by client.This function is passed a GraphQLRequestContext object containing all available information about the request. It should return an object with clientName and clientVersion fields that identify the associated client.By default, the plugin attempts to obtain these values from the incoming request's HTTP headers (specifically, apollographql-client-name and apollographql-client-version ). |
| If you're using the overrideReportedSchema option with the schema reporting plugin (ApolloServerPluginSchemaReporting ), you should provide the same value for this option. This ensures that the schema ID associated with a request in this plugin's usage reports matches the schema ID that the other plugin reports. |
| Statistics about operations that your server cannot execute are not reported under each document separately to Apollo Studio, but are grouped together as "parse failure", "validation failure", or "unknown operation name". By default, the usage reporting plugin does not include the full operation document in reported traces, because it is challenging to strip potential private information (like string constants) from invalid operations. If you'd like the usage reporting plugin to send the full operation document and operation name so you can view it in Apollo Studio's trace view, set this to true. |
Configuring communication protocol | |
| If true , the plugin sends a usage report to Apollo Studio after every request instead of sending batched reports. By default, this option is set to false .This option is useful for stateless environments like Amazon Lambda where processes terminate after handling a small number of requests.Note that "immediately" does not mean synchronously with completing the response, but rather "very soon", such as after a setImmediate call. |
| Specifies which Fetch API function implementation to use when sending usage reports. |
| The interval at which Apollo Server should send batched trace reports to Studio, in milliseconds.Regardless of this value, Apollo Server sends a trace report whenever the size of a pending batch exceeds the value of maxUncompressedReportSize (default 4MB). |
| Apollo Server sends a trace report whenever the size of a pending batched trace report exceeds this value (in bytes), regardless of its standard reporting interval.Note that this is a rough limit that includes the size of serialized traces and signatures. It ignores the size of the report's header and some other top-level bytes.The default value is 4MB (4194304 ). |
| The maximum number of times Apollo Server should attempt to report each trace report, performing exponential backoff between attempts.The default value is 5 . |
| The minimum amount of backoff (in milliseconds) Apollo Server should perform before retrying a failed trace report.The default value is 100 . |
| Timeout for each individual attempt to send a report to Apollo. (This is for
each HTTP POST, not for all potential retries.)The default value is 30000 (30 seconds). |
| If you provide this object, the plugin sends it all log messages related to Apollo Studio communication, instead of sending them to the default logger. The object must implement all methods of the Logger interface. |
| If you provide this function, the plugin calls it whenever it encounters an error while reporting usage data. The details of the error are passed to the function.By default, the plugin logs these errors to its specified logger . Unlike the logger , this function receives the actual Error object instead of only an error message. |
Internal and non-recommended options | |
| The URL base that the plugin sends reports to (not including the path). This option only needs to be set for testing and Apollo-internal uses. |
| If set, prints all reports as JSON when they are sent. (Note that for technical reasons, traces embedded in a report are printed separately when they are added to a report.) |
| Specify this function to create a signature for a query. This option is not recommended, because Apollo's servers make assumptions about how the signature relates to the operation you executed. |
Valid sendVariableValues
object signatures
Object | Description |
---|---|
{ none: true } | If you provide this object, no GraphQL variable values are sent to Apollo Studio. This is the default behavior. |
{ all: true } | If you provide this object, all GraphQL variable values are sent to Apollo Studio. |
{ onlyNames: ["apple", "orange"]} | If you provide an object with this structure, only values of the GraphQL variables with names that appear in the array are sent to Apollo Studio. To filter individual fields of a variable that contains an input type, use the transform function below instead. Case-sensitive. |
{ exceptNames: ["apple", "orange"]} | If you provide an object with this structure, all GraphQL variable values except values of the variables with names that appear in the array are sent to Apollo Studio. To filter individual fields of a variable that contains an input type, use the transform function below instead. Case-sensitive. |
{ transform: ({ variables, operationString)} => { ... } } | The value of For security reasons, if an error occurs in the |
Valid sendHeaders
object signatures
Object | Description |
---|---|
{ none: true } | If you provide this object, no request header names or values are sent to Apollo Studio. This is the default behavior. |
{ all: true } | If you provide this object, all GraphQL header names and values are sent to Apollo Studio, except for the protected headers listed below. |
{ onlyNames: ["apple", "orange"]} | If you provide an object with this structure, only names and values of the request headers with names that appear in the array are sent to Apollo Studio. Case-insensitive. |
{ exceptNames: ["apple", "orange"]} | If you provide an object with this structure, all GraphQL header values except values of headers with names that appear in the array are sent to Apollo Studio. Case-insensitive. |
Note: Regardless of your configuration, Apollo Server never sends the values of the following headers to Apollo Studio:
authorization
cookie
set-cookie
Valid sendErrors
object signatures
Object | Description |
---|---|
| If you provide this object, error messages are masked and extensions omitted in the traces sent to Apollo Studio. This is the default behavior. |
| If you provide this object, all error messages and extensions are included in the traces sent to Apollo Studio. |
| The value of transform is a function that receives each error (GraphQLError ) and must also return a GraphQLError object (or null to prevent Apollo Server from reporting a particular error entirely).The only properties of the reported error you can modify are its message and its extensions . See Masking and logging errors for more details. |
Disabling the plugin
If you don't want to install the usage reporting plugin and you are providing an API key to Apollo Server for other purposes, you can disable usage reporting by installing the ApolloServerPluginUsageReportingDisabled
plugin, like so:
1import { ApolloServer } from '@apollo/server';
2import { ApolloServerPluginUsageReportingDisabled } from '@apollo/server/plugin/disabled';
3
4const server = new ApolloServer({
5 typeDefs,
6 resolvers,
7 plugins: [
8 ApolloServerPluginUsageReportingDisabled(),
9 ],
10});
This also disables the warning log if you provide an API key but do not provide a graph ref, or if you provide an API key and graph ref and your server is a federated subgraph.