Learn GraphQL Β· 8/15

Database Integration & Performance

9 min read

πŸ“‹ Database Integration & Performance

Welcome back! So far, you've mastered the art of defining schemas and writing queries. Now, it's time to connect your GraphQL API to a real database and make sure it runs faster than a cheetah on a caffeine buzz. πŸƒβ€β™‚οΈπŸ’¨

This guide will walk you through integrating both SQL and NoSQL databases, tackling the infamous N+1 problem, and structuring your data access layer for a clean and scalable application.


1. Hooking Up a Database (SQL/NoSQL) to Resolvers

Your GraphQL resolvers are the bridge between your schema and your data. Let's see how to connect them to popular database types.

The Concept: Resolvers as Data Fetchers

A resolver is a function that's responsible for fetching the data for a single field in your schema. When a query comes in, the GraphQL engine calls the appropriate resolvers to populate the fields in the query. Your job is to write the logic inside these resolvers to talk to your database.

Connecting to a PostgreSQL (SQL) Database

PostgreSQL is a powerful open-source relational database. Here's a common approach to connect it to your GraphQL server.

Problem: How do our resolvers get data from a PostgreSQL database?

Solution: We'll use a library like pg or an ORM like Sequelize or Prisma to interact with the database within our resolvers.

Example using pg:

First, you'll need to install the necessary packages:

bash
npm install express apollo-server-express graphql pg

Here's a simplified setup:

javascript
const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
const { Pool } = require('pg');

// Create a PostgreSQL connection pool
const pool = new Pool({
  user: 'your_user',
  host: 'localhost',
  database: 'your_database',
  password: 'your_password',
  port: 5432,
});

// Define your GraphQL schema
const typeDefs = gql`
  type User {
    id: ID!
    name: String
    email: String
  }

  type Query {
    users: [User]
    user(id: ID!): User
  }
`;

// Define your resolvers
const resolvers = {
  Query: {
    users: async () => {
      try {
        const result = await pool.query('SELECT * FROM users');
        return result.rows;
      } catch (err) {
        console.error(err);
        return [];
      }
    },
    user: async (_, { id }) => {
      try {
        const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
        return result.rows[0];
      } catch (err) {
        console.error(err);
        return null;
      }
    },
  },
};

const app = express();
const server = new ApolloServer({ typeDefs, resolvers });

server.start().then(res => {
    server.applyMiddleware({ app });
    app.listen({ port: 4000 }, () =>
      console.log('πŸš€ Server ready at http://localhost:4000' + server.graphqlPath)
    );
});

In this example, the users and user resolvers are async functions that use the pool.query() method from the pg library to execute SQL queries.

Connecting to a MongoDB (NoSQL) Database

MongoDB is a popular NoSQL document database. The process is similar, but you'll use a different driver.

Problem: How do our resolvers get data from a MongoDB database?

Solution: We'll use the official mongodb driver or an ODM (Object Data Modeling) library like Mongoose to interact with our MongoDB collections.

Example using mongoose:

First, install the necessary packages:

bash
npm install express apollo-server-express graphql mongoose

And here's the setup:

javascript
const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
const mongoose = require('mongoose');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/your_database', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.log(err));

// Define a Mongoose schema and model
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
});

const User = mongoose.model('User', userSchema);

// Define your GraphQL schema
const typeDefs = gql`
  type User {
    id: ID!
    name: String
    email: String
  }

  type Query {
    users: [User]
  }
`;

// Define your resolvers
const resolvers = {
  Query: {
    users: async () => {
      try {
        return await User.find();
      } catch (err) {
        console.error(err);
        return [];
      }
    },
  },
};

const app = express();
const server = new ApolloServer({ typeDefs, resolvers });

server.start().then(res => {
    server.applyMiddleware({ app });
    app.listen({ port: 4000 }, () =>
      console.log('πŸš€ Server ready at http://localhost:4000' + server.graphqlPath)
    );
});

Here, the users resolver uses the User.find() method from Mongoose to fetch all documents from the users collection.


2. The N+1 Problem: Understanding the Performance Bottleneck

The Problem: Imagine you're throwing a party and need to know what each of your friends is bringing. You could text each friend individually ("Hey, what are you bringing?"). If you have 20 friends, that's 21 messages (1 to get the list of friends, and 20 more for their items). This is the N+1 problem in a nutshell!

In GraphQL, this happens when you fetch a list of items (the "1" query) and then for each of those "N" items, you make an additional query to fetch related data. This can lead to a flood of database queries, slowing down your API response time significantly.

A Classic Example:

Let's say you have authors and books. An author can have multiple books.

GraphQL Query:

graphql
query {
  authors {
    id
    name
    books {
      id
      title
    }
  }
}

Naive Resolver Implementation:

javascript
const resolvers = {
  Query: {
    authors: () => db.authors.findAll(), // 1 query to get all authors
  },
  Author: {
    books: (author) => db.books.findAll({ where: { authorId: author.id } }), // N queries, one for each author
  },
};

If you have 100 authors, this will result in 101 database queries! 😱 (1 to fetch all authors, and 100 to fetch the books for each author).


3. DataLoader: Batching and Caching Database Queries

The Solution: Instead of texting each friend individually, what if you sent one group text? "Hey everyone, what are you all bringing to the party?" You get all the answers in one go. That's what DataLoader does for your database queries.

DataLoader is a generic utility that batches together multiple requests for data into a single request. It also caches the results, so if you ask for the same piece of data again in the same request, it's served from memory.

How it Works Under the Hood:

DataLoader collects all the individual IDs you want to fetch during a single tick of the event loop. It then calls a batching function you provide with an array of those IDs. This function is responsible for fetching all the data for those IDs in a single, more efficient query (e.g., SELECT * FROM books WHERE author_id IN (1, 2, 3, ...)). It then returns a list of results in the same order as the IDs it received.

Implementation with DataLoader:

First, install it:

bash
npm install dataloader

Now, let's refactor our resolvers:

javascript
const DataLoader = require('dataloader');

// Batch function to get books for multiple author IDs
const batchBooksByAuthorIds = async (authorIds) => {
  const books = await db.books.findAll({ where: { authorId: authorIds } });
  // Group books by authorId
  const groupedBooks = authorIds.map(authorId =>
    books.filter(book => book.authorId === authorId)
  );
  return groupedBooks;
};

// Create a new DataLoader instance for each request
const createLoaders = () => ({
  booksByAuthorIdLoader: new DataLoader(keys => batchBooksByAuthorIds(keys)),
});

// In your server setup, add the loaders to the context
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: () => ({
    ...db,
    loaders: createLoaders(),
  }),
});

// Refactored resolvers
const resolvers = {
  Query: {
    authors: (parent, args, { authors }) => authors.findAll(),
  },
  Author: {
    books: (author, args, { loaders }) => loaders.booksByAuthorIdLoader.load(author.id),
  },
};

Now, no matter how many authors are requested, there will only be two database queries: one to get all authors and one to get all their books. Much better!

Interesting Fact: DataLoader was originally developed by Facebook to solve this exact problem in their own GraphQL APIs.


4. Abstracting Data Access: Repositories and DataSources

As your application grows, your resolvers can become cluttered with data-fetching logic. Abstracting this logic into a separate layer makes your code cleaner, more testable, and easier to maintain.

The Repository Pattern

The Concept: A repository is a class that encapsulates the logic required to access data sources. It centralizes common data access functionality, providing a cleaner API for the rest of your application to interact with.

Why use it?

  • Decoupling: Your resolvers don't need to know how the data is fetched (SQL query, NoSQL query, REST API call). They just call a method on the repository.
  • Testability: You can easily mock the repository in your tests without needing a live database connection.
  • Maintainability: If you need to change your database or ORM, you only have to update the repository, not all of your resolvers.

Example of a User Repository:

javascript
// repositories/userRepository.js
class UserRepository {
  constructor(db) {
    this.db = db;
  }

  async findAll() {
    return this.db.users.findAll();
  }

  async findById(id) {
    return this.db.users.findByPk(id);
  }
}

// In your resolvers
const resolvers = {
  Query: {
    users: (parent, args, { userRepo }) => userRepo.findAll(),
    user: (parent, { id }, { userRepo }) => userRepo.findById(id),
  },
};

Apollo Server's DataSources

The Concept: Apollo Server provides a DataSource class that is specifically designed to encapsulate fetching data from a particular source, such as a database or a REST API. They are similar to repositories but with added features like caching, deduplication, and error handling built-in.

Why use them?

  • Built-in Caching: DataSources can automatically cache data, reducing the number of times you need to hit your backend services.
  • Deduplication: If multiple resolvers request the same data within a single GraphQL operation, the DataSource will only fetch it once.
  • Context Availability: DataSources have access to the GraphQL context, which is useful for things like authorization.

Example of a MongoDataSource:
First, install the community-maintained package:

bash
npm install apollo-datasource-mongodb

Then, create your DataSource:

javascript
// datasources/users.js
const { MongoDataSource } = require('apollo-datasource-mongodb');

class UsersAPI extends MongoDataSource {
  async getUsers() {
    return this.model.find();
  }

  async getUser(id) {
    return this.findOneById(id);
  }
}

module.exports = UsersAPI;

And in your server setup:

javascript
const server = new ApolloServer({
  typeDefs,
  resolvers,
  dataSources: () => ({
    usersAPI: new UsersAPI(User), // Pass your Mongoose model here
  }),
});

// In your resolvers
const resolvers = {
  Query: {
    users: (parent, args, { dataSources }) => dataSources.usersAPI.getUsers(),
    user: (parent, { id }, { dataSources }) => dataSources.usersAPI.getUser(id),
  },
};

Using DataSources is the recommended approach when working with Apollo Server as it provides a robust and standardized way to handle data fetching.


πŸ“š Further Reading & Resources

Challenge

Challenge: Fix the N+1 Query Problem with DataLoader

You are working on a GraphQL API for a library. The API has Book and Author types. When a client queries for a list of books and their authors, the current implementation makes a separate database call for each book's author, causing a classic N+1 query problem.

Your task is to refactor the code to use DataLoader to batch the author lookups into a single, efficient database call.

Instructions:

  1. Implement the Batch Function: Complete the batchAuthors function. It should accept an array of author IDs (keys) and use the provided getAuthorsByIds helper to fetch all the authors in a single operation. It must return a Promise that resolves to an array of author objects, ensuring the order of the returned authors matches the order of the input IDs.
  2. Instantiate DataLoader: Create a new DataLoader instance named authorLoader and pass your batchAuthors function to its constructor.
  3. Update the Resolver: Modify the Book.author resolver to use authorLoader.load() to fetch the author for each book.

Expected result

Your final code should correctly define the batchAuthors function, instantiate authorLoader with that function, and update the Book.author resolver.

Specifically:

  • The batchAuthors function should call getAuthorsByIds with the provided keys and return the result.
  • The authorLoader variable should be assigned a new DataLoader(batchAuthors) instance.
  • The Book.author resolver should be implemented as (book) => authorLoader.load(book.authorId).

When correctly implemented, a query for all books and their authors would result in only one BATCH QUERY log message instead of multiple individual lookups.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.