Series
A Fast GraphQL API With Fastify and Yoga
Build a GraphQL API in TypeScript with Fastify and GraphQL Yoga, and make it fast: DataLoader, live subscriptions across instances with Valkey, a response cache and query limits.
Intermediate
Eight parts, from an empty folder to a GraphQL API that is ready for real traffic. You build the API of a guild board on Fastify and GraphQL Yoga, with PostgreSQL and Drizzle underneath and types generated from the schema. Then you make it fast and keep it fast: DataLoader batches the database queries, subscriptions push every change over Server-Sent Events and reach every instance through Valkey, a shared cache answers repeated reads, and limits turn away the queries that would cost too much. Every command was run, and every output is real.
Quest line
- Part 1: Fastify Meets GraphQL YogaSet up a TypeScript project that runs without a build step, put GraphQL Yoga on a Fastify server and send it your first queries.20 min
- Part 2: A Database With PostgreSQL and DrizzleStart PostgreSQL in Docker, describe the tables of the guild board in TypeScript with Drizzle, create them with a migration and fill them with sample data.25 min
- Part 3: Schema First, Typed by CodegenWrite the GraphQL schema of the guild board, let GraphQL Codegen generate the resolver types from it, answer queries from PostgreSQL and find the N+1 problem in the SQL log.25 min
- Part 4: Batching With DataLoaderCollect the lookups of a request with DataLoader and answer them with one query per table, so the quest board needs three SQL queries instead of sixteen.25 min
- Part 5: Mutations and Live Updates With SubscriptionsPost, accept and complete quests with mutations, push every change to subscribed clients over Server-Sent Events, and keep the DataLoader cache from going stale in long-lived subscriptions.30 min
- Part 6: Subscriptions Across Instances With ValkeyRun a second instance of the API, watch its subscribers miss the events of the first, and share the events through Valkey, so every instance hears every change, even after Valkey restarts.20 min
- Part 7: Caching Whole Responses in ValkeyCache complete query results in Valkey with the response cache of Yoga, clear them when mutations change the data, answer repeated GET requests with 304, and keep the API up when the cache is down.25 min
- Part 8: Query Limits and Persisted OperationsProtect the API from operations that are too deep or too expensive with a depth limit and a cost limit, and lock it to the operations of your own clients with persisted operations.25 min