Understanding the Dataloader

Dataloader is one of the most useful and smart packages I have in my toolbox.

In this post we are going to navigate a simple but complex enough example to find out the need for a Dataloader.
After that we will implement a naive version of the dataloader to understand its beauty and how useful it is.

About the project

We have data about libraries and their dependencies. We want to implement a tool that renders the tree of dependencies of a given library.
The tree should show the library and its dependencies, and the dependencies of the dependencies.

These are the dependencies of the libraries:

WebRender depends on HttpClient, Utils, and Logger.
HttpClient depends on NetworkTools and Logger.
Utils depends on NetworkTools, CacheManager, and Logger.
NetworkTools depends on Logger.
CacheManager depends on Logger.
DatabaseConnector depends on NetworkTools and CacheManager.
AuthService depends on HttpClient and Logger.
ApiGateway depends on HttpClient and DatabaseConnector.
PaymentProcessor depends on DatabaseConnector and CacheManager.
Logger has no dependencies (it's a foundational library).

The information lives in two different services: one knows about dependencies, the other one about the metadata of each library (owner, license, etc).

And this is the view we want to implement for WebRender:

WebRender 1.0.0 (WebDevCorp, MIT)
  HttpClient 2.1.0 (NetToolsInc, Apache-2.0)
    NetworkTools 1.5.0 (NetToolsInc, MIT)
      Logger 1.2.0 (LoggerTools, MIT)
    Logger 1.2.0 (LoggerTools, MIT)
  Utils 3.0.0 (CoreUtils, GPL-3.0)
    NetworkTools 1.5.0 (NetToolsInc, MIT)
      Logger 1.2.0 (LoggerTools, MIT)
    CacheManager 4.2.0 (TechCore, MIT)
      Logger 1.2.0 (LoggerTools, MIT)
    Logger 1.2.0 (LoggerTools, MIT)
  Logger 1.2.0 (LoggerTools, MIT)

The tree has 12 nodes but only 6 different libraries. Keep those numbers in mind.

Initial Setup

Create the package and install express:

mkdir dataloader
cd dataloader
npm init -y
npm install express
mkdir src data

To be able to use import we need to add

  "type": "module",

to the package.json file.

Data

Save the data in two json files.

data/dependencies.json:

[
  {"name": "WebRender", "version": "1.0.0", "dependencies": [{"name": "HttpClient", "version": "2.1.0"}, {"name": "Utils", "version": "3.0.0"}, {"name": "Logger", "version": "1.2.0"}]},
  {"name": "HttpClient", "version": "2.1.0", "dependencies": [{"name": "NetworkTools", "version": "1.5.0"}, {"name": "Logger", "version": "1.2.0"}]},
  {"name": "Utils", "version": "3.0.0", "dependencies": [{"name": "NetworkTools", "version": "1.5.0"}, {"name": "CacheManager", "version": "4.2.0"}, {"name": "Logger", "version": "1.2.0"}]},
  {"name": "NetworkTools", "version": "1.5.0", "dependencies": [{"name": "Logger", "version": "1.2.0"}]},
  {"name": "CacheManager", "version": "4.2.0", "dependencies": [{"name": "Logger", "version": "1.2.0"}]},
  {"name": "DatabaseConnector", "version": "2.4.0", "dependencies": [{"name": "NetworkTools", "version": "1.5.0"}, {"name": "CacheManager", "version": "4.2.0"}]},
  {"name": "AuthService", "version": "1.1.0", "dependencies": [{"name": "HttpClient", "version": "2.1.0"}, {"name": "Logger", "version": "1.2.0"}]},
  {"name": "ApiGateway", "version": "3.3.0", "dependencies": [{"name": "HttpClient", "version": "2.1.0"}, {"name": "DatabaseConnector", "version": "2.4.0"}]},
  {"name": "PaymentProcessor", "version": "5.1.0", "dependencies": [{"name": "DatabaseConnector", "version": "2.4.0"}, {"name": "CacheManager", "version": "4.2.0"}]},
  {"name": "Logger", "version": "1.2.0", "dependencies": []}
]

data/metadata.json:

[
  {"name": "WebRender", "owner": "WebDevCorp", "repo_url": "https://github.com/WebDevCorp/WebRender", "release_date": "2023-01-15", "license": "MIT", "maintainers": ["Alice Johnson", "Bob Smith"]},
  {"name": "HttpClient", "owner": "NetToolsInc", "repo_url": "https://github.com/NetToolsInc/HttpClient", "release_date": "2022-09-30", "license": "Apache-2.0", "maintainers": ["Charlie Brown", "Dave White"]},
  {"name": "Utils", "owner": "CoreUtils", "repo_url": "https://github.com/CoreUtils/Utils", "release_date": "2021-12-05", "license": "GPL-3.0", "maintainers": ["Eve Green", "Frank Black"]},
  {"name": "NetworkTools", "owner": "NetToolsInc", "repo_url": "https://github.com/NetToolsInc/NetworkTools", "release_date": "2021-08-22", "license": "MIT", "maintainers": ["Grace Blue"]},
  {"name": "CacheManager", "owner": "TechCore", "repo_url": "https://github.com/TechCore/CacheManager", "release_date": "2023-05-10", "license": "MIT", "maintainers": ["Hannah Red", "Ivy Gold"]},
  {"name": "DatabaseConnector", "owner": "DatabaseTech", "repo_url": "https://github.com/DatabaseTech/DatabaseConnector", "release_date": "2022-11-20", "license": "Apache-2.0", "maintainers": ["Jack Silver"]},
  {"name": "AuthService", "owner": "AuthCorp", "repo_url": "https://github.com/AuthCorp/AuthService", "release_date": "2023-03-14", "license": "MIT", "maintainers": ["Kevin Purple", "Lily Orange"]},
  {"name": "ApiGateway", "owner": "GatewayTech", "repo_url": "https://github.com/GatewayTech/ApiGateway", "release_date": "2022-07-01", "license": "GPL-3.0", "maintainers": ["Mason Yellow"]},
  {"name": "PaymentProcessor", "owner": "FinTechCo", "repo_url": "https://github.com/FinTechCo/PaymentProcessor", "release_date": "2023-02-17", "license": "MIT", "maintainers": ["Nina Blue", "Oscar Grey"]},
  {"name": "Logger", "owner": "LoggerTools", "repo_url": "https://github.com/LoggerTools/Logger", "release_date": "2020-04-10", "license": "MIT", "maintainers": ["Paul Black"]}
]

Step 1: Naive implementation

libraryService.js

We are going to simulate the two remote services with a module that returns data based on the json files we just created.
There is a delay to simulate a real service, and every request is logged to the console so we can see what is going on.

// src/libraryService.js
import dependencies from "../data/dependencies.json" with { type: "json" };
import metadata from "../data/metadata.json" with { type: "json" };

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function getDependencies(names) {
  console.log("GET /dependencies?names=" + names.join(","));
  await sleep(100);
  return names.map((name) => dependencies.find((d) => d.name === name));
}

export async function getMetadata(names) {
  console.log("GET /metadata?names=" + names.join(","));
  await sleep(100);
  return names.map((name) => metadata.find((d) => d.name === name));
}

Both functions receive a list of names and return a list of results. A very important requirement is that data needs to be returned to the caller in the same order as the names, and all elements need to be returned (same length of names and results arrays). This will be clear when we put in place the dataloader.

resolver.js

The resolver builds the tree. It loads the dependencies and the metadata of a library and then does the same, recursively, for each of its dependencies.

It does not call the service directly. It receives loaders: objects with a load(name) function. The contract is not random, it is based on the real dataloader, so the resolver will not change over the course of the post.

// src/resolver.js
export async function getTree(loaders, name) {
  const [library, metadata] = await Promise.all([
    loaders.dependencies.load(name),
    loaders.metadata.load(name),
  ]);

  return {
    name,
    version: library.version,
    owner: metadata.owner,
    license: metadata.license,
    dependencies: await Promise.all(
      library.dependencies.map((d) => getTree(loaders, d.name))
    ),
  };
}

It uses a brute force approach on purpose. The code is simple but far away from being optimal. In one function it looks obvious, but sometimes, when we are building graphql or similar apis, or complex workflows, we might be doing exactly this kind of brute force requests.

view.js

Nothing advanced. Just render the libraries in a nested way.

// src/view.js
export function render(node) {
  return `<div style="padding-left: 16px">
    ${node.name} ${node.version} (${node.owner}, ${node.license})
    ${node.dependencies.map(render).join("")}
  </div>`;
}

index.js

// src/index.js
import express from "express";
import * as libraryService from "./libraryService.js";
import { getTree } from "./resolver.js";
import { render } from "./view.js";

const app = express();

// No cache, no batching: each load is a request to the service
const direct = (loadManyFn) => ({
  load: async (name) => (await loadManyFn([name]))[0],
});

app.get("/tree/:name", async (req, res) => {
  const loaders = {
    dependencies: direct(libraryService.getDependencies),
    metadata: direct(libraryService.getMetadata),
  };

  const tree = await getTree(loaders, req.params.name);

  res.send(render(tree));
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Run

node src/index.js

And open http://localhost:3000/tree/WebRender.

If we check our console we will find:

GET /dependencies?names=WebRender
GET /metadata?names=WebRender
GET /dependencies?names=HttpClient
GET /metadata?names=HttpClient
GET /dependencies?names=Utils
GET /metadata?names=Utils
GET /dependencies?names=Logger
GET /metadata?names=Logger
GET /dependencies?names=NetworkTools
GET /metadata?names=NetworkTools
GET /dependencies?names=Logger
GET /metadata?names=Logger
GET /dependencies?names=NetworkTools
GET /metadata?names=NetworkTools
GET /dependencies?names=CacheManager
GET /metadata?names=CacheManager
GET /dependencies?names=Logger
GET /metadata?names=Logger
GET /dependencies?names=Logger
GET /metadata?names=Logger
GET /dependencies?names=Logger
GET /metadata?names=Logger
GET /dependencies?names=Logger
GET /metadata?names=Logger

We are loading data for 6 libraries but we are doing 24 requests: two for each node of the tree. Logger alone is requested 5 times to each service. We could easily improve the situation by adding some sort of cache per request.

Step 2: Cache per request

We are going to add a cache to the system. It will be empty at the start of each request, so we do not need to worry about expirations. The benefits will be:

cache.js

Simple cache implementation:

// src/cache.js
export function make(loadManyFn) {
  const cache = {};

  async function loadMany(names) {
    const notCached = names.filter((name) => !cache[name]);

    if (notCached.length > 0) {
      const results = await loadManyFn(notCached);
      notCached.forEach((name, idx) => (cache[name] = results[idx]));
    }

    return names.map((name) => cache[name]);
  }

  return {
    load: async (name) => (await loadMany([name]))[0],
    loadMany,
  };
}

The cache needs a function to retrieve multiple items by name (or in general by a key). It will check the data that is cached and request only the names that are not found.

It implements the contract our resolver expects, so the only change is in index.js. Import it:

import * as cache from "./cache.js";

and create the loaders with it (inside the handler, so each request gets an empty cache):

const loaders = {
  dependencies: cache.make(libraryService.getDependencies),
  metadata: cache.make(libraryService.getMetadata),
};

Run

Let's restart the server and repeat the request:

GET /dependencies?names=WebRender
GET /metadata?names=WebRender
GET /dependencies?names=HttpClient
GET /metadata?names=HttpClient
GET /dependencies?names=Utils
GET /metadata?names=Utils
GET /dependencies?names=Logger
GET /metadata?names=Logger
GET /dependencies?names=NetworkTools
GET /metadata?names=NetworkTools
GET /dependencies?names=Logger
GET /metadata?names=Logger
GET /dependencies?names=NetworkTools
GET /metadata?names=NetworkTools
GET /dependencies?names=CacheManager
GET /metadata?names=CacheManager
GET /dependencies?names=Logger
GET /metadata?names=Logger

We reduced the number of requests from 24 to 18, which is something. But, wait a moment, what happened here? Why are we still requesting Logger three times and NetworkTools twice?

If we unnest the request flow based on how nodejs works (and how we implemented our resolver) this is what happened:

1. Load WebRender                                => requested
2. Load its dependencies, all at the same time:
   2.1 HttpClient                                => requested
   2.2 Utils                                     => requested
   2.3 Logger                                    => requested
3. Responses arrive one by one. As soon as a library is ready we load its dependencies:
   3.1 NetworkTools (dependency of HttpClient)   => requested
   3.2 Logger       (dependency of HttpClient)   => requested, the response of 2.3 is not in the cache yet
   3.3 NetworkTools (dependency of Utils)        => requested, 3.1 has not answered yet
   3.4 CacheManager (dependency of Utils)        => requested
   3.5 Logger       (dependency of Utils)        => requested, neither 2.3 nor 3.2 are in the cache yet
4. Responses arrive. The remaining Logger nodes  => all cached

The cache only knows about a library once its response has arrived. Requests that start while the first one is still in flight do not find anything in the cache, so they go to the service again.

For example, if we did:

const libs = await Promise.all([load("Logger"), load("Logger")]);

there would be 2 requests before the cache has data for Logger.

So with our simple cache, we did not reduce the requests to the minimum we wanted. Let's fix this. And while we are at it: the services accept several names per request, so the ideal would be one request per service and level of the tree:

GET /dependencies?names=WebRender
GET /metadata?names=WebRender
GET /dependencies?names=HttpClient,Utils,Logger
GET /metadata?names=HttpClient,Utils,Logger
GET /dependencies?names=NetworkTools,CacheManager
GET /metadata?names=NetworkTools,CacheManager

Step 3: Dataloader

Using nodejs process.nextTick(...) we can postpone the execution of a function until the code that is currently running has finished. From the nodejs documentation:

By using process.nextTick() we guarantee that apiCall() always runs its callback after the rest of the user's code and before the event loop is allowed to proceed.

Using it we can accumulate all the keys that are being requested during the same cycle (2.1, 2.2 and 2.3 in the example above) and request them together at the end. In the next cycle we would accumulate again the ones that were depending on the previous ones and so on.

This simple version of dataloader also incorporates the cache:

// src/dataloader.js
export function make(loadManyFn) {
  const cache = {};
  let pending = [];
  let scheduled = false;

  function scheduleSearch() {
    if (!scheduled) {
      scheduled = true;
      process.nextTick(runSearch);
    }
  }

  async function runSearch() {
    const batch = pending;
    pending = [];
    scheduled = false;

    const results = await loadManyFn(batch.map((p) => p.name));
    batch.forEach(({ resolve }, idx) => resolve(results[idx]));
  }

  function loadMany(names) {
    for (const name of names) {
      if (!cache[name]) {
        cache[name] = new Promise((resolve) => {
          pending.push({ name, resolve });
        });
        scheduleSearch();
      }
    }

    return Promise.all(names.map((name) => cache[name]));
  }

  return {
    load: async (name) => (await loadMany([name]))[0],
    loadMany,
  };
}

The important bits are:

Accumulating requests

cache[name] = new Promise((resolve) => {
  pending.push({ name, resolve });
});

We add the names that are not cached to the list of pending ones. We keep the name and the resolve function, so we can resolve them afterwards with the right value.

We cache the promise itself, not the result. That is what solves the problem we had with the simple cache: a second load("Logger") finds the promise of the first one even if the response has not arrived yet. It would also allow us to cache rejected promises, so we do not request the same failure over and over. It is not used in this implementation, though.

Scheduling the request

function scheduleSearch() {
  if (!scheduled) {
    scheduled = true;
    process.nextTick(runSearch);
  }
}

That is where the magic happens. This function is short but it is the most important one: we delay the request until all the load calls of the current cycle have been made.

async function runSearch() {
  const batch = pending;
  pending = [];
  scheduled = false;

  const results = await loadManyFn(batch.map((p) => p.name));
  batch.forEach(({ resolve }, idx) => resolve(results[idx]));
}

We take the pending names (so new ones can be accumulated while the request is in flight) and call loadManyFn so we can resolve the promises we had pending. Remember the requirement of returning the data in the right order and all the elements? This is where it is needed. We can reference the results by index and resolve the right pending promises.

Let's run it!

Run

Replace the cache with the dataloader in index.js:

import * as dataloader from "./dataloader.js";
const loaders = {
  dependencies: dataloader.make(libraryService.getDependencies),
  metadata: dataloader.make(libraryService.getMetadata),
};

The same request produces the following output:

GET /dependencies?names=WebRender
GET /metadata?names=WebRender
GET /dependencies?names=HttpClient,Utils,Logger
GET /metadata?names=HttpClient,Utils,Logger
GET /dependencies?names=NetworkTools,CacheManager
GET /metadata?names=NetworkTools,CacheManager

From 24 requests to 6. Exactly what we wanted.

Conclusion