Production, Persisted Queries & Monitoring

◕ GraphQLLesson 15Advanced

Running GraphQL in production requires disabling introspection, implementing persisted queries for performance, setting query depth limits to prevent abuse, and connecting to monitoring/tracing tools.

1 Production Security Settings
JavaScript — Apollo Server Production Config
const { ApolloServer } = require("@apollo/server");
const depthLimit = require("graphql-depth-limit");
const { createComplexityLimitRule } = require("graphql-validation-complexity");

const server = new ApolloServer({
  typeDefs,
  resolvers,

  // Disable introspection in production (hides schema from attackers)
  introspection: process.env.NODE_ENV !== "production",

  // Query validation rules
  validationRules: [
    depthLimit(7),                              // Max 7 levels of nesting
    createComplexityLimitRule(1000)             // Max complexity score
  ],

  // Plugin for request logging
  plugins: [
    {
      requestDidStart: async () => ({
        willSendResponse: async ({ response, request }) => {
          console.log({ operation: request.operationName, status: response.http.status });
        }
      })
    }
  ]
});
2 Persisted Queries
JavaScript — Automatic Persisted Queries (APQ)
// Server: install persisted queries plugin
npm install @apollo/server-plugin-operation-registry

// Client: enable APQ in Apollo Client
import { createPersistedQueryLink } from "@apollo/client/link/persisted-queries";
import { sha256 } from "crypto-hash";

const persistedQueriesLink = createPersistedQueryLink({ sha256 });

const client = new ApolloClient({
  link: persistedQueriesLink.concat(authLink).concat(httpLink),
  cache: new InMemoryCache()
});

// How it works:
// 1. Client sends only the hash of the query (tiny payload)
// 2. If server recognizes hash -> executes query
// 3. If not -> client resends with full query text
// 4. Server stores hash->query mapping
// Benefit: massive reduction in request payload size
3 Monitoring with Apollo Studio
JavaScript — Apollo Studio Connection
// .env
APOLLO_KEY=service:my-api:xxxxx
APOLLO_GRAPH_REF=my-api@current

// Automatic with @apollo/server — just set APOLLO_KEY env var
// Apollo Studio provides:
// - Field-level usage analytics
// - Slow query tracing
// - Error rate monitoring
// - Schema change alerts
// - Client-aware metrics
4 Code Challenge
Challenge: Deploy your Apollo Server to Railway.app or Render.com. Configure it with: introspection disabled, depth limit of 5, CORS restricted to your frontend domain, and a /health REST endpoint for uptime monitoring.