Matsimitsu

Apollo Query Batching and graphql-ruby


Query batching is a way to speed up your application. Instead of waiting on multiple client-server roundtrips to load data, everything is loaded at once.

Enabling query batching in Apollo is as easy as using another network provider:

  import ApolloClient, { createBatchingNetworkInterface } from 'apollo-client';
  const batchingNetworkInterface = createBatchingNetworkInterface({
    uri: 'localhost:3000',
    batchInterval: 10,  // in milliseconds
    batchMax: 10,
    opts: {
      // Options to pass along to `fetch`
    }
  });
  const apolloClient = new ApolloClient({
    networkInterface: batchingNetworkInterface,
  });

On the Ruby you need to make a few more changes, but all can be done in your GraphQL Controller. You need to map the array of given queries to a format that graphql-ruby understands. The gist below handles both batched and non-batched queries.

def execute
  context = {}

  # Apollo sends the params in a _json
  # variable when batching is enabled
  # see the Apollo Documentation about query batching:
  # http://dev.apollodata.com/core/network.html#query-batching
  result = if params[:_json]
    queries = params[:_json].map do |param|
      {
        query: param['query'],
        operation_name: param['operationName'],
        variables: ensure_hash(param['variables']),
        context: context
      }
    end
    MySchema.multiplex(queries)
  else
    MySchema.execute(
      params[:query],
      operation_name: params[:operationName],
      variables: ensure_hash(params[:variables]),
      context: context
    )
  end

  render json: result
end

Batching queries can reduce the time your app is loading by a large amount, making for a more pleasant user experience.

More posts


Switching to Svelte

I have rewritten my middleman site to Svelte/SvelteKit, here's what I encountered.

Remote uploads with pre-signed URLs on Scaleway's object storage.

Or, make sure your headers match, otherwise you'll get a lot of strange errors.

Upload a file to an AWS pre-signed S3 url with RestClient.

Or, how something so simple cost me so much time.

Publish articles from iA Writer to your static site.

My hope with this project is that with less friction to write and publish a note/article, I'll do it more.

AppSignal

Kafka and Ruby, a Sidekiq lovestory

In today's article, we’ll cover performance from a different angle: The choices we made in our stack for AppSignal.