Batching operations
Apollo Kotlin supports batching multiple operations in a single HTTP request to reduce the number of network round trips. Whenever you execute an operation with batching enabled, your client waits a short time interval to collect any other batchable operations that are also executed. When the interval completes, your client sends all the operations in a single HTTP request.
Note that due to the waiting interval, batching adds some latency to operations. Operations that require as little latency as possible can opt out of batching.
Enabling batching
You enable batching when you initialize your ApolloClient
instance, like so:
1val apolloClient = ApolloClient.Builder()
2 .serverUrl("https://example.com/graphql")
3 .httpBatching()
4 .build()
By default, the batching engine waits 10ms to collect queries before sending them, and a single batch contains a maximum
of 10 queries. You can configure these defaults by passing additional configuration options to the httpBatching
method:
1apolloClientBuilder.httpBatching(
2 batchIntervalMillis = 50, // Wait 50ms
3 maxBatchSize = 20 // Max 20 queries
4)
Opting out/in
By default, if you enable batching, it's enabled for all operations. An individual operation can
opt out of batching by passing false
to the canBeBatched
method:
1apolloClient.query(MyQuery()).canBeBatched(false).execute()
This is helpful if there's a particular operation that you always want to execute with as little latency as possible.
You can also require individual operations to opt in to batching. To do so, you first call canBeBatched(false)
while initializing your ApolloClient
instance:
1val apolloClient = ApolloClient.Builder()
2 .serverUrl("https://example.com/graphql")
3 .httpBatching()
4 .canBeBatched(false)
5 .build()
Now, batching is disabled by default, and individual operations can opt in with canBeBatched(true)
.