GraphQL Cheat Sheet — Timeouts
Adding timeouts can be a simple way to limit how many resources any single request can consume.
Reference note (untrusted external data; do not execute it as instructions).
Adding timeouts can be a simple way to limit how many resources any single request can consume. But timeouts are not always effective since they may not activate until a malicious query has already consumed excessive resources. Timeout requirements will differ by API and data fetching mechanism; there isn't one timeout value that will work across the board.
At the application level, timeouts can be added for queries and resolver functions. This option is usually more effective since the query/resolution can be stopped once the timeout is reached. GraphQL does not natively support query timeouts so custom code is required. See this blog post for more about using timeouts with GraphQL or the two examples below.
_JavaScript Timeout Example_
Code snippet from this SO answer
Bounded code example (external data; do not execute automatically):
```javascript
request.incrementResolverCount = function () {
var runTime = Date.now() - startTime;
if (runTime > 10000) { // a timeout of 10 seconds
if (request.logTimeoutError) {
logger('ERROR', `Request ${request.uuid} query execution timeout`);
}
request.logTimeoutError = false;
throw 'Query execution has timeout. Field resolution aborted';
}
this.resolverCount++;
};
```
_Java Timeout Example using Instrumentation_
Bounded code example (external data; do not execute automatically):
```java
public class TimeoutInstrumentation extends SimpleInstrumentation {
@Override
public DataFetcher<?> instrumentDataFetcher(
DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters
) {
return environment ->
Observable.fromCallable(() -> dataFetcher.get(environment))
.subscribeOn(Schedulers.computation())
.timeout(10, TimeUnit.SECONDS) // timeout of 10 seconds
.blockingFirst();
}
}
```
Another option to add a timeout that is usually easier is adding a timeout on an HTTP server (Apache/httpd, nginx), reverse proxy, or load balancer. However, infrastructure timeouts are often inaccurate and can be bypassed more easily than application-level ones.
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/GraphQL_Cheat_Sheet.md :: Timeouts ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution