Cloudflare DevelopersCD
Cloudflare Developers9mo ago
1 reply
huw

* [Accounts, zones, and profiles](https://developers.cloudflare.com/fundamentals/setup/accounts-and-

I got MongoDB connection pooling working by using a Durable Object!

My
index.js
looks like this. I’ve provided a locationHint to my DO, based on where my MongoDB databases are:

export { MongoDBConnection } from "./MongoDBConnection.js";

export default {
  async fetch(request, { MONGO_DB_CONNECTION, MONGO_DB_URI }) {
    // FWIW, you’ll probably want to do an auth check or similar here, to prevent wasting resources on fuzzing attacks
    // We can just forward the request straight onto the Durable Object
    const id = MONGO_DB_CONNECTION.idFromName(MONGO_DB_URI);
    const connection = MONGO_DB_CONNECTION.get(id, { locationHint: "apac" });
    return await connection.fetch(request);
  }
};


Then MongoDBConnection.js looks like this:

import { DurableObject } from "cloudflare:workers";
import mongoose from "mongoose";

export class MongoDBConnection extends DurableObject {
  connection;

  constructor(ctx, env) {
    super(ctx, env);
    this.connection = mongoose.createConnection(env.MONGO_DB_URI, {
      // Decrease the selection timeout from 30s (default) to 5s, so that if something breaks, we don't wait around for it.
      serverSelectionTimeoutMS: 5000,
    });
  }

  async fetch(request) {
    // Wait for the connection to become available
    await this.connection.asPromise();
    // Do work here
    return new Response("OK");
  }
}


This code just transparently forwards all requests straight onto the DO, which can hold onto the connection pool across multiple requests and re-use it. My end-to-end timings went from ~2000ms to ~300ms after doing this!

(Also cross-posted this to the workerd discussion above)
Was this page helpful?